diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0df1eed46f..9322cba454 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -782,7 +782,7 @@ jobs: lake env lean --run Scripts/CheckCiFilters.lean --self-test lake env lean --run Scripts/CheckCiFilters.lean - name: Run primary IxTests - run: lake env .lake/build/bin/IxTests + run: lake env .lake/build/bin/IxTests -j 16 - name: Test Ixon contracts and primitives run: | lake env .lake/build/bin/ixon-primitives diff --git a/Ix/Common.lean b/Ix/Common.lean index 14b52c0f81..fe165ddd2f 100644 --- a/Ix/Common.lean +++ b/Ix/Common.lean @@ -5,6 +5,7 @@ public import Lean.Expr public import Lean.Declaration public import Lean.Environment public import Lean.Elab.Frontend +import Std.Sync.Mutex public section @@ -322,14 +323,24 @@ def checkToolchain : IO Unit := do if version != expectedVersion then IO.println s!"Warning: expected toolchain '{expectedVersion}' but got '{version}'" +private initialize leanImportMutex : Std.Mutex Unit ← Std.Mutex.new () + +/-- Serialize `Lean.enableInitializersExecution` + `importModules` / `processHeader` + across concurrent threads: `enableInitializersExecution` sets a process-global + flag that `importModules` resets on completion, and `initSearchPath` mutates + process-global `Lean.searchPathRef`. -/ +def _root_.Ix.withImportLock (action : IO α) : IO α := + leanImportMutex.atomically action + open Elab in open System (FilePath) in def runFrontend (input : String) (filePath : FilePath) : IO Environment := do checkToolchain let inputCtx := Parser.mkInputContext input filePath.toString let (header, parserState, messages) ← Parser.parseHeader inputCtx - unsafe enableInitializersExecution -- required for `processHeader`'s `loadExts := true` import - let (env, messages) ← processHeader header default messages inputCtx 0 + let (env, messages) ← _root_.Ix.withImportLock do + unsafe enableInitializersExecution -- required for `processHeader`'s `loadExts := true` import + processHeader header default messages inputCtx 0 let env := env.setMainModule default let commandState := Command.mkState env messages default let s ← IO.processCommands inputCtx parserState commandState diff --git a/Ix/Meta.lean b/Ix/Meta.lean index 201ca7d440..5dc2cf3df2 100644 --- a/Ix/Meta.lean +++ b/Ix/Meta.lean @@ -100,16 +100,15 @@ isolation the mode exists for (TruthMines' `module-header-v1` patch) without corrupting stored content. See `Ix.EnvScope.defaultConstList`. -/ def getFileEnvCore (path : FilePath) : IO FileEnv := do let path ← IO.FS.realPath path - initLeanSearchPathFor path let source ← IO.FS.readFile path let inputCtx := Parser.mkInputContext source path.toString let (header, parserState, messages) ← Parser.parseHeader inputCtx - -- Required for `processHeaderCore`'s `loadExts := true` import; a completed - -- import resets the flag, so it is re-armed before every import. - unsafe enableInitializersExecution - let (env, messages) ← processHeaderCore - (HeaderSyntax.startPos header) (HeaderSyntax.imports header) - (isModule := false) default messages inputCtx 0 + let (env, messages) ← Ix.withImportLock do + initLeanSearchPathFor path + unsafe enableInitializersExecution + processHeaderCore + (HeaderSyntax.startPos header) (HeaderSyntax.imports header) + (isModule := false) default messages inputCtx 0 if messages.hasErrors then throw $ IO.userError $ "\n\n".intercalate $ (← messages.toList.mapM (·.toString)).map (String.trimAscii · |>.toString) @@ -139,15 +138,16 @@ callers union locally-elaborated names (`getModuleIdxFor? · |>.isNone`) from the full-content env. -/ def moduleVisibleNames (path : FilePath) : IO (Option NameSet) := do let path ← IO.FS.realPath path - initLeanSearchPathFor path let source ← IO.FS.readFile path let inputCtx := Parser.mkInputContext source path.toString let (header, _, messages) ← Parser.parseHeader inputCtx if !HeaderSyntax.isModule header then return none - unsafe enableInitializersExecution -- re-armed per import; see `getFileEnvCore` - let (env, messages) ← processHeaderCore - (HeaderSyntax.startPos header) (HeaderSyntax.imports header) - (isModule := true) default messages inputCtx 0 + let (env, messages) ← Ix.withImportLock do + initLeanSearchPathFor path + unsafe enableInitializersExecution -- re-armed per import; see `getFileEnvCore` + processHeaderCore + (HeaderSyntax.startPos header) (HeaderSyntax.imports header) + (isModule := true) default messages inputCtx 0 if messages.hasErrors then throw $ IO.userError $ "\n\n".intercalate $ (← messages.toList.mapM (·.toString)).map (String.trimAscii · |>.toString) @@ -171,10 +171,11 @@ initial value — all imported entries sit in raw form but the computed state σ is empty, which silently breaks any test that reads extension state via `get_env!`. Matches `Lean.Elab.processHeaderCore`'s import path (used by `getFileEnv`) and Lake's own `importModulesUsingCache`. -/ -def getCompileEnv (imports : Array Name) : IO Environment := do - initLeanSearchPath - unsafe enableInitializersExecution -- required for `loadExts := true` - importModules (imports.map ({ module := · : Import })) default (loadExts := true) +def getCompileEnv (imports : Array Name) : IO Environment := + Ix.withImportLock do + initLeanSearchPath + unsafe enableInitializersExecution -- required for `loadExts := true` + importModules (imports.map ({ module := · : Import })) default (loadExts := true) macro "get_env!" : term => `(getCompileEnv this_file!) diff --git a/Ix/RoleBinding/Compile.lean b/Ix/RoleBinding/Compile.lean index e145257c76..3ac54ad499 100644 --- a/Ix/RoleBinding/Compile.lean +++ b/Ix/RoleBinding/Compile.lean @@ -5,6 +5,7 @@ public import Ix.Cert.Compile public import Ix.EnvScope public import Ix.LeanExport public import Ix.Meta +public import Ix.Common public import IxCK.Kernel.PinGen.Certs /-! Artifact-specific support and evidence for the production compiler. @@ -647,12 +648,14 @@ def elaborateNativeCertSource : IO Lean.Environment := do let opts := Lean.Options.empty.setBool `linter.deprecated false let inputCtx := Lean.Parser.mkInputContext nativeCertSourceText "IxCK/Kernel/PinGen/Certs.lean" let (header, _, _) ← Lean.Parser.parseHeader inputCtx - unsafe Lean.enableInitializersExecution - let some certElabEnv ← Lean.Elab.runFrontend nativeCertSourceText opts - "IxCK/Kernel/PinGen/Certs.lean" `IxCK.Kernel.PinGen.Certs - | throw (IO.userError "nativeCertSource: failed to elaborate embedded IxCK.Kernel.PinGen.Certs") - unsafe Lean.enableInitializersExecution - let baseEnv ← Lean.importModules (Lean.Elab.HeaderSyntax.imports header) default (loadExts := false) + let (certElabEnv, baseEnv) ← _root_.Ix.withImportLock do + unsafe Lean.enableInitializersExecution + let some certElabEnv ← Lean.Elab.runFrontend nativeCertSourceText opts + "IxCK/Kernel/PinGen/Certs.lean" `IxCK.Kernel.PinGen.Certs + | throw (IO.userError "nativeCertSource: failed to elaborate embedded IxCK.Kernel.PinGen.Certs") + unsafe Lean.enableInitializersExecution + let baseEnv ← Lean.importModules (Lean.Elab.HeaderSyntax.imports header) default (loadExts := false) + pure (certElabEnv, baseEnv) let baseConsts := baseEnv.constants.fold (init := #[]) fun acc n ci => acc.push (n, ci) let certConsts := certElabEnv.constants.map₂.foldl (init := #[]) fun acc n ci => acc.push (n, ci) Ix.LeanExport.environment (baseConsts ++ certConsts) @@ -665,25 +668,40 @@ without invoking `lake`. -/ def nativeCertSource : IO Lean.Environment := do if let some env ← cachedNativeCertSource.get then return env - if (← (← Lean.searchPathRef.get).findWithExt "olean" `Init).isNone then - Lean.initSearchPath (← Lean.findSysroot) - if (← (← Lean.searchPathRef.get).findModuleWithExt "olean" `IxCK.Kernel.PinGen.Certs).isNone then - let mut localDirs : List System.FilePath := [] - for dir in ([".lake/kernel/lib/lean", "../.lake/kernel/lib/lean", - "../../.lake/kernel/lib/lean"] : List System.FilePath) do - if ← dir.pathExists then - localDirs := localDirs ++ [dir] - unless localDirs.isEmpty do - let current ← Lean.searchPathRef.get - Lean.searchPathRef.set (localDirs ++ current) - let hasOlean ← match ← (← Lean.searchPathRef.get).findModuleWithExt "olean" `IxCK.Kernel.PinGen.Certs with - | some path => System.FilePath.pathExists (System.FilePath.mk (path.toString ++ ".private")) - | none => pure false - let env ← if hasOlean then - Lean.importModules #[{ module := `IxCK.Kernel.PinGen.Certs }] default (loadExts := false) - else - elaborateNativeCertSource - cachedNativeCertSource.set (some env) + let env ← _root_.Ix.withImportLock do + if let some env ← cachedNativeCertSource.get then + return env + if (← (← Lean.searchPathRef.get).findWithExt "olean" `Init).isNone then + Lean.initSearchPath (← Lean.findSysroot) + if (← (← Lean.searchPathRef.get).findModuleWithExt "olean" `IxCK.Kernel.PinGen.Certs).isNone then + let mut localDirs : List System.FilePath := [] + for dir in ([".lake/kernel/lib/lean", "../.lake/kernel/lib/lean", + "../../.lake/kernel/lib/lean"] : List System.FilePath) do + if ← dir.pathExists then + localDirs := localDirs ++ [dir] + unless localDirs.isEmpty do + let current ← Lean.searchPathRef.get + Lean.searchPathRef.set (localDirs ++ current) + let hasOlean ← match ← (← Lean.searchPathRef.get).findModuleWithExt "olean" `IxCK.Kernel.PinGen.Certs with + | some path => System.FilePath.pathExists (System.FilePath.mk (path.toString ++ ".private")) + | none => pure false + let env ← if hasOlean then + Lean.importModules #[{ module := `IxCK.Kernel.PinGen.Certs }] default (loadExts := false) + else do + let opts := Lean.Options.empty.setBool `linter.deprecated false + let inputCtx := Lean.Parser.mkInputContext nativeCertSourceText "IxCK/Kernel/PinGen/Certs.lean" + let (header, _, _) ← Lean.Parser.parseHeader inputCtx + unsafe Lean.enableInitializersExecution + let some certElabEnv ← Lean.Elab.runFrontend nativeCertSourceText opts + "IxCK/Kernel/PinGen/Certs.lean" `IxCK.Kernel.PinGen.Certs + | throw (IO.userError "nativeCertSource: failed to elaborate embedded IxCK.Kernel.PinGen.Certs") + unsafe Lean.enableInitializersExecution + let baseEnv ← Lean.importModules (Lean.Elab.HeaderSyntax.imports header) default (loadExts := false) + let baseConsts := baseEnv.constants.fold (init := #[]) fun acc n ci => acc.push (n, ci) + let certConsts := certElabEnv.constants.map₂.foldl (init := #[]) fun acc n ci => acc.push (n, ci) + Ix.LeanExport.environment (baseConsts ++ certConsts) + cachedNativeCertSource.set (some env) + return env return env /-- Release a `CheckedStore`'s decoded record map on a background task after diff --git a/Tests/AggrBindingReuse.lean b/Tests/AggrBindingReuse.lean index f6b0ef5752..6dc720b744 100644 --- a/Tests/AggrBindingReuse.lean +++ b/Tests/AggrBindingReuse.lean @@ -35,6 +35,8 @@ public section namespace Tests.Aggr.BindingReuse +open LSpec + /-- The closures of `names` and of the constants the kernel fabricates during reduction, with every inductive's recursors (`IxVM.ClaimHarness.collectCertifiedClosure`: the binder-data annotator @@ -180,8 +182,9 @@ def runWith (name : String) (aggregate : Bool) : IO UInt32 := do bindingProof aggregate let right ← claimSet exe home dir "right" rightEnv 2 bindingProof aggregate (traceShards := true) - LSpec.lspecIO (.ofList [(name, - (left ++ right).toList.map fun (label, ok) => LSpec.test label ok)]) [] + LSpec.lspecMain (describe name do + for (label, ok) in left ++ right do + itBool label ok) [] finally IO.FS.removeDirAll home IO.FS.removeDirAll dir diff --git a/Tests/AggrSemantics.lean b/Tests/AggrSemantics.lean index f62b7e44e6..07daf14cda 100644 --- a/Tests/AggrSemantics.lean +++ b/Tests/AggrSemantics.lean @@ -20,7 +20,7 @@ open LSpec Aiur namespace Tests.Aggr -open Tests.ProofHelpers (expectOk expectErr recCommitParams innerFri u64le) +open Tests.ProofHelpers (recCommitParams innerFri u64le) private def canonicalTree (leaves : Array Address) : Ix.AssumptionTree := (Ix.AssumptionTree.canonical leaves).get! @@ -771,94 +771,93 @@ def semanticSuite : IO UInt32 := do finally IO.FS.removeDirAll tmpDir - lspecIO (.ofList [("ix-aggr-semantics", [ - test "recursion FRI cache encoding is the pinned 40-byte layout" - defaultFriEncodingStable, - test "FRI and commitment overrides independently change recursion identity" - recursionParametersIndependent, - test "aggregate cache version is 2" (Aggr.aggregateCacheVersion == 2), - test "aggregate cache key is stable for identical inputs" cacheKeyStable, - test "aggregate cache key binds the uniform outer claim" cacheKeyBindsOuter, - test "aggregate cache key binds recursion FRI parameters" cacheKeyBindsFri, - test "aggregate cache key binds the recursion verifying key" cacheKeyBindsVk, - test "aggregate cache key rejects version-1 entries" cacheKeyBindsVersion, - test "Rust and Lean aggregate cache identity share a fixed vector" - cacheKeyMatchesRustVector, - test "wrap-first specs precompute every uniform claim and cache key" - wrapSpecsComplete, - test "direct specs retain raw IxVM leaves and one aggregate root" - directSpecsUseRawLeaves, - test "wrap-first and direct policies derive the same flat root claim" - policiesShareRootClaim, - test "aggregate outer claims bind the exact CheckEnv value" outerClaimBindsValue, - test "aggregate verifier accepts a content-addressed proof wrapper" - wrapperContentAddressAccepted, - test "aggregate verifier rejects a wrapper stored under the wrong address" - wrapperContentAddressRejected, - test "flat host fold constructs canonical union/discharge trees" flatHostCorrect, - test "structural host fold constructs root-of-roots and survivors" - structuralHostCorrect, - test "CheckEnvTrees.ofClaim rejects overlapping subjects and assumptions" - ofClaimRejectsSelfAssumption, - test "host join helpers do not self-discharge assumptions" - hostJoinRejectsSelfDischarge, - test "manifest tree lowers to post-order binary slots" - (manifestPlan == expectedPlan), - test "manifest parser exposes its validated bisection tree" parsedManifestPlan, - test "manifest parser rejects repeated aggregation leaves" - malformedManifestRejected, - test "coverage accepts legacy zero-constant manifest leaves" singleCoverage, - test "empty manifest leaves contract and retained ids remap densely" - emptyPruningCorrect, - test "one retained shard reconstructs one value-based root" singletonValueRoot, - test "two-shard manifest passes exact environment coverage" pairCoverage, - test "aggregate startup prepares every shard from one ownership pass" - batchedShardPreparationCorrect, - test "flat manifest value equals the canonical environment root" - manifestFlatIsCanonical, - test "structural manifest value equals the manifest-relative hybrid root" - manifestStructuralIsHybrid, - test "flat and structural schedules produce distinguishable values" - manifestValuesDiffer, - test "shard prep preserves trees and one-pass closure semantics" - shardPrepPreservesSemantics, - test "verified aggregate proof audit certifies every fixture constant" - aggregateProofAuditsEveryConstant, - test "dated Mathlib Stage 2 proof is pinned and rejected by the current protocol" - productionStage2FixturePinnedAndFenced, - test "aggregate constant audit rejects an omitted environment constant" - missingConstantRejected, - test "aggregate constant audit rejects a foreign subject" - foreignConstantRejected, - test "aggregate constant audit rejects a duplicate subject" - duplicateConstantRejected, - test "aggregate constant audit rejects residual assumptions" - residualAssumptionRejected, - test "threshold scheduling is flat below and structural above monotonically" - mixedScheduleCorrect, - test "flat self-pair RAM reserve is affine in subject leaves" - flatWeightAffine, - test "aggregate scheduler parses MemTotal for its default budget" - memTotalParsing, - test "invalid non-post-order schedules are rejected" invalidScheduleRejected, - test "CodecTag has no custom aliasing for tags 0/1/2" codecTagNoAliasing, - test "DynamicLinkStatement with (spec, binding) BridgeBinding round-trips and is rejected by Claim.de" - dlStmtRoundTripsAndDisjoint, - test "LinkedCircuitEntry (0xE8 0x0F, with evalType) round-trips and is rejected by Claim.de" - dlEntryRoundTripsAndDisjoint, - test "Shape 18 Mode 3a cannot emit validator 3/4 or erase linkedCircuits" - mode3aCannotEmitValidator3Or4, - test "ClaimPolicy rejects linkedCircuits != none (validators 12/13) by default" - defaultPolicyRefusesLinked, - test "ClaimPolicy.refusalDynamicBytes rejects LinkedClaim, EvalAssumedClaim, and DynamicLinkStatement by default" - defaultPolicyRefusesDynamicBytes, - test "ClaimPolicy enforces no wildcard, separate Mode-3a allowlist, full tuple pinning, and rejects forged (myTrue, myFalse, MyProp)" - allowlistPolicyChecks, - test "ClaimPolicy.refusalDynamicLinkStatement enforces bridge.binding/customBinding and codec arities" - dynamicLinkStatementPolicyChecks, - test "VerifyCmd CLI fails closed on wildcards and routes --dynamic-claim through ClaimPolicy" - verifyCmdDynamicDispatchChecks - ])]) [] + lspecMain (describe "ix-aggr-semantics" do + itBool "recursion FRI cache encoding is the pinned 40-byte layout" + defaultFriEncodingStable + itBool "FRI and commitment overrides independently change recursion identity" + recursionParametersIndependent + itBool "aggregate cache version is 2" (Aggr.aggregateCacheVersion == 2) + itBool "aggregate cache key is stable for identical inputs" cacheKeyStable + itBool "aggregate cache key binds the uniform outer claim" cacheKeyBindsOuter + itBool "aggregate cache key binds recursion FRI parameters" cacheKeyBindsFri + itBool "aggregate cache key binds the recursion verifying key" cacheKeyBindsVk + itBool "aggregate cache key rejects version-1 entries" cacheKeyBindsVersion + itBool "Rust and Lean aggregate cache identity share a fixed vector" + cacheKeyMatchesRustVector + itBool "wrap-first specs precompute every uniform claim and cache key" + wrapSpecsComplete + itBool "direct specs retain raw IxVM leaves and one aggregate root" + directSpecsUseRawLeaves + itBool "wrap-first and direct policies derive the same flat root claim" + policiesShareRootClaim + itBool "aggregate outer claims bind the exact CheckEnv value" outerClaimBindsValue + itBool "aggregate verifier accepts a content-addressed proof wrapper" + wrapperContentAddressAccepted + itBool "aggregate verifier rejects a wrapper stored under the wrong address" + wrapperContentAddressRejected + itBool "flat host fold constructs canonical union/discharge trees" flatHostCorrect + itBool "structural host fold constructs root-of-roots and survivors" + structuralHostCorrect + itBool "CheckEnvTrees.ofClaim rejects overlapping subjects and assumptions" + ofClaimRejectsSelfAssumption + itBool "host join helpers do not self-discharge assumptions" + hostJoinRejectsSelfDischarge + itBool "manifest tree lowers to post-order binary slots" + (manifestPlan == expectedPlan) + itBool "manifest parser exposes its validated bisection tree" parsedManifestPlan + itBool "manifest parser rejects repeated aggregation leaves" + malformedManifestRejected + itBool "coverage accepts legacy zero-constant manifest leaves" singleCoverage + itBool "empty manifest leaves contract and retained ids remap densely" + emptyPruningCorrect + itBool "one retained shard reconstructs one value-based root" singletonValueRoot + itBool "two-shard manifest passes exact environment coverage" pairCoverage + itBool "aggregate startup prepares every shard from one ownership pass" + batchedShardPreparationCorrect + itBool "flat manifest value equals the canonical environment root" + manifestFlatIsCanonical + itBool "structural manifest value equals the manifest-relative hybrid root" + manifestStructuralIsHybrid + itBool "flat and structural schedules produce distinguishable values" + manifestValuesDiffer + itBool "shard prep preserves trees and one-pass closure semantics" + shardPrepPreservesSemantics + itBool "verified aggregate proof audit certifies every fixture constant" + aggregateProofAuditsEveryConstant + itBool "dated Mathlib Stage 2 proof is pinned and rejected by the current protocol" + productionStage2FixturePinnedAndFenced + itBool "aggregate constant audit rejects an omitted environment constant" + missingConstantRejected + itBool "aggregate constant audit rejects a foreign subject" + foreignConstantRejected + itBool "aggregate constant audit rejects a duplicate subject" + duplicateConstantRejected + itBool "aggregate constant audit rejects residual assumptions" + residualAssumptionRejected + itBool "threshold scheduling is flat below and structural above monotonically" + mixedScheduleCorrect + itBool "flat self-pair RAM reserve is affine in subject leaves" + flatWeightAffine + itBool "aggregate scheduler parses MemTotal for its default budget" + memTotalParsing + itBool "invalid non-post-order schedules are rejected" invalidScheduleRejected + itBool "CodecTag has no custom aliasing for tags 0/1/2" codecTagNoAliasing + itBool "DynamicLinkStatement with (spec, binding) BridgeBinding round-trips and is rejected by Claim.de" + dlStmtRoundTripsAndDisjoint + itBool "LinkedCircuitEntry (0xE8 0x0F, with evalType) round-trips and is rejected by Claim.de" + dlEntryRoundTripsAndDisjoint + itBool "Shape 18 Mode 3a cannot emit validator 3/4 or erase linkedCircuits" + mode3aCannotEmitValidator3Or4 + itBool "ClaimPolicy rejects linkedCircuits != none (validators 12/13) by default" + defaultPolicyRefusesLinked + itBool "ClaimPolicy.refusalDynamicBytes rejects LinkedClaim, EvalAssumedClaim, and DynamicLinkStatement by default" + defaultPolicyRefusesDynamicBytes + itBool "ClaimPolicy enforces no wildcard, separate Mode-3a allowlist, full tuple pinning, and rejects forged (myTrue, myFalse, MyProp)" + allowlistPolicyChecks + itBool "ClaimPolicy.refusalDynamicLinkStatement enforces bridge.binding/customBinding and codec arities" + dynamicLinkStatementPolicyChecks + itBool "VerifyCmd CLI fails closed on wildcards and routes --dynamic-claim through ClaimPolicy" + verifyCmdDynamicDispatchChecks) [] def convergedSuite : IO UInt32 := semanticSuite diff --git a/Tests/AggrToolchains.lean b/Tests/AggrToolchains.lean index 607e42b483..1149d5a2de 100644 --- a/Tests/AggrToolchains.lean +++ b/Tests/AggrToolchains.lean @@ -41,6 +41,8 @@ public section namespace Tests.Aggr.Toolchains +open LSpec + private def isAddressHex (s : String) : Bool := s.length == 64 && s.all fun c => c.isDigit || ('a' ≤ c && c ≤ 'f') @@ -204,8 +206,9 @@ def run : IO UInt32 := do #["--max-ram", toString maxRam]) checks := checks.push ("the join refuses a catalog with a member root missing", refusedJoin.exitCode != 0) - LSpec.lspecIO (.ofList [("aggregate-toolchains", - checks.toList.map fun (label, ok) => LSpec.test label ok)]) [] + LSpec.lspecMain (describe "aggregate-toolchains" do + for (label, ok) in checks do + itBool label ok) [] finally IO.FS.removeDirAll home IO.FS.removeDirAll dir diff --git a/Tests/Aiur/Cost.lean b/Tests/Aiur/Cost.lean index 0bae3983e7..d6687cf62e 100644 --- a/Tests/Aiur/Cost.lean +++ b/Tests/Aiur/Cost.lean @@ -30,49 +30,52 @@ quotient chunks `q·D = 6`; at `h = 8`: `(B+1)·7·F(8) + D·F(16) + q·D·F(32) = 35·24 + 3·64 + 6·160 = 1992`. -/ def handComputed : Float := 1992.0 -def transformCostTests : TestSeq := - test "F(0) = 0 (empty circuit is deactivated)" (transformCost 0 == 0.0) ++ - test "F(1) = 1 (clamp keeps height-1 transforms nonzero)" - (transformCost 1 == 1.0) ++ - test "F(2) = 2" (transformCost 2 == 2.0) ++ - test "F(4) = 8" (transformCost 4 == 8.0) ++ - test "F(1024) = 10240" (transformCost 1024 == 10240.0) ++ - test "F strictly increases across a power-of-two boundary" - (transformCost 1023 < transformCost 1024 && - transformCost 1024 < transformCost 1025) +def transformCostTests : LSpec.Spec := do + itBool "F(0) = 0 (empty circuit is deactivated)" (transformCost 0 == 0.0) + itBool "F(1) = 1 (clamp keeps height-1 transforms nonzero)" + (transformCost 1 == 1.0) + itBool "F(2) = 2" (transformCost 2 == 2.0) + itBool "F(4) = 8" (transformCost 4 == 8.0) + itBool "F(1024) = 10240" (transformCost 1024 == 10240.0) + itBool "F strictly increases across a power-of-two boundary" + (decide (transformCost 1023 < transformCost 1024) && + decide (transformCost 1024 < transformCost 1025)) -def fftCostTests : TestSeq := - test "cost is zero at h = 0" (fftCost fnShape 0 2 == 0.0) ++ - test "hand-computed value at h = 8, logBlowup = 2" - (fftCost fnShape 8 2 == handComputed) ++ - test "one-row sensitivity at small heights" - (fftCost fnShape 1 2 < fftCost fnShape 2 2 && - fftCost fnShape 2 2 < fftCost fnShape 3 2) ++ - test "one-row sensitivity across a power-of-two boundary" - (fftCost fnShape 1023 2 < fftCost fnShape 1024 2 && - fftCost fnShape 1024 2 < fftCost fnShape 1025 2) ++ - test "wider main trace costs more" - (fftCost fnShape 8 2 < - fftCost { fnShape with mainWidth := fnShape.mainWidth + 1 } 8 2) ++ - test "extra lookup (wider stage 2) costs more" - (fftCost fnShape 8 2 < - fftCost { fnShape with stage2Width := fnShape.stage2Width + 2 } 8 2) ++ - test "higher quotient degree costs more" - (fftCost fnShape 8 2 < - fftCost { fnShape with quotientDegree := 4 } 8 2) ++ - test "larger blowup costs more" - (fftCost fnShape 8 1 < fftCost fnShape 8 2) ++ - test "committedWidth = main + stage2 + q·D" +def fftCostTests : LSpec.Spec := do + itBool "cost is zero at h = 0" (fftCost fnShape 0 2 == 0.0) + itBool "hand-computed value at h = 8, logBlowup = 2" + (fftCost fnShape 8 2 == handComputed) + itBool "one-row sensitivity at small heights" + (decide (fftCost fnShape 1 2 < fftCost fnShape 2 2) && + decide (fftCost fnShape 2 2 < fftCost fnShape 3 2)) + itBool "one-row sensitivity across a power-of-two boundary" + (decide (fftCost fnShape 1023 2 < fftCost fnShape 1024 2) && + decide (fftCost fnShape 1024 2 < fftCost fnShape 1025 2)) + itBool "wider main trace costs more" + (decide (fftCost fnShape 8 2 < + fftCost { fnShape with mainWidth := fnShape.mainWidth + 1 } 8 2)) + itBool "extra lookup (wider stage 2) costs more" + (decide (fftCost fnShape 8 2 < + fftCost { fnShape with stage2Width := fnShape.stage2Width + 2 } 8 2)) + itBool "higher quotient degree costs more" + (decide (fftCost fnShape 8 2 < + fftCost { fnShape with quotientDegree := 4 } 8 2)) + itBool "larger blowup costs more" + (decide (fftCost fnShape 8 1 < fftCost fnShape 8 2)) + itBool "committedWidth = main + stage2 + q·D" (fnShape.committedWidth == 4 + 3 + 2 * G.extensionDegree) -def formatSciTests : TestSeq := - test "formatSci 0 = 0" (formatSci 0.0 == "0") ++ - test "formatSci 1 = 1.00e0" (formatSci 1.0 == "1.00e0") ++ - test "formatSci 1424 = 1.42e3" (formatSci 1424.0 == "1.42e3") ++ - test "formatSci 174253453 = 1.74e8" (formatSci 174253453.0 == "1.74e8") ++ - test "mantissa carry: formatSci 999.9 = 1.00e3" (formatSci 999.9 == "1.00e3") +def formatSciTests : LSpec.Spec := do + itBool "formatSci 0 = 0" (formatSci 0.0 == "0") + itBool "formatSci 1 = 1.00e0" (formatSci 1.0 == "1.00e0") + itBool "formatSci 1424 = 1.42e3" (formatSci 1424.0 == "1.42e3") + itBool "formatSci 174253453 = 1.74e8" (formatSci 174253453.0 == "1.74e8") + itBool "mantissa carry: formatSci 999.9 = 1.00e3" (formatSci 999.9 == "1.00e3") -def tests : TestSeq := transformCostTests ++ fftCostTests ++ formatSciTests +def tests : LSpec.Spec := do + transformCostTests + fftCostTests + formatSciTests end AiurTests.Cost diff --git a/Tests/FFI.lean b/Tests/FFI.lean index 36d260e97e..b827d15840 100644 --- a/Tests/FFI.lean +++ b/Tests/FFI.lean @@ -12,14 +12,13 @@ public import Tests.FFI.Refcount namespace Tests.FFI -public def suiteWith (cfg : SlimCheck.Configuration := {}) (valgrind : Bool := false) : - List LSpec.TestSeq := List.foldr (· ++ ·) [] - [ Tests.FFI.Basic.suiteWith cfg - , Tests.FFI.Ixon.suiteWith cfg - , Tests.FFI.Lifecycle.suiteWith cfg - , Tests.FFI.Refcount.suiteWith cfg valgrind - ] +public def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) (valgrind : Bool := false) : + LSpec.Spec := do + Tests.FFI.Basic.suiteWith cfg + Tests.FFI.Ixon.suiteWith cfg + Tests.FFI.Lifecycle.suiteWith cfg + Tests.FFI.Refcount.suiteWith cfg valgrind -public def suite : List LSpec.TestSeq := suiteWith {} false +public def suite : LSpec.Spec := suiteWith {} false end Tests.FFI diff --git a/Tests/FFI/Basic.lean b/Tests/FFI/Basic.lean index 8794caad12..69dd101a3c 100644 --- a/Tests/FFI/Basic.lean +++ b/Tests/FFI/Basic.lean @@ -8,7 +8,7 @@ public import LSpec public import Tests.Gen.Basic public import Std.Data.HashMap -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen namespace Tests.FFI.Basic @@ -42,25 +42,25 @@ def assocListEq (l1 l2 : AssocList Nat (fun _ => Nat)) : Bool := l.toList.map fun ⟨k, v⟩ => (k, v) toSimpleList l1 == toSimpleList l2 -def assocListTests : TestSeq := +def assocListTests : LSpec.Spec := do let emptyList : AssocList Nat (fun _ => Nat) := .nil let single : AssocList Nat (fun _ => Nat) := .cons 1 42 .nil let double : AssocList Nat (fun _ => Nat) := .cons 2 99 (.cons 1 42 .nil) - test "AssocList nil" (assocListEq (roundtripAssocListNatNat emptyList) emptyList) ++ - test "AssocList single" (assocListEq (roundtripAssocListNatNat single) single) ++ - test "AssocList double" (assocListEq (roundtripAssocListNatNat double) double) + itBool "AssocList nil" (assocListEq (roundtripAssocListNatNat emptyList) emptyList) + itBool "AssocList single" (assocListEq (roundtripAssocListNatNat single) single) + itBool "AssocList double" (assocListEq (roundtripAssocListNatNat double) double) -def hashMapTests : TestSeq := - test "HashMap empty" (hashMapEq (roundtripHashMapNatNat {}) {}) ++ - test "HashMap single" (hashMapEq (roundtripHashMapNatNat (({} : Std.HashMap Nat Nat).insert 1 42)) (({} : Std.HashMap Nat Nat).insert 1 42)) +def hashMapTests : LSpec.Spec := do + itBool "HashMap empty" (hashMapEq (roundtripHashMapNatNat {}) {}) + itBool "HashMap single" (hashMapEq (roundtripHashMapNatNat (({} : Std.HashMap Nat Nat).insert 1 42)) (({} : Std.HashMap Nat Nat).insert 1 42)) -def dHashMapRawTests : TestSeq := +def dHashMapRawTests : LSpec.Spec := do let emptyMap : DHashMapRaw Nat (fun _ => Nat) := {} let single : DHashMapRaw Nat (fun _ => Nat) := ({} : DHashMapRaw Nat (fun _ => Nat)).insert 1 42 let double : DHashMapRaw Nat (fun _ => Nat) := (({} : DHashMapRaw Nat (fun _ => Nat)).insert 1 42).insert 2 99 - test "DHashMapRaw empty" (dHashMapRawEq (roundtripDHashMapRawNatNat emptyMap) emptyMap) ++ - test "DHashMapRaw single" (dHashMapRawEq (roundtripDHashMapRawNatNat single) single) ++ - test "DHashMapRaw double" (dHashMapRawEq (roundtripDHashMapRawNatNat double) double) + itBool "DHashMapRaw empty" (dHashMapRawEq (roundtripDHashMapRawNatNat emptyMap) emptyMap) + itBool "DHashMapRaw single" (dHashMapRawEq (roundtripDHashMapRawNatNat single) single) + itBool "DHashMapRaw double" (dHashMapRawEq (roundtripDHashMapRawNatNat double) double) /-! ## Mixed-width scalar records @@ -86,30 +86,31 @@ opaque mixedScalarsFields : @& MixedScalars → String × Array Nat @[extern "rs_roundtrip_mixed_scalars"] opaque roundtripMixedScalars : @& MixedScalars → MixedScalars -def mixedScalarsTests : TestSeq := +def mixedScalarsTests : LSpec.Spec := do let m : MixedScalars := ⟨true, 0x0102030405060708, "mixed", 0xab, 0xcdef, 0x89abcdef, 12345, 678⟩ let z : MixedScalars := ⟨false, 0, "", 0, 0, 0, 0, 0⟩ - test "MixedScalars fields read from Lean" (mixedScalarsFields m == - ("mixed", #[1, 0x0102030405060708, 0xab, 0xcdef, 0x89abcdef, 12345, 678])) ++ - test "MixedScalars zero fields read from Lean" (mixedScalarsFields z == - ("", #[0, 0, 0, 0, 0, 0, 0])) ++ - test "MixedScalars roundtrip" (roundtripMixedScalars m == m) ++ - test "MixedScalars zero roundtrip" (roundtripMixedScalars z == z) + itBool "MixedScalars fields read from Lean" (mixedScalarsFields m == + ("mixed", #[1, 0x0102030405060708, 0xab, 0xcdef, 0x89abcdef, 12345, 678])) + itBool "MixedScalars zero fields read from Lean" (mixedScalarsFields z == + ("", #[0, 0, 0, 0, 0, 0, 0])) + itBool "MixedScalars roundtrip" (roundtripMixedScalars m == m) + itBool "MixedScalars zero roundtrip" (roundtripMixedScalars z == z) /-! ## Test Suite -/ -public def suiteWith (cfg : SlimCheck.Configuration := {}) : List TestSeq := [ - assocListTests, - hashMapTests, - dHashMapRawTests, - mixedScalarsTests, - checkIO "HashMap Nat Nat roundtrip" (∀ m : Std.HashMap Nat Nat, hashMapEq (roundtripHashMapNatNat m) m) .done cfg, - checkIO "DHashMapRaw Nat Nat roundtrip" (∀ m : Std.HashMap Nat Nat, - let raw := m.toList.foldl (init := ({} : DHashMapRaw Nat (fun _ => Nat))) fun acc (k, v) => acc.insert k v - dHashMapRawEq (roundtripDHashMapRawNatNat raw) raw) .done cfg, -] - -public def suite : List TestSeq := suiteWith {} +set_option compiler.extract_closed false in +public def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := do + assocListTests + hashMapTests + dHashMapRawTests + mixedScalarsTests + propWith "HashMap Nat Nat roundtrip" cfg fun (m : Std.HashMap Nat Nat) => + hashMapEq (roundtripHashMapNatNat m) m + propWith "DHashMapRaw Nat Nat roundtrip" cfg fun (m : Std.HashMap Nat Nat) => + let raw := m.toList.foldl (init := ({} : DHashMapRaw Nat (fun _ => Nat))) fun (acc : DHashMapRaw Nat (fun _ => Nat)) (k, v) => acc.insert k v + dHashMapRawEq (roundtripDHashMapRawNatNat raw) raw + +public def suite : Spec := suiteWith {} end Tests.FFI.Basic diff --git a/Tests/FFI/Ixon.lean b/Tests/FFI/Ixon.lean index ee43617179..5ea906b0b9 100644 --- a/Tests/FFI/Ixon.lean +++ b/Tests/FFI/Ixon.lean @@ -12,7 +12,7 @@ public import Ix.Cli.DiffCmd public section -open LSpec SlimCheck Gen Ixon +open LSpec LSpec.Prop Gen Ixon open Ix (DefKind DefinitionSafety QuotKind) namespace Tests.FFI.Ixon @@ -111,66 +111,66 @@ opaque roundtripIxonComm : @& Comm → Comm /-! ## Ixon type FFI unit tests -/ -def ixonDefKindTests : TestSeq := - test "Ixon.DefKind.defn" (roundtripIxonDefKind .defn == .defn) ++ - test "Ixon.DefKind.opaq" (roundtripIxonDefKind .opaq == .opaq) ++ - test "Ixon.DefKind.thm" (roundtripIxonDefKind .thm == .thm) - -def ixonDefinitionSafetyTests : TestSeq := - test "Ixon.DefinitionSafety.unsaf" (roundtripIxonDefinitionSafety .unsaf == .unsaf) ++ - test "Ixon.DefinitionSafety.safe" (roundtripIxonDefinitionSafety .safe == .safe) ++ - test "Ixon.DefinitionSafety.part" (roundtripIxonDefinitionSafety .part == .part) - -def ixonQuotKindTests : TestSeq := - test "Ixon.QuotKind.type" (roundtripIxonQuotKind .type == .type) ++ - test "Ixon.QuotKind.ctor" (roundtripIxonQuotKind .ctor == .ctor) ++ - test "Ixon.QuotKind.lift" (roundtripIxonQuotKind .lift == .lift) ++ - test "Ixon.QuotKind.ind" (roundtripIxonQuotKind .ind == .ind) - -def ixonUnivTests : TestSeq := - test "Ixon.Univ.zero" (roundtripIxonUniv .zero == .zero) ++ - test "Ixon.Univ.var 0" (roundtripIxonUniv (.var 0) == .var 0) ++ - test "Ixon.Univ.var 42" (roundtripIxonUniv (.var 42) == .var 42) ++ - test "Ixon.Univ.succ zero" (roundtripIxonUniv (.succ .zero) == .succ .zero) ++ - test "Ixon.Univ.max" (roundtripIxonUniv (.max .zero (.var 1)) == .max .zero (.var 1)) ++ - test "Ixon.Univ.imax" (roundtripIxonUniv (.imax (.var 0) .zero) == .imax (.var 0) .zero) - -def ixonExprTests : TestSeq := - test "Ixon.Expr.sort" (roundtripIxonExpr (.sort 0) == .sort 0) ++ - test "Ixon.Expr.var" (roundtripIxonExpr (.var 5) == .var 5) ++ - test "Ixon.Expr.ref" (roundtripIxonExpr (.ref 1 #[0, 1]) == .ref 1 #[0, 1]) ++ - test "Ixon.Expr.recur" (roundtripIxonExpr (.recur 2 #[]) == .recur 2 #[]) ++ - test "Ixon.Expr.str" (roundtripIxonExpr (.str 3) == .str 3) ++ - test "Ixon.Expr.nat" (roundtripIxonExpr (.nat 42) == .nat 42) ++ - test "Ixon.Expr.share" (roundtripIxonExpr (.share 0) == .share 0) ++ - test "Ixon.Expr.app" (roundtripIxonExpr (.app (.var 0) (.var 1)) == .app (.var 0) (.var 1)) ++ - test "Ixon.Expr.lam" (roundtripIxonExpr (.lam (.sort 0) (.var 0)) == .lam (.sort 0) (.var 0)) ++ - test "Ixon.Expr.all" (roundtripIxonExpr (.all (.sort 0) (.var 0)) == .all (.sort 0) (.var 0)) ++ - test "Ixon.Expr.letE" (roundtripIxonExpr (.leanLet true (.sort 0) (.var 0) (.var 1)) == .leanLet true (.sort 0) (.var 0) (.var 1)) ++ - test "Ixon.Expr.letE unique" (roundtripIxonExpr (.letE false (.value .unique) (.sort 0) (.var 0) (.var 1)) == - .letE false (.value .unique) (.sort 0) (.var 0) (.var 1)) ++ - test "Ixon.Expr.letE borrow" (roundtripIxonExpr (.letE true .borrow (.sort 0) (.var 0) (.var 1)) == - .letE true .borrow (.sort 0) (.var 0) (.var 1)) ++ - test "Ixon.Expr.prj" (roundtripIxonExpr (.prj 0 1 (.var 0)) == .prj 0 1 (.var 0)) +def ixonDefKindTests : LSpec.Spec := do + itBool "Ixon.DefKind.defn" (roundtripIxonDefKind .defn == .defn) + itBool "Ixon.DefKind.opaq" (roundtripIxonDefKind .opaq == .opaq) + itBool "Ixon.DefKind.thm" (roundtripIxonDefKind .thm == .thm) + +def ixonDefinitionSafetyTests : LSpec.Spec := do + itBool "Ixon.DefinitionSafety.unsaf" (roundtripIxonDefinitionSafety .unsaf == .unsaf) + itBool "Ixon.DefinitionSafety.safe" (roundtripIxonDefinitionSafety .safe == .safe) + itBool "Ixon.DefinitionSafety.part" (roundtripIxonDefinitionSafety .part == .part) + +def ixonQuotKindTests : LSpec.Spec := do + itBool "Ixon.QuotKind.type" (roundtripIxonQuotKind .type == .type) + itBool "Ixon.QuotKind.ctor" (roundtripIxonQuotKind .ctor == .ctor) + itBool "Ixon.QuotKind.lift" (roundtripIxonQuotKind .lift == .lift) + itBool "Ixon.QuotKind.ind" (roundtripIxonQuotKind .ind == .ind) + +def ixonUnivTests : LSpec.Spec := do + itBool "Ixon.Univ.zero" (roundtripIxonUniv .zero == .zero) + itBool "Ixon.Univ.var 0" (roundtripIxonUniv (.var 0) == .var 0) + itBool "Ixon.Univ.var 42" (roundtripIxonUniv (.var 42) == .var 42) + itBool "Ixon.Univ.succ zero" (roundtripIxonUniv (.succ .zero) == .succ .zero) + itBool "Ixon.Univ.max" (roundtripIxonUniv (.max .zero (.var 1)) == .max .zero (.var 1)) + itBool "Ixon.Univ.imax" (roundtripIxonUniv (.imax (.var 0) .zero) == .imax (.var 0) .zero) + +def ixonExprTests : LSpec.Spec := do + itBool "Ixon.Expr.sort" (roundtripIxonExpr (.sort 0) == .sort 0) + itBool "Ixon.Expr.var" (roundtripIxonExpr (.var 5) == .var 5) + itBool "Ixon.Expr.ref" (roundtripIxonExpr (.ref 1 #[0, 1]) == .ref 1 #[0, 1]) + itBool "Ixon.Expr.recur" (roundtripIxonExpr (.recur 2 #[]) == .recur 2 #[]) + itBool "Ixon.Expr.str" (roundtripIxonExpr (.str 3) == .str 3) + itBool "Ixon.Expr.nat" (roundtripIxonExpr (.nat 42) == .nat 42) + itBool "Ixon.Expr.share" (roundtripIxonExpr (.share 0) == .share 0) + itBool "Ixon.Expr.app" (roundtripIxonExpr (.app (.var 0) (.var 1)) == .app (.var 0) (.var 1)) + itBool "Ixon.Expr.lam" (roundtripIxonExpr (.lam (.sort 0) (.var 0)) == .lam (.sort 0) (.var 0)) + itBool "Ixon.Expr.all" (roundtripIxonExpr (.all (.sort 0) (.var 0)) == .all (.sort 0) (.var 0)) + itBool "Ixon.Expr.letE" (roundtripIxonExpr (.leanLet true (.sort 0) (.var 0) (.var 1)) == .leanLet true (.sort 0) (.var 0) (.var 1)) + itBool "Ixon.Expr.letE unique" (roundtripIxonExpr (.letE false (.value .unique) (.sort 0) (.var 0) (.var 1)) == + .letE false (.value .unique) (.sort 0) (.var 0) (.var 1)) + itBool "Ixon.Expr.letE borrow" (roundtripIxonExpr (.letE true .borrow (.sort 0) (.var 0) (.var 1)) == + .letE true .borrow (.sort 0) (.var 0) (.var 1)) + itBool "Ixon.Expr.prj" (roundtripIxonExpr (.prj 0 1 (.var 0)) == .prj 0 1 (.var 0)) /-! ## Metadata Unit Tests -/ -def exprMetaDataTests : TestSeq := +def exprMetaDataTests : LSpec.Spec := do let testAddr := Address.blake3 (ByteArray.mk #[1, 2, 3]) let _kvmap : KVMap := #[(testAddr, DataValue.ofBool true)] - test "ExprMetaData.leaf" (roundtripIxonExprMetaData .leaf == .leaf) ++ - test "ExprMetaData.app" (roundtripIxonExprMetaData (.app 0 1) == .app 0 1) ++ - test "ExprMetaData.ref" (roundtripIxonExprMetaData (.ref testAddr) == .ref testAddr) ++ - test "ExprMetaData.prj" (roundtripIxonExprMetaData (.prj testAddr 5) == .prj testAddr 5) ++ - test "ExprMetaData.letBinder" (roundtripIxonExprMetaData (.letBinder testAddr 0 1 2) == .letBinder testAddr 0 1 2) ++ - test "ExprMetaData.mdata empty" (roundtripIxonExprMetaData (.mdata #[] 0) == .mdata #[] 0) ++ - test "ExprMetaData.mdata with kvmap" (roundtripIxonExprMetaData (.mdata #[_kvmap] 3) == .mdata #[_kvmap] 3) ++ - test "ExprMetaData.binder default" (roundtripIxonExprMetaData (.binder testAddr .default 0 1) == .binder testAddr .default 0 1) ++ - test "ExprMetaData.binder implicit" (roundtripIxonExprMetaData (.binder testAddr .implicit 2 3) == .binder testAddr .implicit 2 3) ++ - test "ExprMetaData.binder strictImplicit" (roundtripIxonExprMetaData (.binder testAddr .strictImplicit 0 0) == .binder testAddr .strictImplicit 0 0) ++ - test "ExprMetaData.binder instImplicit" (roundtripIxonExprMetaData (.binder testAddr .instImplicit 0 0) == .binder testAddr .instImplicit 0 0) - -def exprMetaArenaTests : TestSeq := + itBool "ExprMetaData.leaf" (roundtripIxonExprMetaData .leaf == .leaf) + itBool "ExprMetaData.app" (roundtripIxonExprMetaData (.app 0 1) == .app 0 1) + itBool "ExprMetaData.ref" (roundtripIxonExprMetaData (.ref testAddr) == .ref testAddr) + itBool "ExprMetaData.prj" (roundtripIxonExprMetaData (.prj testAddr 5) == .prj testAddr 5) + itBool "ExprMetaData.letBinder" (roundtripIxonExprMetaData (.letBinder testAddr 0 1 2) == .letBinder testAddr 0 1 2) + itBool "ExprMetaData.mdata empty" (roundtripIxonExprMetaData (.mdata #[] 0) == .mdata #[] 0) + itBool "ExprMetaData.mdata with kvmap" (roundtripIxonExprMetaData (.mdata #[_kvmap] 3) == .mdata #[_kvmap] 3) + itBool "ExprMetaData.binder default" (roundtripIxonExprMetaData (.binder testAddr .default 0 1) == .binder testAddr .default 0 1) + itBool "ExprMetaData.binder implicit" (roundtripIxonExprMetaData (.binder testAddr .implicit 2 3) == .binder testAddr .implicit 2 3) + itBool "ExprMetaData.binder strictImplicit" (roundtripIxonExprMetaData (.binder testAddr .strictImplicit 0 0) == .binder testAddr .strictImplicit 0 0) + itBool "ExprMetaData.binder instImplicit" (roundtripIxonExprMetaData (.binder testAddr .instImplicit 0 0) == .binder testAddr .instImplicit 0 0) + +def exprMetaArenaTests : LSpec.Spec := do let testAddr := Address.blake3 (ByteArray.mk #[1, 2, 3]) let emptyArena : ExprMetaArena := {} let singleLeaf : ExprMetaArena := { nodes := #[.leaf] } @@ -179,12 +179,12 @@ def exprMetaArenaTests : TestSeq := .leaf, .ref testAddr, .app 0 0, .binder testAddr .default 0 1, .letBinder testAddr 0 1 2, .prj testAddr 0, .mdata #[] 0 ] } - checkIO "ExprMetaArena empty" (roundtripIxonExprMetaArena emptyArena == emptyArena) ++ - checkIO "ExprMetaArena single leaf" (roundtripIxonExprMetaArena singleLeaf == singleLeaf) ++ - checkIO "ExprMetaArena small" (roundtripIxonExprMetaArena smallArena == smallArena) ++ - checkIO "ExprMetaArena mixed" (roundtripIxonExprMetaArena mixedArena == mixedArena) + itBool "ExprMetaArena empty" (roundtripIxonExprMetaArena emptyArena == emptyArena) + itBool "ExprMetaArena single leaf" (roundtripIxonExprMetaArena singleLeaf == singleLeaf) + itBool "ExprMetaArena small" (roundtripIxonExprMetaArena smallArena == smallArena) + itBool "ExprMetaArena mixed" (roundtripIxonExprMetaArena mixedArena == mixedArena) -def constantMetaTests : TestSeq := +def constantMetaTests : LSpec.Spec := do let testAddr := Address.blake3 (ByteArray.mk #[1, 2, 3]) let emptyArena : ExprMetaArena := {} let smallArena : ExprMetaArena := { nodes := #[.leaf, .app 0 0, .ref testAddr] } @@ -195,26 +195,26 @@ def constantMetaTests : TestSeq := .mdata #[#[(testAddr, .ofBool true)]] 0 ] } let rt (cm : ConstantMeta) : Bool := roundtripIxonConstantMeta cm == cm - checkIO "ConstantMeta.empty" (rt .empty) ++ - checkIO "ConstantMeta.defn" (rt (.new - (.defn testAddr #[testAddr] #[] #[] smallArena 0 1))) ++ - checkIO "ConstantMeta.axio" (rt (.new (.axio testAddr #[] emptyArena 0))) ++ - checkIO "ConstantMeta.ctor" (rt (.new - (.ctor testAddr #[] testAddr smallArena 2))) ++ - checkIO "ConstantMeta.recr" (rt (.new - (.recr testAddr #[] #[] #[] #[] smallArena 0 #[1, 2]))) ++ - checkIO "ConstantMeta.muts auxLayout none" (rt (.new - (.muts #[#[testAddr]] none))) ++ + itBool "ConstantMeta.empty" (rt .empty) + itBool "ConstantMeta.defn" (rt (.new + (.defn testAddr #[testAddr] #[] #[] smallArena 0 1))) + itBool "ConstantMeta.axio" (rt (.new (.axio testAddr #[] emptyArena 0))) + itBool "ConstantMeta.ctor" (rt (.new + (.ctor testAddr #[] testAddr smallArena 2))) + itBool "ConstantMeta.recr" (rt (.new + (.recr testAddr #[] #[] #[] #[] smallArena 0 #[1, 2]))) + itBool "ConstantMeta.muts auxLayout none" (rt (.new + (.muts #[#[testAddr]] none))) -- `evaporated` fixtures spell the canonical one-flag-per-perm-entry -- form the compiler materializes (the Rust FFI decode expands the -- `#[]` construction default to that shape). - checkIO "ConstantMeta.muts auxLayout some" (rt (.new - (.muts #[#[testAddr]] (some ⟨#[1, 0], #[2, 3], #[0, 0]⟩)))) ++ - checkIO "ConstantMeta.muts auxLayout evaporated" (rt (.new - (.muts #[#[testAddr]] (some ⟨#[1, 0], #[2, 3], #[0, 1]⟩)))) ++ - checkIO "ConstantMeta mdata arena" (rt (.new - (.defn testAddr #[] #[] #[] recordArena 0 1))) ++ - checkIO "ConstantMeta extension tables" (rt + itBool "ConstantMeta.muts auxLayout some" (rt (.new + (.muts #[#[testAddr]] (some ⟨#[1, 0], #[2, 3], #[0, 0]⟩)))) + itBool "ConstantMeta.muts auxLayout evaporated" (rt (.new + (.muts #[#[testAddr]] (some ⟨#[1, 0], #[2, 3], #[0, 1]⟩)))) + itBool "ConstantMeta mdata arena" (rt (.new + (.defn testAddr #[] #[] #[] recordArena 0 1))) + itBool "ConstantMeta extension tables" (rt { info := .defn testAddr #[] #[] #[] recordArena 0 1, metaSharing := #[.app (.share 0) (.var 3), .sort 1], metaRefs := #[testAddr], @@ -245,16 +245,6 @@ opaque rsEqEnvSerialization : @& RawEnv → @& ByteArray → Bool @[extern "rs_roundtrip_raw_env"] opaque roundtripRawEnv : @& RawEnv → RawEnv -instance : Shrinkable RawEnv where - shrink env := - if env.consts.isEmpty && env.named.isEmpty && env.blobs.isEmpty && env.comms.isEmpty then [] - else [{ - consts := if env.consts.isEmpty then #[] else env.consts.pop, - named := if env.named.isEmpty then #[] else env.named.pop, - blobs := if env.blobs.isEmpty then #[] else env.blobs.pop, - comms := if env.comms.isEmpty then #[] else env.comms.pop - }] - /-- Compare RawEnv with content-aware comparison. Checks array sizes and content matching by Address. -/ def rawEnvEq (a b : RawEnv) : Bool := @@ -277,7 +267,7 @@ def rawEnvEq (a b : RawEnv) : Bool := /-! ## RawEnv unit tests -/ -def rawEnvTests : TestSeq := +def rawEnvTests : LSpec.Spec := do let empty : RawEnv := { consts := #[], named := #[], blobs := #[], comms := #[] } -- Create test data for non-empty case let testAddr := Address.blake3 (ByteArray.mk #[1, 2, 3]) @@ -303,8 +293,8 @@ def rawEnvTests : TestSeq := blobs := #[testRawBlob], comms := #[testRawComm] } - test "RawEnv empty" (rawEnvEq (roundtripRawEnv empty) empty) ++ - test "RawEnv with data" (rawEnvEq (roundtripRawEnv withData) withData) + itBool "RawEnv empty" (rawEnvEq (roundtripRawEnv empty) empty) + itBool "RawEnv with data" (rawEnvEq (roundtripRawEnv withData) withData) /-! ## Env diff FFI (`rs_diff_envs`) @@ -312,7 +302,7 @@ The classification logic is covered by Rust unit tests (`crates/ixon/src/diff.rs`); these tests pin the FFI marshaling — a constructor-slot swap would surface as wrong-category contents. -/ -def envDiffTests : TestSeq := +def envDiffTests : LSpec.Spec := do let fooName := Ix.Name.mkStr Ix.Name.mkAnon "foo" let barName := Ix.Name.mkStr Ix.Name.mkAnon "bar" -- `.var` exprs only: classification resolves table indices, so a @@ -349,34 +339,36 @@ def envDiffTests : TestSeq := let runDiff (a b : Env) (compareMeta : Bool := false) : Option Ixon.EnvDiff := (Ixon.rsDiffEnvs (serEnv! a) (serEnv! b) compareMeta).toOption - (TestSeq.individualIO "EnvDiff: CLI exit codes" none (do + it "EnvDiff: CLI exit codes" do let dir ← IO.FS.createTempDir - let pa := dir / "a.ixe" - let pb := dir / "b.ixe" - IO.FS.writeBinFile pa (serEnv! envBase) - IO.FS.writeBinFile pb (serEnv! envValueChanged) - let (sameOut, sameCode) ← IO.FS.withIsolatedStreams - (diffCmd.validate [pa.toString, pa.toString, "--meta"]) - let (_, differCode) ← IO.FS.withIsolatedStreams - (diffCmd.validate [pa.toString, pb.toString, "--anon"]) - IO.FS.removeDirAll dir - let ok := sameCode == 0 && sameOut.contains "identical" && differCode == 1 - return (ok, if ok then 1 else 0, 1, if ok then none else some s!"CLI exits {sameCode}/{differCode}")) .done) ++ - test "EnvDiff: self-diff empty (anon)" - ((runDiff envBase envBase).any (·.isEmpty)) ++ - test "EnvDiff: self-diff empty (meta)" - ((runDiff envBase envBase true).any (·.isEmpty)) ++ - test "EnvDiff: stats populated" + try + let pa := dir / "a.ixe" + let pb := dir / "b.ixe" + IO.FS.writeBinFile pa (serEnv! envBase) + IO.FS.writeBinFile pb (serEnv! envValueChanged) + let (sameOut, sameCode) ← IO.FS.withIsolatedStreams + (diffCmd.validate [pa.toString, pa.toString, "--meta"]) + let (_, differCode) ← IO.FS.withIsolatedStreams + (diffCmd.validate [pa.toString, pb.toString, "--anon"]) + expect (sameCode == 0 && sameOut.contains "identical" && differCode == 1) + s!"CLI exits {sameCode}/{differCode}" + finally + IO.FS.removeDirAll dir + itBool "EnvDiff: self-diff empty (anon)" + ((runDiff envBase envBase).any (·.isEmpty)) + itBool "EnvDiff: self-diff empty (meta)" + ((runDiff envBase envBase true).any (·.isEmpty)) + itBool "EnvDiff: stats populated" ((runDiff envBase envBase).any fun d => - d.statsA.consts == 1 && d.statsA.named == 1 && d.statsB == d.statsA) ++ - test "EnvDiff: added name" + d.statsA.consts == 1 && d.statsA.named == 1 && d.statsB == d.statsA) + itBool "EnvDiff: added name" ((runDiff envBase envExtra).any fun d => d.namedAdded == #[("bar", addrB)] && d.constsOnlyB == #[addrB] - && d.namedRemoved.isEmpty && d.namedChanged.isEmpty) ++ - test "EnvDiff: removed name" + && d.namedRemoved.isEmpty && d.namedChanged.isEmpty) + itBool "EnvDiff: removed name" ((runDiff envExtra envBase).any fun d => - d.namedRemoved == #[("bar", addrB)] && d.constsOnlyA == #[addrB]) ++ - test "EnvDiff: value change classified" + d.namedRemoved == #[("bar", addrB)] && d.constsOnlyA == #[addrB]) + itBool "EnvDiff: value change classified" ((runDiff envBase envValueChanged).any fun d => d.namedChanged.size == 1 && (d.namedChanged[0]!).name == "foo" && @@ -386,10 +378,10 @@ def envDiffTests : TestSeq := (d.namedChanged[0]!).newKind == "defn" && (d.namedChanged[0]!).fields == #["value"] && (d.namedChanged[0]!).metaFields.isEmpty && - (d.namedChanged[0]!).rippled == false) ++ + (d.namedChanged[0]!).rippled == false) -- A dependent whose only change is its ref re-addressing must marshal -- `rippled == true` (pins the num_8 scalar slot against layout swaps). - test "EnvDiff: ripple verdict marshals" + itBool "EnvDiff: ripple verdict marshals" (let mkRefConst (r : Address) : Constant := { info := .defn { kind := .defn, safety := .safe, lvls := 0, typ := .var 3, value := .ref 0 #[] } @@ -409,22 +401,22 @@ def envDiffTests : TestSeq := (runDiff (mkPair constA) (mkPair constB)).any fun d => d.namedChanged.size == 2 && (d.namedChanged.find? (·.name == "foo")).any (·.rippled == false) && - (d.namedChanged.find? (·.name == "bar")).any (·.rippled == true)) ++ + (d.namedChanged.find? (·.name == "bar")).any (·.rippled == true)) -- Hints live only in the env-level hints section, so a hint tweak -- is a pure `hintsChanged` row — no metadata difference in either -- mode (the named entries are identical). - test "EnvDiff: hint change visible in anon mode" + itBool "EnvDiff: hint change visible in anon mode" ((runDiff envBase envHintChanged).any fun d => d.hintsChanged == #[(addrA, "regular(5)", "regular(6)")] - && d.namedMetaOnly.isEmpty && d.namedChanged.isEmpty) ++ - test "EnvDiff: hint change is not a metadata change" + && d.namedMetaOnly.isEmpty && d.namedChanged.isEmpty) + itBool "EnvDiff: hint change is not a metadata change" ((runDiff envBase envHintChanged true).any fun d => d.hintsChanged.size == 1 && d.namedMetaOnly.isEmpty - && d.namedChanged.isEmpty) ++ - test "EnvDiff: main change" + && d.namedChanged.isEmpty) + itBool "EnvDiff: main change" ((runDiff { envBase with main := some addrA } envBase).any fun d => - d.mainChanged == some (some addrA, none)) ++ - test "EnvDiff: assumptions delta" + d.mainChanged == some (some addrA, none)) + itBool "EnvDiff: assumptions delta" (let p := Address.blake3 (ByteArray.mk #[1]) let q := Address.blake3 (ByteArray.mk #[2]) let r := Address.blake3 (ByteArray.mk #[3]) @@ -433,30 +425,25 @@ def envDiffTests : TestSeq := let b := { envBase with assumptions := ({} : Std.HashSet Address).insert q |>.insert r } (runDiff a b).any fun d => - d.assumptionsAdded == #[r] && d.assumptionsRemoved == #[p]) ++ + d.assumptionsAdded == #[r] && d.assumptionsRemoved == #[p]) -- The mmap file-path entry must agree with the bytes-based one, and -- the byte-equality fast path must distinguish same vs different. - (TestSeq.individualIO "EnvDiff: file-based diff matches bytes-based" - none (do - let dir ← IO.FS.createTempDir + it "EnvDiff: file-based diff matches bytes-based" do + let dir ← IO.FS.createTempDir + try let pa := dir / "a.ixe" let pb := dir / "b.ixe" let bytesA := serEnv! envBase let bytesB := serEnv! envValueChanged IO.FS.writeBinFile pa bytesA IO.FS.writeBinFile pb bytesB - let r ← try - let eqSame ← Ixon.rsIxeFilesEqual pa.toString pa.toString - let eqDiff ← Ixon.rsIxeFilesEqual pa.toString pb.toString - let dFiles ← Ixon.rsDiffEnvFiles pa.toString pb.toString false - let ok := eqSame && !eqDiff && - (match Ixon.rsDiffEnvs bytesA bytesB false with - | .ok dBytes => dFiles == dBytes - | .error _ => false) - pure (ok, if ok then none else some "file/bytes reports disagree") - catch e => pure (false, some e.toString) + let eqSame ← Ixon.rsIxeFilesEqual pa.toString pa.toString + let eqDiff ← Ixon.rsIxeFilesEqual pa.toString pb.toString + let dFiles ← Ixon.rsDiffEnvFiles pa.toString pb.toString false + let dBytes ← expectOk (Ixon.rsDiffEnvs bytesA bytesB false) + expect (eqSame && !eqDiff && dFiles == dBytes) "file/bytes reports disagree" + finally IO.FS.removeDirAll dir - pure (r.1, 0, 0, r.2)) .done) /-- Self-diff over the pure-Lean writer's bytes must be empty in both modes (also exercises report marshaling on arbitrary inputs). -/ @@ -496,23 +483,20 @@ private def packFixture (env : Env) (mainName : String) /-- IO test asserting on a successfully packed bundle. -/ private def packTest (descr : String) (act : IO (Except String Env)) - (check : Env → Bool) : TestSeq := - .individualIO descr none (do - match ← act with - | .ok bundle => - let ok := check bundle - pure (ok, 0, 0, if ok then none else some "bundle assertion failed") - | .error e => pure (false, 0, 0, some e)) .done + (check : Env → Bool) : Spec := + it descr do + let bundle ← expectOk (← act) + expect (check bundle) "bundle assertion failed" /-- IO test asserting the pack call fails. -/ private def packErrTest (descr : String) (act : IO (Except String Env)) : - TestSeq := - .individualIO descr none (do + Spec := + it descr do match ← act with - | .ok _ => pure (false, 0, 0, some "expected pack to fail") - | .error _ => pure (true, 0, 0, none)) .done + | .ok _ => fail "expected pack to fail" + | .error _ => pure () -def envPackTests : TestSeq := +def envPackTests : LSpec.Spec := do let fooName := Ix.Name.mkStr Ix.Name.mkAnon "foo" let barName := Ix.Name.mkStr Ix.Name.mkAnon "bar" let quxName := Ix.Name.mkStr Ix.Name.mkAnon "qux" @@ -551,35 +535,30 @@ def envPackTests : TestSeq := && b.getAddr? fooName == some fooAddr && (b.getAddr? quxName).isNone && b.consts.size == 2 - && b.assumptions.isEmpty) ++ - (TestSeq.individualIO "EnvPack: bundle is a removals-only subset under diff" - none (do - match ← packFixture src "bar" #[] with - | .error e => pure (false, 0, 0, some e) - | .ok b => - match Ixon.rsDiffEnvs (serEnv! src) (serEnv! b) with - | .error e => pure (false, 0, 0, some s!"diff failed: {e}") - | .ok d => - let ok := d.mainChanged == some (none, some barAddr) - && d.namedRemoved.size == 1 - && d.namedAdded.isEmpty && d.namedChanged.isEmpty - && d.constsOnlyB.isEmpty && d.blobsOnlyB.isEmpty - let msg := s!"mainOk={d.mainChanged == some (none, some barAddr)} \ - removed={d.namedRemoved.map (·.1)} \ - added={d.namedAdded.map (·.1)} \ - changed={d.namedChanged.map (·.name)} \ - constsOnlyB={d.constsOnlyB.size} blobsOnlyB={d.blobsOnlyB.size}" - pure (ok, 0, 0, if ok then none else some msg)) .done) ++ + && b.assumptions.isEmpty) + it "EnvPack: bundle is a removals-only subset under diff" do + let b ← expectOk (← packFixture src "bar" #[]) + let d ← expectOk (Ixon.rsDiffEnvs (serEnv! src) (serEnv! b)) + let ok := d.mainChanged == some (none, some barAddr) + && d.namedRemoved.size == 1 + && d.namedAdded.isEmpty && d.namedChanged.isEmpty + && d.constsOnlyB.isEmpty && d.blobsOnlyB.isEmpty + let msg := s!"mainOk={d.mainChanged == some (none, some barAddr)} \ + removed={d.namedRemoved.map (·.1)} \ + added={d.namedAdded.map (·.1)} \ + changed={d.namedChanged.map (·.name)} \ + constsOnlyB={d.constsOnlyB.size} blobsOnlyB={d.blobsOnlyB.size}" + expect ok msg packTest "EnvPack: assume cut (by name) records assumption" (packFixture src "bar" #["foo"]) (fun b => b.main == some barAddr && (b.getAddr? fooName).isNone && b.consts.size == 1 && b.assumptions.size == 1 - && b.assumptions.contains fooAddr) ++ + && b.assumptions.contains fooAddr) packTest "EnvPack: assume cut (by hex address) records assumption" (packFixture src "bar" #[toString fooAddr]) (fun b => - b.consts.size == 1 && b.assumptions.contains fooAddr) ++ + b.consts.size == 1 && b.assumptions.contains fooAddr) packTest "EnvPack: anon bundle has no metadata, keeps the value pin" (packFixture src "bar" #[] (anon := true)) (fun b => b.main == some barAddr @@ -587,62 +566,62 @@ def envPackTests : TestSeq := -- The writer always emits the anonymous name as §4 entry 0. && b.names.size <= 1 && b.consts.size == 2 - && (b.getAddr? barName).isNone) ++ + && (b.getAddr? barName).isNone) packErrTest "EnvPack: unknown root name errors" - (packFixture src "nope" #[]) ++ + (packFixture src "nope" #[]) packErrTest "EnvPack: main cannot be assumed" (packFixture src "bar" #["bar"]) /-! ## Test Suite -/ -def suiteWith (cfg : SlimCheck.Configuration := {}) : List TestSeq := [ +set_option compiler.extract_closed false in +def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := do -- Ixon type unit tests - ixonDefKindTests, - ixonDefinitionSafetyTests, - ixonQuotKindTests, - ixonUnivTests, - ixonExprTests, - exprMetaDataTests, - exprMetaArenaTests, - constantMetaTests, - rawEnvTests, + ixonDefKindTests + ixonDefinitionSafetyTests + ixonQuotKindTests + ixonUnivTests + ixonExprTests + exprMetaDataTests + exprMetaArenaTests + constantMetaTests + rawEnvTests -- Ixon property tests - recursive & composite types -- (finite enums `DefKind`, `DefinitionSafety`, `QuotKind` are exhaustively unit-tested above) - checkIO "Ixon.Univ roundtrip" (∀ x : Univ, roundtripIxonUniv x == x) .done cfg, - checkIO "Ixon.Expr roundtrip" (∀ x : Expr, roundtripIxonExpr x == x) .done cfg, - checkIO "Ixon.Definition roundtrip" (∀ x : Definition, roundtripIxonDefinition x == x) .done cfg, - checkIO "Ixon.RecursorRule roundtrip" (∀ x : RecursorRule, roundtripIxonRecursorRule x == x) .done cfg, - checkIO "Ixon.Recursor roundtrip" (∀ x : Recursor, roundtripIxonRecursor x == x) .done cfg, - checkIO "Ixon.Axiom roundtrip" (∀ x : Axiom, roundtripIxonAxiom x == x) .done cfg, - checkIO "Ixon.Quotient roundtrip" (∀ x : Quotient, roundtripIxonQuotient x == x) .done cfg, - checkIO "Ixon.Constructor roundtrip" (∀ x : Constructor, roundtripIxonConstructor x == x) .done cfg, - checkIO "Ixon.Inductive roundtrip" (∀ x : Inductive, roundtripIxonInductive x == x) .done cfg, - checkIO "Ixon.InductiveProj roundtrip" (∀ x : InductiveProj, roundtripIxonInductiveProj x == x) .done cfg, - checkIO "Ixon.ConstructorProj roundtrip" (∀ x : ConstructorProj, roundtripIxonConstructorProj x == x) .done cfg, - checkIO "Ixon.RecursorProj roundtrip" (∀ x : RecursorProj, roundtripIxonRecursorProj x == x) .done cfg, - checkIO "Ixon.DefinitionProj roundtrip" (∀ x : DefinitionProj, roundtripIxonDefinitionProj x == x) .done cfg, - checkIO "Ixon.MutConst roundtrip" (∀ x : MutConst, roundtripIxonMutConst x == x) .done cfg, - checkIO "Ixon.ConstantInfo roundtrip" (∀ x : ConstantInfo, roundtripIxonConstantInfo x == x) .done cfg, - checkIO "Ixon.Constant roundtrip" (∀ x : Constant, roundtripIxonConstant x == x) .done cfg, - checkIO "Ixon.DataValue roundtrip" (∀ x : DataValue, roundtripIxonDataValue x == x) .done cfg, - checkIO "Ixon.Comm roundtrip" (∀ x : Comm, roundtripIxonComm x == x) .done cfg, + propWith "Ixon.Univ roundtrip" cfg fun (x : Univ) => roundtripIxonUniv x == x + propWith "Ixon.Expr roundtrip" cfg fun (x : Expr) => roundtripIxonExpr x == x + propWith "Ixon.Definition roundtrip" cfg fun (x : Definition) => roundtripIxonDefinition x == x + propWith "Ixon.RecursorRule roundtrip" cfg fun (x : RecursorRule) => roundtripIxonRecursorRule x == x + propWith "Ixon.Recursor roundtrip" cfg fun (x : Recursor) => roundtripIxonRecursor x == x + propWith "Ixon.Axiom roundtrip" cfg fun (x : Axiom) => roundtripIxonAxiom x == x + propWith "Ixon.Quotient roundtrip" cfg fun (x : Quotient) => roundtripIxonQuotient x == x + propWith "Ixon.Constructor roundtrip" cfg fun (x : Constructor) => roundtripIxonConstructor x == x + propWith "Ixon.Inductive roundtrip" cfg fun (x : Inductive) => roundtripIxonInductive x == x + propWith "Ixon.InductiveProj roundtrip" cfg fun (x : InductiveProj) => roundtripIxonInductiveProj x == x + propWith "Ixon.ConstructorProj roundtrip" cfg fun (x : ConstructorProj) => roundtripIxonConstructorProj x == x + propWith "Ixon.RecursorProj roundtrip" cfg fun (x : RecursorProj) => roundtripIxonRecursorProj x == x + propWith "Ixon.DefinitionProj roundtrip" cfg fun (x : DefinitionProj) => roundtripIxonDefinitionProj x == x + propWith "Ixon.MutConst roundtrip" cfg fun (x : MutConst) => roundtripIxonMutConst x == x + propWith "Ixon.ConstantInfo roundtrip" cfg fun (x : ConstantInfo) => roundtripIxonConstantInfo x == x + propWith "Ixon.Constant roundtrip" cfg fun (x : Constant) => roundtripIxonConstant x == x + propWith "Ixon.DataValue roundtrip" cfg fun (x : DataValue) => roundtripIxonDataValue x == x + propWith "Ixon.Comm roundtrip" cfg fun (x : Comm) => roundtripIxonComm x == x -- Metadata types (arena-based) - checkIO "Ixon.ExprMetaData roundtrip" (∀ x : ExprMetaData, roundtripIxonExprMetaData x == x) .done cfg, - checkIO "Ixon.ConstantMeta roundtrip" (∀ x : ConstantMeta, roundtripIxonConstantMeta x == x) .done cfg, - checkIO "Ixon.Named roundtrip" (∀ x : Named, roundtripIxonNamed x == x) .done cfg, + propWith "Ixon.ExprMetaData roundtrip" cfg fun (x : ExprMetaData) => roundtripIxonExprMetaData x == x + propWith "Ixon.ConstantMeta roundtrip" cfg fun (x : ConstantMeta) => roundtripIxonConstantMeta x == x + propWith "Ixon.Named roundtrip" cfg fun (x : Named) => roundtripIxonNamed x == x ---- RawEnv roundtrip - checkIO "Ixon.RawEnv roundtrip" (∀ env : RawEnv, rawEnvEq (roundtripRawEnv env) env) .done cfg, + propWith "Ixon.RawEnv roundtrip" cfg fun (env : RawEnv) => rawEnvEq (roundtripRawEnv env) env ---- Env diff - envDiffTests, - checkIO "Ixon.EnvDiff self-diff empty (anon)" - (∀ env : RawEnv, selfDiffEmpty false env) .done cfg, - checkIO "Ixon.EnvDiff self-diff empty (meta)" - (∀ env : RawEnv, selfDiffEmpty true env) .done cfg, + envDiffTests + propWith "Ixon.EnvDiff self-diff empty (anon)" cfg fun (env : RawEnv) => + selfDiffEmpty false env + propWith "Ixon.EnvDiff self-diff empty (meta)" cfg fun (env : RawEnv) => + selfDiffEmpty true env ---- Env pack - envPackTests, -] + envPackTests -def suite : List TestSeq := suiteWith {} +def suite : Spec := suiteWith {} end Tests.FFI.Ixon diff --git a/Tests/FFI/Lifecycle.lean b/Tests/FFI/Lifecycle.lean index d7b124138e..a2b50a27f2 100644 --- a/Tests/FFI/Lifecycle.lean +++ b/Tests/FFI/Lifecycle.lean @@ -12,7 +12,7 @@ public import Ix.Ixon public import Tests.Gen.Ixon public import Tests.FFI.Ixon -open LSpec SlimCheck Gen Ixon +open LSpec LSpec.Prop Gen Ixon open Tests.Gen.Ixon open Tests.FFI.Ixon (rawEnvEq) @@ -21,121 +21,114 @@ namespace Tests.FFI.Lifecycle /-! ## Keccak external object lifecycle tests -/ /-- Basic hash lifecycle: init → update → finalize -/ -def keccakBasicTests : TestSeq := +def keccakBasicTests : LSpec.Spec := do -- Known test vector: SHA3-256 of [0] let input : ByteArray := ⟨#[0]⟩ let expected : ByteArray := ⟨#[ 188, 54, 120, 158, 122, 30, 40, 20, 54, 70, 66, 41, 130, 143, 129, 125, 102, 18, 247, 180, 119, 214, 101, 145, 255, 150, 169, 224, 100, 188, 201, 138 ]⟩ - let result := Keccak.hash input - test "Keccak basic hash [0]" (result == expected) ++ + itBool "Keccak basic hash [0]" (Keccak.hash input == expected) -- Empty input - let emptyResult := Keccak.hash ByteArray.empty - test "Keccak empty input produces 32 bytes" (emptyResult.size == 32) ++ + itBool "Keccak empty input produces 32 bytes" ((Keccak.hash ByteArray.empty).size == 32) -- Determinism: same input twice - let result2 := Keccak.hash input - test "Keccak deterministic" (result == result2) + itBool "Keccak deterministic" (Keccak.hash input == Keccak.hash input) /-- Multi-update lifecycle: init → update × N → finalize Creates N+1 external Hasher objects, exercising the destructor path. -/ -def keccakMultiUpdateTests : TestSeq := +def keccakMultiUpdateTests : LSpec.Spec := do -- Multi-update should produce same result as single update of concatenated input let chunk1 : ByteArray := ⟨#[1, 2, 3]⟩ let chunk2 : ByteArray := ⟨#[4, 5, 6]⟩ let chunk3 : ByteArray := ⟨#[7, 8, 9]⟩ let combined : ByteArray := ⟨#[1, 2, 3, 4, 5, 6, 7, 8, 9]⟩ - let singleHash := Keccak.hash combined - let multiHash := - let h := Keccak.Hasher.init () - let h := h.update chunk1 - let h := h.update chunk2 - let h := h.update chunk3 - h.finalize - test "Keccak multi-update == single" (singleHash == multiHash) ++ + itBool "Keccak multi-update == single" ( + let singleHash := Keccak.hash combined + let multiHash := + let h := Keccak.Hasher.init () + let h := h.update chunk1 + let h := h.update chunk2 + let h := h.update chunk3 + h.finalize + singleHash == multiHash) -- Many updates to stress the external object destructor - let manyHash := Id.run do - let mut h := Keccak.Hasher.init () - for i in [:20] do - h := h.update ⟨#[i.toUInt8]⟩ - return h.finalize - test "Keccak 20 updates produces 32 bytes" (manyHash.size == 32) + itBool "Keccak 20 updates produces 32 bytes" ( + let manyHash := Id.run do + let mut h := Keccak.Hasher.init () + for i in [:20] do + h := h.update ⟨#[i.toUInt8]⟩ + return h.finalize + manyHash.size == 32) /-- Large input to exercise large ByteArray across FFI boundary -/ -def keccakLargeInputTests : TestSeq := +def keccakLargeInputTests : LSpec.Spec := do let large : ByteArray := ⟨Array.range 4096 |>.map Nat.toUInt8⟩ - let result := Keccak.hash large - test "Keccak large input (4096 bytes)" (result.size == 32) ++ + itBool "Keccak large input (4096 bytes)" ((Keccak.hash large).size == 32) -- Verify determinism on large input - let result2 := Keccak.hash large - test "Keccak large input deterministic" (result == result2) + itBool "Keccak large input deterministic" (Keccak.hash large == Keccak.hash large) /-! ## Blake3 external object lifecycle tests -/ /-- Basic hash lifecycle against the official BLAKE3 empty-input test vector. -/ -def blake3BasicTests : TestSeq := +def blake3BasicTests : LSpec.Spec := do -- Official BLAKE3 vector: blake3("") = af1349b9f5f9a1a6…cae41f3262. let expected : ByteArray := ⟨#[ 175, 19, 73, 185, 245, 249, 161, 166, 160, 64, 77, 234, 54, 220, 201, 73, 155, 203, 37, 201, 173, 193, 18, 183, 204, 154, 147, 202, 228, 31, 50, 98 ]⟩ - let emptyResult := (Blake3.Rust.hash ByteArray.empty).val - test "Blake3 empty matches official vector" (emptyResult == expected) ++ - test "Blake3 empty produces 32 bytes" (emptyResult.size == 32) ++ + itBool "Blake3 empty matches official vector" ((Blake3.Rust.hash ByteArray.empty).val == expected) + itBool "Blake3 empty produces 32 bytes" ((Blake3.Rust.hash ByteArray.empty).val.size == 32) -- Determinism: same input twice. let input : ByteArray := ⟨#[1, 2, 3]⟩ - test "Blake3 deterministic" ((Blake3.Rust.hash input).val == (Blake3.Rust.hash input).val) + itBool "Blake3 deterministic" ((Blake3.Rust.hash input).val == (Blake3.Rust.hash input).val) /-- Multi-update lifecycle: init → update × N → finalize. Creates N+1 external `Hasher` objects (exercising the destructor path); must equal the one-shot hash. -/ -def blake3MultiUpdateTests : TestSeq := +def blake3MultiUpdateTests : LSpec.Spec := do let combined : ByteArray := ⟨#[1, 2, 3, 4, 5, 6, 7, 8, 9]⟩ - let singleHash := (Blake3.Rust.hash combined).val - let multiHash := Id.run do - let mut h := Blake3.Rust.Hasher.init () - h := h.update ⟨#[1, 2, 3]⟩ - h := h.update ⟨#[4, 5, 6]⟩ - h := h.update ⟨#[7, 8, 9]⟩ - return (h.finalizeWithLength 32).val - test "Blake3 multi-update == single" (singleHash == multiHash) ++ + itBool "Blake3 multi-update == single" ( + let singleHash := (Blake3.Rust.hash combined).val + let multiHash := Id.run do + let mut h := Blake3.Rust.Hasher.init () + h := h.update ⟨#[1, 2, 3]⟩ + h := h.update ⟨#[4, 5, 6]⟩ + h := h.update ⟨#[7, 8, 9]⟩ + return (h.finalizeWithLength 32).val + singleHash == multiHash) -- Many updates to stress the external object destructor. - let manyHash := Id.run do - let mut h := Blake3.Rust.Hasher.init () - for i in [:20] do - h := h.update ⟨#[i.toUInt8]⟩ - return (h.finalizeWithLength 32).val - let manyExpected := (Blake3.Rust.hash ⟨Array.range 20 |>.map Nat.toUInt8⟩).val - test "Blake3 many-update == single" (manyHash == manyExpected) + itBool "Blake3 many-update == single" ( + let manyHash := Id.run do + let mut h := Blake3.Rust.Hasher.init () + for i in [:20] do + h := h.update ⟨#[i.toUInt8]⟩ + return (h.finalizeWithLength 32).val + let manyExpected := (Blake3.Rust.hash ⟨Array.range 20 |>.map Nat.toUInt8⟩).val + manyHash == manyExpected) /-- Large-input determinism, mirroring the Keccak large-input test. -/ -def blake3LargeInputTests : TestSeq := +def blake3LargeInputTests : LSpec.Spec := do let large : ByteArray := ⟨Array.range 4096 |>.map Nat.toUInt8⟩ - let result := (Blake3.Rust.hash large).val - test "Blake3 large input (4096 bytes)" (result.size == 32) ++ - test "Blake3 large input deterministic" (result == (Blake3.Rust.hash large).val) + itBool "Blake3 large input (4096 bytes)" ((Blake3.Rust.hash large).val.size == 32) + itBool "Blake3 large input deterministic" ((Blake3.Rust.hash large).val == (Blake3.Rust.hash large).val) /-! ## SHA256 hashing tests -/ -def sha256Tests : TestSeq := +def sha256Tests : LSpec.Spec := do -- Empty input: SHA-256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 - let emptyHash := Sha256.hash ByteArray.empty let expectedEmpty : ByteArray := ⟨#[ 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 ]⟩ - test "SHA256 empty" (emptyHash == expectedEmpty) ++ + itBool "SHA256 empty" (Sha256.hash ByteArray.empty == expectedEmpty) -- "abc": SHA-256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad - let abcHash := Sha256.hash ⟨#[0x61, 0x62, 0x63]⟩ let expectedAbc : ByteArray := ⟨#[ 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad ]⟩ - test "SHA256 abc" (abcHash == expectedAbc) ++ + itBool "SHA256 abc" (Sha256.hash ⟨#[0x61, 0x62, 0x63]⟩ == expectedAbc) -- Determinism: hash same input twice - let hash1 := Sha256.hash ⟨#[1, 2, 3]⟩ - let hash2 := Sha256.hash ⟨#[1, 2, 3]⟩ - test "SHA256 deterministic" (hash1 == hash2) ++ - test "SHA256 produces 32 bytes" (hash1.size == 32) + itBool "SHA256 deterministic" (Sha256.hash ⟨#[1, 2, 3]⟩ == Sha256.hash ⟨#[1, 2, 3]⟩) + itBool "SHA256 produces 32 bytes" ((Sha256.hash ⟨#[1, 2, 3]⟩).size == 32) /-! ## Ixon serialization roundtrip tests (ser_env → de_env) -/ @@ -153,34 +146,15 @@ private def serdeEnvEq (a b : RawEnv) : Bool := rc.const.refs.size == rc'.const.refs.size && rc.const.univs.size == rc'.const.univs.size -/-- Wrap a pure computation in an IO action that only executes when the - IO value is run — not when it is constructed. Lean normally evaluates - pure `let` bindings strictly even inside `do` blocks, so `rsSerEnvFFI` - would otherwise fire at `TestSeq` construction time. Placing the - computation inside `fun s => ...` puts it under a lambda, which Lean - does not evaluate until the outer closure is applied — i.e., until the - IO action actually runs. See `EST.pure`/`EST.bind` in - `refs/lean4/src/Init/System/ST.lean`; this is hand-rolled `pure` that - cannot accidentally beta-reduce eagerly. -/ -@[inline] private def deferIO (f : Unit → α) : IO α := fun s => - EST.Out.ok (f ()) s - /-- Build a single serde roundtrip test that defers all FFI calls to - execution time. Constructing the returned `TestSeq` does no FFI work — - the `rsSerEnvFFI` / `rsDeEnvFFI` pair fires only when LSpec actually - runs the test. -/ -private def mkSerdeRoundtripTest (descr : String) (env : RawEnv) : TestSeq := - .individualIO descr none (deferIO fun () => - match rsSerEnvFFI env >>= rsDeEnvFFI with - | .ok decoded => - let ok := serdeEnvEq decoded env - (ok, 0, 0, if ok then none else some "mismatch") - | .error e => - (false, 0, 0, some s!"serialization/deserialization failed: {e}")) .done + execution time via `it`. -/ +private def mkSerdeRoundtripTest (descr : String) (env : RawEnv) : Spec := + it descr do + let decoded ← expectOk (rsSerEnvFFI env >>= rsDeEnvFFI) + expect (serdeEnvEq decoded env) "mismatch" -def serdeTests : TestSeq := - -- Empty RawEnv. Only data construction happens eagerly; FFI is deferred - -- inside `mkSerdeRoundtripTest`. +def serdeTests : LSpec.Spec := do + -- Empty RawEnv. FFI is deferred inside `mkSerdeRoundtripTest`. let empty : RawEnv := { consts := #[], named := #[], blobs := #[], comms := #[] } -- RawEnv with data. Consts AND blobs must be content-addressed — the -- Rust loader verifies `Address::hash(bytes) == addr` per entry for @@ -215,7 +189,7 @@ def serdeTests : TestSeq := comms := #[testRawComm], names := #[testNameEntry, testConstNameEntry] } - mkSerdeRoundtripTest "serde empty RawEnv" empty ++ + mkSerdeRoundtripTest "serde empty RawEnv" empty mkSerdeRoundtripTest "serde RawEnv with data" withData /-- Generate a ConstantInfo without embedded Address fields. @@ -234,19 +208,19 @@ private def genSimpleConstantInfo : Gen ConstantInfo := name table; random RawEnvs almost always violate this. -/ private def genSerdeRawEnv : Gen RawEnv := do -- Build a pool of (address, name) pairs; all addresses used below come from here - let poolSize ← Gen.choose Nat 2 8 + let poolSize ← Gen.chooseNat 2 8 let mut pool : Array (Address × Ix.Name) := #[] for i in [:poolSize] do let addr ← genAddress pool := pool.push (addr, Ix.Name.mkNat Ix.Name.mkAnon i) let pickAddr : Gen Address := do - let idx ← Gen.choose Nat 0 (pool.size - 1) + let idx ← Gen.chooseNat 0 (pool.size - 1) pure pool[idx]!.1 -- Consts: derive addr from content (`Env::get` verifies -- `Address::hash(bytes) == addr` on load). Each canonical address -- gets its own name entry appended to the names table so the serde -- pipeline can resolve it. - let numConsts ← Gen.choose Nat 0 3 + let numConsts ← Gen.chooseNat 0 3 let mut consts : Array RawConst := #[] let mut constNames : Array RawNameEntry := #[] for i in [:numConsts] do @@ -262,23 +236,23 @@ private def genSerdeRawEnv : Gen RawEnv := do -- Named: pool names over stored const addresses with empty metadata — -- §5 keys each entry's constant by §2 rank, so the writers reject -- named entries referencing anything outside `consts`. - let numNamed ← Gen.choose Nat 0 3 + let numNamed ← Gen.chooseNat 0 3 let mut named : Array RawNamed := #[] if consts.size > 0 then for _ in [:numNamed] do - let idx ← Gen.choose Nat 0 (pool.size - 1) + let idx ← Gen.chooseNat 0 (pool.size - 1) let (_, name) := pool[idx]! - let cidx ← Gen.choose Nat 0 (consts.size - 1) + let cidx ← Gen.chooseNat 0 (consts.size - 1) named := named.push { name, addr := (consts[cidx]!).addr, constMeta := .empty } -- Blobs: content-addressed (the loaders verify blake3(bytes) == addr) - let numBlobs ← Gen.choose Nat 0 3 + let numBlobs ← Gen.chooseNat 0 3 let mut blobs : Array RawBlob := #[] for _ in [:numBlobs] do let bytes ← Tests.Gen.Ixon.genByteArray blobs := blobs.push { addr := Address.blake3 bytes, bytes } -- Comms: pool addresses - let numComms ← Gen.choose Nat 0 2 + let numComms ← Gen.chooseNat 0 2 let mut comms : Array RawComm := #[] for _ in [:numComms] do let addr ← pickAddr @@ -296,7 +270,7 @@ private def genSerdeRawEnv : Gen RawEnv := do if acc.any (·.addr == x.addr) then acc else acc.push x pure { consts := consts', named := named', blobs := blobs', comms := comms', names } -/-- Wrapper so we can give well-formed RawEnvs their own SampleableExt instance. -/ +/-- Wrapper so we can give well-formed RawEnvs their own Sampleable instance. -/ private structure serdeRawEnv where env : RawEnv @@ -306,8 +280,8 @@ private instance : Repr serdeRawEnv where private instance : Shrinkable serdeRawEnv where shrink _ := [] -private instance : SampleableExt serdeRawEnv := - SampleableExt.mkSelfContained (serdeRawEnv.mk <$> genSerdeRawEnv) +private instance : Sampleable serdeRawEnv := + ⟨serdeRawEnv.mk <$> genSerdeRawEnv⟩ /-- Check that serialize → deserialize roundtrips for a well-formed RawEnv. -/ def serdeRoundtripOk (env : RawEnv) : Bool := @@ -315,24 +289,25 @@ def serdeRoundtripOk (env : RawEnv) : Bool := | .ok decoded => serdeEnvEq decoded env | .error _ => false +set_option compiler.extract_closed false in /-- Property test: random well-formed RawEnv → serialize → deserialize → compare -/ -def serdePropertyTest (cfg : SlimCheck.Configuration := {}) : TestSeq := - checkIO "serde RawEnv roundtrip" (∀ e : serdeRawEnv, serdeRoundtripOk e.env) .done cfg +def serdePropertyTest (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := + propWith "serde RawEnv roundtrip" cfg fun (e : serdeRawEnv) => serdeRoundtripOk e.env /-! ## Test Suite -/ -public def suiteWith (cfg : SlimCheck.Configuration := {}) : List TestSeq := [ - keccakBasicTests, - keccakMultiUpdateTests, - keccakLargeInputTests, - blake3BasicTests, - blake3MultiUpdateTests, - blake3LargeInputTests, - sha256Tests, - serdeTests, - serdePropertyTest cfg, -] +set_option compiler.extract_closed false in +public def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := do + keccakBasicTests + keccakMultiUpdateTests + keccakLargeInputTests + blake3BasicTests + blake3MultiUpdateTests + blake3LargeInputTests + sha256Tests + serdeTests + serdePropertyTest cfg -public def suite : List TestSeq := suiteWith {} +public def suite : Spec := suiteWith {} end Tests.FFI.Lifecycle diff --git a/Tests/FFI/Refcount.lean b/Tests/FFI/Refcount.lean index 256a3ecd3c..f5fd4ff10b 100644 --- a/Tests/FFI/Refcount.lean +++ b/Tests/FFI/Refcount.lean @@ -22,7 +22,7 @@ public import Tests.Gen.Ix public import Ix.Environment public import Ix.Address -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen open Tests.Gen.Ix namespace Tests.FFI.Refcount @@ -88,123 +88,125 @@ private def persistentName : Ix.Name := Ix.Name.mkStr Ix.Name.mkAnon "persistent Verifies that to_owned_ref (lean_inc) produces a valid owned handle. A refcount bug here would manifest as use-after-free or double-free. -/ -def borrowToOwnedTests : TestSeq := - test "borrow→owned Name anonymous" (borrowToOwnedName testAnon == testAnon) ++ - test "borrow→owned Name str" (borrowToOwnedName testStr == testStr) ++ - test "borrow→owned Name num" (borrowToOwnedName testNum == testNum) +def borrowToOwnedTests : LSpec.Spec := do + itBool "borrow→owned Name anonymous" (borrowToOwnedName testAnon == testAnon) + itBool "borrow→owned Name str" (borrowToOwnedName testStr == testStr) + itBool "borrow→owned Name num" (borrowToOwnedName testNum == testNum) /-! ## Multiple borrows from same object Verifies that reading fields multiple times from the same borrowed ctor doesn't corrupt data (no dangling pointer from intermediate borrow). -/ -def multiBorrowTests : TestSeq := +def multiBorrowTests : LSpec.Spec := do let name := Ix.Name.mkStr Ix.Name.mkAnon "hello" - test "multi-borrow Name str" (multiBorrowName name == "hello|hello") + itBool "multi-borrow Name str" (multiBorrowName name == "hello|hello") /-! ## Owned drop tests Passes owned (NOT @&) arrays. Rust drops each element on scope exit. A missing drop leaks; an extra drop crashes. -/ -def ownedDropTests : TestSeq := +def ownedDropTests : LSpec.Spec := do let names := #[testAnon, testStr, testNum] - test "owned array drop 3 names" (ownedArrayDrop names == 3) ++ - test "owned array drop empty" (ownedArrayDrop #[] == 0) + itBool "owned array drop 3 names" (ownedArrayDrop names == 3) + itBool "owned array drop empty" (ownedArrayDrop #[] == 0) /-! ## Clone tests Makes two owned clones of a borrowed Name, decodes both. After decode, both clones are dropped → two lean_dec_ref calls. Would double-free if clone didn't lean_inc. -/ -def cloneTests : TestSeq := - test "clone anonymous" (cloneAndCompare testAnon == 1) ++ - test "clone str name" (cloneAndCompare testStr == 1) ++ - test "clone num name" (cloneAndCompare testNum == 1) +def cloneTests : LSpec.Spec := do + itBool "clone anonymous" (cloneAndCompare testAnon == 1) + itBool "clone str name" (cloneAndCompare testStr == 1) + itBool "clone num name" (cloneAndCompare testNum == 1) /-! ## Roundtrip loop tests Each iteration: decode borrowed → build new owned → drop old → repeat. Stresses N alloc/dealloc cycles. Would crash on any refcount error. -/ -def roundtripLoopTests : TestSeq := - test "roundtrip loop 1x" (roundtripLoop testStr 1 == testStr) ++ - test "roundtrip loop 5x" (roundtripLoop testStr 5 == testStr) ++ - test "roundtrip loop 20x" (roundtripLoop testStr 20 == testStr) ++ - test "roundtrip loop anon 10x" (roundtripLoop testAnon 10 == testAnon) ++ - test "roundtrip loop num 10x" (roundtripLoop testNum 10 == testNum) +def roundtripLoopTests : LSpec.Spec := do + itBool "roundtrip loop 1x" (roundtripLoop testStr 1 == testStr) + itBool "roundtrip loop 5x" (roundtripLoop testStr 5 == testStr) + itBool "roundtrip loop 20x" (roundtripLoop testStr 20 == testStr) + itBool "roundtrip loop anon 10x" (roundtripLoop testAnon 10 == testAnon) + itBool "roundtrip loop num 10x" (roundtripLoop testNum 10 == testNum) /-! ## Persistent object tests Module-level defs have m_rc == 0. Refcount ops are no-ops. Verifies that the typed API handles these correctly. -/ -def persistentTests : TestSeq := - test "persistent name is_persistent" (isPersistent persistentName == 1) ++ - test "persistent roundtrip" (persistentRoundtrip persistentName == persistentName) +def persistentTests : LSpec.Spec := do + itBool "persistent name is_persistent" (isPersistent persistentName == 1) + itBool "persistent roundtrip" (persistentRoundtrip persistentName == persistentName) /-! ## Cache dedup tests Builds N copies of the same Name via LeanBuildCache, which clones cached entries (incrementing refcount). Dropping the array decrements each copy. Would crash if clone refcount was wrong. -/ -def cacheDedupTests : TestSeq := - let duped := cacheDedup testStr 5 - test "cache dedup size 5" (duped.size == 5) ++ - test "cache dedup all equal" (duped.all (· == testStr)) ++ - let duped20 := cacheDedup testNum 20 - test "cache dedup size 20" (duped20.size == 20 && duped20.all (· == testNum)) +def cacheDedupTests : LSpec.Spec := do + itBool "cache dedup size 5" ((cacheDedup testStr 5).size == 5) + itBool "cache dedup all equal" ((cacheDedup testStr 5).all (· == testStr)) + itBool "cache dedup size 20" ( + let duped20 := cacheDedup testNum 20 + duped20.size == 20 && duped20.all (· == testNum)) /-! ## String lifecycle tests -/ -def stringTests : TestSeq := - test "string lifecycle" (stringLifecycle "hello" == "olleh") ++ - test "string lifecycle empty" (stringLifecycle "" == "") ++ - test "string lifecycle unicode" (stringLifecycle "café" == "éfac") +def stringTests : LSpec.Spec := do + itBool "string lifecycle" (stringLifecycle "hello" == "olleh") + itBool "string lifecycle empty" (stringLifecycle "" == "") + itBool "string lifecycle unicode" (stringLifecycle "café" == "éfac") /-! ## Alloc/drop stress tests Builds and immediately drops N Lean objects in a loop. Under `IX_VALGRIND=1`, cap at 100x to skip the redundant 1000x loop. -/ -def allocDropTests (valgrind : Bool := false) : TestSeq := - let base := test "alloc/drop 100x" (allocDropLoop testStr 100 == testStr) - if valgrind then base - else base ++ test "alloc/drop 1000x" (allocDropLoop testNum 1000 == testNum) +set_option compiler.extract_closed false in +def allocDropTests (valgrind : Bool := false) : Spec := do + itBool "alloc/drop 100x" (allocDropLoop testStr 100 == testStr) + unless valgrind do + itBool "alloc/drop 1000x" (allocDropLoop testNum 1000 == testNum) /-! ## Multi-threaded LeanShared tests These exercise lean_mark_mt + atomic refcounting on ix domain types across real OS threads. A refcount bug would cause SIGSEGV or assertion failure. -/ -def mtTests : TestSeq := +def mtTests : LSpec.Spec := do let names := #[testAnon, testStr, testNum] -- Parallel decode: N threads × 3 names each - test "MT parallel decode names 4 threads" (mtParallelDecodeNames names 4 == 12) ++ - test "MT parallel decode names 1 thread" (mtParallelDecodeNames names 1 == 3) ++ - test "MT parallel decode names empty" (mtParallelDecodeNames #[] 4 == 0) ++ + itBool "MT parallel decode names 4 threads" (mtParallelDecodeNames names 4 == 12) + itBool "MT parallel decode names 1 thread" (mtParallelDecodeNames names 1 == 3) + itBool "MT parallel decode names empty" (mtParallelDecodeNames #[] 4 == 0) -- Parallel roundtrip: decode and rebuild from multiple threads - test "MT parallel roundtrip names" (mtParallelRoundtripNames names 4 == names) ++ - test "MT parallel roundtrip empty" (mtParallelRoundtripNames #[] 4 == #[]) + itBool "MT parallel roundtrip names" (mtParallelRoundtripNames names 4 == names) + itBool "MT parallel roundtrip empty" (mtParallelRoundtripNames #[] 4 == #[]) /-! ## Property tests -/ -def propertyTests (cfg : SlimCheck.Configuration := {}) : TestSeq := - checkIO "borrow→owned Name" (∀ n : Ix.Name, borrowToOwnedName n == n) .done cfg ++ - checkIO "clone always equal" (∀ n : Ix.Name, cloneAndCompare n == 1) .done cfg ++ - checkIO "roundtrip loop 3x" (∀ n : Ix.Name, roundtripLoop n 3 == n) .done cfg +set_option compiler.extract_closed false in +def propertyTests (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := do + propWith "borrow→owned Name" cfg fun (n : Ix.Name) => borrowToOwnedName n == n + propWith "clone always equal" cfg fun (n : Ix.Name) => cloneAndCompare n == 1 + propWith "roundtrip loop 3x" cfg fun (n : Ix.Name) => roundtripLoop n 3 == n /-! ## Test Suite -/ -public def suiteWith (cfg : SlimCheck.Configuration := {}) (valgrind : Bool := false) : - List TestSeq := [ - borrowToOwnedTests, - multiBorrowTests, - ownedDropTests, - cloneTests, - roundtripLoopTests, - persistentTests, - cacheDedupTests, - stringTests, - allocDropTests valgrind, - mtTests, - propertyTests cfg, -] - -public def suite : List TestSeq := suiteWith {} false +set_option compiler.extract_closed false in +public def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) (valgrind : Bool := false) : + Spec := do + borrowToOwnedTests + multiBorrowTests + ownedDropTests + cloneTests + roundtripLoopTests + persistentTests + cacheDedupTests + stringTests + allocDropTests valgrind + mtTests + propertyTests cfg + +public def suite : Spec := suiteWith {} false end Tests.FFI.Refcount diff --git a/Tests/FFIMain.lean b/Tests/FFIMain.lean index 160d3a662b..d6ce59a797 100644 --- a/Tests/FFIMain.lean +++ b/Tests/FFIMain.lean @@ -7,7 +7,7 @@ the merge queue's Valgrind job builds and runs the Rust FFI boundary without the rest of `IxTests`, whose import closure holds the certification's proofs. -/ -def main (_args : List String) : IO UInt32 := do +def main (args : List String) : IO UInt32 := do let valgrind := (← IO.getEnv "IX_VALGRIND") == some "1" - let cfg : SlimCheck.Configuration := if valgrind then { numInst := 8 } else {} - LSpec.lspecIO (.ofList [("ffi", Tests.FFI.suiteWith cfg valgrind)]) [] + let cfg : LSpec.Prop.PropertyConfig := if valgrind then { numTests := 8 } else {} + LSpec.lspecMain (LSpec.describe "ffi" (Tests.FFI.suiteWith cfg valgrind)) args diff --git a/Tests/FormalPackageMain.lean b/Tests/FormalPackageMain.lean index 933826105d..e43b4f8d5b 100644 --- a/Tests/FormalPackageMain.lean +++ b/Tests/FormalPackageMain.lean @@ -21,8 +21,8 @@ private def runNamed (getEnv : IO Lean.Environment) (name : String) : IO UInt32 | "instance-symbols" => Tests.Ix.InstanceSymbols.run | "ixvm-source" => do Tests.Ix.VMSource.run (← getEnv) | "multistark-verifier" => do - let ts ← Tests.Ix.MultiStarkVerifier.suite - LSpec.lspecIO (.ofList [("multistark-verifier", ts)]) [] + let spec ← Tests.Ix.MultiStarkVerifier.suite + LSpec.lspecMain (LSpec.describe "multistark-verifier" spec) [] | "ixvm-export-safe-walk" => Tests.Ix.IxVM.SafeReferencesWalk.exportWalkArtifact | other => IO.eprintln s!"[formal-package-tests] unknown entry: {other}" diff --git a/Tests/Gen/Basic.lean b/Tests/Gen/Basic.lean index cc078b043d..75ff8885f9 100644 --- a/Tests/Gen/Basic.lean +++ b/Tests/Gen/Basic.lean @@ -9,64 +9,58 @@ public import Std.Data.HashMap public section -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen /-! ## Helper combinators -/ def genUInt8 : Gen UInt8 := - UInt8.ofNat <$> choose Nat 0 0xFF + Gen.chooseUInt8 def genUInt32 : Gen UInt32 := - UInt32.ofNat <$> choose Nat 0 0xFFFFFFFF + Gen.chooseUInt32 def genUInt64 : Gen UInt64 := - UInt64.ofNat <$> choose Nat 0 0xFFFFFFFFFFFFFFFF + Gen.chooseUInt64 def genUSize : Gen USize := - .ofNat <$> choose Nat 0 (2^System.Platform.numBits - 1) + .ofNat <$> Gen.chooseNat 0 (2^System.Platform.numBits - 1) -def frequency' (default: Gen α) (xs: List (Nat × Gen α)) : Gen α := do - let n ← choose Nat 0 total - pick n xs - where - total := List.sum (Prod.fst <$> xs) - pick n xs := match xs with - | [] => default - | (k, x) :: xs => if n <= k then x else pick (n - k) xs +def frequency' (default : Gen α) (xs : List (Nat × Gen α)) : Gen α := + Gen.frequency xs.toArray default -def frequency [Inhabited α] (xs: List (Nat × Gen α)) : Gen α := - frequency' xs.head!.snd xs +def frequency [Inhabited α] (xs : List (Nat × Gen α)) : Gen α := + Gen.frequency xs.toArray (pure default) -def oneOf' [Inhabited α] (xs: List (Gen α)) : Gen α := - frequency (xs.map (fun x => (100, x))) +def oneOf' [Inhabited α] (xs : List (Gen α)) : Gen α := + Gen.oneOf! xs.toArray /-! ## Basic type generators -/ /-- Generate Nats across the full range: small, medium, large, and huge -/ def genNat : Gen Nat := do - let choice ← choose Nat 0 100 + let choice ← Gen.chooseNat 0 100 if choice < 50 then -- 50%: small nats (0-1000) - choose Nat 0 1000 + Gen.chooseNat 0 1000 else if choice < 75 then -- 25%: medium nats (up to 2^32) - choose Nat 0 (2^32) + Gen.chooseNat 0 (2^32) else if choice < 90 then -- 15%: large nats (up to 2^64) - choose Nat 0 (2^64) + Gen.chooseNat 0 (2^64) else -- 10%: huge nats (up to 2^256) - choose Nat 0 (2^256) + Gen.chooseNat 0 (2^256) -def genSmallNat : Gen Nat := choose Nat 0 1000 +def genSmallNat : Gen Nat := Gen.chooseNat 0 1000 def genString : Gen String := do - let len ← choose Nat 0 100 - let chars ← Gen.listOf (choose Nat 32 126 >>= fun n => pure (Char.ofNat n)) + let len ← Gen.chooseNat 0 100 + let chars ← Gen.listOf (Gen.chooseNat 32 126 >>= fun n => pure (Char.ofNat n)) pure (String.ofList (chars.take len)) def genListNat : Gen (List Nat) := do - let len ← choose Nat 0 20 + let len ← Gen.chooseNat 0 20 let mut result := [] for _ in [:len] do result := (← genSmallNat) :: result @@ -77,17 +71,17 @@ def genArrayNat : Gen (Array Nat) := do pure list.toArray def genByteArray : Gen ByteArray := do - let len ← choose Nat 0 100 + let len ← Gen.chooseNat 0 100 let mut bytes := ByteArray.emptyWithCapacity len for _ in [:len] do - let b ← choose Nat 0 255 + let b ← Gen.chooseNat 0 255 bytes := bytes.push b.toUInt8 pure bytes -def genBool : Gen Bool := choose Bool .false true +def genBool : Gen Bool := Gen.bool def genHashMapNatNat : Gen (Std.HashMap Nat Nat) := do - let len ← choose Nat 0 20 + let len ← Gen.chooseNat 0 20 let mut map : Std.HashMap Nat Nat := {} for _ in [:len] do let k ← genSmallNat @@ -95,27 +89,13 @@ def genHashMapNatNat : Gen (Std.HashMap Nat Nat) := do map := map.insert k v pure map -/-! ## Shrinkable instances -/ - -instance : Shrinkable Nat where - shrink n := if n == 0 then [] else [n / 2] - -instance : Shrinkable (List Nat) where - shrink xs := match xs with - | [] => [] - | _ :: tail => [tail] - -instance : Shrinkable (Array Nat) where - shrink arr := if arr.isEmpty then [] else [arr.pop] +/-! ## FormatValue / Shrinkable / Sampleable instances -/ instance : Repr ByteArray where reprPrec ba _ := s!"ByteArray#{ba.toList}" -instance : Shrinkable ByteArray where - shrink ba := if ba.isEmpty then [] else [ba.extract 0 (ba.size - 1)] - -instance : Shrinkable String where - shrink s := if s.isEmpty then [] else [s.dropEnd 1 |>.toString] +instance : FormatValue (Std.HashMap Nat Nat) where + formatValue m := reprStr m.toList instance : Shrinkable (Std.HashMap Nat Nat) where shrink m := @@ -124,18 +104,6 @@ instance : Shrinkable (Std.HashMap Nat Nat) where | [] => [] | _ :: tail => [Std.HashMap.ofList tail] -/-! ## SampleableExt instances -/ - -instance : SampleableExt Nat := SampleableExt.mkSelfContained genNat - -instance : SampleableExt (List Nat) := SampleableExt.mkSelfContained genListNat - -instance : SampleableExt (Array Nat) := SampleableExt.mkSelfContained genArrayNat - -instance : SampleableExt ByteArray := SampleableExt.mkSelfContained genByteArray - -instance : SampleableExt String := SampleableExt.mkSelfContained genString - -instance : SampleableExt (Std.HashMap Nat Nat) := SampleableExt.mkSelfContained genHashMapNatNat +instance : Sampleable (Std.HashMap Nat Nat) := ⟨genHashMapNatNat⟩ end diff --git a/Tests/Gen/Claim.lean b/Tests/Gen/Claim.lean index f562a4b47b..c553b141d0 100644 --- a/Tests/Gen/Claim.lean +++ b/Tests/Gen/Claim.lean @@ -9,7 +9,7 @@ public import Ix.Claim public section -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen open Ix (RevealConstructorInfo RevealRecursorRule RevealMutConstInfo RevealConstantInfo CompilePolicy CompileClaim Claim DefKind DefinitionSafety QuotKind) open Tests.Gen.Ixon (genAddress genUInt64Small genDefKind genDefinitionSafety genQuotKindNew @@ -168,13 +168,13 @@ instance : Shrinkable Claim where | .binding _ _ => [] | .compile _ => [] -/-! ## SampleableExt instances -/ +/-! ## Sampleable instances -/ -instance : SampleableExt RevealConstructorInfo := SampleableExt.mkSelfContained genRevealConstructorInfo -instance : SampleableExt RevealRecursorRule := SampleableExt.mkSelfContained genRevealRecursorRule -instance : SampleableExt RevealMutConstInfo := SampleableExt.mkSelfContained genRevealMutConstInfo -instance : SampleableExt RevealConstantInfo := SampleableExt.mkSelfContained genRevealConstantInfo -instance : SampleableExt Claim := SampleableExt.mkSelfContained genClaim +instance : Sampleable RevealConstructorInfo := ⟨genRevealConstructorInfo⟩ +instance : Sampleable RevealRecursorRule := ⟨genRevealRecursorRule⟩ +instance : Sampleable RevealMutConstInfo := ⟨genRevealMutConstInfo⟩ +instance : Sampleable RevealConstantInfo := ⟨genRevealConstantInfo⟩ +instance : Sampleable Claim := ⟨genClaim⟩ end Tests.Gen.Claim diff --git a/Tests/Gen/Ix.lean b/Tests/Gen/Ix.lean index c3fb90bae1..72f7fcf0da 100644 --- a/Tests/Gen/Ix.lean +++ b/Tests/Gen/Ix.lean @@ -14,7 +14,7 @@ public import Ix.CondenseM public section -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen namespace Tests.Gen.Ix @@ -27,13 +27,13 @@ def genIxName : Nat → Gen Ix.Name (1, pure Ix.Name.mkAnon), (4, do let parent ← genIxName fuel - let len ← choose Nat 1 12 - let chars ← Gen.listOf (choose Nat 97 122 >>= fun n => pure (Char.ofNat n)) + let len ← Gen.chooseNat 1 12 + let chars ← Gen.listOf (Gen.chooseNat 97 122 >>= fun n => pure (Char.ofNat n)) let s := String.ofList (chars.take len) pure (Ix.Name.mkStr parent s)), (3, do let parent ← genIxName fuel - let n ← choose Nat 0 1000 + let n ← Gen.chooseNat 0 1000 pure (Ix.Name.mkNat parent n)) ] (pure Ix.Name.mkAnon) @@ -76,27 +76,27 @@ def genBinderInfo : Gen Lean.BinderInfo := /-- Generate a Literal -/ def genLiteral : Gen Lean.Literal := frequency [ - (5, Lean.Literal.natVal <$> choose Nat 0 1000), - (5, Lean.Literal.strVal <$> Gen.elements #["hello", "world", "foo", "bar", "test", "literal"]), + (5, Lean.Literal.natVal <$> Gen.chooseNat 0 1000), + (5, Lean.Literal.strVal <$> Gen.elements! #["hello", "world", "foo", "bar", "test", "literal"]), ] /-- Generate an Ix.Int for DataValue -/ def genIxInt : Gen Ix.Int := frequency [ - (5, Ix.Int.ofNat <$> choose Nat 0 100), - (5, Ix.Int.negSucc <$> choose Nat 0 50), + (5, Ix.Int.ofNat <$> Gen.chooseNat 0 100), + (5, Ix.Int.negSucc <$> Gen.chooseNat 0 50), ] /-- Generate a random string from a list of options -/ def genIxString : Gen String := - Gen.elements #["foo", "bar", "test", "x", "y", "value", "item", "data", "node", "leaf"] + Gen.elements! #["foo", "bar", "test", "x", "y", "value", "item", "data", "node", "leaf"] /-- Generate Ix.Substring -/ def genIxSubstring : Gen Ix.Substring := do - let s ← Gen.elements #["hello world", "test string", "foo bar baz", "quick brown fox", "lorem ipsum"] + let s ← Gen.elements! #["hello world", "test string", "foo bar baz", "quick brown fox", "lorem ipsum"] let maxLen := s.length - let startPos ← choose Nat 0 (maxLen / 2) - let stopPos ← choose Nat startPos maxLen + let startPos ← Gen.chooseNat 0 (maxLen / 2) + let stopPos ← Gen.chooseNat startPos maxLen pure (Ix.Substring.mk s startPos stopPos) instance : Shrinkable Ix.Name where @@ -109,7 +109,7 @@ instance : Shrinkable Ix.Substring where shrink ss := (if ss.str.length > 0 then [{ ss with str := "", startPos := 0, stopPos := 0 }] else []) ++ (if ss.stopPos > ss.startPos then [{ ss with stopPos := ss.startPos }] else []) -instance : SampleableExt Ix.Substring := SampleableExt.mkSelfContained genIxSubstring +instance : Sampleable Ix.Substring := ⟨genIxSubstring⟩ /-- Generate Ix.SourceInfo with all variants -/ def genIxSourceInfo : Gen Ix.SourceInfo := @@ -117,13 +117,13 @@ def genIxSourceInfo : Gen Ix.SourceInfo := (5, pure Ix.SourceInfo.none), (3, do let leading ← genIxSubstring - let leadingPos ← choose Nat 0 100 + let leadingPos ← Gen.chooseNat 0 100 let trailing ← genIxSubstring - let trailingPos ← choose Nat 0 100 + let trailingPos ← Gen.chooseNat 0 100 pure (Ix.SourceInfo.original leading leadingPos trailing trailingPos)), (2, do - let start ← choose Nat 0 100 - let stop ← choose Nat 100 200 + let start ← Gen.chooseNat 0 100 + let stop ← Gen.chooseNat 100 200 let canonical ← frequency [(1, pure true), (1, pure false)] pure (Ix.SourceInfo.synthetic start stop canonical)), ] @@ -133,7 +133,7 @@ instance : Shrinkable Ix.SourceInfo where | .none => [] | _ => [.none] -instance : SampleableExt Ix.SourceInfo := SampleableExt.mkSelfContained genIxSourceInfo +instance : Sampleable Ix.SourceInfo := ⟨genIxSourceInfo⟩ /-- Generate Ix.SyntaxPreresolved with all variants -/ def genIxSyntaxPreresolved : Gen Ix.SyntaxPreresolved := @@ -141,7 +141,7 @@ def genIxSyntaxPreresolved : Gen Ix.SyntaxPreresolved := (1, Ix.SyntaxPreresolved.namespace <$> genIxName 3), (1, do let name ← genIxName 3 - let numAliases ← Gen.choose Nat 0 3 + let numAliases ← Gen.chooseNat 0 3 let mut aliases : Array String := #[] for _ in [:numAliases] do aliases := aliases.push (← genIxString) @@ -155,7 +155,7 @@ instance : Shrinkable Ix.SyntaxPreresolved where [.namespace n] ++ (if aliases.size > 0 then [.decl n aliases.pop] else []) ++ ((.decl · aliases) <$> Shrinkable.shrink n) -instance : SampleableExt Ix.SyntaxPreresolved := SampleableExt.mkSelfContained genIxSyntaxPreresolved +instance : Sampleable Ix.SyntaxPreresolved := ⟨genIxSyntaxPreresolved⟩ /-- Generate Ix.Syntax with all variants including node -/ def genIxSyntaxAux : Nat → Gen Ix.Syntax @@ -166,7 +166,7 @@ def genIxSyntaxAux : Nat → Gen Ix.Syntax let info ← genIxSourceInfo let rawVal ← genIxSubstring let name ← genIxName 2 - let numPreresolved ← Gen.choose Nat 0 2 + let numPreresolved ← Gen.chooseNat 0 2 let mut preresolved : Array Ix.SyntaxPreresolved := #[] for _ in [:numPreresolved] do preresolved := preresolved.push (← genIxSyntaxPreresolved) @@ -179,7 +179,7 @@ def genIxSyntaxAux : Nat → Gen Ix.Syntax let info ← genIxSourceInfo let rawVal ← genIxSubstring let name ← genIxName 2 - let numPreresolved ← Gen.choose Nat 0 2 + let numPreresolved ← Gen.chooseNat 0 2 let mut preresolved : Array Ix.SyntaxPreresolved := #[] for _ in [:numPreresolved] do preresolved := preresolved.push (← genIxSyntaxPreresolved) @@ -187,7 +187,7 @@ def genIxSyntaxAux : Nat → Gen Ix.Syntax (3, do let info ← genIxSourceInfo let kind ← genIxName 2 - let numChildren ← Gen.choose Nat 0 3 + let numChildren ← Gen.chooseNat 0 3 let mut children : Array Ix.Syntax := #[] for _ in [:numChildren] do children := children.push (← genIxSyntaxAux (fuel / 2)) @@ -202,7 +202,7 @@ def genIxDataValue : Gen Ix.DataValue := (10, Ix.DataValue.ofString <$> genIxString), (10, Ix.DataValue.ofBool <$> frequency [(1, pure true), (1, pure false)]), (10, Ix.DataValue.ofName <$> genIxName 3), - (10, Ix.DataValue.ofNat <$> choose Nat 0 1000), + (10, Ix.DataValue.ofNat <$> Gen.chooseNat 0 1000), (10, Ix.DataValue.ofInt <$> genIxInt), (5, Ix.DataValue.ofSyntax <$> genIxSyntax), ] @@ -210,14 +210,14 @@ def genIxDataValue : Gen Ix.DataValue := /-- Generate Ix.Expr with all variants and deeper nesting -/ def genIxExpr : Nat → Gen Ix.Expr | 0 => Gen.frequency #[ - (3, do let idx ← choose Nat 0 20; pure (Ix.Expr.mkBVar idx)), + (3, do let idx ← Gen.chooseNat 0 20; pure (Ix.Expr.mkBVar idx)), (2, do let u ← genIxLevel 3; pure (Ix.Expr.mkSort u)), (2, do let n ← genIxName 3; pure (Ix.Expr.mkFVar n)), (1, Ix.Expr.mkLit <$> genLiteral) ] (pure (Ix.Expr.mkBVar 0)) | fuel + 1 => Gen.frequency #[ -- Base cases (weighted higher to ensure termination) - (4, do let idx ← choose Nat 0 20; pure (Ix.Expr.mkBVar idx)), + (4, do let idx ← Gen.chooseNat 0 20; pure (Ix.Expr.mkBVar idx)), (2, do let u ← genIxLevel 4; pure (Ix.Expr.mkSort u)), (2, do let n ← genIxName 4; pure (Ix.Expr.mkFVar n)), (1, do let n ← genIxName 4; pure (Ix.Expr.mkMVar n)), @@ -225,7 +225,7 @@ def genIxExpr : Nat → Gen Ix.Expr -- Const with universe levels (4, do let n ← genIxName 4 - let numLevels ← choose Nat 0 4 + let numLevels ← Gen.chooseNat 0 4 let mut levels : Array Ix.Level := #[] for _ in [:numLevels] do levels := levels.push (← genIxLevel 4) @@ -259,7 +259,7 @@ def genIxExpr : Nat → Gen Ix.Expr pure (Ix.Expr.mkLetE n ty val body nonDep)), -- MData with metadata (2, do - let numEntries ← choose Nat 1 4 + let numEntries ← Gen.chooseNat 1 4 let mut entries : Array (Ix.Name × Ix.DataValue) := #[] for _ in [:numEntries] do let key ← genIxName 2 @@ -270,12 +270,12 @@ def genIxExpr : Nat → Gen Ix.Expr -- Proj (2, do let typeName ← genIxName 4 - let idx ← choose Nat 0 10 + let idx ← Gen.chooseNat 0 10 let struct ← genIxExpr (fuel / 2) pure (Ix.Expr.mkProj typeName idx struct)) ] (pure (Ix.Expr.mkBVar 0)) -instance : SampleableExt Ix.Name := SampleableExt.mkSelfContained (genIxName 5) +instance : Sampleable Ix.Name := ⟨(genIxName 5)⟩ instance : Shrinkable Ix.Level where shrink l := match l with @@ -286,7 +286,7 @@ instance : Shrinkable Ix.Level where | .param _ _ => [Ix.Level.mkZero] | .mvar _ _ => [Ix.Level.mkZero] -instance : SampleableExt Ix.Level := SampleableExt.mkSelfContained (genIxLevel 5) +instance : Sampleable Ix.Level := ⟨(genIxLevel 5)⟩ instance : Shrinkable Ix.Expr where shrink e := match e with @@ -303,11 +303,11 @@ instance : Shrinkable Ix.Expr where | .mdata _ e _ => [e] | .proj _ _ e _ => [e] -instance : SampleableExt Ix.Expr := SampleableExt.mkSelfContained (genIxExpr 5) +instance : Sampleable Ix.Expr := ⟨(genIxExpr 5)⟩ /-- Generate an array of level parameter names with varied sizes -/ def genLevelParams : Gen (Array Ix.Name) := do - let numParams ← choose Nat 0 5 + let numParams ← Gen.chooseNat 0 5 let mut params : Array Ix.Name := #[] for i in [:numParams] do -- Use varied names, not just u, v, w @@ -347,7 +347,7 @@ def genDefinitionSafety : Gen Lean.DefinitionSafety := /-- Generate an array of mutually recursive names -/ def genMutualNames (baseName : Ix.Name) : Gen (Array Ix.Name) := do - let numMutual ← choose Nat 1 4 + let numMutual ← Gen.chooseNat 1 4 let mut names : Array Ix.Name := #[baseName] for i in [1:numMutual] do names := names.push (Ix.Name.mkStr baseName s!"_mutual_{i}") @@ -392,7 +392,7 @@ def genIxQuotVal : Gen Ix.QuotVal := /-- Generate constructor names for an inductive -/ def genConstructorNames (inductName : Ix.Name) : Gen (Array Ix.Name) := do - let numCtors ← choose Nat 1 5 + let numCtors ← Gen.chooseNat 1 5 let mut ctors : Array Ix.Name := #[] let ctorNames := #["mk", "nil", "cons", "zero", "succ", "inl", "inr", "intro", "refl"] for i in [:numCtors] do @@ -403,12 +403,12 @@ def genConstructorNames (inductName : Ix.Name) : Gen (Array Ix.Name) := do /-- Generate a random Ix.InductiveVal -/ def genIxInductiveVal : Gen Ix.InductiveVal := do let cnst ← genIxConstantVal - let numParams ← choose Nat 0 5 - let numIndices ← choose Nat 0 3 + let numParams ← Gen.chooseNat 0 5 + let numIndices ← Gen.chooseNat 0 3 let isRec ← frequency [(6, pure false), (4, pure true)] let isUnsafe ← frequency [(9, pure false), (1, pure true)] let isReflexive ← frequency [(7, pure false), (3, pure true)] - let numNested ← choose Nat 0 3 + let numNested ← Gen.chooseNat 0 3 let all ← genMutualNames cnst.name let ctors ← genConstructorNames cnst.name pure { @@ -427,16 +427,16 @@ def genIxInductiveVal : Gen Ix.InductiveVal := do def genIxConstructorVal : Gen Ix.ConstructorVal := do let cnst ← genIxConstantVal let induct ← genIxName 5 - let cidx ← choose Nat 0 10 - let numParams ← choose Nat 0 5 - let numFields ← choose Nat 0 8 + let cidx ← Gen.chooseNat 0 10 + let numParams ← Gen.chooseNat 0 5 + let numFields ← Gen.chooseNat 0 8 let isUnsafe ← frequency [(9, pure false), (1, pure true)] pure { cnst, induct, cidx, numParams, numFields, isUnsafe } /-- Generate a random Ix.RecursorRule -/ def genIxRecursorRule : Gen Ix.RecursorRule := do let ctor ← genIxName 5 - let nfields ← choose Nat 0 8 + let nfields ← Gen.chooseNat 0 8 let rhs ← genIxExpr 5 pure { ctor, nfields, rhs } @@ -444,11 +444,11 @@ def genIxRecursorRule : Gen Ix.RecursorRule := do def genIxRecursorVal : Gen Ix.RecursorVal := do let cnst ← genIxConstantVal let all ← genMutualNames cnst.name - let numParams ← choose Nat 0 5 - let numIndices ← choose Nat 0 3 - let numMotives ← choose Nat 1 4 - let numMinors ← choose Nat 0 6 - let numRules ← choose Nat 1 5 + let numParams ← Gen.chooseNat 0 5 + let numIndices ← Gen.chooseNat 0 3 + let numMotives ← Gen.chooseNat 1 4 + let numMinors ← Gen.chooseNat 0 6 + let numRules ← Gen.chooseNat 1 5 let mut rules : Array Ix.RecursorRule := #[] for _ in [:numRules] do rules := rules.push (← genIxRecursorRule) @@ -482,14 +482,14 @@ instance : Shrinkable Ix.ConstantInfo where | .axiomInfo _ => [] | _ => [.axiomInfo { cnst := simpleCnst, isUnsafe := false }] -instance : SampleableExt Ix.ConstantInfo := SampleableExt.mkSelfContained genIxConstantInfo +instance : Sampleable Ix.ConstantInfo := ⟨genIxConstantInfo⟩ /-! ## Generators for Additional Ix Types -/ def genAddress : Gen Address := Tests.Gen.Ixon.genAddress instance : Shrinkable Address where shrink _ := [] -instance : SampleableExt Address := SampleableExt.mkSelfContained genAddress +instance : Sampleable Address := ⟨genAddress⟩ -- Ix.Int already has genIxInt defined earlier instance : Shrinkable Ix.Int where @@ -497,7 +497,7 @@ instance : Shrinkable Ix.Int where | .ofNat n => if n > 0 then [.ofNat (n / 2)] else [] | .negSucc n => [.ofNat 0] ++ if n > 0 then [.negSucc (n / 2)] else [] -instance : SampleableExt Ix.Int := SampleableExt.mkSelfContained genIxInt +instance : Sampleable Ix.Int := ⟨genIxInt⟩ -- Ix.Syntax already has genIxSyntax defined earlier instance : Shrinkable Ix.Syntax where @@ -505,7 +505,7 @@ instance : Shrinkable Ix.Syntax where | .missing => [] | _ => [.missing] -instance : SampleableExt Ix.Syntax := SampleableExt.mkSelfContained genIxSyntax +instance : Sampleable Ix.Syntax := ⟨genIxSyntax⟩ -- Ix.DataValue already has genIxDataValue defined earlier instance : Shrinkable Ix.DataValue where @@ -513,7 +513,7 @@ instance : Shrinkable Ix.DataValue where | .ofBool _ => [] | _ => [.ofBool true] -instance : SampleableExt Ix.DataValue := SampleableExt.mkSelfContained genIxDataValue +instance : Sampleable Ix.DataValue := ⟨genIxDataValue⟩ end Tests.Gen.Ix diff --git a/Tests/Gen/Ixon.lean b/Tests/Gen/Ixon.lean index cfd977b7fd..3e88556e0b 100644 --- a/Tests/Gen/Ixon.lean +++ b/Tests/Gen/Ixon.lean @@ -11,7 +11,7 @@ public import Ix.Address public section -open LSpec SlimCheck Gen Ixon +open LSpec LSpec.Prop Gen Ixon open Ix (DefKind DefinitionSafety QuotKind) namespace Tests.Gen.Ixon @@ -22,7 +22,7 @@ namespace Tests.Gen.Ixon def genAddress : Gen Address := do let mut bytes : ByteArray := ByteArray.empty for _ in [:32] do - let b ← Gen.choose Nat 0 255 + let b ← Gen.chooseNat 0 255 bytes := bytes.push b.toUInt8 pure ⟨(Blake3.Rust.hash bytes).val⟩ @@ -35,19 +35,19 @@ def genList (n: Gen α) : Gen (List α) := def genUInt64Small : Gen UInt64 := USize.toUInt64 <$> genUSize def genDefKind : Gen DefKind := - elements #[.defn, .opaq, .thm] + Gen.elements! #[.defn, .opaq, .thm] def genDefinitionSafety : Gen DefinitionSafety := - elements #[.unsaf, .safe, .part] + Gen.elements! #[.unsaf, .safe, .part] def genQuotKindNew : Gen QuotKind := - elements #[.type, .ctor, .lift, .ind] + Gen.elements! #[.type, .ctor, .lift, .ind] def genBinderMode : Gen BinderMode := - elements #[.many, .borrowed, .unique, .uniqueBorrowed, .once, .onceBorrowed, .erased] + Gen.elements! #[.many, .borrowed, .unique, .uniqueBorrowed, .once, .onceBorrowed, .erased] def genResultMode : Gen ResultMode := - elements #[.shared, .borrowed, .unique, .uniqueBorrowed] + Gen.elements! #[.shared, .borrowed, .unique, .uniqueBorrowed] /-- A binder node's mode, the default most of the time. -/ def genAllMode : Gen AllMode := @@ -65,10 +65,10 @@ def genLetMode : Gen LetMode := ] def genDefAsserts : Gen DefAsserts := - DefAsserts.mk <$> elements #[AllocAssert.unrestricted, .noRc, .noAlloc] <*> genBool + DefAsserts.mk <$> Gen.elements! #[AllocAssert.unrestricted, .noRc, .noAlloc] <*> genBool def genFieldMode : Gen FieldMode := - elements #[.inherited, .shared] + Gen.elements! #[.inherited, .shared] /-- Field modes for a constructor with `n` fields: listed (one of them `shared`) for a few fields, otherwise inherited. -/ @@ -78,7 +78,7 @@ def genFieldModes (n : Nat) : Gen (FieldModes n) := do let mut modes : Array FieldMode := #[] for _ in [:n] do modes := modes.push (← genFieldMode) - let i ← Gen.choose Nat 0 (n - 1) + let i ← Gen.chooseNat 0 (n - 1) return FieldModes.ofArray (modes.set! i .shared) def genArray (g: Gen α) : Gen (Array α) := @@ -239,7 +239,7 @@ def genAxiom : Gen Axiom := .mk <$> genBool <*> genUInt64Small <*> genExpr def genQuotKind : Gen Lean.QuotKind := - elements #[.type, .ctor, .lift, .ind] + Gen.elements! #[.type, .ctor, .lift, .ind] def genQuotient : Gen Quotient := .mk <$> genQuotKindNew <*> genUInt64Small <*> genExpr @@ -278,7 +278,7 @@ def genInductive : Gen Inductive := def genBinderInfo : Gen Lean.BinderInfo := - elements #[.default, .implicit, .strictImplicit, .instImplicit] + Gen.elements! #[.default, .implicit, .strictImplicit, .instImplicit] def genReducibilityHints : Gen Lean.ReducibilityHints := frequency [ @@ -455,27 +455,27 @@ instance : Shrinkable DataValue where | .ofBool _ => [] | _ => [.ofBool true] -/-! ## SampleableExt instances -/ - -instance : SampleableExt DefKind := SampleableExt.mkSelfContained genDefKind -instance : SampleableExt DefinitionSafety := SampleableExt.mkSelfContained genDefinitionSafety -instance : SampleableExt QuotKind := SampleableExt.mkSelfContained genQuotKindNew -instance : SampleableExt Univ := SampleableExt.mkSelfContained genUniv -instance : SampleableExt Expr := SampleableExt.mkSelfContained genExpr -instance : SampleableExt Definition := SampleableExt.mkSelfContained genDefinition -instance : SampleableExt Axiom := SampleableExt.mkSelfContained genAxiom -instance : SampleableExt Quotient := SampleableExt.mkSelfContained genQuotient -instance : SampleableExt RecursorRule := SampleableExt.mkSelfContained genRecursorRule -instance : SampleableExt Recursor := SampleableExt.mkSelfContained genRecursor -instance : SampleableExt Constructor := SampleableExt.mkSelfContained genConstructor -instance : SampleableExt Inductive := SampleableExt.mkSelfContained genInductive -instance : SampleableExt InductiveProj := SampleableExt.mkSelfContained genInductiveProj -instance : SampleableExt ConstructorProj := SampleableExt.mkSelfContained genConstructorProj -instance : SampleableExt RecursorProj := SampleableExt.mkSelfContained genRecursorProj -instance : SampleableExt DefinitionProj := SampleableExt.mkSelfContained genDefinitionProj -instance : SampleableExt MutConst := SampleableExt.mkSelfContained genMutConst -instance : SampleableExt ConstantInfo := SampleableExt.mkSelfContained genConstantInfo -instance : SampleableExt Constant := SampleableExt.mkSelfContained genConstant +/-! ## Sampleable instances -/ + +instance : Sampleable DefKind := ⟨genDefKind⟩ +instance : Sampleable DefinitionSafety := ⟨genDefinitionSafety⟩ +instance : Sampleable QuotKind := ⟨genQuotKindNew⟩ +instance : Sampleable Univ := ⟨genUniv⟩ +instance : Sampleable Expr := ⟨genExpr⟩ +instance : Sampleable Definition := ⟨genDefinition⟩ +instance : Sampleable Axiom := ⟨genAxiom⟩ +instance : Sampleable Quotient := ⟨genQuotient⟩ +instance : Sampleable RecursorRule := ⟨genRecursorRule⟩ +instance : Sampleable Recursor := ⟨genRecursor⟩ +instance : Sampleable Constructor := ⟨genConstructor⟩ +instance : Sampleable Inductive := ⟨genInductive⟩ +instance : Sampleable InductiveProj := ⟨genInductiveProj⟩ +instance : Sampleable ConstructorProj := ⟨genConstructorProj⟩ +instance : Sampleable RecursorProj := ⟨genRecursorProj⟩ +instance : Sampleable DefinitionProj := ⟨genDefinitionProj⟩ +instance : Sampleable MutConst := ⟨genMutConst⟩ +instance : Sampleable ConstantInfo := ⟨genConstantInfo⟩ +instance : Sampleable Constant := ⟨genConstant⟩ /-! ## Generators for Metadata Types -/ @@ -490,7 +490,7 @@ def genDataValueNew : Gen DataValue := (10, .ofSyntax <$> genAddress), ] -instance : SampleableExt DataValue := SampleableExt.mkSelfContained genDataValueNew +instance : Sampleable DataValue := ⟨genDataValueNew⟩ /-! ## Generators for Constant Metadata Types -/ @@ -515,7 +515,7 @@ def genAuxLayout? : Gen (Option AuxLayout) := let c ← genSmallArray genUInt64Small let mut e : Array UInt64 := #[] for _ in [0:p.size] do - e := e.push (UInt64.ofNat (← Gen.choose Nat 0 1)) + e := e.push (UInt64.ofNat (← Gen.chooseNat 0 1)) pure (some { perm := p, sourceCtorCounts := c, evaporated := e })), ] @@ -526,7 +526,7 @@ def genExprMetaData (arenaSize : Nat := 0) (genAddr : Gen Address := genAddress) : Gen ExprMetaData := let genIdx : Gen UInt64 := if arenaSize == 0 then pure 0 - else UInt64.ofNat <$> Gen.choose Nat 0 (arenaSize - 1) + else UInt64.ofNat <$> Gen.chooseNat 0 (arenaSize - 1) frequency [ (20, pure .leaf), (15, ExprMetaData.app <$> genIdx <*> genIdx), @@ -552,7 +552,7 @@ where /-- Generate a valid ExprMetaArena by building nodes bottom-up so child indices always reference earlier entries. -/ def genExprMetaArena (genAddr : Gen Address := genAddress) : Gen ExprMetaArena := do - let numNodes ← Gen.choose Nat 0 6 + let numNodes ← Gen.chooseNat 0 6 let mut arena : ExprMetaArena := {} for _ in [:numNodes] do let node ← genExprMetaData arena.nodes.size genAddr @@ -564,7 +564,7 @@ def genConstantMetaInfo (genAddr : Gen Address := genAddress) : Gen ConstantMeta let arena ← genExprMetaArena genAddr let genRoot : Gen UInt64 := if arena.nodes.size == 0 then pure 0 - else UInt64.ofNat <$> Gen.choose Nat 0 (arena.nodes.size - 1) + else UInt64.ofNat <$> Gen.chooseNat 0 (arena.nodes.size - 1) frequency [ (10, pure .empty), (15, ConstantMetaInfo.defn <$> genAddr <*> genSmallArray genAddr @@ -627,14 +627,15 @@ instance : Shrinkable ConstantMeta where else [] | _ => [{ m with info := .empty }] -instance : SampleableExt AuxLayout := SampleableExt.mkSelfContained do +instance : Sampleable AuxLayout where + sample := do match ← genAuxLayout? with | some l => pure l | none => pure {} -instance : SampleableExt ExprMetaData := SampleableExt.mkSelfContained (genExprMetaData 5) -instance : SampleableExt ExprMetaArena := SampleableExt.mkSelfContained (genExprMetaArena) -instance : SampleableExt ConstantMetaInfo := SampleableExt.mkSelfContained (genConstantMetaInfo) -instance : SampleableExt ConstantMeta := SampleableExt.mkSelfContained (genConstantMeta) +instance : Sampleable ExprMetaData := ⟨(genExprMetaData 5)⟩ +instance : Sampleable ExprMetaArena := ⟨(genExprMetaArena)⟩ +instance : Sampleable ConstantMetaInfo := ⟨(genConstantMetaInfo)⟩ +instance : Sampleable ConstantMeta := ⟨(genConstantMeta)⟩ /-- Generate a Named entry with proper metadata. Exercises both `none` and `some (addr, meta)` for the `original` field @@ -664,17 +665,17 @@ instance : Shrinkable Named where instance : Shrinkable Comm where shrink _ := [] -instance : SampleableExt Named := SampleableExt.mkSelfContained genNamed -instance : SampleableExt Comm := SampleableExt.mkSelfContained genCommNew +instance : Sampleable Named := ⟨genNamed⟩ +instance : Sampleable Comm := ⟨genCommNew⟩ /-! ## Generators for RawEnv Types -/ /-- Generate a ByteArray for blobs -/ def genByteArray : Gen ByteArray := do - let len ← Gen.choose Nat 0 32 + let len ← Gen.chooseNat 0 32 let mut bytes : Array UInt8 := #[] for _ in [:len] do - let b ← Gen.choose Nat 0 255 + let b ← Gen.chooseNat 0 255 bytes := bytes.push b.toUInt8 pure (ByteArray.mk bytes) @@ -685,11 +686,11 @@ def genIxName : Nat → Gen Ix.Name (3, pure Ix.Name.mkAnon), (5, do let parent ← genIxName fuel - let s ← Gen.elements #["a", "b", "test", "foo", "bar"] + let s ← Gen.elements! #["a", "b", "test", "foo", "bar"] pure (Ix.Name.mkStr parent s)), (2, do let parent ← genIxName fuel - let n ← Gen.choose Nat 0 100 + let n ← Gen.chooseNat 0 100 pure (Ix.Name.mkNat parent n)) ] (pure Ix.Name.mkAnon) @@ -782,10 +783,10 @@ def genRawEnv : Gen RawEnv := do pool := nameComponentAddrs e.name pool for n in namedNames do pool := nameComponentAddrs n pool - let genPoolAddr : Gen Address := SlimCheck.Gen.elements pool + let genPoolAddr : Gen Address := Gen.elements! pool let mut named : Array RawNamed := #[] for name in namedNames do - let i ← Gen.choose Nat 0 (consts.size - 1) + let i ← Gen.chooseNat 0 (consts.size - 1) let addr := (consts[i % consts.size]!).addr let constMeta ← genConstantMeta genPoolAddr -- `original` stays a raw address on the wire (may reference an @@ -815,7 +816,7 @@ def genRawEnv : Gen RawEnv := do frequency [ (1, pure none), (1, do - let i ← Gen.choose Nat 0 (consts.size - 1) + let i ← Gen.chooseNat 0 (consts.size - 1) pure (consts[i % consts.size]?.map (·.addr))), ] else pure none @@ -824,7 +825,7 @@ def genRawEnv : Gen RawEnv := do let anonHints ← if consts.size > 0 then do let hintList ← genList do - let i ← Gen.choose Nat 0 (consts.size - 1) + let i ← Gen.chooseNat 0 (consts.size - 1) let h ← genReducibilityHints pure ((consts[i % consts.size]!).addr, h) pure (hintList.toArray.qsort fun a b => (compare a.1 b.1).isLT) @@ -875,11 +876,11 @@ instance : Shrinkable RawEnv where | some _ => [{ env with main := none }] | none => []) -instance : SampleableExt RawConst := SampleableExt.mkSelfContained genRawConst -instance : SampleableExt RawNamed := SampleableExt.mkSelfContained genRawNamed -instance : SampleableExt RawBlob := SampleableExt.mkSelfContained genRawBlob -instance : SampleableExt RawComm := SampleableExt.mkSelfContained genRawComm -instance : SampleableExt RawEnv := SampleableExt.mkSelfContained genRawEnv +instance : Sampleable RawConst := ⟨genRawConst⟩ +instance : Sampleable RawNamed := ⟨genRawNamed⟩ +instance : Sampleable RawBlob := ⟨genRawBlob⟩ +instance : Sampleable RawComm := ⟨genRawComm⟩ +instance : Sampleable RawEnv := ⟨genRawEnv⟩ end Tests.Gen.Ixon diff --git a/Tests/Gen/IxonSyntax.lean b/Tests/Gen/IxonSyntax.lean index 676b186e0f..9c8be78f71 100644 --- a/Tests/Gen/IxonSyntax.lean +++ b/Tests/Gen/IxonSyntax.lean @@ -20,7 +20,7 @@ public import Ix.IxonSyntax public section -open LSpec SlimCheck Gen Ixon.Syntax +open LSpec LSpec.Prop Gen Ixon.Syntax namespace Tests.Gen.IxonSyntax @@ -39,16 +39,16 @@ def strPool : Array String := "Except", "def", "weird name", "123", "max"] def genStrComponent : Gen NameComponent := - .str <$> elements strPool + .str <$> Gen.elements! strPool def genComponent : Gen NameComponent := frequency [ - (1, .num <$> choose Nat 0 999), + (1, .num <$> Gen.chooseNat 0 999), (4, genStrComponent) ] def genSName : Gen SName := do - let n ← choose Nat 0 2 + let n ← Gen.chooseNat 0 2 let mut parts := #[← genStrComponent] for _ in [0:n] do parts := parts.push (← genComponent) @@ -61,28 +61,28 @@ def hexChars : Array Char := def genHex (len : Nat) : Gen String := do let mut s := "" for _ in [0:len] do - s := s.push (← elements hexChars) + s := s.push (← Gen.elements! hexChars) return s def genHash : Gen HashRef := do - return { hex := ← genHex (4 + (← choose Nat 0 11)) } + return { hex := ← genHex (4 + (← Gen.chooseNat 0 11)) } /-- Universe variables: `Str` only; includes `"max"` (must print escaped in universe positions). -/ def genUvar : Gen NameComponent := - .str <$> elements #["u", "v", "w", "max", "weird name"] + .str <$> Gen.elements! #["u", "v", "w", "max", "weird name"] def genUniv : Nat → Gen UnivExpr | 0 => frequency [ - (1, (.nat · {}) <$> choose Nat 0 3), + (1, (.nat · {}) <$> Gen.chooseNat 0 3), (1, (.var · {}) <$> genUvar) ] | d + 1 => frequency [ - (1, (.nat · {}) <$> choose Nat 0 3), + (1, (.nat · {}) <$> Gen.chooseNat 0 3), (1, (.var · {}) <$> genUvar), - (1, do return .add (← genUniv d) (1 + (← choose Nat 0 2)) {}), + (1, do return .add (← genUniv d) (1 + (← Gen.chooseNat 0 2)) {}), (1, do return .max (← genUniv d) (← genUniv d) {}), (1, do return .imax (← genUniv d) (← genUniv d) {}) ] @@ -94,7 +94,7 @@ def genCref : Gen ConstRef := do else frequency [(1, some <$> genHash), (3, pure none)] let levels ← frequency [ (1, do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut ls := #[] for _ in [0:n] do ls := ls.push (← genUniv 1) @@ -121,15 +121,15 @@ def genSort : Gen SortKind := pool. -/ def genLitString : Gen String := frequency [ - (3, elements #["", "hi", "line\nbreak", "q\"uote", "tab\there\\"]), + (3, Gen.elements! #["", "hi", "line\nbreak", "q\"uote", "tab\there\\"]), (1, do - let n ← choose Nat 0 12 + let n ← Gen.chooseNat 0 12 let mut s := "" for _ in [0:n] do let c ← frequency [ - (3, elements #['"', '\\', '\n', '\t', 'a', ' ', '«', '»', '¤']), - (2, Char.ofNat <$> choose Nat 0x20 0x7e), - (1, Char.ofNat <$> choose Nat 0xa0 0x2fff) + (3, Gen.elements! #['"', '\\', '\n', '\t', 'a', ' ', '«', '»', '¤']), + (2, Char.ofNat <$> Gen.chooseNat 0x20 0x7e), + (1, Char.ofNat <$> Gen.chooseNat 0xa0 0x2fff) ] s := s.push c pure s) @@ -137,29 +137,29 @@ def genLitString : Gen String := def genValueContract : Gen Ixon.ValueContract := do return { - owned := if (← choose Nat 0 1) == 0 then .unique else .shared - locality := if (← choose Nat 0 1) == 0 then .unrestricted else .local } + owned := if (← Gen.chooseNat 0 1) == 0 then .unique else .shared + locality := if (← Gen.chooseNat 0 1) == 0 then .unrestricted else .local } def genBinderContract : Gen Ixon.BinderContract := do - let uses ← elements #[Ixon.Uses.erased, .linear, .affine, .many] + let uses ← Gen.elements! #[Ixon.Uses.erased, .linear, .affine, .many] return { uses, value := ← genValueContract } def genLetContract : Gen Ixon.LetContract := do return { - nonDep := (← choose Nat 0 1) == 0 - kind := if (← choose Nat 0 1) == 0 then .value else .borrowShared + nonDep := (← Gen.chooseNat 0 1) == 0 + kind := if (← Gen.chooseNat 0 1) == 0 then .value else .borrowShared binder := ← genBinderContract } mutual partial def genBinder (depth : Nat) : Gen BinderGroup := do - let info ← elements #[Lean.BinderInfo.default, .implicit, + let info ← Gen.elements! #[Lean.BinderInfo.default, .implicit, .strictImplicit, .instImplicit] let names ← - if info == Lean.BinderInfo.instImplicit && (← choose Nat 0 1) == 0 then + if info == Lean.BinderInfo.instImplicit && (← Gen.chooseNat 0 1) == 0 then pure #[] else do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut ns := #[] for _ in [0:n] do ns := ns.push (← genBinderName) @@ -169,7 +169,7 @@ partial def genBinder (depth : Nat) : Gen BinderGroup := do partial def genTerm (depth : Nat) : Gen Term := do if depth == 0 then frequency [ - (1, (.natLit · {}) <$> choose Nat 0 1000000), + (1, (.natLit · {}) <$> Gen.chooseNat 0 1000000), (1, (.strLit · {}) <$> genLitString), (1, (.sort · {}) <$> genSort), (3, .ref <$> genCref) @@ -179,19 +179,19 @@ partial def genTerm (depth : Nat) : Gen Term := do frequency [ (1, (.sort · {}) <$> genSort), (2, do - let n ← choose Nat 1 3 + let n ← Gen.chooseNat 1 3 let mut args := #[] for _ in [0:n] do args := args.push (← genTerm d) return .app (← genTerm d) args {}), (2, do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut bs := #[] for _ in [0:n] do bs := bs.push (← genBinder d) return .lam bs (← genTerm d) {}), (1, do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut bs := #[] for _ in [0:n] do bs := bs.push (← genBinder d) @@ -200,14 +200,14 @@ partial def genTerm (depth : Nat) : Gen Term := do (1, do return .letE (← genLetContract) (← genBinderName) (← genTerm d) (← genTerm d) (← genTerm d) {}), - (1, do return .proj (← genCref) (← choose Nat 0 7) (← genTerm d) {}), + (1, do return .proj (← genCref) (← Gen.chooseNat 0 7) (← genTerm d) {}), (1, .ref <$> genCref) ] end def genUParams : Gen (Array UParam) := do - let n ← choose Nat 0 2 + let n ← Gen.chooseNat 0 2 let mut out := #[] for _ in [0:n] do out := out.push { name := ← genUvar } @@ -218,85 +218,85 @@ def genName? : Gen (Option SName) := /-- The parser rejects `partial` on non-`def` and unsafe+partial. -/ def genModifiers (kw : DefKw) : Gen Modifiers := do - match ← choose Nat 0 3 with + match ← Gen.chooseNat 0 3 with | 0 => return { isUnsafe := true } | 1 => if kw == .defn then return { isPartial := true } else return {} | _ => return {} def genDefDecl (depth : Nat) : Gen DefDecl := do - let kw ← elements #[DefKw.defn, .thm, .opaq] + let kw ← Gen.elements! #[DefKw.defn, .thm, .opaq] return { kw, mods := ← genModifiers kw, name := ← genName? uparams := ← genUParams, ty := ← genTerm depth value := ← genTerm depth } def genIndDecl (depth : Nat) : Gen IndDecl := do - let nCtors ← choose Nat 0 2 + let nCtors ← Gen.chooseNat 0 2 let mut ctors := #[] for _ in [0:nCtors] do ctors := ctors.push - { name := ← genName?, params := ← choose Nat 0 3 - fields := ← choose Nat 0 3, ty := ← genTerm depth } - return { isUnsafe := (← choose Nat 0 1) == 0, name := ← genName? - uparams := ← genUParams, params := ← choose Nat 0 3 - indices := ← choose Nat 0 3, ty := ← genTerm depth, ctors } + { name := ← genName?, params := ← Gen.chooseNat 0 3 + fields := ← Gen.chooseNat 0 3, ty := ← genTerm depth } + return { isUnsafe := (← Gen.chooseNat 0 1) == 0, name := ← genName? + uparams := ← genUParams, params := ← Gen.chooseNat 0 3 + indices := ← Gen.chooseNat 0 3, ty := ← genTerm depth, ctors } def genRecrDecl (depth : Nat) : Gen RecrDecl := do - let nRules ← choose Nat 0 2 + let nRules ← Gen.chooseNat 0 2 let mut rules := #[] for _ in [0:nRules] do rules := rules.push - { fields := ← choose Nat 0 3, rhs := ← genTerm depth } - return { isUnsafe := (← choose Nat 0 1) == 0, name := ← genName? - uparams := ← genUParams, params := ← choose Nat 0 3 - indices := ← choose Nat 0 3, motives := 1 + (← choose Nat 0 1) - minors := ← choose Nat 0 3, k := (← choose Nat 0 1) == 0 + { fields := ← Gen.chooseNat 0 3, rhs := ← genTerm depth } + return { isUnsafe := (← Gen.chooseNat 0 1) == 0, name := ← genName? + uparams := ← genUParams, params := ← Gen.chooseNat 0 3 + indices := ← Gen.chooseNat 0 3, motives := 1 + (← Gen.chooseNat 0 1) + minors := ← Gen.chooseNat 0 3, k := (← Gen.chooseNat 0 1) == 0 ty := ← genTerm depth, rules } def genDecl (depth : Nat) : Gen Decl := do - match ← choose Nat 0 7 with + match ← Gen.chooseNat 0 7 with | 0 | 1 => .defn <$> genDefDecl depth | 2 => - return .axio { isUnsafe := (← choose Nat 0 1) == 0 + return .axio { isUnsafe := (← Gen.chooseNat 0 1) == 0 name := ← genName?, uparams := ← genUParams ty := ← genTerm depth } | 3 => - return .quot { kind := ← elements #[QuotKindKw.type, .ctor, .lift, .ind] + return .quot { kind := ← Gen.elements! #[QuotKindKw.type, .ctor, .lift, .ind] name := ← genName?, uparams := ← genUParams ty := ← genTerm depth } | 4 => .indc <$> genIndDecl depth | 5 => .recr <$> genRecrDecl depth | 6 => do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut members := #[] for _ in [0:n] do - let m ← match ← choose Nat 0 2 with + let m ← match ← Gen.chooseNat 0 2 with | 0 => Decl.indc <$> genIndDecl depth | 1 => Decl.recr <$> genRecrDecl depth | _ => Decl.defn <$> genDefDecl depth members := members.push m return .muts members {} | _ => do - let kind ← elements #[PrjKind.dprj, .iprj, .cprj, .rprj] + let kind ← Gen.elements! #[PrjKind.dprj, .iprj, .cprj, .rprj] let cidx ← - if kind == .cprj then some <$> choose Nat 0 7 else pure none + if kind == .cprj then some <$> Gen.chooseNat 0 7 else pure none return .prj { kind, name := ← genName?, block := ← genHash - idx := ← choose Nat 0 7, cidx } + idx := ← Gen.chooseNat 0 7, cidx } def genImport : Gen ImportDecl := do return { prefixName := ← frequency [(1, some <$> genSName), (1, pure none)] hash := { hex := ← genHex 64 } } def genFile : Gen File := do - let nImports ← choose Nat 0 2 + let nImports ← Gen.chooseNat 0 2 let mut imports := #[] for _ in [0:nImports] do imports := imports.push (← genImport) - let nDecls ← choose Nat 0 3 + let nDecls ← Gen.chooseNat 0 3 let mut decls := #[] for _ in [0:nDecls] do decls := decls.push (← genDecl 2) let main ← - if (← choose Nat 0 2) == 0 then + if (← Gen.chooseNat 0 2) == 0 then pure (some { value := ← genTerm 2, ty := ← genTerm 2 : MainExpr }) else pure none return { version := VERSION, imports, decls, main } @@ -383,13 +383,11 @@ instance : Shrinkable File where out := out ++ [{ f with decls := f.decls.set! i s }] return out -/-! ## SampleableExt instances -/ +/-! ## Sampleable instances -/ -instance : SampleableExt Term := - SampleableExt.mkSelfContained (genTerm 4) +instance : Sampleable Term := ⟨(genTerm 4)⟩ -instance : SampleableExt File := - SampleableExt.mkSelfContained genFile +instance : Sampleable File := ⟨genFile⟩ /-- Fuzz input: strings biased toward syntax-relevant characters (delimiters, escapes, digits, unicode) — a sharper boundary walk @@ -404,13 +402,13 @@ def fuzzChars : Array Char := 'a', 'x', 'f', '0', '1', '9', 'α', 'd', 'e', 'u', 'n', '-', '/'] def genFuzz : Gen Fuzz := do - let n ← choose Nat 0 60 + let n ← Gen.chooseNat 0 60 let mut s := "" for _ in [0:n] do let c ← frequency [ - (6, elements fuzzChars), - (1, Char.ofNat <$> choose Nat 0x20 0x7e), - (1, Char.ofNat <$> choose Nat 0xa0 0x2fff) + (6, Gen.elements! fuzzChars), + (1, Char.ofNat <$> Gen.chooseNat 0x20 0x7e), + (1, Char.ofNat <$> Gen.chooseNat 0xa0 0x2fff) ] s := s.push c return ⟨s⟩ @@ -424,7 +422,7 @@ instance : Shrinkable Fuzz where ⟨String.ofList (l.drop (l.length / 2))⟩, ⟨String.ofList l.tail⟩] -instance : SampleableExt Fuzz := SampleableExt.mkSelfContained genFuzz +instance : Sampleable Fuzz := ⟨genFuzz⟩ /-- A batch of (position, pool-index) char mutations for the near-valid fuzz property. -/ @@ -433,15 +431,15 @@ structure Muts where deriving Repr, Inhabited def genMuts : Gen Muts := do - let n ← choose Nat 0 6 + let n ← Gen.chooseNat 0 6 let mut out : List (Nat × Nat) := [] for _ in [0:n] do - out := (← choose Nat 0 100000, ← choose Nat 0 1000) :: out + out := (← Gen.chooseNat 0 100000, ← Gen.chooseNat 0 1000) :: out return ⟨out⟩ instance : Shrinkable Muts where shrink m := if m.muts.isEmpty then [] else [⟨m.muts.tail⟩] -instance : SampleableExt Muts := SampleableExt.mkSelfContained genMuts +instance : Sampleable Muts := ⟨genMuts⟩ end Tests.Gen.IxonSyntax diff --git a/Tests/Ix/AiurStatistics.lean b/Tests/Ix/AiurStatistics.lean index 26ba43c03b..1ec96facf9 100644 --- a/Tests/Ix/AiurStatistics.lean +++ b/Tests/Ix/AiurStatistics.lean @@ -6,6 +6,8 @@ public section namespace Tests.Ix.AiurStatistics open Aiur LSpec Lean +set_option compiler.extract_closed false + private def shape : CircuitShape := { mainWidth := 3, stage2Width := 3, quotientDegree := 2, preprocessedWidth := 100, preprocessedHeight := 0 } @@ -23,37 +25,41 @@ private def raw (c : Json) (degree : Nat := 3) : Json := Json.mkObj [ ("log_blowup", toJson (2 : Nat)), ("extension_degree", toJson degree), ("circuits", .arr #[c])] -def suite : List TestSeq := [ - AiurTests.Cost.tests, - let stats := computeStats { logBlowup := 2, circuits := #[measurement "small" 1 3, measurement "large" 4 0] } - test "cached and uncached totals use the same model" - (stats.roundedFftCost == 780 && stats.totalUncachedFftCost == 1392.0 && stats.totalCacheHits == 3) - ++ test "display ranks circuits by cost" (stats.circuits[0]!.name == "large"), - test "decode real host field names" +def suite : LSpec.Spec := do + AiurTests.Cost.tests + it "cached and uncached totals use the same model" do + let stats := computeStats { logBlowup := 2, circuits := #[measurement "small" 1 3, measurement "large" 4 0] } + expect (stats.roundedFftCost == 780 && stats.totalUncachedFftCost == 1392.0 && stats.totalCacheHits == 3) + it "display ranks circuits by cost" do + let stats := computeStats { logBlowup := 2, circuits := #[measurement "small" 1 3, measurement "large" 4 0] } + expect (stats.circuits[0]!.name == "large") + itBool "decode real host field names" ((ExecutionMeasurements.fromJson (raw (rawCircuit 3 2 0))).toOption.any fun m => m.circuits.size == 1 && m.circuits[0]!.height == 3 && m.circuits[0]!.cacheHits == 2) - ++ test "fixed tables keep their full height" + itBool "fixed tables keep their full height" ((ExecutionMeasurements.fromJson (raw (rawCircuit 4 0 4))).isOk) - ++ test "reject truncated fixed tables" + itBool "reject truncated fixed tables" ((ExecutionMeasurements.fromJson (raw (rawCircuit 3 0 4))).toOption.isNone) - ++ test "reject cache savings on fixed tables" + itBool "reject cache savings on fixed tables" ((ExecutionMeasurements.fromJson (raw (rawCircuit 4 1 4))).toOption.isNone) - ++ test "reject missing counts" + itBool "reject missing counts" ((ExecutionMeasurements.fromJson (raw (Json.mkObj []))).toOption.isNone) - ++ test "reject an incompatible extension degree" - ((ExecutionMeasurements.fromJson (raw (rawCircuit 4 0 0) 2)).toOption.isNone), - let report := Json.mkObj [("execution_statistics", raw (rawCircuit 4 0 0)), - ("verified", toJson true)] - let enriched := enrichExecutionReport report - test "benchmark reports contain Lean-computed FFT costs" - ((enriched >>= (·.getObjValAs? Nat "fft-cost")).toOption == some 696) - ++ test "keep existing report fields" - ((enriched >>= (·.getObjValAs? Bool "verified")).toOption == some true) - ++ test "a missing execution does not fabricate zero cost" + itBool "reject an incompatible extension degree" + ((ExecutionMeasurements.fromJson (raw (rawCircuit 4 0 0) 2)).toOption.isNone) + it "benchmark reports contain Lean-computed FFT costs" do + let report := Json.mkObj [("execution_statistics", raw (rawCircuit 4 0 0)), + ("verified", toJson true)] + let enriched := enrichExecutionReport report + expect ((enriched >>= (·.getObjValAs? Nat "fft-cost")).toOption == some 696) + it "keep existing report fields" do + let report := Json.mkObj [("execution_statistics", raw (rawCircuit 4 0 0)), + ("verified", toJson true)] + let enriched := enrichExecutionReport report + expect ((enriched >>= (·.getObjValAs? Bool "verified")).toOption == some true) + itBool "a missing execution does not fabricate zero cost" (((enrichExecutionReport (Json.mkObj [])) >>= (·.getObjVal? "fft-cost")).toOption.isNone) - ++ test "malformed measurements fail the report" + itBool "malformed measurements fail the report" ((enrichExecutionReport (Json.mkObj [("execution_statistics", .null)])).toOption.isNone) -] end Tests.Ix.AiurStatistics end diff --git a/Tests/Ix/AssumptionTree.lean b/Tests/Ix/AssumptionTree.lean index 1a403f53b9..fb7aac36bf 100644 --- a/Tests/Ix/AssumptionTree.lean +++ b/Tests/Ix/AssumptionTree.lean @@ -11,6 +11,8 @@ open Ix.AssumptionTree open Ix.Merkle (merkleRootCanonical merkleJoin verifyMerkleProof) open Ixon (runGet) +set_option compiler.extract_closed false + private def addr (s : String) : Address := Address.blake3 s.toUTF8 /-! ## Canonical construction -/ @@ -20,65 +22,70 @@ private partial def hasPad : Ix.AssumptionTree → Bool | .leaf _ => false | .node l r => hasPad l || hasPad r -private def canonicalUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - test "canonical of empty is none" ((Ix.AssumptionTree.canonical #[]) == none) - ++ test "canonical of single leaf" - ((Ix.AssumptionTree.canonical #[a]) == some (.leaf a)) - ++ test "canonical of three leaves contains padding" - (let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! - hasPad t) +private def canonicalUnits : LSpec.Spec := do + itBool "canonical of empty is none" ((Ix.AssumptionTree.canonical #[]) == none) + itBool "canonical of single leaf" + (let a := addr "a"; (Ix.AssumptionTree.canonical #[a]) == some (.leaf a)) + itBool "canonical of three leaves contains padding" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! + hasPad t) /-! ## Root agreement with `merkleRootCanonical` -/ -private def rootAgreementUnits : TestSeq := +private def rootAgreementUnits : LSpec.Spec := do let mkLeaves (n : Nat) : Array Address := Array.range n |>.map fun i => addr s!"leaf-{i}" let check (n : Nat) : Bool := let leaves := mkLeaves n let t := (Ix.AssumptionTree.canonical leaves).get! some t.root == merkleRootCanonical leaves - test "root matches merkleRootCanonical for n=1" (check 1) - ++ test "root matches merkleRootCanonical for n=2" (check 2) - ++ test "root matches merkleRootCanonical for n=3" (check 3) - ++ test "root matches merkleRootCanonical for n=4" (check 4) - ++ test "root matches merkleRootCanonical for n=5" (check 5) - ++ test "root matches merkleRootCanonical for n=7" (check 7) - ++ test "root matches merkleRootCanonical for n=8" (check 8) + itBool "root matches merkleRootCanonical for n=1" (check 1) + itBool "root matches merkleRootCanonical for n=2" (check 2) + itBool "root matches merkleRootCanonical for n=3" (check 3) + itBool "root matches merkleRootCanonical for n=4" (check 4) + itBool "root matches merkleRootCanonical for n=5" (check 5) + itBool "root matches merkleRootCanonical for n=7" (check 7) + itBool "root matches merkleRootCanonical for n=8" (check 8) /-! ## Join agreement -/ -private def joinUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let l := (Ix.AssumptionTree.canonical #[a]).get! - let r := (Ix.AssumptionTree.canonical #[b]).get! - let joined := Ix.AssumptionTree.join l r - test "join root matches merkleJoin" - (joined.root == merkleJoin l.root r.root) +private def joinUnits : LSpec.Spec := do + it "join root matches merkleJoin" do + let a := addr "a" + let b := addr "b" + let l := (Ix.AssumptionTree.canonical #[a]).get! + let r := (Ix.AssumptionTree.canonical #[b]).get! + let joined := Ix.AssumptionTree.join l r + expect (joined.root == merkleJoin l.root r.root) /-! ## Leaves + contains -/ -private def leavesUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - let absent := addr "absent" - let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! - -- Sorted leaves. - let sorted := (#[a, b, c]).qsort fun a b => compare a b == .lt - test "leaves skip padding and yield sorted set" - (t.leaves == sorted) - ++ test "contains true for members" - (t.contains a && t.contains b && t.contains c) - ++ test "contains false for nonmember" - (!t.contains absent) +private def leavesUnits : LSpec.Spec := do + it "leaves skip padding and yield sorted set" do + let a := addr "a" + let b := addr "b" + let c := addr "c" + let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! + let sorted := (#[a, b, c]).qsort fun a b => compare a b == .lt + expect (t.leaves == sorted) + it "contains true for members" do + let a := addr "a" + let b := addr "b" + let c := addr "c" + let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! + expect (t.contains a && t.contains b && t.contains c) + it "contains false for nonmember" do + let a := addr "a" + let b := addr "b" + let c := addr "c" + let absent := addr "absent" + let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! + expect (!t.contains absent) /-! ## Merkle proofs -/ -private def merkleProofUnits : TestSeq := +private def merkleProofUnits : LSpec.Spec := do let mkLeaves (n : Nat) : Array Address := Array.range n |>.map fun i => addr s!"leaf-{i}" let checkAll (n : Nat) : Bool := @@ -89,21 +96,20 @@ private def merkleProofUnits : TestSeq := match t.merkleProof leaf with | none => false | some path => verifyMerkleProof root leaf path - test "single-leaf empty path verifies" + itBool "single-leaf empty path verifies" (let a := addr "x" let t : Ix.AssumptionTree := .leaf a - let ok : Bool := match t.merkleProof a with - | some path => path.isEmpty && verifyMerkleProof t.root a path - | none => false - ok) - ++ test "all leaves prove for n=2" (checkAll 2) - ++ test "all leaves prove for n=3" (checkAll 3) - ++ test "all leaves prove for n=5" (checkAll 5) - ++ test "all leaves prove for n=8" (checkAll 8) - ++ test "nonmember returns none" - (let leaves := mkLeaves 3 - let t := (Ix.AssumptionTree.canonical leaves).get! - t.merkleProof (addr "absent") == none) + match t.merkleProof a with + | some path => path.isEmpty && verifyMerkleProof t.root a path + | none => false) + itBool "all leaves prove for n=2" (checkAll 2) + itBool "all leaves prove for n=3" (checkAll 3) + itBool "all leaves prove for n=5" (checkAll 5) + itBool "all leaves prove for n=8" (checkAll 8) + itBool "nonmember returns none" + (let leaves := mkLeaves 3 + let t := (Ix.AssumptionTree.canonical leaves).get! + t.merkleProof (addr "absent") == none) /-! ## Serialization -/ @@ -113,40 +119,33 @@ private def serdeRoundtrip (t : Ix.AssumptionTree) : Bool := | .ok t' => t == t' | .error _ => false -private def serdeUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let leaf := Ix.AssumptionTree.leaf a - let pad := Ix.AssumptionTree.padding - let nodeLeaves := - Ix.AssumptionTree.node (Ix.AssumptionTree.leaf a) (Ix.AssumptionTree.leaf b) - let canon := (Ix.AssumptionTree.canonical #[a, b, addr "c"]).get! - -- Outer tag byte - let leafBytes := Ix.AssumptionTree.ser leaf - let padBytes := Ix.AssumptionTree.ser pad - let nodeBytes := Ix.AssumptionTree.ser nodeLeaves - test "outer tag byte is 0xE2 (Leaf)" (leafBytes.data[0]! == 0xE2) - ++ test "outer tag byte is 0xE2 (Padding)" (padBytes.data[0]! == 0xE2) - ++ test "outer tag byte is 0xE2 (Node)" (nodeBytes.data[0]! == 0xE2) - ++ test "Leaf body tag is 0x00" (leafBytes.data[1]! == 0x00) - ++ test "Padding body tag is 0x01" (padBytes.data[1]! == 0x01) - ++ test "Node body tag is 0x02" (nodeBytes.data[1]! == 0x02) - ++ test "Leaf total bytes" (leafBytes.size == 1 + 1 + 32) - ++ test "Padding total bytes" (padBytes.size == 2) - ++ test "Node total bytes" (nodeBytes.size == 1 + 1 + (1 + 32) + (1 + 32)) +private def serdeUnits : LSpec.Spec := do + let mkLeaf := fun () => Ix.AssumptionTree.leaf (addr "a") + let mkPad := fun () => Ix.AssumptionTree.padding + let mkNode := fun () => + Ix.AssumptionTree.node (Ix.AssumptionTree.leaf (addr "a")) (Ix.AssumptionTree.leaf (addr "b")) + let mkCanon := fun () => (Ix.AssumptionTree.canonical #[addr "a", addr "b", addr "c"]).get! + itBool "outer tag byte is 0xE2 (Leaf)" ((Ix.AssumptionTree.ser (mkLeaf ())).data[0]! == 0xE2) + itBool "outer tag byte is 0xE2 (Padding)" ((Ix.AssumptionTree.ser (mkPad ())).data[0]! == 0xE2) + itBool "outer tag byte is 0xE2 (Node)" ((Ix.AssumptionTree.ser (mkNode ())).data[0]! == 0xE2) + itBool "Leaf body tag is 0x00" ((Ix.AssumptionTree.ser (mkLeaf ())).data[1]! == 0x00) + itBool "Padding body tag is 0x01" ((Ix.AssumptionTree.ser (mkPad ())).data[1]! == 0x01) + itBool "Node body tag is 0x02" ((Ix.AssumptionTree.ser (mkNode ())).data[1]! == 0x02) + itBool "Leaf total bytes" ((Ix.AssumptionTree.ser (mkLeaf ())).size == 1 + 1 + 32) + itBool "Padding total bytes" ((Ix.AssumptionTree.ser (mkPad ())).size == 2) + itBool "Node total bytes" ((Ix.AssumptionTree.ser (mkNode ())).size == 1 + 1 + (1 + 32) + (1 + 32)) -- Roundtrips - ++ test "roundtrip Leaf" (serdeRoundtrip leaf) - ++ test "roundtrip Padding" (serdeRoundtrip pad) - ++ test "roundtrip Node simple" (serdeRoundtrip nodeLeaves) - ++ test "roundtrip canonical n=3" (serdeRoundtrip canon) + itBool "roundtrip Leaf" (serdeRoundtrip (mkLeaf ())) + itBool "roundtrip Padding" (serdeRoundtrip (mkPad ())) + itBool "roundtrip Node simple" (serdeRoundtrip (mkNode ())) + itBool "roundtrip canonical n=3" (serdeRoundtrip (mkCanon ())) /-! ## Suite -/ -public def Tests.AssumptionTree.suite : List TestSeq := [ - canonicalUnits, - rootAgreementUnits, - joinUnits, - leavesUnits, - merkleProofUnits, - serdeUnits, -] +public def Tests.AssumptionTree.suite : LSpec.Spec := do + canonicalUnits + rootAgreementUnits + joinUnits + leavesUnits + merkleProofUnits + serdeUnits diff --git a/Tests/Ix/BenchMeasures.lean b/Tests/Ix/BenchMeasures.lean index d2c6b65cab..5dc944994a 100644 --- a/Tests/Ix/BenchMeasures.lean +++ b/Tests/Ix/BenchMeasures.lean @@ -15,6 +15,8 @@ public section open LSpec Ix.Cli.BenchCmd +set_option compiler.extract_closed false + namespace Tests.Ix.BenchMeasures def envNames : Array String := (envSpecs.map (·.name)).toArray @@ -22,30 +24,30 @@ def envNames : Array String := (envSpecs.map (·.name)).toArray def constantNames : Array String := Ix.BenchConstants.benchConstants.map (·.name) -def testRows : TestSeq := - test "every shared constant's env is a registry env" +def testRows : LSpec.Spec := do + itBool "every shared constant's env is a registry env" (Ix.BenchConstants.benchConstants.all (envNames.contains ·.env)) - ++ test "every backend has env rows" + itBool "every backend has env rows" (backendSpecs.all (!·.envMetrics.isEmpty)) - ++ test "an env-row measure plots every env" + itBool "an env-row measure plots every env" (backendSpecs.all fun b => b.envMetrics.all fun m => envNames.all (b.benchmarkNames m).contains) - ++ test "a constant-row measure plots every shared constant" + itBool "a constant-row measure plots every shared constant" (backendSpecs.all fun b => b.constantMetrics.all fun m => constantNames.all (b.benchmarkNames m).contains) - ++ test "a measure no row kind carries plots nothing" + itBool "a measure no row kind carries plots nothing" (backendSpecs.all fun b => (b.benchmarkNames "no-such-measure").isEmpty) - ++ test "ixvm and ixvm-ooc have constant rows" + itBool "ixvm and ixvm-ooc have constant rows" (["ixvm", "ixvm-ooc"].all fun n => ((findBackend n).map (·.hasConstants)).getD false) - ++ test "compile and decompile have only env rows" + itBool "compile and decompile have only env rows" (["compile", "decompile"].all fun n => ((findBackend n).map (!·.hasConstants)).getD false) - ++ test "stage measures plot the row kinds that support them" + itBool "stage measures plot the row kinds that support them" (backendSpecs.all fun b => b.stages.all fun (_, ms) => ms.all fun m => b.benchmarkNames m == constantNames ++ (if b.envStages.any (·.2.contains m) then envNames else #[])) - ++ test "stage measures are tracked" + itBool "stage measures are tracked" (backendSpecs.all fun b => (b.stages ++ b.envStages).all fun (_, ms) => ms.all b.trackedMetrics.contains) - ++ test "backend testbeds are distinct" + itBool "backend testbeds are distinct" ((backendSpecs.map (·.testbed)).eraseDups.length == backendSpecs.length) /-- Results rows: each `(name, fields)` is one row of numeric fields, with @@ -58,176 +60,180 @@ def rowsOf (rows : List (String × List (String × Nat)) ) (status : List (Strin (name, Lean.Json.mkObj (base ++ extra)) open Ix.Cli.BenchReport in -def testCells : TestSeq := +def testCells : LSpec.Spec := do let cell := fun (b p : Nat) (metric : String) => metricCells (rowsOf [("Nat.add_comm", [(metric, b)])]) (rowsOf [("Nat.add_comm", [(metric, p)])]) "Nat.add_comm" metric 3.0 - test "a slower run past 3% is a regression" + itBool "a slower run past 3% is a regression" (let (text, bad, good) := cell 100 110 "check-time" text == #["1m 40.0s", "1m 50.0s", "+10.0% (1.10× slower) ⚠️"] && bad && !good) - ++ test "a faster run past 3% is an improvement" + itBool "a faster run past 3% is an improvement" (let (text, bad, good) := cell 100 96 "check-time" text[2]! == "-4.0% 🟢" && !bad && good) - ++ test "a change within 3% is unmarked" + itBool "a change within 3% is unmarked" (let (text, bad, good) := cell 100 102 "check-time" text[2]! == "+2.0%" && !bad && !good) - ++ test "a change of 5% or more names its factor in the metric's terms" + itBool "a change of 5% or more names its factor in the metric's terms" ((cell 100 50 "check-time").1[2]! == "-50.0% (2.00× faster) 🟢" && (metricCells (rowsOf [("Nat.add_comm", [("prove-proof-size", 100)])]) (rowsOf [("Nat.add_comm", [("prove-proof-size", 120)])]) "Nat.add_comm" "prove-proof-size" 3.0).1[2]! == "+20.0% (1.20× larger) ⚠️") - ++ test "trace shards render as counts and more of them is a regression" + itBool "trace shards render as counts and more of them is a regression" ((metricCells (rowsOf [("Nat.add_comm", [("prove-trace-shards", 4)])]) (rowsOf [("Nat.add_comm", [("prove-trace-shards", 6)])]) "Nat.add_comm" "prove-trace-shards" 3.0).1 == #["4", "6", "+50.0% (1.50× more) ⚠️"]) - ++ test "higher throughput is an improvement" + itBool "higher throughput is an improvement" ((cell 100 110 "throughput").2.2) - ++ test "a rejected row renders ❌" + itBool "a rejected row renders ❌" ((metricCells (rowsOf [("Nat.add_comm", [("check-time", 1)])]) (rowsOf [("Nat.add_comm", [])] [("Nat.add_comm", "rejected")]) "Nat.add_comm" "check-time" 3.0).1 == #["1.000 s", "❌", "n/a"]) - ++ test "a crashed row renders a generic failure" + itBool "a crashed row renders a generic failure" ((metricCells (rowsOf [("Nat.add_comm", [("check-time", 1)])]) (rowsOf [("Nat.add_comm", [])] [("Nat.add_comm", "crash")]) "Nat.add_comm" "check-time" 3.0).1 == #["1.000 s", "❌ failed", "n/a"]) - ++ test "an OOM row keeps its measured stages and marks the ones it lost" + itBool "an OOM row keeps its measured stages and marks the ones it lost" (let base := rowsOf [("Nat.add_comm", [("execute-time", 1), ("prove-time", 30)])] let pr := rowsOf [("Nat.add_comm", [("execute-time", 1)])] [("Nat.add_comm", "oom")] (metricCells base pr "Nat.add_comm" "execute-time" 3.0).1[2]! == "+0.0%" && (metricCells base pr "Nat.add_comm" "prove-time" 3.0).1 == #["30.000 s", "❌ OOM", "n/a"]) - ++ test "the env row leads, then its constants in registry order" + itBool "the env row leads, then its constants in registry order" ({ backend := "ixvm", env := "InitStd" base := rowsOf [("Std.HashMap", []), ("InitStd", []), ("Nat.add_comm", [])] : Cell }.rows == #[("InitStd", true), ("Nat.add_comm", false), ("Std.HashMap", false)]) - ++ test "constants without an env row get no env label row" + itBool "constants without an env row get no env label row" ({ backend := "ixvm", env := "InitStd", pr := rowsOf [("Nat.add_comm", [])] : Cell }.rows == #[("Nat.add_comm", false)]) open Ix.Cli.BenchReport in -def testReport : TestSeq := .individualIO "ixvm report: an env table, then a constant table, stages on demand" none (do - let some spec := findBackend "ixvm" | return (false, 0, 0, none) - let base := rowsOf [("InitStd", [("execute-time", 40)]), ("Nat.add_comm", [("execute-time", 1)])] - let pr := rowsOf [("InitStd", [("execute-time", 41)]), ("Nat.add_comm", [("execute-time", 1)])] - let plain ← renderBackend spec #[{ backend := "ixvm", env := "InitStd", base, pr }] 3.0 "main" - let lines := plain.splitOn "\n" - let envAt := lines.findIdx? (·.startsWith "| InitStd |") - let constAt := lines.findIdx? (·.startsWith "| `Nat.add_comm` |") - let envHead := lines.findIdx? (· == "#### `ixvm` · envs") - let constHead := lines.findIdx? (· == "#### `ixvm` · constants") - let proved := rowsOf [("Nat.add_comm", [("execute-time", 1), ("prove-time", 30)])] - let staged ← renderBackend spec - #[{ backend := "ixvm", env := "InitStd", base := proved, pr := proved }] 3.0 "main" - let whole := rowsOf [("Init", [("prove-time", 30), ("e2e-time", 40)])] - let envStages ← renderBackend spec - #[{ backend := "ixvm", env := "Init", base := whole, pr := whole }] 3.0 "main" - let ok := plain.startsWith "### `ixvm`" - && (match envHead, envAt, constHead, constAt with - | some eh, some e, some ch, some c => eh < e && e < ch && ch < c - | _, _, _, _ => false) - && (plain.splitOn "| env | execute-time (main)").length == 2 - && (plain.splitOn "| constant | execute-time (main)").length == 2 - && (plain.splitOn "· prove").length == 1 - && (staged.splitOn "#### `ixvm` · prove").length == 2 - && (staged.splitOn "| constant | prove-time (main) | prove-time (PR) | Δ% |\n").length == 2 - && (plain.splitOn "check-time").length == 1 - && (envStages.splitOn "#### `ixvm` · env prove").length == 2 - && (envStages.splitOn "#### `ixvm` · env e2e").length == 2 - && (envStages.splitOn "| env | prove-time (main)").length == 2 - return (ok, 0, 0, if ok then none else some plain)) .done +def testReport : LSpec.Spec := do + it "ixvm report: an env table, then a constant table, stages on demand" do + let some spec := findBackend "ixvm" | fail "missing ixvm backend" + let base := rowsOf [("InitStd", [("execute-time", 40)]), ("Nat.add_comm", [("execute-time", 1)])] + let pr := rowsOf [("InitStd", [("execute-time", 41)]), ("Nat.add_comm", [("execute-time", 1)])] + let plain ← renderBackend spec #[{ backend := "ixvm", env := "InitStd", base, pr }] 3.0 "main" + let lines := plain.splitOn "\n" + let envAt := lines.findIdx? (·.startsWith "| InitStd |") + let constAt := lines.findIdx? (·.startsWith "| `Nat.add_comm` |") + let envHead := lines.findIdx? (· == "#### `ixvm` · envs") + let constHead := lines.findIdx? (· == "#### `ixvm` · constants") + let proved := rowsOf [("Nat.add_comm", [("execute-time", 1), ("prove-time", 30)])] + let staged ← renderBackend spec + #[{ backend := "ixvm", env := "InitStd", base := proved, pr := proved }] 3.0 "main" + let whole := rowsOf [("Init", [("prove-time", 30), ("e2e-time", 40)])] + let envStages ← renderBackend spec + #[{ backend := "ixvm", env := "Init", base := whole, pr := whole }] 3.0 "main" + let ok := plain.startsWith "### `ixvm`" + && (match envHead, envAt, constHead, constAt with + | some eh, some e, some ch, some c => eh < e && e < ch && ch < c + | _, _, _, _ => false) + && (plain.splitOn "| env | execute-time (main)").length == 2 + && (plain.splitOn "| constant | execute-time (main)").length == 2 + && (plain.splitOn "· prove").length == 1 + && (staged.splitOn "#### `ixvm` · prove").length == 2 + && (staged.splitOn "| constant | prove-time (main) | prove-time (PR) | Δ% |\n").length == 2 + && (plain.splitOn "check-time").length == 1 + && (envStages.splitOn "#### `ixvm` · env prove").length == 2 + && (envStages.splitOn "#### `ixvm` · env e2e").length == 2 + && (envStages.splitOn "| env | prove-time (main)").length == 2 + expect ok plain open Ix.Cli.BenchReport in -def testFftCost : TestSeq := .individualIO "ixvm tables show the FFT cost on both row kinds" none (do - let some spec := findBackend "ixvm" | return (false, 0, 0, none) - let rows := fun (env c : Nat) => rowsOf [ - ("InitStd", [("execute-time", 40), ("peak-rss", 1), ("shards", 12), ("fft-cost", env)]), - ("Nat.add_comm", [("execute-time", 1), ("peak-rss", 1), ("fft-cost", c)])] - let text ← renderBackend spec - #[{ backend := "ixvm", env := "InitStd", base := rows 100000000000 390000000, pr := rows 100000000000 400000000 }] - 3.0 "main" - let ok := (text.splitOn "| env-shards (main) | env-shards (PR) | Δ% | fft-cost (main) |").length == 2 - && (text.splitOn "| `Nat.add_comm` | 1.000 s | 1.000 s | +0.0% | 1 B | 1 B | +0.0% | 390.00M | 400.00M | +2.6% |").length == 2 - return (ok, 0, 0, if ok then none else some text)) .done +def testFftCost : LSpec.Spec := do + it "ixvm tables show the FFT cost on both row kinds" do + let some spec := findBackend "ixvm" | fail "missing ixvm backend" + let rows := fun (env c : Nat) => rowsOf [ + ("InitStd", [("execute-time", 40), ("peak-rss", 1), ("shards", 12), ("fft-cost", env)]), + ("Nat.add_comm", [("execute-time", 1), ("peak-rss", 1), ("fft-cost", c)])] + let text ← renderBackend spec + #[{ backend := "ixvm", env := "InitStd", base := rows 100000000000 390000000, pr := rows 100000000000 400000000 }] + 3.0 "main" + let ok := (text.splitOn "| env-shards (main) | env-shards (PR) | Δ% | fft-cost (main) |").length == 2 + && (text.splitOn "| `Nat.add_comm` | 1.000 s | 1.000 s | +0.0% | 1 B | 1 B | +0.0% | 390.00M | 400.00M | +2.6% |").length == 2 + expect ok text open Ix.Cli.BenchReport in -def testThroughput : TestSeq := .individualIO "every measure gets columns, throughputs improve upward" none (do - let some spec := findBackend "ixvm" | return (false, 0, 0, none) - let rows := fun (t : Nat) => rowsOf [ - ("InitStd", [("execute-time", 40), ("throughput", t), ("peak-rss", 1), ("shards", 12), - ("fft-cost", 100)]), - ("Nat.add_comm", [("execute-time", 1), ("prove-time", 30), ("prove-throughput", t)])] - let text ← renderBackend spec - #[{ backend := "ixvm", env := "InitStd", base := rows 100, pr := rows 110 }] 3.0 "main" - let ok := (text.splitOn "| env | execute-time (main) | execute-time (PR) | Δ% | throughput (const/s) (main) | throughput (const/s) (PR) | Δ% | peak-ram (main) | peak-ram (PR) | Δ% | env-shards (main) | env-shards (PR) | Δ% | fft-cost (main) | fft-cost (PR) | Δ% |").length == 2 - && (text.splitOn "more metrics").length == 1 - && (text.splitOn "| prove-throughput (const/s) (main) |").length == 2 - && (text.splitOn "+10.0% (1.10× faster) 🟢").length == 3 - return (ok, 0, 0, if ok then none else some text)) .done +def testThroughput : LSpec.Spec := do + it "every measure gets columns, throughputs improve upward" do + let some spec := findBackend "ixvm" | fail "missing ixvm backend" + let rows := fun (t : Nat) => rowsOf [ + ("InitStd", [("execute-time", 40), ("throughput", t), ("peak-rss", 1), ("shards", 12), + ("fft-cost", 100)]), + ("Nat.add_comm", [("execute-time", 1), ("prove-time", 30), ("prove-throughput", t)])] + let text ← renderBackend spec + #[{ backend := "ixvm", env := "InitStd", base := rows 100, pr := rows 110 }] 3.0 "main" + let ok := (text.splitOn "| env | execute-time (main) | execute-time (PR) | Δ% | throughput (const/s) (main) | throughput (const/s) (PR) | Δ% | peak-ram (main) | peak-ram (PR) | Δ% | env-shards (main) | env-shards (PR) | Δ% | fft-cost (main) | fft-cost (PR) | Δ% |").length == 2 + && (text.splitOn "more metrics").length == 1 + && (text.splitOn "| prove-throughput (const/s) (main) |").length == 2 + && (text.splitOn "+10.0% (1.10× faster) 🟢").length == 3 + expect ok text open Ix.Cli.BenchReport in -def testRowKinds : TestSeq := .individualIO "a row shows and compares only its kind's measures" none (do - let some ooc := findBackend "ixvm-ooc" | return (false, 0, 0, none) - -- The constant rows share one process's peak RSS, which ixvm-ooc does not - -- compare per constant. - let shared := rowsOf [("Nat.add_comm", [("check-time", 5), ("peak-rss", 100)])] - let grew := rowsOf [("Nat.add_comm", [("check-time", 5), ("peak-rss", 200)])] - let oocText ← renderBackend ooc - #[{ backend := "ixvm-ooc", env := "InitStd", base := shared, pr := grew }] 3.0 "main" - let some ixvm := findBackend "ixvm" | return (false, 0, 0, none) - let consts := rowsOf [("Nat.add_comm", [("execute-time", 1)])] - let ixvmText ← renderBackend ixvm - #[{ backend := "ixvm", env := "InitStd", base := consts, pr := consts }] 3.0 "main" - let ok := (oocText.splitOn "0 with regressions").length == 2 - && (oocText.splitOn "peak-ram").length == 1 - && (ixvmText.splitOn "shards").length == 1 - return (ok, 0, 0, if ok then none else some (oocText ++ "\n" ++ ixvmText))) .done +def testRowKinds : LSpec.Spec := do + it "a row shows and compares only its kind's measures" do + let some ooc := findBackend "ixvm-ooc" | fail "missing ixvm-ooc backend" + -- The constant rows share one process's peak RSS, which ixvm-ooc does not + -- compare per constant. + let shared := rowsOf [("Nat.add_comm", [("check-time", 5), ("peak-rss", 100)])] + let grew := rowsOf [("Nat.add_comm", [("check-time", 5), ("peak-rss", 200)])] + let oocText ← renderBackend ooc + #[{ backend := "ixvm-ooc", env := "InitStd", base := shared, pr := grew }] 3.0 "main" + let some ixvm := findBackend "ixvm" | fail "missing ixvm backend" + let consts := rowsOf [("Nat.add_comm", [("execute-time", 1)])] + let ixvmText ← renderBackend ixvm + #[{ backend := "ixvm", env := "InitStd", base := consts, pr := consts }] 3.0 "main" + let ok := (oocText.splitOn "0 with regressions").length == 2 + && (oocText.splitOn "peak-ram").length == 1 + && (ixvmText.splitOn "shards").length == 1 + expect ok (oocText ++ "\n" ++ ixvmText) open Ix.Cli.BenchReport in -def testCommands : TestSeq := +def testCommands : LSpec.Spec := do let modes := fun command => (parseCommand command).toOption.map fun parsed => parsed.matrix.map fun cell => let field := fun key => (cell.getObjValAs? String key).toOption.getD "" (field "backend", field "env", field "mode") let selected := " BENCH_CONSTANTS=Nat.add_comm BENCH_ENVS=none" let rejects := fun command => (parseCommand command).toOption.isNone - test "bare ixvm defaults to execution" + itBool "bare ixvm defaults to execution" (modes ("!benchmark ixvm" ++ selected) == some #[ ("ixvm", "InitStd", "execute") ]) - ++ test "ixvm execute selects execution" + itBool "ixvm execute selects execution" (modes ("!benchmark ixvm execute" ++ selected) == some #[ ("ixvm", "InitStd", "execute") ]) - ++ test "ixvm prove selects proving" + itBool "ixvm prove selects proving" (modes ("!benchmark ixvm prove" ++ selected) == some #[ ("ixvm", "InitStd", "prove") ]) - ++ test "ixvm compress selects compression" + itBool "ixvm compress selects compression" (modes ("!benchmark ixvm compress" ++ selected) == some #[ ("ixvm", "InitStd", "compress") ]) - ++ test "the ixvm mode does not apply to other backends" + itBool "the ixvm mode does not apply to other backends" (modes ("!benchmark ixvm compress ixvm-ooc" ++ selected) == some #[ ("ixvm", "InitStd", "compress"), ("ixvm-ooc", "InitStd", "execute") ]) - ++ test "env-only ixvm cells stay execution-only" + itBool "env-only ixvm cells stay execution-only" (modes "!benchmark ixvm prove BENCH_CONSTANTS=Nat.add_comm BENCH_ENVS=Mathlib" == some #[ ("ixvm", "InitStd", "prove"), ("ixvm", "Mathlib", "execute") ]) - ++ test "all defaults every cell to execution" + itBool "all defaults every cell to execution" ((modes "!benchmark all").any (·.all fun (_, _, mode) => mode == "execute")) - ++ test "all can include an explicit ixvm mode" + itBool "all can include an explicit ixvm mode" ((modes "!benchmark all ixvm compress").any fun cells => cells.any (fun (backend, _, mode) => backend == "ixvm" && mode == "compress") && cells.all (fun (backend, _, mode) => backend == "ixvm" || mode == "execute")) - ++ test "backend and subcommand names are case-insensitive" + itBool "backend and subcommand names are case-insensitive" (modes ("!benchmark IXVM PROVE" ++ selected) == some #[ ("ixvm", "InitStd", "prove") ]) - ++ test "a mode must follow ixvm" + itBool "a mode must follow ixvm" (["!benchmark prove ixvm", "!benchmark ixvm-ooc prove", "!benchmark all compress"].all rejects) - ++ test "conflicting or repeated modes are rejected" + itBool "conflicting or repeated modes are rejected" (["!benchmark ixvm prove compress", "!benchmark ixvm prove ixvm compress"].all rejects) - ++ test "a misspelled mode is rejected" + itBool "a misspelled mode is rejected" (rejects "!benchmark ixvm proev") - ++ test "proving and compression require constant rows" + itBool "proving and compression require constant rows" (["!benchmark ixvm prove BENCH_CONSTANTS=none", "!benchmark ixvm compress BENCH_CONSTANTS=none"].all rejects) - ++ test "stage environment settings are rejected inline and on later lines" + itBool "stage environment settings are rejected inline and on later lines" (["!benchmark ixvm BENCH_PROVE=1", "!benchmark ixvm BENCH_COMPRESS=kzg", "!benchmark ixvm\nBENCH_PROVE=1", "!benchmark ixvm\nBENCH_COMPRESS=kzg"].all rejects) - ++ test "compress reports the complete pipeline and only forwards unrelated settings" + itBool "compress reports the complete pipeline and only forwards unrelated settings" ((parseCommand "!benchmark ixvm compress RUST_LOG=debug").toOption.any fun parsed => (parsed.summary.splitOn "stages `execute+prove+compress`").length == 2 && parsed.passthrough == #["RUST_LOG=debug"]) - ++ test "fresh applies to every backend and retains the ixvm mode" + itBool "fresh applies to every backend and retains the ixvm mode" ((parseCommand "!benchmark ixvm compress ixvm-ooc fresh").toOption.any fun parsed => parsed.fresh && parsed.passthrough.isEmpty && (parsed.summary.splitOn "baseline `fresh`").length == 2 && @@ -235,27 +241,27 @@ def testCommands : TestSeq := (cell.getObjValAs? String "mode").toOption == some (if (cell.getObjValAs? String "backend").toOption == some "ixvm" then "compress" else "execute"))) - ++ test "fresh is case-insensitive and works with all" + itBool "fresh is case-insensitive and works with all" ((parseCommand "!benchmark all FRESH").toOption.any (·.fresh)) - ++ test "ordinary requests retain cache reuse" + itBool "ordinary requests retain cache reuse" ((parseCommand "!benchmark ixvm execute").toOption.any (!·.fresh)) - ++ test "fresh alone does not select a backend" + itBool "fresh alone does not select a backend" (rejects "!benchmark fresh") - ++ test "with neither key set, every shared constant and the InitStd env row run" + itBool "with neither key set, every shared constant and the InitStd env row run" ((parseCommand "!benchmark ixvm").toOption.any fun parsed => parsed.matrix.any (fun cell => (cell.getObjValAs? String "env-row").toOption == some "1") && parsed.matrix.size == 2) - ++ test "BENCH_CONSTANTS alone selects no env rows" + itBool "BENCH_CONSTANTS alone selects no env rows" ((parseCommand "!benchmark ixvm BENCH_CONSTANTS=Nat.add_comm").toOption.any fun parsed => parsed.matrix.size == 1 && parsed.matrix.all (fun cell => (cell.getObjValAs? String "env-row").toOption == some "0")) - ++ test "BENCH_ENVS alone selects no constant rows" + itBool "BENCH_ENVS alone selects no constant rows" ((parseCommand "!benchmark ixvm\nBENCH_ENVS=Mathlib").toOption.any fun parsed => parsed.matrix.size == 1 && parsed.matrix.all (fun cell => (cell.getObjValAs? String "constants").toOption == some "none")) - ++ test "proving with only env rows selected is rejected" + itBool "proving with only env rows selected is rejected" (rejects "!benchmark ixvm prove BENCH_ENVS=InitStd") - ++ test "proving with neither key set selects only Nat.add_comm" + itBool "proving with neither key set selects only Nat.add_comm" (["!benchmark ixvm prove", "!benchmark ixvm compress"].all fun c => modes c == some #[ ("ixvm", "InitStd", c.splitOn " " |>.getLast!) ] && (parseCommand c).toOption.any fun parsed => @@ -263,51 +269,59 @@ def testCommands : TestSeq := (cell.getObjValAs? String "constants").toOption == some "Nat.add_comm" && (cell.getObjValAs? String "env-row").toOption == some "0")) -def testRunMode : TestSeq := .individualIO "invalid run modes fail before starting measured tools" none (do - let mut ok := true - for args in [["--backend", "ixvm", "--mode", "unknown"], - ["--backend", "ixvm-ooc", "--mode", "prove"], - ["--backend", "ixvm", "--mode", "compress", "--constants", "none"], - ["--backend", "ixvm", "--env-mode", "unknown"], - ["--backend", "compile", "--env-mode", "prove"], - ["--backend", "ixvm", "--env-mode", "prove", "--no-env-row"], - ["--backend", "ixvm", "--gpu-device", "0"], - ["--backend", "ixvm", "--env-mode", "prove", "--env-dev-srs"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "chain.json"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "kzg", "--aiur-chain", "chain.json"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "chain.json", "--aiur-gl", "gl.ixa"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "unknown"]] do - let (_, code) ← IO.FS.withIsolatedStreams (benchRunCmd.validate args) - ok := ok && code == 2 - return (ok, 0, 0, none)) .done +def testRunMode : LSpec.Spec := do + it "invalid run modes fail before starting measured tools" do + let mut ok := true + for args in [["--backend", "ixvm", "--mode", "unknown"], + ["--backend", "ixvm-ooc", "--mode", "prove"], + ["--backend", "ixvm", "--mode", "compress", "--constants", "none"], + ["--backend", "ixvm", "--env-mode", "unknown"], + ["--backend", "compile", "--env-mode", "prove"], + ["--backend", "ixvm", "--env-mode", "prove", "--no-env-row"], + ["--backend", "ixvm", "--gpu-device", "0"], + ["--backend", "ixvm", "--env-mode", "prove", "--env-dev-srs"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "chain.json"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "kzg", "--aiur-chain", "chain.json"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "chain.json", "--aiur-gl", "gl.ixa"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "unknown"]] do + let (_, code) ← IO.FS.withIsolatedStreams (benchRunCmd.validate args) + ok := ok && code == 2 + expect ok -def testEnvProofOptions : TestSeq := +def testEnvProofOptions : LSpec.Spec := do let options := fun (args : List String) => do let (_, parsed) ← (benchRunCmd.parse ("--backend" :: "ixvm" :: args)).toOption (envProofOptions parsed "ixvm" true).toOption - test "whole-env proving is explicitly selected without constant rows" + itBool "whole-env proving is explicitly selected without constant rows" ((options ["--env", "Init", "--constants", "none", "--env-mode", "prove"]).any fun opts => opts.mode == .prove && opts.hostArgs.isEmpty && !opts.development) - ++ test "whole-env compression defaults to production PLONK" + itBool "whole-env compression defaults to production PLONK" ((options ["--env-mode", "compress"]).any fun opts => opts.compressArgs == #["--plonk"]) - ++ test "development PLONK selects both development setups" + itBool "development PLONK selects both development setups" ((options ["--env-mode", "compress", "--env-dev-srs"]).any fun opts => opts.compressArgs == #["--plonk", "--dev-kzg-srs", "--dev-final-srs"]) - ++ test "KZG and GPU configuration reach the measured tools" + itBool "KZG and GPU configuration reach the measured tools" ((options ["--env-mode", "compress", "--env-compression", "kzg", "--env-dev-srs", "--gpu-device", "0", "--max-ram", "200"]).any fun opts => opts.compressArgs == #["--dev-kzg-srs"] && opts.hostArgs == #["--gpu-device", "0", "--max-ram", "200"]) - ++ test "Aiur BN forwards only the independently selected chain manifest" + itBool "Aiur BN forwards only the independently selected chain manifest" ((options ["--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "trusted-chain.json", "--aiur-chain-blake3", "expected-pin", "--env-dev-srs"]).any fun opts => opts.aiurArgs == #["--aiur-chain", "trusted-chain.json", "--aiur-chain-blake3", "expected-pin"] && opts.compressArgs == #["--dev-kzg-srs", "--aiur-chain", "trusted-chain.json", "--aiur-chain-blake3", "expected-pin"]) -def suite : List TestSeq := - [testRows, testCells, testReport, testFftCost, testThroughput, testRowKinds, testCommands, - testRunMode, testEnvProofOptions] +def suite : LSpec.Spec := do + testRows + testCells + testReport + testFftCost + testThroughput + testRowKinds + testCommands + testRunMode + testEnvProofOptions end Tests.Ix.BenchMeasures diff --git a/Tests/Ix/Catalog.lean b/Tests/Ix/Catalog.lean index ae59e11f72..9af567cfaf 100644 --- a/Tests/Ix/Catalog.lean +++ b/Tests/Ix/Catalog.lean @@ -40,6 +40,8 @@ public section open LSpec +set_option compiler.extract_closed false + namespace Tests.Ix.Catalog @[extern "rs_env_section_counts"] @@ -118,7 +120,7 @@ private def compilePieceToFile (consts : List (Lean.Name × Lean.ConstantInfo)) /-- The end-to-end fixture gate: compile two overlapping pieces, assemble, and pin format parity + identity dedup. -/ -private def assembleParityTest : IO (Bool × Nat × Nat × Option String) := do +private def assembleParityTest : AssertM Unit := do let dir ← IO.FS.createTempDir try -- Piece A: base + idA. Piece B: base + idA + idB (A ⊂ B content). @@ -139,16 +141,12 @@ private def assembleParityTest : IO (Bool × Nat × Nat × Option String) := do ("deps", Lean.Json.arr #[Lean.toJson (0 : Nat)])] ] let summary ← Ix.Cli.CatalogCmd.rsCatalogAssembleFFI ixcDir.toString members.compress - let json ← match Lean.Json.parse summary with - | .ok j => pure j - | .error e => return (false, 0, 0, some s!"assemble JSON: {e}") + let json ← expectOk ((Lean.Json.parse summary).mapError (s!"assemble JSON: {·}")) unless (← (ixcDir / "A.ixe").pathExists) do - return (false, 0, 0, some "piece not ingested into the .ixc dir") + fail "piece not ingested into the .ixc dir" -- Lean mirror: parse the Rust-written manifest inside the dir. let bytes ← IO.FS.readBinFile (ixcDir / "manifest") - let cat ← match Ix.Catalog.de bytes with - | .ok c => pure c - | .error e => return (false, 0, 0, some s!"Lean mirror de: {e}") + let cat ← expectOk ((Ix.Catalog.de bytes).mapError (s!"Lean mirror de: {·}")) let checks : List (String × Bool) := [ -- Byte-identity: Lean ser ∘ de reproduces the Rust bytes. ("mirror re-serializes byte-identical", @@ -166,16 +164,13 @@ private def assembleParityTest : IO (Bool × Nat × Nat × Option String) := do toString cat.members[0]!.envRoot == rootA), ("deps carried", cat.members[1]!.deps == #[0]), ("fat profile", !(cat.storage matches .chunked _)) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => - return (true, cat.members[0]!.constCount.toNat, - cat.members[1]!.constCount.toNat, none) + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" finally IO.FS.removeDirAll dir /-- Strict-anon compile: §5 empty, §3 survives, root unmoved. -/ -private def anonCompileTest : IO (Bool × Nat × Nat × Option String) := do +private def anonCompileTest : AssertM Unit := do let dir ← IO.FS.createTempDir try let consts ← fixtureConsts [defnOver `TCat.idA 1] @@ -187,12 +182,8 @@ private def anonCompileTest : IO (Bool × Nat × Nat × Option String) := do match Lean.Json.parse (← rsEnvSectionCountsFFI path) with | .ok j => return .ok j | .error e => return .error e - let cNamed ← match ← countsOf named with - | .ok j => pure j - | .error e => return (false, 0, 0, some s!"counts(named): {e}") - let cAnon ← match ← countsOf anon with - | .ok j => pure j - | .error e => return (false, 0, 0, some s!"counts(anon): {e}") + let cNamed ← expectOk ((← countsOf named).mapError (s!"counts(named): {·}")) + let cAnon ← expectOk ((← countsOf anon).mapError (s!"counts(anon): {·}")) let checks : List (String × Bool) := [ ("roots equal (anon-invariance)", rootNamed == rootAnon), ("named piece carries §5", (num cNamed "named").getD 0 > 0), @@ -204,10 +195,8 @@ private def anonCompileTest : IO (Bool × Nat × Nat × Option String) := do ("§3 hints survive --anon", (num cAnon "hints").getD 0 > 0 && num cAnon "hints" == num cNamed "hints") ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, (num cAnon "consts").getD 0, - (num cAnon "hints").getD 0, none) + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" finally IO.FS.removeDirAll dir @@ -227,10 +216,10 @@ private def fatOf (members : Array Ix.Catalog.Member) : Ix.Catalog.Catalog := members storage := .fat (members.map fun m => ⟨addr s!"f{m.label}", 10⟩) } -private def fatCat : Ix.Catalog.Catalog := +private def mkFatCat (_ : Unit) : Ix.Catalog.Catalog := fatOf #[member "A" (addr "rootA"), member "B" (addr "rootB") #[0] (some (addr "pre"))] -private def chunkedCat : Ix.Catalog.Catalog := +private def mkChunkedCat (_ : Unit) : Ix.Catalog.Catalog := let members := #[member "A" (addr "rootA")] { membersRoot := Ix.Catalog.membersRootOf members contentRoot := addr "content" @@ -260,34 +249,34 @@ private def setByte (i : Nat) (v : UInt8) (b : ByteArray) : ByteArray := /-- The offset of the first member's preimage tag in `fatCat`'s bytes: the fixed header (magic, version, flags, scope, two roots, the member count), then the member up to its last byte. -/ -private def firstPreimageTag : Nat := +private def firstPreimageTag (fatCat : Ix.Catalog.Catalog) : Nat := 8 + 4 + 4 + 2 + 32 + 32 + 4 + (Ixon.runPut (Ix.Catalog.putMember fatCat.members[0]!)).size - 1 /-- Malformed manifests, each with a phrase that both readers' refusals contain (an empty phrase: any refusal). -/ -private def malformed : List (String × ByteArray × String) := - let good := serOk fatCat - [ ("bad magic", setByte 0 0xFF good, "magic"), - ("legacy version", setByte 8 1 good, "version"), - ("unknown flags", setByte 12 0xFF good, "flags"), - ("other object format", setByte 16 3 good, "format"), - ("resource validator", setByte 17 2 good, "validator"), - ("members_root drift", setByte (8 + 4 + 4 + 2) 0xFF good, "members_root"), - ("truncated", good.extract 0 (good.size - 1), ""), - ("trailing byte", good.push 0, "trailing"), - ("preimage tag 2", setByte firstPreimageTag 2 good, "preimage tag"), - ("one env root twice", +private def malformedSpecs : List (String × (Unit → ByteArray) × String) := + [ ("bad magic", fun () => setByte 0 0xFF (serOk (mkFatCat ())), "magic"), + ("legacy version", fun () => setByte 8 1 (serOk (mkFatCat ())), "version"), + ("unknown flags", fun () => setByte 12 0xFF (serOk (mkFatCat ())), "flags"), + ("other object format", fun () => setByte 16 3 (serOk (mkFatCat ())), "format"), + ("resource validator", fun () => setByte 17 2 (serOk (mkFatCat ())), "validator"), + ("members_root drift", fun () => setByte (8 + 4 + 4 + 2) 0xFF (serOk (mkFatCat ())), "members_root"), + ("truncated", fun () => let g := serOk (mkFatCat ()); g.extract 0 (g.size - 1), ""), + ("trailing byte", fun () => (serOk (mkFatCat ())).push 0, "trailing"), + ("preimage tag 2", fun () => + let fc := mkFatCat (); setByte (firstPreimageTag fc) 2 (serOk fc), "preimage tag"), + ("one env root twice", fun () => serOk (fatOf #[member "A" (addr "rootA"), member "B" (addr "rootA")]), "duplicate member env root"), - ("one label twice", + ("one label twice", fun () => serOk (fatOf #[member "A" (addr "rootA"), member "A" (addr "rootB")]), "duplicate member label"), - ("dependency not before its member", + ("dependency not before its member", fun () => serOk (fatOf #[member "A" (addr "rootA") #[0]]), "strictly before"), - ("path-traversal label", + ("path-traversal label", fun () => serOk (fatOf #[member "../evil" (addr "rootA")]), "bare filename"), - ("chunk owner out of range", - serOk { chunkedCat with storage := .chunked #[⟨addr "c0", addr "f0", 5, 1⟩] }, + ("chunk owner out of range", fun () => + serOk { mkChunkedCat () with storage := .chunked #[⟨addr "c0", addr "f0", 5, 1⟩] }, "out of range") ] private def deFails (bytes : ByteArray) (needle : String) : Bool := @@ -296,29 +285,30 @@ private def deFails (bytes : ByteArray) (needle : String) : Bool := | .error e => contains e needle /-- A string the writer's `u16` length cannot carry. -/ -private def oversized : String := String.ofList (List.replicate 65536 'x') - -def unitTests : TestSeq := - test "fat catalog roundtrips" (roundtrips fatCat) - ++ test "chunked catalog roundtrips" (roundtrips chunkedCat) - ++ test "the first member's preimage tag is where the malformed cases set it" - ((serOk fatCat)[firstPreimageTag]! == 0) - ++ malformed.foldl (init := .done) fun acc (what, bytes, needle) => - acc ++ test s!"{what} rejected" (deFails bytes needle) - ++ test "writer refuses a source pin over 64 KiB" - (Ix.Catalog.ser (fatOf #[{ member "A" (addr "rootA") with sourcePin := oversized }]) - matches .error _) - ++ test "writer accepts a source pin of exactly 64 KiB - 1" - (Ix.Catalog.ser (fatOf #[{ member "A" (addr "rootA") with - sourcePin := String.ofList (List.replicate 65535 'x') }]) matches .ok _) - ++ test "writer refuses a fat catalog without one storage row per member" - (Ix.Catalog.ser { fatCat with storage := .fat #[] } matches .error _) - ++ test "bare label accepted" - (Ix.Catalog.validateLabel "Mathlib" matches .ok _) +private def mkOversized (_ : Unit) : String := String.ofList (List.replicate 65536 'x') + +def unitTests : LSpec.Spec := do + itBool "fat catalog roundtrips" (roundtrips (mkFatCat ())) + itBool "chunked catalog roundtrips" (roundtrips (mkChunkedCat ())) + it "the first member's preimage tag is where the malformed cases set it" do + let fc := mkFatCat () + expect ((serOk fc)[firstPreimageTag fc]! == 0) + for (what, mkBytes, needle) in malformedSpecs do + itBool s!"{what} rejected" (deFails (mkBytes ()) needle) + itBool "writer refuses a source pin over 64 KiB" + (Ix.Catalog.ser (fatOf #[{ member "A" (addr "rootA") with sourcePin := mkOversized () }]) + matches .error _) + itBool "writer accepts a source pin of exactly 64 KiB - 1" + (Ix.Catalog.ser (fatOf #[{ member "A" (addr "rootA") with + sourcePin := String.ofList (List.replicate 65535 'x') }]) matches .ok _) + itBool "writer refuses a fat catalog without one storage row per member" + (Ix.Catalog.ser { mkFatCat () with storage := .fat #[] } matches .error _) + itBool "bare label accepted" + (Ix.Catalog.validateLabel "Mathlib" matches .ok _) /-- Reject parity: the Lean mirror and the Rust reader (`rs_catalog_info`) refuse the same malformed manifests, and accept the well-formed one. -/ -private def rejectParityTest : IO (Bool × Nat × Nat × Option String) := do +private def rejectParityTest : AssertM Unit := do let dir ← IO.FS.createTempDir try let write (name : String) (bytes : ByteArray) : IO String := do @@ -326,44 +316,47 @@ private def rejectParityTest : IO (Bool × Nat × Nat × Option String) := do IO.FS.createDirAll ixc IO.FS.writeBinFile (ixc / "manifest") bytes return ixc.toString - let good ← write "good" (serOk fatCat) - try - discard <| Ix.Cli.CatalogCmd.rsCatalogInfoFFI good - catch e => return (false, 0, 0, some s!"Rust refuses the well-formed manifest: {e}") - unless Ix.Catalog.de (serOk fatCat) matches .ok _ do - return (false, 0, 0, some "Lean refuses the well-formed manifest") + let goodBytes := serOk (mkFatCat ()) + let good ← write "good" goodBytes + let goodRust : Option String ← liftM (m := IO) do + try + discard <| Ix.Cli.CatalogCmd.rsCatalogInfoFFI good + pure none + catch e => pure (some (toString e)) + if let some e := goodRust then + fail s!"Rust refuses the well-formed manifest: {e}" + unless Ix.Catalog.de goodBytes matches .ok _ do + fail "Lean refuses the well-formed manifest" let mut i := 0 - for (what, bytes, needle) in malformed do + for (what, mkBytes, needle) in malformedSpecs do i := i + 1 + let bytes := mkBytes () let ixc ← write s!"bad{i}" bytes - let rust ← try + let rust : Option String ← liftM (m := IO) do + try discard <| Ix.Cli.CatalogCmd.rsCatalogInfoFFI ixc pure none catch e => pure (some (toString e)) match rust with - | none => return (false, i, 0, some s!"Rust accepts: {what}") + | none => fail s!"Rust accepts: {what}" | some e => unless contains e needle do - return (false, i, 0, some s!"Rust refuses {what} for another reason: {e}") + fail s!"Rust refuses {what} for another reason: {e}" match Ix.Catalog.de bytes with - | .ok _ => return (false, i, 0, some s!"Lean accepts: {what}") + | .ok _ => fail s!"Lean accepts: {what}" | .error e => unless contains e needle do - return (false, i, 0, some s!"Lean refuses {what} for another reason: {e}") - return (true, i, 0, none) + fail s!"Lean refuses {what} for another reason: {e}" finally IO.FS.removeDirAll dir -def suite : List TestSeq := [ - unitTests, - .individualIO - "assemble parity: Rust .ixc ↔ Lean mirror byte-identical, dedup observed" - none assembleParityTest .done, - .individualIO - "reject parity: Lean and Rust refuse the same malformed manifests" - none rejectParityTest .done, - .individualIO - "strict-anon compile: §5 empty, §3 survives, root unmoved" - none anonCompileTest .done ] +def suite : LSpec.Spec := do + unitTests + it "assemble parity: Rust .ixc ↔ Lean mirror byte-identical, dedup observed" + assembleParityTest + it "reject parity: Lean and Rust refuse the same malformed manifests" + rejectParityTest + it "strict-anon compile: §5 empty, §3 survives, root unmoved" + anonCompileTest end Tests.Ix.Catalog diff --git a/Tests/Ix/CatalogDedup.lean b/Tests/Ix/CatalogDedup.lean index 9097ba08d7..89890b74f8 100644 --- a/Tests/Ix/CatalogDedup.lean +++ b/Tests/Ix/CatalogDedup.lean @@ -51,12 +51,12 @@ private def compilePiece (exe : System.FilePath) (driver out : String) : {r.stderr.take 300} … {(r.stdout.takeEnd 300).toString}" return .ok () -private def dedupTest : IO (Bool × Nat × Nat × Option String) := do +private def dedupTest : AssertM Unit := do unless (← ixExe.pathExists) do - return (false, 0, 0, some s!"{ixExe} missing — run `lake build ix` first") + fail s!"{ixExe} missing — run `lake build ix` first" for fixture in [fixtureA, fixtureB] do unless (← fixture.pathExists) do - return (false, 0, 0, some s!"fixture source missing: {fixture}") + fail s!"fixture source missing: {fixture}" let exe ← IO.FS.realPath ixExe let dir ← IO.FS.createTempDir try @@ -67,10 +67,8 @@ private def dedupTest : IO (Bool × Nat × Nat × Option String) := do let taskB ← IO.asTask (prio := .dedicated) (compilePiece exe fixtureB.toString pieceB) let resA ← IO.wait taskA let resB ← IO.wait taskB - if let .error e ← IO.ofExcept resA then - return (false, 0, 0, some e) - if let .error e ← IO.ofExcept resB then - return (false, 0, 0, some e) + discard <| expectOk (← IO.ofExcept resA) + discard <| expectOk (← IO.ofExcept resB) -- Assemble the self-contained .ixc dir via the CLI, then gate on -- the manifest through the in-process core (info/verify FFI) — no -- report artifacts anywhere in this flow. @@ -80,8 +78,7 @@ private def dedupTest : IO (Bool × Nat × Nat × Option String) := do args := #["catalog", "assemble", ixc, pieceA, pieceB, "--labels", "A,B"] } if r.exitCode != 0 then - return (false, 0, 0, some s!"assemble failed ({r.exitCode}): \ -{r.stderr.take 300}") + fail s!"assemble failed ({r.exitCode}): {r.stderr.take 300}" let infoContent ← Ix.Cli.CatalogCmd.rsCatalogInfoFFI ixc let verifyContent ← Ix.Cli.CatalogCmd.rsCatalogVerifyFFI ixc false let checks : Except String (Nat × Nat) := do @@ -100,15 +97,11 @@ content got different addresses across processes" throw s!"union {union} not larger than both pieces ({a}, {b}) — \ the collision pair's distinct content collapsed" return (union, a + b) - match checks with - | .ok (union, sum) => return (true, union, sum, none) - | .error m => return (false, 0, 0, some m) + discard <| expectOk checks finally IO.FS.removeDirAll dir -def suite : List TestSeq := [ - .individualIO - "catalog-dedup: cross-process pieces share addresses, collisions coexist" - none dedupTest .done ] +def suite : LSpec.Spec := do + it "catalog-dedup: cross-process pieces share addresses, collisions coexist" dedupTest end Tests.Ix.CatalogDedup diff --git a/Tests/Ix/Cert/Statement.lean b/Tests/Ix/Cert/Statement.lean index 07f92bb0f7..020830e0d5 100644 --- a/Tests/Ix/Cert/Statement.lean +++ b/Tests/Ix/Cert/Statement.lean @@ -1599,12 +1599,12 @@ def hintCase (leanEnv : Lean.Environment) : IO (Array String × Array String) := return (#[s!"hints: refused, but naming {n.pretty}, not a definition at Nat.add's address"], #[]) | none => return (#["hints: the check accepts an artifact with Nat.add's hint erased"], #[]) -def report (name : String) (action : IO (Array String × Array String)) (count : Nat) : TestSeq := - .individualIO name none (do +def report (name : String) (action : IO (Array String × Array String)) (_count : Nat := 1) : Spec := + it name do let (errors, lines) ← action for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, count, 0, msg)) .done + unless errors.isEmpty do + fail ("\n".intercalate errors.toList) initialize fixtureEnvCache : IO.Ref (Option Lean.Environment) ← IO.mkRef none @@ -1614,56 +1614,56 @@ private def fixtureEnv : IO Lean.Environment := do fixtureEnvCache.set (some env) return env -def suite : List TestSeq := [ +def suite : LSpec.Spec := do report "Ix.Cert.compile against the IO pipeline and the Rust compiler, on the fixtures" (do let leanEnv ← fixtureEnv - parity "fixtures" (← fixtureConsts leanEnv) 4) 1, + parity "fixtures" (← fixtureConsts leanEnv) 4) 1 report "an axiom α-equal to sorryAx is published at its address and keyed by its role" (do - sorryAliasCase (← fixtureEnv)) 1, + sorryAliasCase (← fixtureEnv)) 1 report "the statements' hypotheses and conclusion, per root, on the accepted fixtures" (do - perRoot (← fixtureEnv)) 1, + perRoot (← fixtureEnv)) 1 report "CompileCorrect.checked's premises hold on the closures of Nat.add and List.length" (do - Tests.Ix.Cert.ExecutedChecks.checkedCase (← fixtureEnv)) 1, + Tests.Ix.Cert.ExecutedChecks.checkedCase (← fixtureEnv)) 1 report "the evidence check refuses a misbound table and a replaced fallback record" (do - Tests.Ix.Cert.ExecutedChecks.evidenceRefusals (← fixtureEnv)) 1, + Tests.Ix.Cert.ExecutedChecks.evidenceRefusals (← fixtureEnv)) 1 report "annotated source refused on both sides, on the resolved source-contract syntax fixtures" (do - contractAgreement (← getCompileEnv #[syntaxModule])) 1, + contractAgreement (← getCompileEnv #[syntaxModule])) 1 report "the shipped role table's certificates check on their pinned closure (Route A, B6b)" - roleEvidenceCase 1, + roleEvidenceCase 1 report "a closure with a well-founded Nat operation, at the bundle evidence (Nat.div)" (do - natDivClosure (← fixtureEnv)) 1, + natDivClosure (← fixtureEnv)) 1 report "a closure with a string literal holds its literal support (outOfBounds)" (do - literalClosure (← fixtureEnv) `outOfBounds) 1, + literalClosure (← fixtureEnv) `outOfBounds) 1 report "a Nat literal whose bytes are another constant's record is refused (blob check)" - blobRecordCase 1, + blobRecordCase 1 report "a recursor with all = [J] in I's motive slot is refused (recursor check)" (do - recursorFamilyCase (← fixtureEnv)) 1, + recursorFamilyCase (← fixtureEnv)) 1 report "a record of the wrong kind at a bound role's address is refused (role check)" (do - roleKindCase (← fixtureEnv)) 1, + roleKindCase (← fixtureEnv)) 1 report "a copy of Nat without Nat: accepted alone, refused beside a Nat literal" (do - literalRoleCase (← getCompileEnv #[`Tests.Ix.Kernel.TutorialDefs])) 1, + literalRoleCase (← getCompileEnv #[`Tests.Ix.Kernel.TutorialDefs])) 1 report "a recursor rule naming a hash twin of its constructor is refused (inductive input check)" (do - familyNameCase (← fixtureEnv)) 1, + familyNameCase (← fixtureEnv)) 1 report "constructors declaring each other's index are refused (inductive input check)" (do - constructorIndexCase (← fixtureEnv)) 1, + constructorIndexCase (← fixtureEnv)) 1 report "a constructor with its inductive's level parameters reordered is refused (inductive input check)" (do - levelParamsCase (← fixtureEnv)) 1, + levelParamsCase (← fixtureEnv)) 1 report "a recursor with two level parameters too many is refused (inductive input check)" (do - recursorLevelCountCase (← fixtureEnv)) 1, + recursorLevelCountCase (← fixtureEnv)) 1 report "a recursor whose all is not its family's is refused (inductive input check)" (do - familyBlockCase (← fixtureEnv)) 1, + familyBlockCase (← fixtureEnv)) 1 report "two recursors filed at one motive are refused (inductive input check)" (do - recursorSlotCase (← fixtureEnv)) 1, + recursorSlotCase (← fixtureEnv)) 1 report "recursors with each other's types are refused (inductive input check)" (do - recursorShapeCase (← fixtureEnv)) 1, + recursorShapeCase (← fixtureEnv)) 1 report "an artifact with a published definition's hint erased is refused (hint check)" (do - hintCase (← fixtureEnv)) 1] + hintCase (← fixtureEnv)) 1 /-- `cert-evidence-agreement` (landing): the role table's evidence against quotient Source's on the well-founded operations' closure (`evidenceAgreement`); it compiles and reads the closure, so it stays out of the primary tier. -/ -def evidenceSuite : List TestSeq := [ +def evidenceSuite : LSpec.Spec := do report "the role table's evidence against quotient Source's, on the well-founded operations" (do - evidenceAgreement (← fixtureEnv)) 1] + evidenceAgreement (← fixtureEnv)) 1 end Tests.Ix.Cert.Statement diff --git a/Tests/Ix/CircuitMeta.lean b/Tests/Ix/CircuitMeta.lean index 2bd0234abc..88b370cda0 100644 --- a/Tests/Ix/CircuitMeta.lean +++ b/Tests/Ix/CircuitMeta.lean @@ -14,6 +14,8 @@ namespace Tests.Ix.CircuitMeta open Ixon LSpec +set_option compiler.extract_closed false + private def repAddr (b : UInt8) : Address := ⟨⟨(List.replicate 32 b).toArray⟩⟩ @@ -97,7 +99,7 @@ def expectedGoldenSectionBytes : ByteArray := private def patchByte (ba : ByteArray) (idx : Nat) (val : UInt8) : ByteArray := ⟨ba.data.set! idx val⟩ -private def sampleEnv : Env := Id.run do +private def mkSampleEnv (_ : Unit) : Env := Id.run do let defn : Definition := { kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } @@ -116,111 +118,117 @@ private def allFullReadersReject (bytes : ByteArray) : Bool := (rsDeEnv bytes).toOption.isNone && (deEnvAnon bytes).toOption.isNone -public def units : TestSeq := - let secOk : Bool := match CircuitMeta.serSection goldenMeta with - | .ok b => b == expectedGoldenSectionBytes && b.size == 239 - | .error _ => false - let secRoundTrip : Bool := match runGetExact CircuitMeta.getSection expectedGoldenSectionBytes with - | .ok cm => cm == goldenMeta - | .error _ => false - let canonicalSort : Bool := - let reversed : CircuitMeta := { goldenMeta with byAddress := goldenMeta.byAddress.reverse } - match CircuitMeta.serSection reversed with - | .ok b => b == expectedGoldenSectionBytes - | .error _ => false - let dupRejected : Bool := - let dupAddr : CircuitMeta := { goldenMeta with byAddress := goldenMeta.byAddress.push goldenMeta.byAddress[0]! } - let dupFun : CircuitMeta := { goldenMeta with byFun := goldenMeta.byFun.push goldenMeta.byFun[0]! } - let dupGroup : CircuitMeta := { goldenMeta with groups := goldenMeta.groups.push goldenMeta.groups[0]! } - let dupGuess : CircuitMeta := { goldenMeta with guesses := goldenMeta.guesses.push goldenMeta.guesses[0]! } - (CircuitMeta.serSection dupAddr).toOption.isNone && - (CircuitMeta.serSection dupFun).toOption.isNone && - (CircuitMeta.serSection dupGroup).toOption.isNone && - (CircuitMeta.serSection dupGuess).toOption.isNone - let writerInvariants := - let conflictFuel : CircuitMeta := { - byAddress := #[(repAddr 0x01, { fuelParam := some "n", noFuel := true })] - } - let zeroUnroll : CircuitMeta := { - byAddress := #[(repAddr 0x01, { unroll := some 0 })] - } - let zeroLanes : CircuitMeta := { - byAddress := #[(repAddr 0x01, { lanes := some 0 })] - } - let emptyGroup : CircuitMeta := { - byAddress := #[(repAddr 0x01, { group := some "" })] - } - let zeroLimbs : CircuitMeta := { - byAddress := #[(repAddr 0x01, { repr := some (.limbs 0 64) })] - } - let zeroFlat : CircuitMeta := { - byAddress := #[(repAddr 0x01, { repr := some (.flatArray 0) })] - } - [conflictFuel, zeroUnroll, zeroLanes, emptyGroup, zeroLimbs, zeroFlat].all fun cm => - (CircuitMeta.serSection cm).toOption.isNone - - let env := sampleEnv - let plainBytes := (serEnv env).toOption.getD ByteArray.empty - let withMetaBytes := (serEnvWithCircuitMeta env (some goldenMeta)).toOption.getD ByteArray.empty - let appendedBytes := (appendCircuitMetaSection plainBytes goldenMeta).toOption.getD ByteArray.empty - - let prefixIdentical := - !plainBytes.isEmpty && - withMetaBytes == appendedBytes && - withMetaBytes.size == plainBytes.size + expectedGoldenSectionBytes.size && - withMetaBytes.extract 0 plainBytes.size == plainBytes - - let fullDecodeOk := - match deEnvWithCircuitMeta withMetaBytes, deEnv withMetaBytes, deEnvVerifiedLazy withMetaBytes with - | .ok (e1, some cm1), .ok e2, .ok parts => - cm1 == goldenMeta && - parts.circuitMeta == some goldenMeta && - e1.merkleRoot == env.merkleRoot && - e2.merkleRoot == env.merkleRoot && - parts.env.merkleRoot == env.merkleRoot - | _, _, _ => false - - let legacyDecodeNone := - match deEnvWithCircuitMeta plainBytes, deEnvVerifiedLazy plainBytes with - | .ok (e1, none), .ok parts => - parts.circuitMeta.isNone && e1.merkleRoot == env.merkleRoot - | _, _ => false - - let rustReadersOk := - match rsDeEnv withMetaBytes, deEnvAnon withMetaBytes, rsDeEnvAnon withMetaBytes with - | .ok eFull, .ok eLazy, .ok eAnon => - eFull.merkleRoot == env.merkleRoot && - eLazy.merkleRoot == env.merkleRoot && - eAnon.merkleRoot == env.merkleRoot - | _, _, _ => false - - let badVersion := plainBytes ++ patchByte expectedGoldenSectionBytes 4 2 - let badHeaderFlag := plainBytes ++ patchByte expectedGoldenSectionBytes 5 0x20 - let badRangeCheck := plainBytes ++ patchByte expectedGoldenSectionBytes 5 0x03 - let badAiurBit := plainBytes ++ patchByte expectedGoldenSectionBytes 8 0x80 - let badBudgetBit := plainBytes ++ patchByte expectedGoldenSectionBytes 9 0x20 - let truncatedSec := plainBytes ++ expectedGoldenSectionBytes.extract 0 (expectedGoldenSectionBytes.size - 1) - let trailingAfterSec := withMetaBytes ++ ByteArray.mk #[0x00] - let legacyTrailingZero := plainBytes ++ ByteArray.mk #[0x00] - let legacyTrailingTwo := plainBytes ++ ByteArray.mk #[0x00, 0x00] - - test "circuit_meta: cross-language 239-byte golden vector matches" (secOk = true) ++ - test "circuit_meta: golden section roundtrips" (secRoundTrip = true) ++ - test "circuit_meta: writer canonicalizes unsorted keys" (canonicalSort = true) ++ - test "circuit_meta: writer rejects duplicate keys" (dupRejected = true) ++ - test "circuit_meta: writer enforces field invariants" (writerInvariants = true) ++ - test "circuit_meta: §7 appends cleanly with byte-identical header/Merkle root/§1..§6 prefix" (prefixIdentical = true) ++ - test "circuit_meta: Lean deEnv / deEnvWithCircuitMeta / deEnvVerifiedLazy decode §7" (fullDecodeOk = true) ++ - test "circuit_meta: legacy .ixe without §7 decodes to none" (legacyDecodeNone = true) ++ - test "circuit_meta: Rust rsDeEnv / deEnvAnon / rsDeEnvAnon accept .ixe with §7" (rustReadersOk = true) ++ - test "circuit_meta: Lean+Rust reject bad version in §7" (allFullReadersReject badVersion = true) ++ - test "circuit_meta: Lean+Rust reject reserved header flag in §7" (allFullReadersReject badHeaderFlag = true) ++ - test "circuit_meta: Lean+Rust reject invalid rangeCheck tag in §7" (allFullReadersReject badRangeCheck = true) ++ - test "circuit_meta: Lean+Rust reject reserved aiurConfig bit in §7" (allFullReadersReject badAiurBit = true) ++ - test "circuit_meta: Lean+Rust reject reserved budget bit in §7" (allFullReadersReject badBudgetBit = true) ++ - test "circuit_meta: Lean+Rust reject truncated §7 section" (allFullReadersReject truncatedSec = true) ++ - test "circuit_meta: Lean+Rust reject trailing bytes after §7" (allFullReadersReject trailingAfterSec = true) ++ - test "circuit_meta: legacy trailing garbage still rejected by Lean+Rust" - (allFullReadersReject legacyTrailingZero = true ∧ allFullReadersReject legacyTrailingTwo = true) +public def units : LSpec.Spec := do + itBool "circuit_meta: cross-language 239-byte golden vector matches" + (match CircuitMeta.serSection goldenMeta with + | .ok b => b == expectedGoldenSectionBytes && b.size == 239 + | .error _ => false) + itBool "circuit_meta: golden section roundtrips" + (match runGetExact CircuitMeta.getSection expectedGoldenSectionBytes with + | .ok cm => cm == goldenMeta + | .error _ => false) + itBool "circuit_meta: writer canonicalizes unsorted keys" + (let reversed : CircuitMeta := { goldenMeta with byAddress := goldenMeta.byAddress.reverse } + match CircuitMeta.serSection reversed with + | .ok b => b == expectedGoldenSectionBytes + | .error _ => false) + itBool "circuit_meta: writer rejects duplicate keys" + (let dupAddr : CircuitMeta := { goldenMeta with byAddress := goldenMeta.byAddress.push goldenMeta.byAddress[0]! } + let dupFun : CircuitMeta := { goldenMeta with byFun := goldenMeta.byFun.push goldenMeta.byFun[0]! } + let dupGroup : CircuitMeta := { goldenMeta with groups := goldenMeta.groups.push goldenMeta.groups[0]! } + let dupGuess : CircuitMeta := { goldenMeta with guesses := goldenMeta.guesses.push goldenMeta.guesses[0]! } + (CircuitMeta.serSection dupAddr).toOption.isNone && + (CircuitMeta.serSection dupFun).toOption.isNone && + (CircuitMeta.serSection dupGroup).toOption.isNone && + (CircuitMeta.serSection dupGuess).toOption.isNone) + itBool "circuit_meta: writer enforces field invariants" + (let conflictFuel : CircuitMeta := { + byAddress := #[(repAddr 0x01, { fuelParam := some "n", noFuel := true })] + } + let zeroUnroll : CircuitMeta := { + byAddress := #[(repAddr 0x01, { unroll := some 0 })] + } + let zeroLanes : CircuitMeta := { + byAddress := #[(repAddr 0x01, { lanes := some 0 })] + } + let emptyGroup : CircuitMeta := { + byAddress := #[(repAddr 0x01, { group := some "" })] + } + let zeroLimbs : CircuitMeta := { + byAddress := #[(repAddr 0x01, { repr := some (.limbs 0 64) })] + } + let zeroFlat : CircuitMeta := { + byAddress := #[(repAddr 0x01, { repr := some (.flatArray 0) })] + } + [conflictFuel, zeroUnroll, zeroLanes, emptyGroup, zeroLimbs, zeroFlat].all fun cm => + (CircuitMeta.serSection cm).toOption.isNone) + it "circuit_meta: §7 appends cleanly with byte-identical header/Merkle root/§1..§6 prefix" do + let env := mkSampleEnv () + let plainBytes := (serEnv env).toOption.getD ByteArray.empty + let withMetaBytes := (serEnvWithCircuitMeta env (some goldenMeta)).toOption.getD ByteArray.empty + let appendedBytes := (appendCircuitMetaSection plainBytes goldenMeta).toOption.getD ByteArray.empty + expect (!plainBytes.isEmpty && + withMetaBytes == appendedBytes && + withMetaBytes.size == plainBytes.size + expectedGoldenSectionBytes.size && + withMetaBytes.extract 0 plainBytes.size == plainBytes) + it "circuit_meta: Lean deEnv / deEnvWithCircuitMeta / deEnvVerifiedLazy decode §7" do + let env := mkSampleEnv () + let withMetaBytes := (serEnvWithCircuitMeta env (some goldenMeta)).toOption.getD ByteArray.empty + let fullDecodeOk := + match deEnvWithCircuitMeta withMetaBytes, deEnv withMetaBytes, deEnvVerifiedLazy withMetaBytes with + | .ok (e1, some cm1), .ok e2, .ok parts => + cm1 == goldenMeta && + parts.circuitMeta == some goldenMeta && + e1.merkleRoot == env.merkleRoot && + e2.merkleRoot == env.merkleRoot && + parts.env.merkleRoot == env.merkleRoot + | _, _, _ => false + expect fullDecodeOk + it "circuit_meta: legacy .ixe without §7 decodes to none" do + let env := mkSampleEnv () + let plainBytes := (serEnv env).toOption.getD ByteArray.empty + let legacyDecodeNone := + match deEnvWithCircuitMeta plainBytes, deEnvVerifiedLazy plainBytes with + | .ok (e1, none), .ok parts => + parts.circuitMeta.isNone && e1.merkleRoot == env.merkleRoot + | _, _ => false + expect legacyDecodeNone + it "circuit_meta: Rust rsDeEnv / deEnvAnon / rsDeEnvAnon accept .ixe with §7" do + let env := mkSampleEnv () + let withMetaBytes := (serEnvWithCircuitMeta env (some goldenMeta)).toOption.getD ByteArray.empty + let rustReadersOk := + match rsDeEnv withMetaBytes, deEnvAnon withMetaBytes, rsDeEnvAnon withMetaBytes with + | .ok eFull, .ok eLazy, .ok eAnon => + eFull.merkleRoot == env.merkleRoot && + eLazy.merkleRoot == env.merkleRoot && + eAnon.merkleRoot == env.merkleRoot + | _, _, _ => false + expect rustReadersOk + it "circuit_meta: Lean+Rust reject bad version in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 4 2)) + it "circuit_meta: Lean+Rust reject reserved header flag in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 5 0x20)) + it "circuit_meta: Lean+Rust reject invalid rangeCheck tag in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 5 0x03)) + it "circuit_meta: Lean+Rust reject reserved aiurConfig bit in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 8 0x80)) + it "circuit_meta: Lean+Rust reject reserved budget bit in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 9 0x20)) + it "circuit_meta: Lean+Rust reject truncated §7 section" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + let truncatedSec := plainBytes ++ expectedGoldenSectionBytes.extract 0 (expectedGoldenSectionBytes.size - 1) + expect (allFullReadersReject truncatedSec) + it "circuit_meta: Lean+Rust reject trailing bytes after §7" do + let withMetaBytes := (serEnvWithCircuitMeta (mkSampleEnv ()) (some goldenMeta)).toOption.getD ByteArray.empty + expect (allFullReadersReject (withMetaBytes ++ ByteArray.mk #[0x00])) + it "circuit_meta: legacy trailing garbage still rejected by Lean+Rust" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ ByteArray.mk #[0x00]) && + allFullReadersReject (plainBytes ++ ByteArray.mk #[0x00, 0x00])) end Tests.Ix.CircuitMeta diff --git a/Tests/Ix/Claim.lean b/Tests/Ix/Claim.lean index 9ef725820f..8f4066eeb4 100644 --- a/Tests/Ix/Claim.lean +++ b/Tests/Ix/Claim.lean @@ -7,10 +7,12 @@ public import Ix.Claim public import Ix.SpecDigest public import Tests.Gen.Claim -open LSpec SlimCheck +open LSpec LSpec.Prop open Ixon (runGet) open Ix (RevealConstructorInfo RevealRecursorRule RevealConstantInfo Claim) +set_option compiler.extract_closed false + /-! ## Roundtrip helper -/ def claimSerde (c : Claim) : Bool := @@ -27,73 +29,73 @@ def proofSerde (p : Ixon.Proof) : Bool := /-! ## Unit tests -/ -private def addr1 : Address := Address.blake3 "hello".toUTF8 -private def addr2 : Address := Address.blake3 "world".toUTF8 -private def addr3 : Address := Address.blake3 "test".toUTF8 +private def mkAddr1 (_ : Unit) : Address := Address.blake3 "hello".toUTF8 +private def mkAddr2 (_ : Unit) : Address := Address.blake3 "world".toUTF8 +private def mkAddr3 (_ : Unit) : Address := Address.blake3 "test".toUTF8 /-- This specification set, a stand-in binding hash, the standard axioms only. The same fixture as `test_ctx` in `crates/ixon/src/proof.rs`. -/ -private def ctx : Ix.ClaimContext := +private def mkCtx (_ : Unit) : Ix.ClaimContext := { spec := Ix.SpecDigest.specDigest.toOption.getD default binding := Address.blake3 "binding".toUTF8 axioms := none } -def claimUnits : TestSeq := +def claimUnits : LSpec.Spec := do -- Typechecking claims: both no-asm and with-asm forms. - test "Eval no-asm roundtrip" (claimSerde (.eval ctx addr1 addr2 none)) - ++ test "Eval with-asm roundtrip" - (claimSerde (.eval ctx addr1 addr2 (some addr3))) - ++ test "Check no-asm roundtrip" (claimSerde (.check ctx addr1 none)) - ++ test "Check with-asm roundtrip" - (claimSerde (.check ctx addr1 (some addr2))) - ++ test "CheckEnv no-asm roundtrip" (claimSerde (.checkEnv ctx addr1 none)) - ++ test "CheckEnv with-asm roundtrip" - (claimSerde (.checkEnv ctx addr1 (some addr2))) + itBool "Eval no-asm roundtrip" (claimSerde (.eval (mkCtx ()) (mkAddr1 ()) (mkAddr2 ()) none)) + itBool "Eval with-asm roundtrip" + (claimSerde (.eval (mkCtx ()) (mkAddr1 ()) (mkAddr2 ()) (some (mkAddr3 ())))) + itBool "Check no-asm roundtrip" (claimSerde (.check (mkCtx ()) (mkAddr1 ()) none)) + itBool "Check with-asm roundtrip" + (claimSerde (.check (mkCtx ()) (mkAddr1 ()) (some (mkAddr2 ())))) + itBool "CheckEnv no-asm roundtrip" (claimSerde (.checkEnv (mkCtx ()) (mkAddr1 ()) none)) + itBool "CheckEnv with-asm roundtrip" + (claimSerde (.checkEnv (mkCtx ()) (mkAddr1 ()) (some (mkAddr2 ())))) -- Contains - ++ test "Contains roundtrip" (claimSerde (.contains addr1 addr2)) + itBool "Contains roundtrip" (claimSerde (.contains (mkAddr1 ()) (mkAddr2 ()))) -- Catalog (the first multi-byte claim tag) - ++ test "Catalog roundtrip" (claimSerde (.catalog addr1)) - ++ test "CheckEnv under a literal class roundtrip" - (claimSerde (.checkEnv { ctx with literalClass := true } addr1 none)) + itBool "Catalog roundtrip" (claimSerde (.catalog (mkAddr1 ()))) + itBool "CheckEnv under a literal class roundtrip" + (claimSerde (.checkEnv { mkCtx () with literalClass := true } (mkAddr1 ()) none)) -- Reveal claim variants (carried over from previous suite) - ++ test "Reveal defn safety-only" (claimSerde (.reveal addr1 + itBool "Reveal defn safety-only" (claimSerde (.reveal (mkAddr1 ()) (.defn none (some .safe) none none none none) none)) - ++ test "Reveal defn all fields" (claimSerde (.reveal addr1 - (.defn (some .defn) (some .safe) (some 3) (some addr2) (some addr3) - (some { alloc := .noAlloc, boundedStack := true })) (some addr3))) - ++ test "Reveal axio with type" (claimSerde (.reveal addr1 - (.axio none none (some addr2)) none)) - ++ test "Reveal recr with rules" (claimSerde (.reveal addr1 + itBool "Reveal defn all fields" (claimSerde (.reveal (mkAddr1 ()) + (.defn (some .defn) (some .safe) (some 3) (some (mkAddr2 ())) (some (mkAddr3 ())) + (some { alloc := .noAlloc, boundedStack := true })) (some (mkAddr3 ())))) + itBool "Reveal axio with type" (claimSerde (.reveal (mkAddr1 ()) + (.axio none none (some (mkAddr2 ()))) none)) + itBool "Reveal recr with rules" (claimSerde (.reveal (mkAddr1 ()) (.recr (some true) none (some 2) none none none none none - (some #[⟨0, 3, addr2⟩])) none)) - ++ test "Reveal muts with component" (claimSerde (.reveal addr1 + (some #[⟨0, 3, mkAddr2 ()⟩])) none)) + itBool "Reveal muts with component" (claimSerde (.reveal (mkAddr1 ()) (.muts #[(0, .defn (some .defn) (some .safe) none none none (some { alloc := .noRc, boundedStack := false }))]) none)) - ++ test "Reveal muts constructor field modes" (claimSerde (.reveal addr1 + itBool "Reveal muts constructor field modes" (claimSerde (.reveal (mkAddr1 ()) (.muts #[(0, .indc none none none none none (some #[(0, { fieldModes := some #[.inherited, .shared] }), - (1, { fieldModes := some #[] })]))]) (some addr2))) - ++ test "Reveal cPrj" (claimSerde (.reveal addr1 - (.cPrj (some 0) (some 1) (some addr2)) none)) - ++ test "Reveal rPrj" (claimSerde (.reveal addr1 - (.rPrj (some 2) (some addr2)) none)) - ++ test "Reveal iPrj" (claimSerde (.reveal addr1 - (.iPrj (some 3) (some addr2)) none)) - ++ test "Reveal dPrj" (claimSerde (.reveal addr1 - (.dPrj (some 0) (some addr2)) none)) - ++ test "Reveal defn all none" (claimSerde (.reveal addr1 + (1, { fieldModes := some #[] })]))]) (some (mkAddr2 ())))) + itBool "Reveal cPrj" (claimSerde (.reveal (mkAddr1 ()) + (.cPrj (some 0) (some 1) (some (mkAddr2 ()))) none)) + itBool "Reveal rPrj" (claimSerde (.reveal (mkAddr1 ()) + (.rPrj (some 2) (some (mkAddr2 ()))) none)) + itBool "Reveal iPrj" (claimSerde (.reveal (mkAddr1 ()) + (.iPrj (some 3) (some (mkAddr2 ()))) none)) + itBool "Reveal dPrj" (claimSerde (.reveal (mkAddr1 ()) + (.dPrj (some 0) (some (mkAddr2 ()))) none)) + itBool "Reveal defn all none" (claimSerde (.reveal (mkAddr1 ()) (.defn none none none none none none) none)) - ++ test "Reveal quot" (claimSerde (.reveal addr1 - (.quot (some .type) (some 1) (some addr2)) none)) + itBool "Reveal quot" (claimSerde (.reveal (mkAddr1 ()) + (.quot (some .type) (some 1) (some (mkAddr2 ()))) none)) -- Compile claims - ++ test "Compile immortal roundtrip" (claimSerde (.compile - { env := addr1, roleTable := none, target := addr2, policy := .immortal, abiArity := 2, elfHash := addr3 })) - ++ test "Compile zeroRc roundtrip" (claimSerde (.compile - { env := addr1, roleTable := some addr2, target := addr2, policy := .zeroRc, abiArity := 3, elfHash := addr3 })) - ++ test "Compile plainRc roundtrip" (claimSerde (.compile - { env := addr1, roleTable := some addr3, target := addr2, policy := .plainRc, abiArity := 1, elfHash := addr3 })) - ++ test "Compile proof roundtrip" (proofSerde - { claim := .compile { env := addr1, roleTable := some addr1, target := addr2, policy := .zeroRc, abiArity := 2, elfHash := addr3 } + itBool "Compile immortal roundtrip" (claimSerde (.compile + { env := mkAddr1 (), roleTable := none, target := mkAddr2 (), policy := .immortal, abiArity := 2, elfHash := mkAddr3 () })) + itBool "Compile zeroRc roundtrip" (claimSerde (.compile + { env := mkAddr1 (), roleTable := some (mkAddr2 ()), target := mkAddr2 (), policy := .zeroRc, abiArity := 3, elfHash := mkAddr3 () })) + itBool "Compile plainRc roundtrip" (claimSerde (.compile + { env := mkAddr1 (), roleTable := some (mkAddr3 ()), target := mkAddr2 (), policy := .plainRc, abiArity := 1, elfHash := mkAddr3 () })) + itBool "Compile proof roundtrip" (proofSerde + { claim := .compile { env := mkAddr1 (), roleTable := some (mkAddr1 ()), target := mkAddr2 (), policy := .zeroRc, abiArity := 2, elfHash := mkAddr3 () } proof := ⟨#[0x10, 0x20, 0x30]⟩ }) /-! ## Byte-level encoding tests @@ -106,118 +108,131 @@ def claimUnits : TestSeq := `0x01`+32-byte address for `some`). -/ -def claimEncodingTests : TestSeq := - let evalBytes := Claim.ser (.eval ctx addr1 addr2 none) - let evalWithAsm := Claim.ser (.eval ctx addr1 addr2 (some addr3)) - let checkBytes := Claim.ser (.check ctx addr1 none) - let checkWithAsm := Claim.ser (.check ctx addr1 (some addr2)) - let checkEnvBytes := Claim.ser (.checkEnv ctx addr1 none) - let containsBytes := Claim.ser (.contains addr1 addr2) - let revealSafetyOnly := Claim.ser - (.reveal addr1 (.defn none (some .safe) none none none none) none) - let revealAllFields := Claim.ser (.reveal addr1 - (.defn (some .defn) (some .safe) (some 3) (some addr2) (some addr3) - (some { alloc := .noAlloc, boundedStack := true })) (some addr3)) - let retiredRefused : Bool := match Claim.de (checkBytes.set! 2 1) with - | .error e => (e.splitOn "erased-lean-v1 is retired").length > 1 - | .ok _ => false +def claimEncodingTests : LSpec.Spec := do + let mkEvalBytes (_ : Unit) : ByteArray := Claim.ser (.eval (mkCtx ()) (mkAddr1 ()) (mkAddr2 ()) none) + let mkEvalWithAsm (_ : Unit) : ByteArray := Claim.ser (.eval (mkCtx ()) (mkAddr1 ()) (mkAddr2 ()) (some (mkAddr3 ()))) + let mkCheckBytes (_ : Unit) : ByteArray := Claim.ser (.check (mkCtx ()) (mkAddr1 ()) none) + let mkCheckWithAsm (_ : Unit) : ByteArray := Claim.ser (.check (mkCtx ()) (mkAddr1 ()) (some (mkAddr2 ()))) + let mkCheckEnvBytes (_ : Unit) : ByteArray := Claim.ser (.checkEnv (mkCtx ()) (mkAddr1 ()) none) + let mkContainsBytes (_ : Unit) : ByteArray := Claim.ser (.contains (mkAddr1 ()) (mkAddr2 ())) + let mkRevealSafetyOnly (_ : Unit) : ByteArray := Claim.ser + (.reveal (mkAddr1 ()) (.defn none (some .safe) none none none none) none) + let mkRevealAllFields (_ : Unit) : ByteArray := Claim.ser (.reveal (mkAddr1 ()) + (.defn (some .defn) (some .safe) (some 3) (some (mkAddr2 ())) (some (mkAddr3 ())) + (some { alloc := .noAlloc, boundedStack := true })) (some (mkAddr3 ()))) -- Two scope bytes follow each claim tag, then the 65-byte context. -- Eval = 133 bytes; with asm = 165 - test "Eval tag byte is 0xE3" (evalBytes.data[0]! == 0xE3) - ++ test "Eval scope is object format 4, erased-lean-v2" - (evalBytes.data[1]! == 4 && evalBytes.data[2]! == 3) - ++ test "Eval context follows the scope" - (evalBytes.extract 3 35 == ctx.spec.hash - && evalBytes.extract 35 67 == ctx.binding.hash - && evalBytes.data[67]! == 0) - ++ test "Eval no-asm size is 133" (evalBytes.size == 133) - ++ test "Eval with-asm size is 165" (evalWithAsm.size == 165) + itBool "Eval tag byte is 0xE3" ((mkEvalBytes ()).get! 0 == (0xE3 : UInt8)) + it "Eval scope is object format 4, erased-lean-v2" do + let evalBytes := mkEvalBytes () + expect (evalBytes.get! 1 == (4 : UInt8) && evalBytes.get! 2 == (3 : UInt8)) + it "Eval context follows the scope" do + let ctx := mkCtx () + let evalBytes := Claim.ser (.eval ctx (mkAddr1 ()) (mkAddr2 ()) none) + expect (evalBytes.extract 3 35 == ctx.spec.hash + && evalBytes.extract 35 67 == ctx.binding.hash + && evalBytes.get! 67 == (0 : UInt8)) + itBool "Eval no-asm size is 133" ((mkEvalBytes ()).size == 133) + itBool "Eval with-asm size is 165" ((mkEvalWithAsm ()).size == 165) -- Check: tag + scope + context + 32 + option = 101 bytes; with asm = 133 - ++ test "Check tag byte is 0xE4" (checkBytes.data[0]! == 0xE4) - ++ test "Check no-asm size is 101" (checkBytes.size == 101) - ++ test "Check with-asm size is 133" (checkWithAsm.size == 133) + itBool "Check tag byte is 0xE4" ((mkCheckBytes ()).get! 0 == (0xE4 : UInt8)) + itBool "Check no-asm size is 101" ((mkCheckBytes ()).size == 101) + itBool "Check with-asm size is 133" ((mkCheckWithAsm ()).size == 133) -- CheckEnv: tag + scope + context + 32 + option = 101 bytes - ++ test "CheckEnv tag byte is 0xE5" (checkEnvBytes.data[0]! == 0xE5) - ++ test "CheckEnv no-asm size is 101" (checkEnvBytes.size == 101) - ++ test "Check for the retired erased-lean-v1 validator is refused" retiredRefused - ++ test "Check with an axioms commitment roundtrips" - (claimSerde (.check { ctx with axioms := some addr3 } addr1 none)) + itBool "CheckEnv tag byte is 0xE5" ((mkCheckEnvBytes ()).get! 0 == (0xE5 : UInt8)) + itBool "CheckEnv no-asm size is 101" ((mkCheckEnvBytes ()).size == 101) + it "Check for the retired erased-lean-v1 validator is refused" do + let checkBytes := mkCheckBytes () + let retiredRefused : Bool := match Claim.de (checkBytes.set! 2 1) with + | .error e => (e.splitOn "erased-lean-v1 is retired").length > 1 + | .ok _ => false + expect retiredRefused + itBool "Check with an axioms commitment roundtrips" + (claimSerde (.check { mkCtx () with axioms := some (mkAddr3 ()) } (mkAddr1 ()) none)) -- Reveal claim: 0xE6 - ++ test "Reveal tag byte is 0xE6" (revealSafetyOnly.data[0]! == 0xE6) + itBool "Reveal tag byte is 0xE6" ((mkRevealSafetyOnly ()).get! 0 == (0xE6 : UInt8)) -- Reveal: tag + scope + commitment + variant + mask + safety + binders(none) = 39 - ++ test "Reveal safety-only defn size is 39" (revealSafetyOnly.size == 39) - ++ test "Reveal all-fields defn is larger" - (revealAllFields.size > revealSafetyOnly.size) + itBool "Reveal safety-only defn size is 39" ((mkRevealSafetyOnly ()).size == 39) + itBool "Reveal all-fields defn is larger" + (decide ((mkRevealAllFields ()).size > (mkRevealSafetyOnly ()).size)) -- Contains: tag + scope + two addresses = 67 - ++ test "Contains tag byte is 0xE7" (containsBytes.data[0]! == 0xE7) - ++ test "Contains size is 67" (containsBytes.size == 67) + itBool "Contains tag byte is 0xE7" ((mkContainsBytes ()).get! 0 == (0xE7 : UInt8)) + itBool "Contains size is 67" ((mkContainsBytes ()).size == 67) -- Compile: deterministic 103- and 135-byte wire vectors shared with IxCC.CompileClaim - ++ (let envHash : Address := ⟨ByteArray.mk (Array.replicate 32 0x11)⟩ - let target : Address := ⟨ByteArray.mk (Array.replicate 32 0x22)⟩ - let elfHash : Address := ⟨ByteArray.mk (Array.replicate 32 0x33)⟩ - let cc : Ix.CompileClaim := - { env := envHash, roleTable := none, target := target, policy := .plainRc, abiArity := 3 - elfHash := elfHash } - let compileBytes := Claim.ser (.compile cc) - -- The claim names the role table (validator `07`): `00` after `env` for an - -- environment without a role binding, `01` and the table's address otherwise. - let boundCc : Ix.CompileClaim := - { cc with roleTable := some ⟨ByteArray.mk (Array.replicate 32 0x44)⟩ } - let expectedBoundBytes : ByteArray := - ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] - ++ Array.replicate 32 0x11 ++ #[0x01] ++ Array.replicate 32 0x44 - ++ Array.replicate 32 0x22 ++ #[0x02, 0x03] ++ Array.replicate 32 0x33) - -- The former format (validator `06`, no role table) is refused. - let formerBytes : ByteArray := - ByteArray.mk (#[0xE8, 0x05, 0x04, 0x06] - ++ Array.replicate 32 0x11 ++ Array.replicate 32 0x22 - ++ #[0x02, 0x03] ++ Array.replicate 32 0x33) - let expectedCompileBytes : ByteArray := - ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] - ++ Array.replicate 32 0x11 ++ #[0x00] - ++ Array.replicate 32 0x22 - ++ #[0x02, 0x03] - ++ Array.replicate 32 0x33) - -- `abiArity`'s `N0` code at its boundaries; `IxCC/IxCCTests/Pipeline/Compiler.lean` - -- pins the same vectors for `IxCC.CompileClaim` (B4-2). `80 80` is 256. - let arityClaimBytes (arity : List UInt8) : ByteArray := - ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] ++ Array.replicate 32 0x11 ++ #[0x00] - ++ Array.replicate 32 0x22 ++ #[0x02] ++ arity.toArray ++ Array.replicate 32 0x33) - let arityVectors : List (UInt64 × List UInt8) := [ - (0, [0x00]), (5, [0x05]), (6, [0x06]), (127, [0x7F]), (128, [0x80, 0x00]), - (256, [0x80, 0x80]), (16511, [0xBF, 0xFF]), (16512, [0xC0, 0x00, 0x00]), - (18446744073709551615, [0xC3, 0x7F, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF])] - let arityRejected : List (List UInt8) := - [[0xC4], [0xC3, 0x80, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]] - test "Compile wire header is E8 05 04 07" - (compileBytes.extract 0 4 == ⟨#[0xE8, 0x05, 0x04, 0x07]⟩) - ++ test "Compile wire size is 103 without a role table" (compileBytes.size == 103) - ++ test "Compile wire matches deterministic 103-byte vector" - (compileBytes == expectedCompileBytes) - ++ test "Compile with a role table matches deterministic 135-byte vector and roundtrips" - (Claim.ser (.compile boundCc) == expectedBoundBytes && - (Claim.de expectedBoundBytes).toOption == some (.compile boundCc)) - ++ test "Compile former format (validator 06, no role table) is refused" - ((Claim.de formerBytes).toOption.isNone && (Claim.de (formerBytes.set! 3 0x07)).toOption.isNone - && (Claim.de (expectedCompileBytes.set! 3 0x06)).toOption.isNone - && (Claim.de (expectedCompileBytes.set! 3 0x09)).toOption.isNone - && (Claim.de (expectedCompileBytes.set! 36 0x02)).toOption.isNone) - ++ test "Compile deterministic vector roundtrips via Claim.de" - ((Claim.de compileBytes).toOption == some (.compile cc)) - ++ test "Compile abiArity N0 vectors shared with IxCC.CompileClaim" - (arityVectors.all fun (arity, bytes) => - Claim.ser (.compile { cc with abiArity := arity }) == arityClaimBytes bytes && - (Claim.de (arityClaimBytes bytes)).toOption == some (.compile { cc with abiArity := arity })) - ++ test "Compile invalid and overflowing abiArity codes are refused" - (arityRejected.all fun bytes => (Claim.de (arityClaimBytes bytes)).toOption.isNone) - ++ test "Compile is not read under the role-binding (E8 03) or literal-class (E8 04) tags" - ((Claim.de (compileBytes.set! 1 0x03)).toOption.isNone - && (Claim.de (compileBytes.set! 1 0x04)).toOption.isNone) - ++ test "Compile proof (F8 00) wraps the compile claim" - (let proof : Ixon.Proof := { claim := .compile cc, proof := ⟨#[7]⟩ } - let bytes := Ixon.Proof.ser proof - bytes.extract 0 2 == ⟨#[0xF8, 0x00]⟩ && - (Ixon.Proof.de bytes).toOption.map (·.claim) == some (.compile cc))) + let mkCc (_ : Unit) : Ix.CompileClaim := + { env := ⟨ByteArray.mk (Array.replicate 32 0x11)⟩ + roleTable := none + target := ⟨ByteArray.mk (Array.replicate 32 0x22)⟩ + policy := .plainRc + abiArity := 3 + elfHash := ⟨ByteArray.mk (Array.replicate 32 0x33)⟩ } + let mkCompileBytes (_ : Unit) : ByteArray := Claim.ser (.compile (mkCc ())) + -- The claim names the role table (validator `07`): `00` after `env` for an + -- environment without a role binding, `01` and the table's address otherwise. + let mkBoundCc (_ : Unit) : Ix.CompileClaim := + { mkCc () with roleTable := some ⟨ByteArray.mk (Array.replicate 32 0x44)⟩ } + let mkExpectedBoundBytes (_ : Unit) : ByteArray := + ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] + ++ Array.replicate 32 0x11 ++ #[0x01] ++ Array.replicate 32 0x44 + ++ Array.replicate 32 0x22 ++ #[0x02, 0x03] ++ Array.replicate 32 0x33) + -- The former format (validator `06`, no role table) is refused. + let mkFormerBytes (_ : Unit) : ByteArray := + ByteArray.mk (#[0xE8, 0x05, 0x04, 0x06] + ++ Array.replicate 32 0x11 ++ Array.replicate 32 0x22 + ++ #[0x02, 0x03] ++ Array.replicate 32 0x33) + let mkExpectedCompileBytes (_ : Unit) : ByteArray := + ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] + ++ Array.replicate 32 0x11 ++ #[0x00] + ++ Array.replicate 32 0x22 + ++ #[0x02, 0x03] + ++ Array.replicate 32 0x33) + -- `abiArity`'s `N0` code at its boundaries; `IxCC/IxCCTests/Pipeline/Compiler.lean` + -- pins the same vectors for `IxCC.CompileClaim` (B4-2). `80 80` is 256. + let arityClaimBytes (arity : List UInt8) : ByteArray := + ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] ++ Array.replicate 32 0x11 ++ #[0x00] + ++ Array.replicate 32 0x22 ++ #[0x02] ++ arity.toArray ++ Array.replicate 32 0x33) + let arityVectors : List (UInt64 × List UInt8) := [ + (0, [0x00]), (5, [0x05]), (6, [0x06]), (127, [0x7F]), (128, [0x80, 0x00]), + (256, [0x80, 0x80]), (16511, [0xBF, 0xFF]), (16512, [0xC0, 0x00, 0x00]), + (18446744073709551615, [0xC3, 0x7F, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF])] + let arityRejected : List (List UInt8) := + [[0xC4], [0xC3, 0x80, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]] + itBool "Compile wire header is E8 05 04 07" + ((mkCompileBytes ()).extract 0 4 == ⟨#[0xE8, 0x05, 0x04, 0x07]⟩) + itBool "Compile wire size is 103 without a role table" ((mkCompileBytes ()).size == 103) + itBool "Compile wire matches deterministic 103-byte vector" + (mkCompileBytes () == mkExpectedCompileBytes ()) + itBool "Compile with a role table matches deterministic 135-byte vector and roundtrips" + (let boundCc := mkBoundCc () + let expectedBoundBytes := mkExpectedBoundBytes () + Claim.ser (.compile boundCc) == expectedBoundBytes && + (Claim.de expectedBoundBytes).toOption == some (.compile boundCc)) + itBool "Compile former format (validator 06, no role table) is refused" + (let formerBytes := mkFormerBytes () + let expectedCompileBytes := mkExpectedCompileBytes () + (Claim.de formerBytes).toOption.isNone && (Claim.de (formerBytes.set! 3 0x07)).toOption.isNone + && (Claim.de (expectedCompileBytes.set! 3 0x06)).toOption.isNone + && (Claim.de (expectedCompileBytes.set! 3 0x09)).toOption.isNone + && (Claim.de (expectedCompileBytes.set! 36 0x02)).toOption.isNone) + itBool "Compile deterministic vector roundtrips via Claim.de" + ((Claim.de (mkCompileBytes ())).toOption == some (.compile (mkCc ()))) + itBool "Compile abiArity N0 vectors shared with IxCC.CompileClaim" + (let cc := mkCc () + arityVectors.all fun (arity, bytes) => + Claim.ser (.compile { cc with abiArity := arity }) == arityClaimBytes bytes && + (Claim.de (arityClaimBytes bytes)).toOption == some (.compile { cc with abiArity := arity })) + itBool "Compile invalid and overflowing abiArity codes are refused" + (arityRejected.all fun bytes => (Claim.de (arityClaimBytes bytes)).toOption.isNone) + itBool "Compile is not read under the role-binding (E8 03) or literal-class (E8 04) tags" + (let compileBytes := mkCompileBytes () + (Claim.de (compileBytes.set! 1 0x03)).toOption.isNone + && (Claim.de (compileBytes.set! 1 0x04)).toOption.isNone) + itBool "Compile proof (F8 00) wraps the compile claim" + (let cc := mkCc () + let proof : Ixon.Proof := { claim := .compile cc, proof := ⟨#[7]⟩ } + let bytes := Ixon.Proof.ser proof + bytes.extract 0 2 == ⟨#[0xF8, 0x00]⟩ && + (Ixon.Proof.de bytes).toOption.map (·.claim) == some (.compile cc)) /-! ## Catalog claim: wire pin + Rust digest parity @@ -229,64 +244,67 @@ def claimEncodingTests : TestSeq := without one of the pins going red. -/ -private def catMembers : Address := Address.blake3 "members".toUTF8 +private def mkCatMembers (_ : Unit) : Address := Address.blake3 "members".toUTF8 /-- Must equal the Rust pin in `proof.rs::catalog_claim_wire_bytes_pinned`. -/ private def catalogDigestPin : String := "4f5686bd1a8386231370703d58223aca769c82c835964d4914ca41305a8030f3" -def catalogClaimTests : TestSeq := - let bytes := Claim.ser (.catalog catMembers) - let proof : Ixon.Proof := { claim := .catalog catMembers, proof := .empty } - let proofBytes := Ixon.Proof.ser proof - let proofRoundtrips : Bool := match Ixon.Proof.de proofBytes with - | .ok p => p.claim == proof.claim && p.proof == proof.proof - | .error _ => false - test "Catalog tag is 2 bytes 0xE8 0x00 (TagN 4 0xE 8)" - (bytes.data[0]! == 0xE8 && bytes.data[1]! == 0x00) - ++ test "Catalog scope is object format 4, erased-lean-v2" - (bytes.data[2]! == 4 && bytes.data[3]! == 3) - ++ test "Catalog is the scope and the members root, 36 bytes" (bytes.size == 4 + 32) - ++ test "Catalog digest parity with Rust pin" - (toString (Address.blake3 bytes) == catalogDigestPin) - ++ test "Catalog proof wrapper tag is single-byte 0xF5" - (proofBytes.data[0]! == 0xF5) - ++ test "Catalog proof wrapper roundtrips" proofRoundtrips +def catalogClaimTests : LSpec.Spec := do + let mkBytes := fun () => Claim.ser (.catalog (mkCatMembers ())) + it "Catalog tag is 2 bytes 0xE8 0x00 (TagN 4 0xE 8)" do + let bytes := mkBytes () + expect (bytes.get! 0 == (0xE8 : UInt8) && bytes.get! 1 == (0x00 : UInt8)) + it "Catalog scope is object format 4, erased-lean-v2" do + let bytes := mkBytes () + expect (bytes.get! 2 == (4 : UInt8) && bytes.get! 3 == (3 : UInt8)) + itBool "Catalog is the scope and the members root, 36 bytes" ((mkBytes ()).size == 4 + 32) + itBool "Catalog digest parity with Rust pin" + (toString (Address.blake3 (mkBytes ())) == catalogDigestPin) + it "Catalog proof wrapper tag is single-byte 0xF5" do + let proof : Ixon.Proof := { claim := .catalog (mkCatMembers ()), proof := .empty } + let proofBytes := Ixon.Proof.ser proof + expect (proofBytes.get! 0 == (0xF5 : UInt8)) + it "Catalog proof wrapper roundtrips" do + let proof : Ixon.Proof := { claim := .catalog (mkCatMembers ()), proof := .empty } + let proofBytes := Ixon.Proof.ser proof + let proofRoundtrips : Bool := match Ixon.Proof.de proofBytes with + | .ok p => p.claim == proof.claim && p.proof == proof.proof + | .error _ => false + expect proofRoundtrips /-- A reveal mask bit beyond the variant's fields is refused, so one claim has one encoding. The Rust reader refuses the same bytes (`proof.rs::reveal_mask_refuses_unknown_bits`): a Reveal claim over the zero commitment, its variant byte, the one-byte mask, then `0x00` (`binders = none`). -/ -def revealMaskTests : TestSeq := - let header : Array UInt8 := #[0xE6, 0x04, 0x00] ++ Array.replicate 32 0 - let bytes (variant mask : UInt8) : ByteArray := ⟨header ++ #[variant, mask, 0x00]⟩ - test "Reveal defn with no fields reads" (Ix.Claim.de (bytes 0 0) matches .ok _) - ++ test "Reveal defn mask bit 5 reads valid DefAsserts" - (Ix.Claim.de ⟨header ++ #[0, 0x20, 0x06, 0x00]⟩ matches .ok _) - ++ test "Reveal defn mask bit 5 refuses alloc 3" - (Ix.Claim.de ⟨header ++ #[0, 0x20, 0x03, 0x00]⟩ matches .error _) - ++ test "Reveal defn mask bit 5 refuses code 8" - (Ix.Claim.de ⟨header ++ #[0, 0x20, 0x08, 0x00]⟩ matches .error _) - ++ test "Reveal defn mask bit 6 refused" (Ix.Claim.de (bytes 0 0x40) matches .error _) - ++ test "Reveal muts ctor mask bit 6 reads fieldModes" - (Ix.Claim.de ⟨header ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x40, 2, 0, 1, 0x00]⟩ matches .ok _) - ++ test "Reveal muts ctor fieldMode 2 refused" - (Ix.Claim.de ⟨header ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x40, 2, 0, 2, 0x00]⟩ matches .error _) - ++ test "Reveal muts ctor mask bit 7 refused" - (Ix.Claim.de ⟨header ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x80, 0x00, 0x00]⟩ matches .error _) - ++ test "Reveal binders opt tag 2 refused" - (Ix.Claim.de ⟨header ++ #[0, 0, 0x02]⟩ matches .error _) - ++ test "Reveal axio with no fields reads" (Ix.Claim.de (bytes 2 0) matches .ok _) - ++ test "Reveal axio mask bit 3 refused" (Ix.Claim.de (bytes 2 0x08) matches .error _) - ++ test "Reveal dprj mask bit 2 refused" (Ix.Claim.de (bytes 7 0x04) matches .error _) +def revealMaskTests : LSpec.Spec := do + let mkHeader (_ : Unit) : Array UInt8 := #[0xE6, 0x04, 0x00] ++ Array.replicate 32 0 + let bytes (variant mask : UInt8) : ByteArray := ⟨mkHeader () ++ #[variant, mask, 0x00]⟩ + itBool "Reveal defn with no fields reads" (Ix.Claim.de (bytes 0 0) matches .ok _) + itBool "Reveal defn mask bit 5 reads valid DefAsserts" + (Ix.Claim.de ⟨mkHeader () ++ #[0, 0x20, 0x06, 0x00]⟩ matches .ok _) + itBool "Reveal defn mask bit 5 refuses alloc 3" + (Ix.Claim.de ⟨mkHeader () ++ #[0, 0x20, 0x03, 0x00]⟩ matches .error _) + itBool "Reveal defn mask bit 5 refuses code 8" + (Ix.Claim.de ⟨mkHeader () ++ #[0, 0x20, 0x08, 0x00]⟩ matches .error _) + itBool "Reveal defn mask bit 6 refused" (Ix.Claim.de (bytes 0 0x40) matches .error _) + itBool "Reveal muts ctor mask bit 6 reads fieldModes" + (Ix.Claim.de ⟨mkHeader () ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x40, 2, 0, 1, 0x00]⟩ matches .ok _) + itBool "Reveal muts ctor fieldMode 2 refused" + (Ix.Claim.de ⟨mkHeader () ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x40, 2, 0, 2, 0x00]⟩ matches .error _) + itBool "Reveal muts ctor mask bit 7 refused" + (Ix.Claim.de ⟨mkHeader () ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x80, 0x00, 0x00]⟩ matches .error _) + itBool "Reveal binders opt tag 2 refused" + (Ix.Claim.de ⟨mkHeader () ++ #[0, 0, 0x02]⟩ matches .error _) + itBool "Reveal axio with no fields reads" (Ix.Claim.de (bytes 2 0) matches .ok _) + itBool "Reveal axio mask bit 3 refused" (Ix.Claim.de (bytes 2 0x08) matches .error _) + itBool "Reveal dprj mask bit 2 refused" (Ix.Claim.de (bytes 7 0x04) matches .error _) /-! ## Suite -/ -public def Tests.Claim.suite : List TestSeq := [ - claimUnits, - claimEncodingTests, - catalogClaimTests, - revealMaskTests, - checkIO "Claim serde roundtrips" (∀ c : Claim, claimSerde c), -] - +public def Tests.Claim.suite : LSpec.Spec := do + claimUnits + claimEncodingTests + catalogClaimTests + revealMaskTests + prop "Claim serde roundtrips" fun (c : Claim) => claimSerde c diff --git a/Tests/Ix/ClaimPolicy.lean b/Tests/Ix/ClaimPolicy.lean index 641c8d816e..a6eb94059f 100644 --- a/Tests/Ix/ClaimPolicy.lean +++ b/Tests/Ix/ClaimPolicy.lean @@ -32,13 +32,15 @@ namespace Tests.ClaimPolicy open LSpec Ix.Cli.ClaimPolicy Ix.Cli.TableAdmission +set_option compiler.extract_closed false + private def addr (s : String) : Address := Address.blake3 s.toUTF8 /-- This build's specification digest. -/ -private def spec : Address := Ix.SpecDigest.specDigest.toOption.getD default +private def mkSpec (_ : Unit) : Address := Ix.SpecDigest.specDigest.toOption.getD default -private def ctx : Ix.ClaimContext := - { spec, binding := Ix.Kernel.Reader.defaultTableAddress.toOption.getD default, +private def mkCtx (_ : Unit) : Ix.ClaimContext := + { spec := mkSpec (), binding := Ix.Kernel.Reader.defaultTableAddress.toOption.getD default, axioms := none } /-- Whether `pol` admits `claim`. -/ @@ -67,37 +69,37 @@ private def allBut (except : String) : Policy := binding := except != "binding" } /-- A claim of each kind that no theorem states, with its kind and its flag. -/ -private def untyped : List (String × Ix.Claim × Policy) := [ - ("eval", .eval ctx (addr "in") (addr "out") none, { eval := true }), - ("reveal", .reveal (addr "comm") (.axio none none none) none, { reveal := true }), - ("contains", .contains (addr "tree") (addr "const"), { contains := true }), - ("binding", .binding spec (addr "binding"), { binding := true })] +private def mkUntyped (_ : Unit) : List (String × (Unit → Ix.Claim) × Policy) := [ + ("eval", fun () => .eval (mkCtx ()) (addr "in") (addr "out") none, { eval := true }), + ("reveal", fun () => .reveal (addr "comm") (.axio none none none) none, { reveal := true }), + ("contains", fun () => .contains (addr "tree") (addr "const"), { contains := true }), + ("binding", fun () => .binding (mkSpec ()) (addr "binding"), { binding := true })] /-- Refusals by kind and by specification set. -/ -def kindTests : TestSeq := - let catalog : Ix.Claim := .catalog (addr "members") - let otherSpec := addr "another specification set" - untyped.foldl (init := TestSeq.done) (fun acc (kind, claim, flag) => - acc ++ test s!"a {kind} claim is refused by default, naming --allow-{kind}-claim" - (refusesSaying {} claim s!"--allow-{kind}-claim") - ++ test s!" accepted under --allow-{kind}-claim" (admits flag claim) - ++ test s!" and refused under every other flag" (!admits (allBut kind) claim)) - ++ test "a catalog is refused by default, naming --ixc" (refusesSaying {} catalog "--ixc") - ++ test " and under every flag" (!admits everyFlag catalog) - ++ test "a typing claim under another specification set is refused" - (refusesSaying {} (.checkEnv { ctx with spec := otherSpec } (addr "root") none) - "specification set") - ++ test " under every flag" (!admits everyFlag (.check { ctx with spec := otherSpec } (addr "c") none)) - ++ test " and under a table the kernel admits" - (!admits everyFlag (.checkEnv { ctx with spec := otherSpec, binding := addr "table" } - (addr "root") none) (tableAdmitted := true)) - ++ test " and as an evaluation" (!admits everyFlag (.eval { ctx with spec := otherSpec } - (addr "in") (addr "out") none)) - ++ test "a binding claim under another specification set is refused under its flag" - (!admits { binding := true } (.binding otherSpec (addr "binding"))) - ++ test "the kind flags accept no conditional typing claim" - (!admits { reveal := true, contains := true, binding := true } - (.checkEnv { ctx with axioms := some (addr "axioms") } (addr "root") none)) +def kindTests : LSpec.Spec := do + let mkCatalog (_ : Unit) : Ix.Claim := .catalog (addr "members") + let mkOtherSpec := fun () => addr "another specification set" + for (kind, mkClaim, flag) in mkUntyped () do + itBool s!"a {kind} claim is refused by default, naming --allow-{kind}-claim" + (refusesSaying {} (mkClaim ()) s!"--allow-{kind}-claim") + itBool s!" accepted under --allow-{kind}-claim" (admits flag (mkClaim ())) + itBool s!" and refused under every other flag" (!admits (allBut kind) (mkClaim ())) + itBool "a catalog is refused by default, naming --ixc" (refusesSaying {} (mkCatalog ()) "--ixc") + itBool " and under every flag" (!admits everyFlag (mkCatalog ())) + itBool "a typing claim under another specification set is refused" + (refusesSaying {} (.checkEnv { mkCtx () with spec := mkOtherSpec () } (addr "root") none) + "specification set") + itBool " under every flag" (!admits everyFlag (.check { mkCtx () with spec := mkOtherSpec () } (addr "c") none)) + itBool " and under a table the kernel admits" + (!admits everyFlag (.checkEnv { mkCtx () with spec := mkOtherSpec (), binding := addr "table" } + (addr "root") none) (tableAdmitted := true)) + itBool " and as an evaluation" (!admits everyFlag (.eval { mkCtx () with spec := mkOtherSpec () } + (addr "in") (addr "out") none)) + itBool "a binding claim under another specification set is refused under its flag" + (!admits { binding := true } (.binding (mkOtherSpec ()) (addr "binding"))) + itBool "the kind flags accept no conditional typing claim" + (!admits { reveal := true, contains := true, binding := true } + (.checkEnv { mkCtx () with axioms := some (addr "axioms") } (addr "root") none)) /-- Whether `claim`'s statement says every one of `texts`. -/ private def statementSays (claim : Ix.Claim) (texts : List String) @@ -108,122 +110,126 @@ private def statementSays (claim : Ix.Claim) (texts : List String) | .error _ => false /-- The verifier's report of each kind. -/ -def statementTests : TestSeq := - let defaultTable := ctx.binding - test "an unconditional check-env names its kind, subject and conditions" - (statementSays (.checkEnv ctx (addr "root") none) +def statementTests : LSpec.Spec := do + it "an unconditional check-env names its kind, subject and conditions" do + let ctx := mkCtx () + let spec := mkSpec () + let defaultTable := ctx.binding + expect (statementSays (.checkEnv ctx (addr "root") none) ["kind: check-env", s!"subject: the constants of the canonical tree with root {addr "root"}", "conditions:", s!"specification set: {spec}, this build's", s!"role table: {defaultTable}, the default role table", "axioms: the standard three only", "role binding: validated lazily by this proof", "typing assumptions: none"]) - ++ test "a check names its constant" (statementSays (.check ctx (addr "c") none) - ["kind: check", s!"subject: the constant {addr "c"}"]) - ++ test " states typing under Ix's rules, not Lean's kernel" - (statementSays (.check ctx (addr "c") none) - ["type-checks under Ix's kernel rules", "equality reflection", "not Lean's kernel"] - && !statementSays (.check ctx (addr "c") none) ["well-typed"]) - ++ test " and names the theorem, which needs a binding proof this run did not verify" - (statementSays (.check ctx (addr "c") none) - ["theorem: IxVM.Refinement.Endpoint.circuitComposed covers this claim only together with \ - an accepted binding claim", "which this run did not verify", - "has a model in every set theory", "no typing by Lean's kernel", - "role binding: validated lazily by this proof", - "established only by a binding proof for it"]) - ++ test " or states what it gives with a binding proof for its table" - (statementSays (.check ctx (addr "c") none) (bindingDischarged := true) - [s!"with the binding proof for role table {defaultTable} verified in this run", - "a BLAKE3 collision, or the table is valid", - "established by the binding proof verified with it"]) - ++ test " and that no theorem covers a table only the kernel admitted" - (statementSays (.check { ctx with binding := addr "table" } (addr "c") none) - (tableAdmitted := true) - ["the kernel's admission of the table is not such a proof", - "no theorem connects that admission"]) - ++ test "a claim with assumed leaves is covered by no theorem" - (statementSays (.checkEnv ctx (addr "root") (some (addr "leaves"))) (assumptionsDischarged := true) - ["theorem: none", "no theorem states the composition of a shard partition"]) - ++ test "nor an aggregation root" - (statementSays (.checkEnv ctx (addr "root") none) (route := .aggregate) - ["theorem: none states an aggregation root", "distinct validators 14/15"]) - ++ test "Mode 2 EvalDischargedClaim (validators 14/15) is distinct from Ix.Claim.de and refused by default" - (let dc : Ix.DynamicLink.EvalDischargedClaim := { ctx, kind := .check (addr "c"), assumptions := none } - let bytes := Ix.DynamicLink.serEvalDischargedClaim dc - (Ix.Claim.de bytes).isOk == false && - (Ix.DynamicLink.deEvalDischargedClaim bytes).toOption == some dc && - (match refusalDynamicBytes {} bytes with | .ok (some _) => true | _ => false) && - (match refusalDynamicBytes { eval := true } bytes with | .ok none => true | _ => false)) - ++ test " nor a compressed one" - (statementSays (.checkEnv ctx (addr "root") none) (route := .compressed) - ["nor a compressed proof to the aggregation proof"]) - ++ test "an eval names its input and output" - (statementSays (.eval ctx (addr "in") (addr "out") none) - ["kind: eval", s!"the constant {addr "in"}, evaluating to the constant {addr "out"}"]) - ++ test "an eval says what it asserts and that no theorem states it" - (statementSays (.eval ctx (addr "in") (addr "out") none) - ["the output is the input's normal form as IxVM's evaluator computes it", - "theorem: none; no theorem states an eval claim", "--allow-eval-claim"]) - ++ test "no other kind carries the eval theorem line" - (!statementSays (.check ctx (addr "c") none) ["no theorem states an eval claim"]) - ++ test "each open condition names the flag that accepted it" - (statementSays (.checkEnv - { ctx with binding := addr "table", axioms := some (addr "ax"), bindingAssumed := true } - (addr "root") (some (addr "leaves"))) - ["not admitted here (open; accepted under --allow-custom-binding)", - s!"user axioms {addr "ax"} (open; accepted under --allow-axioms)", - "(open; accepted under --allow-assumed-binding)", - s!"the leaves under {addr "leaves"} (open; accepted under --allow-assumptions)"]) - ++ test " and each discharged one what discharges it" - (statementSays (.checkEnv { ctx with binding := addr "table", bindingAssumed := true } - (addr "root") (some (addr "leaves"))) (bindingDischarged := true) - (assumptionsDischarged := true) (tableAdmitted := true) - [s!"role table: {addr "table"}, admitted by the kernel", - "discharged by the verified binding proof", "owned by the partition verified with it"]) - ++ test "a literal class is open" (statementSays (.checkEnv { ctx with literalClass := true } - (addr "root") none) ["any with the literal class", "--allow-custom-binding"]) - ++ test "a claim that states no typing says so" - (statementSays (.contains (addr "tree") (addr "const")) - ["kind: contains", s!"the leaf {addr "const"} of the tree with root {addr "tree"}", - "none; the claim states no typing"] - && statementSays (.reveal (addr "comm") (.axio none none none) none) - ["kind: reveal", s!"the constant committed as {addr "comm"}"]) - ++ test "a binding claim names its table and specification set" - (statementSays (.binding spec (addr "binding")) - ["kind: binding", s!"the role table {addr "binding"}", s!"specification set: {spec}, this build's"]) - ++ test "a catalog names its subjects" - (statementSays (.catalog (addr "members")) - ["kind: catalog", s!"root {addr "members"}", "each member's own"]) + itBool "a check names its constant" (statementSays (.check (mkCtx ()) (addr "c") none) + ["kind: check", s!"subject: the constant {addr "c"}"]) + itBool " states typing under Ix's rules, not Lean's kernel" + (statementSays (.check (mkCtx ()) (addr "c") none) + ["type-checks under Ix's kernel rules", "equality reflection", "not Lean's kernel"] + && !statementSays (.check (mkCtx ()) (addr "c") none) ["well-typed"]) + itBool " and names the theorem, which needs a binding proof this run did not verify" + (statementSays (.check (mkCtx ()) (addr "c") none) + ["theorem: IxVM.Refinement.Endpoint.circuitComposed covers this claim only together with \ + an accepted binding claim", "which this run did not verify", + "has a model in every set theory", "no typing by Lean's kernel", + "role binding: validated lazily by this proof", + "established only by a binding proof for it"]) + it " or states what it gives with a binding proof for its table" do + let ctx := mkCtx () + let defaultTable := ctx.binding + expect (statementSays (.check ctx (addr "c") none) (bindingDischarged := true) + [s!"with the binding proof for role table {defaultTable} verified in this run", + "a BLAKE3 collision, or the table is valid", + "established by the binding proof verified with it"]) + itBool " and that no theorem covers a table only the kernel admitted" + (statementSays (.check { mkCtx () with binding := addr "table" } (addr "c") none) + (tableAdmitted := true) + ["the kernel's admission of the table is not such a proof", + "no theorem connects that admission"]) + itBool "a claim with assumed leaves is covered by no theorem" + (statementSays (.checkEnv (mkCtx ()) (addr "root") (some (addr "leaves"))) (assumptionsDischarged := true) + ["theorem: none", "no theorem states the composition of a shard partition"]) + itBool "nor an aggregation root" + (statementSays (.checkEnv (mkCtx ()) (addr "root") none) (route := .aggregate) + ["theorem: none states an aggregation root", "distinct validators 14/15"]) + itBool "Mode 2 EvalDischargedClaim (validators 14/15) is distinct from Ix.Claim.de and refused by default" + (let dc : Ix.DynamicLink.EvalDischargedClaim := { ctx := mkCtx (), kind := .check (addr "c"), assumptions := none } + let bytes := Ix.DynamicLink.serEvalDischargedClaim dc + (Ix.Claim.de bytes).isOk == false && + (Ix.DynamicLink.deEvalDischargedClaim bytes).toOption == some dc && + (match refusalDynamicBytes {} bytes with | .ok (some _) => true | _ => false) && + (match refusalDynamicBytes { eval := true } bytes with | .ok none => true | _ => false)) + itBool " nor a compressed one" + (statementSays (.checkEnv (mkCtx ()) (addr "root") none) (route := .compressed) + ["nor a compressed proof to the aggregation proof"]) + itBool "an eval names its input and output" + (statementSays (.eval (mkCtx ()) (addr "in") (addr "out") none) + ["kind: eval", s!"the constant {addr "in"}, evaluating to the constant {addr "out"}"]) + itBool "an eval says what it asserts and that no theorem states it" + (statementSays (.eval (mkCtx ()) (addr "in") (addr "out") none) + ["the output is the input's normal form as IxVM's evaluator computes it", + "theorem: none; no theorem states an eval claim", "--allow-eval-claim"]) + itBool "no other kind carries the eval theorem line" + (!statementSays (.check (mkCtx ()) (addr "c") none) ["no theorem states an eval claim"]) + itBool "each open condition names the flag that accepted it" + (statementSays (.checkEnv + { mkCtx () with binding := addr "table", axioms := some (addr "ax"), bindingAssumed := true } + (addr "root") (some (addr "leaves"))) + ["not admitted here (open; accepted under --allow-custom-binding)", + s!"user axioms {addr "ax"} (open; accepted under --allow-axioms)", + "(open; accepted under --allow-assumed-binding)", + s!"the leaves under {addr "leaves"} (open; accepted under --allow-assumptions)"]) + itBool " and each discharged one what discharges it" + (statementSays (.checkEnv { mkCtx () with binding := addr "table", bindingAssumed := true } + (addr "root") (some (addr "leaves"))) (bindingDischarged := true) + (assumptionsDischarged := true) (tableAdmitted := true) + [s!"role table: {addr "table"}, admitted by the kernel", + "discharged by the verified binding proof", "owned by the partition verified with it"]) + itBool "a literal class is open" (statementSays (.checkEnv { mkCtx () with literalClass := true } + (addr "root") none) ["any with the literal class", "--allow-custom-binding"]) + itBool "a claim that states no typing says so" + (statementSays (.contains (addr "tree") (addr "const")) + ["kind: contains", s!"the leaf {addr "const"} of the tree with root {addr "tree"}", + "none; the claim states no typing"] + && statementSays (.reveal (addr "comm") (.axio none none none) none) + ["kind: reveal", s!"the constant committed as {addr "comm"}"]) + itBool "a binding claim names its table and specification set" + (statementSays (.binding (mkSpec ()) (addr "binding")) + ["kind: binding", s!"the role table {addr "binding"}", s!"specification set: {mkSpec ()}, this build's"]) + itBool "a catalog names its subjects" + (statementSays (.catalog (addr "members")) + ["kind: catalog", s!"root {addr "members"}", "each member's own"]) -def unitTests : TestSeq := - let unconditional : Ix.Claim := .checkEnv ctx (addr "root") none - let assumed : Ix.Claim := .check ctx (addr "const") (some (addr "leaves")) - let axioms : Ix.Claim := .checkEnv { ctx with axioms := some (addr "axioms") } (addr "root") none - let bound : Ix.Claim := .checkEnv { ctx with bindingAssumed := true } (addr "root") none - let other : Ix.Claim := .checkEnv { ctx with binding := addr "table" } (addr "root") none - let literal : Ix.Claim := .checkEnv { ctx with literalClass := true } (addr "root") none - test "an unconditional typing claim is admitted" (admits {} unconditional) - ++ test "a claim with assumed leaves is refused" (!admits {} assumed) - ++ test " unless --allow-assumptions" (admits { assumptions := true } assumed) - ++ test " or a whole partition discharges them" (admits {} assumed false true) - ++ test "an evaluation with assumed leaves is refused" - (!admits {} (.eval ctx (addr "in") (addr "out") (some (addr "leaves")))) - ++ test "a claim with user axioms is refused" (!admits {} axioms) - ++ test " even when its assumptions are discharged" (!admits {} axioms true true) - ++ test " unless --allow-axioms" (admits { axioms := true } axioms) - ++ test "a claim that assumes its binding is refused" (!admits {} bound) - ++ test " unless a binding proof discharges it" (admits {} bound true) - ++ test " or --allow-assumed-binding" (admits { assumedBinding := true } bound) - ++ test "a claim under another role table is refused" (!admits {} other) - ++ test " and one under a literal class" (!admits {} literal) - ++ test " unless --allow-custom-binding" (admits { customBinding := true } other) - ++ test " or the kernel admits the table" (admits {} other (tableAdmitted := true)) - ++ test " which a literal class never is" (!admits {} literal (tableAdmitted := true)) - ++ test " and a binding proof never discharges a literal class's assumed binding" - (!admits { customBinding := true } - (.checkEnv { ctx with literalClass := true, bindingAssumed := true } (addr "root") none) - (bindingDischarged := true)) - ++ test " and the admission relaxes no other condition" - (!admits {} (.checkEnv { ctx with binding := addr "table", axioms := some (addr "axioms") } - (addr "root") none) (tableAdmitted := true)) +def unitTests : LSpec.Spec := do + let mkUnconditional (_ : Unit) : Ix.Claim := .checkEnv (mkCtx ()) (addr "root") none + let mkAssumed (_ : Unit) : Ix.Claim := .check (mkCtx ()) (addr "const") (some (addr "leaves")) + let mkAxioms (_ : Unit) : Ix.Claim := .checkEnv { mkCtx () with axioms := some (addr "axioms") } (addr "root") none + let mkBound (_ : Unit) : Ix.Claim := .checkEnv { mkCtx () with bindingAssumed := true } (addr "root") none + let mkOther (_ : Unit) : Ix.Claim := .checkEnv { mkCtx () with binding := addr "table" } (addr "root") none + let mkLiteral (_ : Unit) : Ix.Claim := .checkEnv { mkCtx () with literalClass := true } (addr "root") none + itBool "an unconditional typing claim is admitted" (admits {} (mkUnconditional ())) + itBool "a claim with assumed leaves is refused" (!admits {} (mkAssumed ())) + itBool " unless --allow-assumptions" (admits { assumptions := true } (mkAssumed ())) + itBool " or a whole partition discharges them" (admits {} (mkAssumed ()) false true) + itBool "an evaluation with assumed leaves is refused" + (!admits {} (.eval (mkCtx ()) (addr "in") (addr "out") (some (addr "leaves")))) + itBool "a claim with user axioms is refused" (!admits {} (mkAxioms ())) + itBool " even when its assumptions are discharged" (!admits {} (mkAxioms ()) true true) + itBool " unless --allow-axioms" (admits { axioms := true } (mkAxioms ())) + itBool "a claim that assumes its binding is refused" (!admits {} (mkBound ())) + itBool " unless a binding proof discharges it" (admits {} (mkBound ()) true) + itBool " or --allow-assumed-binding" (admits { assumedBinding := true } (mkBound ())) + itBool "a claim under another role table is refused" (!admits {} (mkOther ())) + itBool " and one under a literal class" (!admits {} (mkLiteral ())) + itBool " unless --allow-custom-binding" (admits { customBinding := true } (mkOther ())) + itBool " or the kernel admits the table" (admits {} (mkOther ()) (tableAdmitted := true)) + itBool " which a literal class never is" (!admits {} (mkLiteral ()) (tableAdmitted := true)) + itBool " and a binding proof never discharges a literal class's assumed binding" + (!admits { customBinding := true } + (.checkEnv { mkCtx () with literalClass := true, bindingAssumed := true } (addr "root") none) + (bindingDischarged := true)) + itBool " and the admission relaxes no other condition" + (!admits {} (.checkEnv { mkCtx () with binding := addr "table", axioms := some (addr "axioms") } + (addr "root") none) (tableAdmitted := true)) /-- A standing's shape, for the tests. -/ private def shape : Standing → String @@ -238,7 +244,7 @@ private def says (s : Standing) (text : String) : Bool := | _ => false /-- `standing`'s cases over a temporary cache root. -/ -def standingTests : IO TestSeq := do +def standingTests : IO Spec := do let spec ← IO.ofExcept Ix.SpecDigest.specDigest let defaultTable ← IO.ofExcept Ix.Kernel.Reader.defaultTableAddress let table := addr "a custom table" @@ -268,27 +274,34 @@ def standingTests : IO TestSeq := do -- an entry written by another checker version is a miss IO.FS.writeFile (dir / toString spec / toString table) "table-admission/0\n" let stale ← cached dir spec table - return test "the default table needs no admission and reads no environment" (shape s0 == "default") - ++ test "a literal class is not admitted" (shape s1 == "unestablished") - ++ test "a claim under another specification set is not admitted" (shape s2 == "unestablished") - ++ test "a table no supplied environment carries is not admitted" (shape s3 == "unestablished") - ++ test " nor one only another table's environment carries" (shape s4 == "unestablished") - ++ test "a build with no admission run admits no table" (shape s5 == "unestablished") - ++ test "a table the kernel refuses is not admitted, nor recorded" - (shape s6 == "unestablished" && !recordedEarly) - ++ test " and the refusal gives the refusing stage" (says s6 "the test checker refuses") - ++ test "a table the kernel admits is admitted and recorded" - (shape s7 == "admitted false" && recorded) - ++ test " and the record answers the next claim without an environment or a run" - (shape s8 == "admitted true") - ++ test " under its specification set only" (!otherSpec) - ++ test " and this checker version only" (!stale) - ++ test "the environments were read only where the table needed them" ((← reads.get) == 5) + let readCount ← reads.get + return do + itBool "the default table needs no admission and reads no environment" (shape s0 == "default") + itBool "a literal class is not admitted" (shape s1 == "unestablished") + itBool "a claim under another specification set is not admitted" (shape s2 == "unestablished") + itBool "a table no supplied environment carries is not admitted" (shape s3 == "unestablished") + itBool " nor one only another table's environment carries" (shape s4 == "unestablished") + itBool "a build with no admission run admits no table" (shape s5 == "unestablished") + itBool "a table the kernel refuses is not admitted, nor recorded" + (shape s6 == "unestablished" && !recordedEarly) + itBool " and the refusal gives the refusing stage" (says s6 "the test checker refuses") + itBool "a table the kernel admits is admitted and recorded" + (shape s7 == "admitted false" && recorded) + itBool " and the record answers the next claim without an environment or a run" + (shape s8 == "admitted true") + itBool " under its specification set only" (!otherSpec) + itBool " and this checker version only" (!stale) + itBool "the environments were read only where the table needed them" (readCount == 5) finally IO.FS.removeDirAll dir -def suite : IO (List TestSeq) := do - return [unitTests, kindTests, statementTests, ← standingTests] +def suite : IO Spec := do + let standing ← standingTests + return do + unitTests + kindTests + statementTests + standing end Tests.ClaimPolicy diff --git a/Tests/Ix/CollectDependencies.lean b/Tests/Ix/CollectDependencies.lean index 88667f8861..e726277f47 100644 --- a/Tests/Ix/CollectDependencies.lean +++ b/Tests/Ix/CollectDependencies.lean @@ -63,15 +63,14 @@ def sameSet (ns ms : List Lean.Name) : Bool := ns.length == ms.length && ns.all ms.contains && ms.all ns.contains open LSpec in -def suite : List TestSeq := [ - test "the closure of First lists each declaration once" (distinct fromFirst), - test "the closure of First, in first-discovery order" (fromFirst == firstExpected), - test "the closure of Second lists the family once" (distinct fromSecond && sameSet fromSecond family), - test "the closure of Third lists the family once" (distinct fromThird && sameSet fromThird family), - test "the closure of a constructor lists the family once" - (distinct fromConstructor && sameSet fromConstructor family), - test "two roots of one family share one walk" (distinct fromTwo && sameSet fromTwo family), - test "the single-root collector agrees" (fromFirstOne == fromFirst) -] +def suite : LSpec.Spec := do + itBool "the closure of First lists each declaration once" (distinct fromFirst) + itBool "the closure of First, in first-discovery order" (fromFirst == firstExpected) + itBool "the closure of Second lists the family once" (distinct fromSecond && sameSet fromSecond family) + itBool "the closure of Third lists the family once" (distinct fromThird && sameSet fromThird family) + itBool "the closure of a constructor lists the family once" + (distinct fromConstructor && sameSet fromConstructor family) + itBool "two roots of one family share one walk" (distinct fromTwo && sameSet fromTwo family) + itBool "the single-root collector agrees" (fromFirstOne == fromFirst) end Tests.Ix.CollectDependencies diff --git a/Tests/Ix/Commit.lean b/Tests/Ix/Commit.lean index 4891c80fc4..ab0b958068 100644 --- a/Tests/Ix/Commit.lean +++ b/Tests/Ix/Commit.lean @@ -10,58 +10,67 @@ open LSpec open Ixon (Comm runGet serCommTagged) open Ix (Claim RevealConstantInfo) +set_option compiler.extract_closed false + /-! ## Test addresses -/ -private def payload1 : Address := Address.blake3 "payload1".toUTF8 -private def payload2 : Address := Address.blake3 "payload2".toUTF8 -private def secret1 : Address := Address.blake3 "secret1".toUTF8 -private def secret2 : Address := Address.blake3 "secret2".toUTF8 +private def mkPayload1 (_ : Unit) : Address := Address.blake3 "payload1".toUTF8 +private def mkPayload2 (_ : Unit) : Address := Address.blake3 "payload2".toUTF8 +private def mkSecret1 (_ : Unit) : Address := Address.blake3 "secret1".toUTF8 +private def mkSecret2 (_ : Unit) : Address := Address.blake3 "secret2".toUTF8 /-! ## Comm.commit determinism tests -/ -def commDeterminismTests : TestSeq := - let comm1 := Comm.mk secret1 payload1 - let comm2 := Comm.mk secret1 payload1 - -- Same comm → same address - test "Comm.commit deterministic" (Comm.commit comm1 == Comm.commit comm2) - -- Different secrets → different addresses - ++ test "Different secrets produce different commit addresses" - (Comm.commit (Comm.mk secret1 payload1) != Comm.commit (Comm.mk secret2 payload1)) - -- Different payloads → different addresses - ++ test "Different payloads produce different commit addresses" - (Comm.commit (Comm.mk secret1 payload1) != Comm.commit (Comm.mk secret1 payload2)) - -- Verify commitment format: tagged serialization starts with 0xE1 and is 65 bytes - ++ test "serCommTagged starts with 0xE1" - ((serCommTagged comm1).data[0]! == 0xE1) - ++ test "serCommTagged is 65 bytes" - ((serCommTagged comm1).size == 65) +def commDeterminismTests : LSpec.Spec := do + it "Comm.commit deterministic" do + let comm1 := Comm.mk (mkSecret1 ()) (mkPayload1 ()) + let comm2 := Comm.mk (mkSecret1 ()) (mkPayload1 ()) + expect (Comm.commit comm1 == Comm.commit comm2) + it "Different secrets produce different commit addresses" do + expect (Comm.commit (Comm.mk (mkSecret1 ()) (mkPayload1 ())) != + Comm.commit (Comm.mk (mkSecret2 ()) (mkPayload1 ()))) + it "Different payloads produce different commit addresses" do + expect (Comm.commit (Comm.mk (mkSecret1 ()) (mkPayload1 ())) != + Comm.commit (Comm.mk (mkSecret1 ()) (mkPayload2 ()))) + it "serCommTagged starts with 0xE1" do + let comm1 := Comm.mk (mkSecret1 ()) (mkPayload1 ()) + expect ((serCommTagged comm1).data[0]! == 0xE1) + it "serCommTagged is 65 bytes" do + let comm1 := Comm.mk (mkSecret1 ()) (mkPayload1 ()) + expect ((serCommTagged comm1).size == 65) /-! ## Claim.commit tests -/ /-- A stand-in claim context. -/ -private def ctx : Ix.ClaimContext := +private def mkCtx (_ : Unit) : Ix.ClaimContext := { spec := Address.blake3 "commit-test-spec".toUTF8 binding := Address.blake3 "commit-test-binding".toUTF8 axioms := none } -def claimCommitTests : TestSeq := - let evalClaim := Claim.eval ctx payload1 payload2 none - let checkClaim := Claim.check ctx payload1 none - let revealSafety := Claim.reveal payload1 (.defn none (some .safe) none none none none) none - let revealKind := Claim.reveal payload1 (.defn (some .defn) none none none none none) none - let revealBoth := Claim.reveal payload1 (.defn (some .defn) (some .safe) none none none none) none - -- Claim.commit is deterministic - test "Claim.commit deterministic" (Claim.commit evalClaim == Claim.commit evalClaim) - -- Different claim types → different addresses - ++ test "eval and check have different commit addresses" - (Claim.commit evalClaim != Claim.commit checkClaim) - -- Different reveal fields → different addresses - ++ test "Reveal safety-only differs from kind-only" - (Claim.commit revealSafety != Claim.commit revealKind) - ++ test "Reveal kind-only differs from kind+safety" - (Claim.commit revealKind != Claim.commit revealBoth) - ++ test "Reveal safety-only differs from kind+safety" - (Claim.commit revealSafety != Claim.commit revealBoth) +def claimCommitTests : LSpec.Spec := do + it "Claim.commit deterministic" do + let evalClaim := Claim.eval (mkCtx ()) (mkPayload1 ()) (mkPayload2 ()) none + expect (Claim.commit evalClaim == Claim.commit evalClaim) + it "eval and check have different commit addresses" do + let ctx := mkCtx () + let evalClaim := Claim.eval ctx (mkPayload1 ()) (mkPayload2 ()) none + let checkClaim := Claim.check ctx (mkPayload1 ()) none + expect (Claim.commit evalClaim != Claim.commit checkClaim) + it "Reveal safety-only differs from kind-only" do + let p1 := mkPayload1 () + let revealSafety := Claim.reveal p1 (.defn none (some .safe) none none none none) none + let revealKind := Claim.reveal p1 (.defn (some .defn) none none none none none) none + expect (Claim.commit revealSafety != Claim.commit revealKind) + it "Reveal kind-only differs from kind+safety" do + let p1 := mkPayload1 () + let revealKind := Claim.reveal p1 (.defn (some .defn) none none none none none) none + let revealBoth := Claim.reveal p1 (.defn (some .defn) (some .safe) none none none none) none + expect (Claim.commit revealKind != Claim.commit revealBoth) + it "Reveal safety-only differs from kind+safety" do + let p1 := mkPayload1 () + let revealSafety := Claim.reveal p1 (.defn none (some .safe) none none none none) none + let revealBoth := Claim.reveal p1 (.defn (some .defn) (some .safe) none none none none) none + expect (Claim.commit revealSafety != Claim.commit revealBoth) /-! ## RevealClaim field combination tests -/ @@ -71,41 +80,42 @@ private def claimRoundtrips (c : Claim) : Bool := | .ok c' => c' == c | .error _ => false -private def allNoneClaim : Claim := - Claim.reveal payload1 (.defn none none none none none none) none +private def mkAllNoneClaim (_ : Unit) : Claim := + Claim.reveal (mkPayload1 ()) (.defn none none none none none none) none -private def allFieldsClaim : Claim := - Claim.reveal payload1 - (.defn (some .defn) (some .safe) (some 3) (some payload2) (some payload1) +private def mkAllFieldsClaim (_ : Unit) : Claim := + Claim.reveal (mkPayload1 ()) + (.defn (some .defn) (some .safe) (some 3) (some (mkPayload2 ())) (some (mkPayload1 ())) (some { alloc := .noAlloc, boundedStack := true })) - (some secret1) + (some (mkSecret1 ())) -private def singleFieldAddrsDistinct : Bool := - let comm := payload1 +private def singleFieldAddrsDistinct (_ : Unit) : Bool := + let comm := mkPayload1 () + let p2 := mkPayload2 () let addrK := Claim.commit (.reveal comm (.defn (some .defn) none none none none none) none) let addrS := Claim.commit (.reveal comm (.defn none (some .safe) none none none none) none) let addrL := Claim.commit (.reveal comm (.defn none none (some 1) none none none) none) - let addrT := Claim.commit (.reveal comm (.defn none none none (some payload2) none none) none) - let addrV := Claim.commit (.reveal comm (.defn none none none none (some payload2) none) none) + let addrT := Claim.commit (.reveal comm (.defn none none none (some p2) none none) none) + let addrV := Claim.commit (.reveal comm (.defn none none none none (some p2) none) none) let addrA := Claim.commit (.reveal comm (.defn none none none none none (some { alloc := .noRc, boundedStack := false })) none) - let addrB := Claim.commit (.reveal comm (.defn none none none none none none) (some payload2)) + let addrB := Claim.commit (.reveal comm (.defn none none none none none none) (some p2)) let addrs := #[addrK, addrS, addrL, addrT, addrV, addrA, addrB] (List.range addrs.size).all fun i => (List.range addrs.size).all fun j => i == j || addrs[i]! != addrs[j]! -def fieldCombinationTests : TestSeq := +def fieldCombinationTests : LSpec.Spec := do -- All-none fields still produce a valid claim - test "All-none defn serialization roundtrips" (claimRoundtrips allNoneClaim) + itBool "All-none defn serialization roundtrips" (claimRoundtrips (mkAllNoneClaim ())) -- All fields present still produce a valid claim - ++ test "All-fields defn serialization roundtrips" (claimRoundtrips allFieldsClaim) + itBool "All-fields defn serialization roundtrips" (claimRoundtrips (mkAllFieldsClaim ())) -- Each single field produces a distinct commit address - ++ test "Single-field reveals have distinct commit addresses" singleFieldAddrsDistinct + itBool "Single-field reveals have distinct commit addresses" (singleFieldAddrsDistinct ()) /-! ## compileDef determinism tests -/ -private def emptyCompileEnv : Ix.CompileM.CompileEnv := +private def mkEmptyCompileEnv (_ : Unit) : Ix.CompileM.CompileEnv := Ix.CompileM.CompileEnv.new { consts := {} } -- def anon : Type := Prop @@ -116,27 +126,30 @@ private def simpleValue : Lean.Expr := Lean.mkSort .zero private def simpleType2 : Lean.Expr := Lean.mkSort (.succ (.succ .zero)) private def simpleValue2 : Lean.Expr := Lean.mkSort (.succ .zero) -private def compileDefSucceeds : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue with +private def compileDefSucceeds (_ : Unit) : Bool := + match Ix.Commit.compileDef (mkEmptyCompileEnv ()) [] simpleType simpleValue with | .ok _ => true | .error _ => false -private def compileDefDeterministic : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue, - Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue with +private def compileDefDeterministic (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] simpleType simpleValue, + Ix.Commit.compileDef env [] simpleType simpleValue with | .ok (addr1, _), .ok (addr2, _) => addr1 == addr2 | _, _ => false -private def compileDefDifferentValueDifferentAddr : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue, - Ix.Commit.compileDef emptyCompileEnv [] simpleType2 simpleValue2 with +private def compileDefDifferentValueDifferentAddr (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] simpleType simpleValue, + Ix.Commit.compileDef env [] simpleType2 simpleValue2 with | .ok (addr1, _), .ok (addr2, _) => addr1 != addr2 | _, _ => false -- Alpha-invariance: constant name must not affect the content address -private def compileDefAlphaConstName : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue (name := .anonymous), - Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue (name := .str .anonymous "Foo") with +private def compileDefAlphaConstName (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] simpleType simpleValue (name := .anonymous), + Ix.Commit.compileDef env [] simpleType simpleValue (name := .str .anonymous "Foo") with | .ok (addr1, _), .ok (addr2, _) => addr1 == addr2 | _, _ => false @@ -148,47 +161,50 @@ private def binderValue1 : Lean.Expr := Lean.mkLambda `x .default propExpr (Lean private def binderType2 : Lean.Expr := Lean.mkForall `y .default propExpr propExpr private def binderValue2 : Lean.Expr := Lean.mkLambda `y .default propExpr (Lean.mkBVar 0) -private def compileDefAlphaBinderNames : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] binderType1 binderValue1, - Ix.Commit.compileDef emptyCompileEnv [] binderType2 binderValue2 with +private def compileDefAlphaBinderNames (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] binderType1 binderValue1, + Ix.Commit.compileDef env [] binderType2 binderValue2 with | .ok (addr1, _), .ok (addr2, _) => addr1 == addr2 | _, _ => false -- Alpha-invariance: level parameter names must not affect the content address -- def _.{u} : Sort (u+1) := Sort u vs def _.{v} : Sort (v+1) := Sort v -private def compileDefAlphaLevelNames : Bool := +private def compileDefAlphaLevelNames (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () let typ1 := Lean.mkSort (.succ (.param `u)) let val1 := Lean.mkSort (.param `u) let typ2 := Lean.mkSort (.succ (.param `v)) let val2 := Lean.mkSort (.param `v) - match Ix.Commit.compileDef emptyCompileEnv [`u] typ1 val1, - Ix.Commit.compileDef emptyCompileEnv [`v] typ2 val2 with + match Ix.Commit.compileDef env [`u] typ1 val1, + Ix.Commit.compileDef env [`v] typ2 val2 with | .ok (addr1, _), .ok (addr2, _) => addr1 == addr2 | _, _ => false -def compileDefTests : TestSeq := - test "compileDef succeeds on simple def" compileDefSucceeds - ++ test "compileDef produces same address for same inputs" compileDefDeterministic - ++ test "compileDef produces different address for different inputs" compileDefDifferentValueDifferentAddr - ++ test "alpha-invariance: constant name does not affect address" compileDefAlphaConstName - ++ test "alpha-invariance: binder names do not affect address" compileDefAlphaBinderNames - ++ test "alpha-invariance: level param names do not affect address" compileDefAlphaLevelNames +def compileDefTests : LSpec.Spec := do + itBool "compileDef succeeds on simple def" (compileDefSucceeds ()) + itBool "compileDef produces same address for same inputs" (compileDefDeterministic ()) + itBool "compileDef produces different address for different inputs" (compileDefDifferentValueDifferentAddr ()) + itBool "alpha-invariance: constant name does not affect address" (compileDefAlphaConstName ()) + itBool "alpha-invariance: binder names do not affect address" (compileDefAlphaBinderNames ()) + itBool "alpha-invariance: level param names do not affect address" (compileDefAlphaLevelNames ()) /-! ## checkClaim and revealClaim tests -/ -private def checkClaimSucceeds : Bool := - match Ix.Commit.checkClaim ctx emptyCompileEnv [] simpleType simpleValue with +private def checkClaimSucceeds (_ : Unit) : Bool := + match Ix.Commit.checkClaim (mkCtx ()) (mkEmptyCompileEnv ()) [] simpleType simpleValue with | .ok (.check _ _ _) => true | _ => false -private def checkClaimMatchesCompileDef : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue, - Ix.Commit.checkClaim ctx emptyCompileEnv [] simpleType simpleValue with +private def checkClaimMatchesCompileDef (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] simpleType simpleValue, + Ix.Commit.checkClaim (mkCtx ()) env [] simpleType simpleValue with | .ok (addr, _), .ok (.check _ claimAddr _) => addr == claimAddr | _, _ => false -private def openConstantInfoDefn : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue with +private def openConstantInfoDefn (_ : Unit) : Bool := + match Ix.Commit.compileDef (mkEmptyCompileEnv ()) [] simpleType simpleValue with | .ok (_, env') => -- Look up the compiled constant via the anonymous name let (ixName, _) := (Ix.CanonM.canonName .anonymous).run {} @@ -208,8 +224,8 @@ private def openConstantInfoDefn : Bool := | none => false | .error _ => false -private def openConstantInfoRoundtrips : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue with +private def openConstantInfoRoundtrips (_ : Unit) : Bool := + match Ix.Commit.compileDef (mkEmptyCompileEnv ()) [] simpleType simpleValue with | .ok (_, env') => let (ixName, _) := (Ix.CanonM.canonName .anonymous).run {} match env'.nameToNamed.get? ixName with @@ -221,45 +237,45 @@ private def openConstantInfoRoundtrips : Bool := let info := Ix.Commit.openConstantInfo constant.info let bAddr := Ix.Commit.sectionAddr constant.binders -- The fully-revealed RevealConstantInfo and sectionAddr should serde roundtrip - claimRoundtrips (.reveal payload1 info (some bAddr)) + claimRoundtrips (.reveal (mkPayload1 ()) info (some bAddr)) | .error _ => false | none => false | none => false | .error _ => false -private def revealClaimWrapper : Bool := +private def revealClaimWrapper (_ : Unit) : Bool := + let p1 := mkPayload1 () + let p2 := mkPayload2 () let info : RevealConstantInfo := .defn (some .defn) none none none none none - let claim := Ix.Commit.revealClaim payload1 info - let claimWithBinders := Ix.Commit.revealClaim payload1 info (some payload2) - claim == Claim.reveal payload1 info none && - claimWithBinders == Claim.reveal payload1 info (some payload2) - -def claimConstructorTests : TestSeq := - test "checkClaim succeeds" checkClaimSucceeds - ++ test "checkClaim address matches compileDef" checkClaimMatchesCompileDef - ++ test "openConstantInfo produces defn with all fields" openConstantInfoDefn - ++ test "openConstantInfo result serde roundtrips" openConstantInfoRoundtrips - ++ test "revealClaim wraps correctly" revealClaimWrapper + let claim := Ix.Commit.revealClaim p1 info + let claimWithBinders := Ix.Commit.revealClaim p1 info (some p2) + claim == Claim.reveal p1 info none && + claimWithBinders == Claim.reveal p1 info (some p2) + +def claimConstructorTests : LSpec.Spec := do + itBool "checkClaim succeeds" (checkClaimSucceeds ()) + itBool "checkClaim address matches compileDef" (checkClaimMatchesCompileDef ()) + itBool "openConstantInfo produces defn with all fields" (openConstantInfoDefn ()) + itBool "openConstantInfo result serde roundtrips" (openConstantInfoRoundtrips ()) + itBool "revealClaim wraps correctly" (revealClaimWrapper ()) /-! ## IO tests for commitConst -/ -def commitConstIOTest : TestSeq := - .individualIO "commitConst: different random secrets produce different addresses" none (do +def commitConstIOTest : LSpec.Spec := do + it "commitConst: different random secrets produce different addresses" do let payload := Address.blake3 "test-payload".toUTF8 let (_, commitAddr1) ← Ix.Commit.commitConst payload let (_, commitAddr2) ← Ix.Commit.commitConst payload - return (commitAddr1 != commitAddr2, 0, 0, none)) .done + expect (commitAddr1 != commitAddr2) /-! ## Suite registration -/ -public def Tests.Commit.suite : List TestSeq := [ - commDeterminismTests, - claimCommitTests, - fieldCombinationTests, - compileDefTests, - claimConstructorTests, -] - -public def Tests.Commit.suiteIO : List TestSeq := [ - commitConstIOTest, -] +public def Tests.Commit.suite : LSpec.Spec := do + commDeterminismTests + claimCommitTests + fieldCombinationTests + compileDefTests + claimConstructorTests + +public def Tests.Commit.suiteIO : LSpec.Spec := do + commitConstIOTest diff --git a/Tests/Ix/Compile/AuxiliaryClosureCanon.lean b/Tests/Ix/Compile/AuxiliaryClosureCanon.lean index 9e8b416443..dfad0f5ab7 100644 --- a/Tests/Ix/Compile/AuxiliaryClosureCanon.lean +++ b/Tests/Ix/Compile/AuxiliaryClosureCanon.lean @@ -439,8 +439,8 @@ def runLeg (env : Lean.Environment) (dir : System.FilePath) (ref : Ixon.Env) ({classes.size} distinct closures, {(← IO.monoMsNow) - t0} ms)" return failed -def suite : List TestSeq := [ - .individualIO "aux addresses are closure-invariant" none (do +def suite : LSpec.Spec := do + it "aux addresses are closure-invariant" do let env ← get_env! let fx := `Tests.Ix.Compile.AuxiliaryClosureCanon.Fx let seeds := (env.constants.toList.filterMap fun (n, _) => @@ -455,7 +455,7 @@ def suite : List TestSeq := [ let ref ← match ← compileClosure env dir "ref" (Ix.EnvScope.collectSelectedDepsWith env units seeds.toList) (bind := true) with | .ok e => pure e - | .error e => throw (IO.userError s!"reference compile: {e}") + | .error e => fail s!"reference compile: {e}" IO.println s!"[canon-closure-aux] reference: {seeds.size} seeds, {ref.named.size} names, \ bound ({(← IO.monoMsNow) - t0} ms); files in {dir}" -- Leg 1, the closure producers (`collectDeps`): every address is the @@ -508,12 +508,8 @@ def suite : List TestSeq := [ let twinErrors := twinRecursorCheck env for e in twinErrors do IO.println s!"[canon-closure-aux] FAIL {e}" IO.println s!"[canon-closure-aux] twin: {if twinErrors.isEmpty then "ok" else "FAIL"}" - let n := 3 * seeds.size + auxSeeds.size + 1 let failed := f1 + f2 + f3 + f4 + (if twinErrors.isEmpty then 0 else 1) if failed == 0 then IO.FS.removeDirAll dir - return (failed == 0, n - failed, n, - if failed == 0 then none else some s!"{failed} seed check(s) failed")) - .done -] + expect (failed == 0) s!"{failed} seed check(s) failed" end Tests.Ix.Compile.AuxiliaryClosureCanon diff --git a/Tests/Ix/Compile/Equations.lean b/Tests/Ix/Compile/Equations.lean index 5dd2447ba2..c7a38c2467 100644 --- a/Tests/Ix/Compile/Equations.lean +++ b/Tests/Ix/Compile/Equations.lean @@ -77,7 +77,7 @@ def elaborate (dir : System.FilePath) (file : String) (text : String) : IO Envir IO.FS.writeFile path text getFileEnv path -def suite : IO (List LSpec.TestSeq) := do +def suite : IO LSpec.Spec := do IO.FS.withTempDir fun dir => do let env ← elaborate dir "Equations.lean" source let before := structural.map fun d => env.contains (d ++ `eq_def) @@ -102,32 +102,32 @@ def suite : IO (List LSpec.TestSeq) := do | _, _ => none | .error _ => [] let sorted := listed.map (·.1) - return [ - test "no structural unfolding theorem exists before the export" (before.all (!·)), - test "every local recursive definition is associated with its own eq_def" - (recursive.all pairs.contains), - test "the non-recursive definitions are not associated" - (!pairs.any fun (d, _) => d == `EqnFixture.double || d == `EqnFixture.entry), - test "a library definition the root reaches is associated (List.length)" - (pairs.contains (`List.length, `List.length.eq_def)), - test "no equation generation failed" failed.isEmpty, - test "each definition is associated once" - ((pairs.map (·.1)).eraseDups.length == pairs.length), - test "the closure holds every associated theorem" - (found.all fun a => closedNames.contains a.equation), - test "each realized theorem has the statement Lean's elaborator gives it" sameAsLean, - test "each associated theorem states `f xs = …` for its definition" selfUnfolding, - test "the JSON names its format" - ((json.getObjValAs? String "format").toOption == some "ix/compile-equations/2"), - test "the closure reaches word operations, through log2's omega proof only" - (closed.any fun (n, _) => Ix.Compile.WordEquations.operations.contains n), - test "with the word equations on (ix compile's default) none joins the closure: a proof is a theorem, which the word walk does not enter" + return do + itBool "no structural unfolding theorem exists before the export" (before.all (!·)) + itBool "every local recursive definition is associated with its own eq_def" + (recursive.all pairs.contains) + itBool "the non-recursive definitions are not associated" + (!pairs.any fun (d, _) => d == `EqnFixture.double || d == `EqnFixture.entry) + itBool "a library definition the root reaches is associated (List.length)" + (pairs.contains (`List.length, `List.length.eq_def)) + itBool "no equation generation failed" failed.isEmpty + itBool "each definition is associated once" + ((pairs.map (·.1)).eraseDups.length == pairs.length) + itBool "the closure holds every associated theorem" + (found.all fun a => closedNames.contains a.equation) + itBool "each realized theorem has the statement Lean's elaborator gives it" sameAsLean + itBool "each associated theorem states `f xs = …` for its definition" selfUnfolding + itBool "the JSON names its format" + ((json.getObjValAs? String "format").toOption == some "ix/compile-equations/2") + itBool "the closure reaches word operations, through log2's omega proof only" + (closed.any fun (n, _) => Ix.Compile.WordEquations.operations.contains n) + itBool "with the word equations on (ix compile's default) none joins the closure: a proof is a theorem, which the word walk does not enter" ((json.getObjValAs? (Array Json) "theorems").toOption.map (·.size) == some 0 && - !closed.any fun (n, _) => n.getPrefix == `IxWordEquations), - test "the JSON lists every association, sorted by definition" + !closed.any fun (n, _) => n.getPrefix == `IxWordEquations) + itBool "the JSON lists every association, sorted by definition" (listed.length == found.size && sorted == sorted.mergeSort (· ≤ ·) && - recursive.all fun (d, e) => listed.contains (d.toString, e.toString)), - test "the JSON lists no failure" - (json.getObjValAs? (Array Json) "failures" |>.toOption |>.map (·.isEmpty) |>.getD false)] + recursive.all fun (d, e) => listed.contains (d.toString, e.toString)) + itBool "the JSON lists no failure" + (json.getObjValAs? (Array Json) "failures" |>.toOption |>.map (·.isEmpty) |>.getD false) end Tests.Ix.Compile.Equations diff --git a/Tests/Ix/Compile/GroundRefusal.lean b/Tests/Ix/Compile/GroundRefusal.lean index 71df45a5de..12779bccc4 100644 --- a/Tests/Ix/Compile/GroundRefusal.lean +++ b/Tests/Ix/Compile/GroundRefusal.lean @@ -109,8 +109,8 @@ private def compileEnvBytes (cs : List (Lean.Name × Lean.ConstantInfo)) Ix.RoleBinding.Compile.writeAtomic (System.FilePath.mk path) bytes return { status with bytes := bytes.size.toUInt64 } -def failClosedStatusTest : TestSeq := - .individualIO "compileEnvBytes fail-closed: ungrounded ⇒ no artifact" none (do +def failClosedStatusTest : LSpec.Spec := do + it "compileEnvBytes fail-closed: ungrounded ⇒ no artifact" do let dir ← IO.FS.createTempDir let out := dir / "fail-closed.ixe" let status ← compileEnvBytes statusConsts out.toString false @@ -125,13 +125,11 @@ def failClosedStatusTest : TestSeq := , ("ungrounded names the bad axiom", status.ungrounded[0]?.map (·.1) == some statusBadName.toString) , ("root is 64 hex chars", status.root.length == 64) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, 0, 0, none) - ) .done + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" -def allowPartialStatusTest : TestSeq := - .individualIO "compileEnvBytes allow-partial: grounded subset reloads" none (do +def allowPartialStatusTest : LSpec.Spec := do + it "compileEnvBytes allow-partial: grounded subset reloads" do let dir ← IO.FS.createTempDir let out := dir / "partial.ixe" let status ← compileEnvBytes statusConsts out.toString true @@ -139,7 +137,7 @@ def allowPartialStatusTest : TestSeq := IO.FS.removeDirAll dir let env ← match Ixon.deEnv bytes with | .ok env => pure env - | .error e => return (false, 0, 0, some s!"reload failed: {e}") + | .error e => fail s!"reload failed: {e}" let checks : List (String × Bool) := [ ("bytes matches file size", status.bytes.toNat == bytes.size) , ("one ungrounded entry", status.ungrounded.size == 1) @@ -147,31 +145,27 @@ def allowPartialStatusTest : TestSeq := env.named.size == status.named.toNat && status.named ≥ 1) , ("bad axiom is absent from the reloaded env", env.named.size < statusConsts.length + 1) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, 0, 0, none) - ) .done + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" -def suite : List TestSeq := [ - .individualIO "ground refusal: the closed input compiles with no failure, certified IO and pure compile" none (do +def suite : LSpec.Spec := do + it "ground refusal: the closed input compiles with no failure, certified IO and pure compile" do let env ← get_env! let cs := closure env fun _ => false let cert ← certifiedFailures env cs let pure ← pureFailures env cs let complete ← completeError? env cs let ok := cert.isEmpty && pure.isEmpty && complete.isNone - return (ok, if ok then 1 else 0, 1, - if ok then none else some s!"certified {cert.toList.take 4}; \ - pure {pure.toList.take 4}; compileComplete {complete}")) .done, - .individualIO "ground refusal: an omitted dependency is refused by name, certified IO and pure compile" none (do + expect ok s!"certified {cert.toList.take 4}; \ + pure {pure.toList.take 4}; compileComplete {complete}" + it "ground refusal: an omitted dependency is refused by name, certified IO and pure compile" do let env ← get_env! let cs := closure env (· == ``Nat.add) let cert ← certifiedFailures env cs let pure ← pureFailures env cs let ok := cert == expected && pure == expected - return (ok, if ok then 1 else 0, 1, - if ok then none else some s!"certified {cert}; pure {pure}; expected {expected}")) .done, - .individualIO "ground refusal: the pure compile's report keeps the grounded rest, and compileComplete refuses" none (do + expect ok s!"certified {cert}; pure {pure}; expected {expected}" + it "ground refusal: the pure compile's report keeps the grounded rest, and compileComplete refuses" do let env ← get_env! let cs := closure env (· == ``Nat.add) let (ixe, failures) ← pureReport env cs @@ -185,10 +179,9 @@ def suite : List TestSeq := [ then f else k let ok := failures.blocks.isEmpty && failures.ungrounded.size == 2 && missing.isEmpty && complete == some s!"2 constant(s) failed to compile; {least.1}: {least.2}" - return (ok, if ok then 1 else 0, 1, - if ok then none else some s!"blocks {failures.blocks.toList.take 4}; \ - unpublished {(missing.map (·.1)).take 4}; compileComplete {complete}")) .done, - failClosedStatusTest, - allowPartialStatusTest] + expect ok s!"blocks {failures.blocks.toList.take 4}; \ + unpublished {(missing.map (·.1)).take 4}; compileComplete {complete}" + failClosedStatusTest + allowPartialStatusTest end Tests.Ix.Compile.GroundRefusal diff --git a/Tests/Ix/Compile/KernelReportTests.lean b/Tests/Ix/Compile/KernelReportTests.lean index 4faf5f30d7..c2ddc28a6c 100644 --- a/Tests/Ix/Compile/KernelReportTests.lean +++ b/Tests/Ix/Compile/KernelReportTests.lean @@ -40,65 +40,64 @@ private def failOut : String := "# declaration type mismatch\n#" ++ addressA ++ " (A.h)\n" ++ "# total failures: 3\n" -def suite : List TestSeq := [ - test "certified report covers every alias through its owning address" +def suite : LSpec.Spec := do + itBool "certified report covers every alias through its owning address" ((do let report ← parse accepted checkCoverage report #[("Alias1", addressA), ("Alias2", addressA)]).isOk) - ++ test "a rejected record remains rejected for an unlisted alias" + itBool "a rejected record remains rejected for an unlisted alias" ((do let report ← parse (row addressA "reject" "type mismatch") checkCoverage report #[("AliasNotDisplayed", addressA)] pure (report[addressA]?.map fun (v : Verdict) => (v.outcome, v.reason))).toOption == some (some ("reject", "type mismatch"))) - ++ test "declines retain their reason for the caller's coverage policy" + itBool "declines retain their reason for the caller's coverage policy" ((do let report ← parse (row addressA "decline" "reader: unsafe axiom") pure (report[addressA]?.map Verdict.reason)).toOption == some (some "reader: unsafe axiom")) - ++ test "blocked dependency results are preserved" + itBool "blocked dependency results are preserved" ((do let report ← parse (row addressA "blocked" addressB) pure (report[addressA]?.map Verdict.outcome)).toOption == some (some "blocked")) - ++ test "a tier record the typing tier typed is kept with its safety" + itBool "a tier record the typing tier typed is kept with its safety" ((do let report ← parse (row addressA "typed" "partial" ++ "\n" ++ row addressB "typed" "unsafe") pure ([addressA, addressB].map fun a => report[a]?.map fun (v : Verdict) => (v.outcome, v.reason))).toOption == some [some ("typed", "partial"), some ("typed", "unsafe")]) - ++ test "a typed row whose reason is not a tier safety fails" + itBool "a typed row whose reason is not a tier safety fails" (failsWith (parse (row addressA "typed" "")) "not a tier safety") - ++ test "an incomplete process fails despite complete-looking rows" + itBool "an incomplete process fails despite complete-looking rows" (failsWith (parse accepted 3) "exited with code 3") - ++ test "empty successful output fails" + itBool "empty successful output fails" (failsWith (parse " \n") "wrote no rows") - ++ test "a truncated trailing row invalidates the report" + itBool "a truncated trailing row invalidates the report" (failsWith (parse (accepted ++ "\n{\"address\":")) "certified row 2") - ++ test "missing typed verdict fields fail" + itBool "missing typed verdict fields fail" (failsWith (parse "{}") "certified row 1") - ++ test "unknown verdicts fail" + itBool "unknown verdicts fail" (failsWith (parse (row addressA "success" "")) "unknown outcome") - ++ test "invalid record addresses fail" + itBool "invalid record addresses fail" (failsWith (parse (row "bad-address" "accept" "")) "invalid record address") - ++ test "duplicate records cannot replace earlier failures" + itBool "duplicate records cannot replace earlier failures" (failsWith (parse (row addressA "reject" "bad" ++ "\n" ++ accepted)) "duplicate record") - ++ test "a missing requested record fails even when other rows pass" + itBool "a missing requested record fails even when other rows pass" (failsWith (do let report ← parse accepted checkCoverage report #[("Missing", addressB)]) "omitted 1 requested name") - ++ test "anonymous diagnostic labels resolve to the address" + itBool "anonymous diagnostic labels resolve to the address" (anonymousAddress? ("#" ++ addressA ++ " (Displayed)") == some addressA) - ++ test "a bare address label resolves to itself" + itBool "a bare address label resolves to itself" (anonymousAddress? addressA == some addressA) - ++ test "a source name is no anonymous label" + itBool "a source name is no anonymous label" (anonymousAddress? "A.f" == none) - ++ test "fail-out rows carry their message; header, separator and trailer are skipped" + itBool "fail-out rows carry their message; header, separator and trailer are skipped" (failOutRows failOut == #[("A.f", "AppTypeMismatch: expected Nat"), ("A.g", "AppTypeMismatch: expected Nat"), ("#" ++ addressA ++ " (A.h)", "declaration type mismatch")]) - ++ test "checker summary gives the checked count" + itBool "checker summary gives the checked count" (rsChecked "[check] seeded 7\n[check] 5/7 passed\n" == some 7) - ++ test "no summary, no checked count" + itBool "no summary, no checked count" (rsChecked "[check] seeded 7\n" == none) -] end Tests.Ix.Compile.KernelReportTests diff --git a/Tests/Ix/Compile/LeanReportTests.lean b/Tests/Ix/Compile/LeanReportTests.lean index da8baabe1c..2078a006bd 100644 --- a/Tests/Ix/Compile/LeanReportTests.lean +++ b/Tests/Ix/Compile/LeanReportTests.lean @@ -54,9 +54,8 @@ private def check : IO Nat := do IO.println "check-lean protocol: 2 complete reports with all 5 outcomes; 20 invocation/coverage/protocol refusals" return cases.length + 2 -def suite : List TestSeq := [ - .individualIO "IxCK CLI reports require exact labels and coherent outcome evidence" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "IxCK CLI reports require exact labels and coherent outcome evidence" do + let _ ← check end Tests.Ix.Compile.LeanReportTests diff --git a/Tests/Ix/Compile/SelectedClosure.lean b/Tests/Ix/Compile/SelectedClosure.lean index a41b0b07c2..6fbc6e951b 100644 --- a/Tests/Ix/Compile/SelectedClosure.lean +++ b/Tests/Ix/Compile/SelectedClosure.lean @@ -168,14 +168,12 @@ private def checkerSupportMatchesNatOpDeps : Bool := theorem checkerSupport_matches_natOpDeps : checkerSupportMatchesNatOpDeps = true := by decide -private def report (errors : Array String) (checked : Nat) (what : String) : - IO (Bool × Nat × Nat × Option String) := do +private def report (errors : Array String) (what : String) : AssertM Unit := do for e in errors do IO.println s!"[selected-closure] FAIL {e}" - return (errors.isEmpty, if errors.isEmpty then checked else 0, checked, - if errors.isEmpty then none else some s!"{errors.size} {what} failure(s)") + expect errors.isEmpty s!"{errors.size} {what} failure(s)" -def suite : List TestSeq := [ - .individualIO "selected closures carry the whole unit of PassO2.SA._sizeOf_N" none (do +def suite : LSpec.Spec := do + it "selected closures carry the whole unit of PassO2.SA._sizeOf_N" do let env ← getFileEnv fixture let units := Ix.EnvScope.unitIndex env.constants let required := sizeOfInstances ++ sizeOfUnitSupport @@ -198,12 +196,11 @@ def suite : List TestSeq := [ let raw := nameSet (Ix.EnvScope.collectDeps env sizeOfRoots {}) for n in sizeOfInstances do if raw.contains n then errors := errors.push s!"raw negative control carries {n}" - report errors (seedSets.length + 1) "unit closure") - (.individualIO "selected closures: a matcher's unit, mutual siblings, checker support" none (do + report errors "unit closure" + it "selected closures: a matcher's unit, mutual siblings, checker support" do let env ← get_env! let units := Ix.EnvScope.unitIndex env.constants let mut errors : Array String := #[] - let mut checked := 0 -- 2. the matcher's unit, and nothing outside it let bare := nameSet (Ix.EnvScope.collectSelectedDepsWith env units [``matcher]) let carried := nameSet (Ix.EnvScope.collectSelectedDepsWith env units [``carriedProof]) @@ -213,10 +210,8 @@ def suite : List TestSeq := [ errors := errors.push "the bare matcher lost matcher._arg_pusher of its unit" if bare.contains ``carriedProof then errors := errors.push "the bare matcher pulled its caller carriedProof" - checked := checked + 1 -- 3. mutual siblings for (root, sibling) in mutualSeeds do - checked := checked + 1 unless (nameSet (Ix.EnvScope.collectSelectedDepsWith env units [root])).contains sibling do errors := errors.push s!"{root}: missing its sibling {sibling}" -- 4. checker support @@ -232,7 +227,6 @@ def suite : List TestSeq := [ errors := errors.push "raw negative control: landUser's raw closure carries Nat.mul" unless selected.contains ``Nat.mul do errors := errors.push "landUser's selected closure lacks Nat.mul" - checked := checked + 1 -- 5. self-contained for IxCK: an inductive's recursor, and the string-literal -- support when a closed constant has a string literal unless bare.contains ``Nat.rec do @@ -248,7 +242,7 @@ def suite : List TestSeq := [ if selected.contains ``String.ofList then errors := errors.push "landUser's selected closure (no string literal) carries String.ofList" -- a String literal in a theorem's proof only (`value? (allowOpaque := true)`) - let some proofCi := env.find? ``stringInProof | throw (IO.userError "stringInProof missing") + let some proofCi := env.find? ``stringInProof | fail "stringInProof missing" let isStr : Expr → Bool | .lit (.strVal _) => true | _ => false unless (proofCi.type.find? isStr).isNone && Ix.EnvScope.hasStringLiteral proofCi do errors := errors.push "stringInProof: the literal is not in its proof only, or is not seen there" @@ -257,9 +251,7 @@ def suite : List TestSeq := [ errors := errors.push "stringInProof's closure holds another String literal (the case is vacuous)" unless (nameSet (Ix.EnvScope.collectSelectedDepsWith env units [``stringInProof])).contains ``String.ofList do errors := errors.push "stringInProof's selected closure (a literal in a proof) lacks String.ofList" - checked := checked + 1 - report errors checked "selected closure") .done) -] + report errors "selected closure" /-- `compiler-selected-closure-e2e`: the fixture compiled whole and as each selected closure of `seedSets`, by the Lean pipeline; the Rust compile of diff --git a/Tests/Ix/Compile/WordEquations.lean b/Tests/Ix/Compile/WordEquations.lean index 6606dbfdee..3a2f07139e 100644 --- a/Tests/Ix/Compile/WordEquations.lean +++ b/Tests/Ix/Compile/WordEquations.lean @@ -43,7 +43,7 @@ def elaborate (dir : System.FilePath) (file : String) (text : String) : IO Envir def wordTheorems (names : List Name) : List Name := names.filter fun n => n.getPrefix == `IxWordEquations -def suite : IO (List LSpec.TestSeq) := do +def suite : IO LSpec.Spec := do IO.FS.withTempDir fun dir => do let plain ← elaborate dir "Plain.lean" plainSource let all := Ix.Compile.WordEquations.all @@ -80,25 +80,25 @@ def suite : IO (List LSpec.TestSeq) := do let named := Ix.Compile.WordEquations.all.filter (added.contains ·.theoremName) let subjects : List String := listed.map (·.2.1) let sorted : Bool := subjects == subjects.mergeSort (fun a b => decide (a ≤ b)) - return [ - test "68 equations: per width one per primitive operation (17; `ofNat`'s is the bridge)" - (all.length == 68), - test "every equation elaborates as a level-monomorphic theorem" allTheorems, - test "a closure without words gets no equation" - (wordTheorems (plainClosed.map (·.1))).isEmpty, - test "no unfolding-theorem failure on the word source" failed.isEmpty, - test s!"the word source's closure holds the theorems of its operations and bridges, and only \ + return do + itBool "68 equations: per width one per primitive operation (17; `ofNat`'s is the bridge)" + (all.length == 68) + itBool "every equation elaborates as a level-monomorphic theorem" allTheorems + itBool "a closure without words gets no equation" + (wordTheorems (plainClosed.map (·.1))).isEmpty + itBool "no unfolding-theorem failure on the word source" failed.isEmpty + itBool s!"the word source's closure holds the theorems of its operations and bridges, and only \ those: {added}" - (expected.all added.contains && added.length == expected.length), - test s!"the walk reaches four operations outside theorems, not UInt64.toNat (in the closure, \ - inside UInt64.toUInt8's body): {reached.toList}" exact, - test s!"the output's theorems name each equation of the closure with its operation: {listed}" + (expected.all added.contains && added.length == expected.length) + itBool s!"the walk reaches four operations outside theorems, not UInt64.toNat (in the closure, \ + inside UInt64.toUInt8's body): {reached.toList}" exact + itBool s!"the output's theorems name each equation of the closure with its operation: {listed}" (listed.length == added.length && named.all fun e => - listed.contains ("word", e.operation.toString, e.theoremName.toString)), - test "the output's theorems are sorted by subject" sorted, - test "with words off (`ix compile --no-word-equations`) the word source gets no equation" - (wordTheorems (closedOff.map (·.1))).isEmpty, - test "a closure without words gets no theorem proposal" - (Ix.Compile.Equations.theorems (plainClosed.map (·.1))).isEmpty] + listed.contains ("word", e.operation.toString, e.theoremName.toString)) + itBool "the output's theorems are sorted by subject" sorted + itBool "with words off (`ix compile --no-word-equations`) the word source gets no equation" + (wordTheorems (closedOff.map (·.1))).isEmpty + itBool "a closure without words gets no theorem proposal" + (Ix.Compile.Equations.theorems (plainClosed.map (·.1))).isEmpty end Tests.Ix.Compile.WordEquations diff --git a/Tests/Ix/CompileDeterminism.lean b/Tests/Ix/CompileDeterminism.lean index e87fd00ef7..ff918f1cef 100644 --- a/Tests/Ix/CompileDeterminism.lean +++ b/Tests/Ix/CompileDeterminism.lean @@ -39,10 +39,9 @@ private def compileOnce (source : String) (out : System.FilePath) : /-- Two separate `ix compile` processes over `source`, byte identity asserted via their Blake3 digests (`Ix.FileDigest.blake3File`). -/ -private def determinismLeg (source : String) : - IO (Bool × Nat × Nat × Option String) := do +private def determinismLeg (source : String) : AssertM Unit := do unless (← ixExe.pathExists) do - return (false, 0, 0, some s!"{ixExe} missing — run `lake build ix` first") + fail s!"{ixExe} missing — run `lake build ix` first" let dir ← IO.FS.createTempDir try let out1 := dir / "run1.ixe" @@ -51,25 +50,23 @@ private def determinismLeg (source : String) : let task2 ← IO.asTask (prio := .dedicated) (compileOnce source out2) let res1 ← IO.wait task1 let res2 ← IO.wait task2 - if let .error e ← IO.ofExcept res1 then - return (false, 0, 0, some e) - if let .error e ← IO.ofExcept res2 then - return (false, 0, 0, some e) - let h1 ← try Ix.FileDigest.blake3File out1 - catch e => return (false, 0, 0, some s!"blake3 of {out1}: {e}") - let h2 ← try Ix.FileDigest.blake3File out2 - catch e => return (false, 0, 0, some s!"blake3 of {out2}: {e}") - let bytes := (← out1.metadata).byteSize.toNat + if let Except.error e ← IO.ofExcept res1 then + fail e + if let Except.error e ← IO.ofExcept res2 then + fail e + let h1 ← match ← (Ix.FileDigest.blake3File out1).toBaseIO with + | .ok h => pure h + | .error e => fail s!"blake3 of {out1}: {e}" + let h2 ← match ← (Ix.FileDigest.blake3File out2).toBaseIO with + | .ok h => pure h + | .error e => fail s!"blake3 of {out2}: {e}" if h1 != h2 then - return (false, bytes, 0, some s!"{source}: cross-process compile \ -is nondeterministic — {h1} vs {h2}") - return (true, bytes, 0, none) + fail s!"{source}: cross-process compile is nondeterministic — {h1} vs {h2}" finally IO.FS.removeDirAll dir -def suite : List TestSeq := [ - .individualIO - "compile determinism: fixture corpus, two processes, Blake3-identical" - none (determinismLeg "Tests/Ix/Compile/Mutual.lean") .done ] +public def suite : LSpec.Spec := do + it "compile determinism: fixture corpus, two processes, Blake3-identical" do + determinismLeg "Tests/Ix/Compile/Mutual.lean" end Tests.Ix.CompileDeterminism diff --git a/Tests/Ix/Decompile.lean b/Tests/Ix/Decompile.lean index 5e6b184562..28bfd7b5b1 100644 --- a/Tests/Ix/Decompile.lean +++ b/Tests/Ix/Decompile.lean @@ -21,6 +21,8 @@ public import Tests.Ix.Fixtures open LSpec +set_option compiler.extract_closed false + namespace Tests.Decompile /-! ## Extension-table append (pure unit) @@ -43,7 +45,7 @@ private def nX : Ix.Name := Ix.Name.mkStr Ix.Name.mkAnon "x" /-- Type `∀ (x : B), Sort (max u 0)` where ref index 1 and univ index 1 are VIRTUAL — resolvable only through the appended extension tables. -/ -private def extFixture : +private def mkExtFixture (_ : Unit) : Ixon.Constant × ConstantMeta × ExprMetaArena × Ixon.Expr := Id.run do let ty : Ixon.Expr := .leanAll (.ref 1 #[]) (.sort 1) let aAddr := Address.blake3 "ext-fixture-A".toUTF8 @@ -59,7 +61,7 @@ private def extFixture : ]⟩ return (cnst, cm, arena, ty) -private def extEnv : DecompileEnv := Id.run do +private def mkExtEnv (_ : Unit) : DecompileEnv := Id.run do let base : Ixon.Env := {} let names := [nB, nU, nX].foldl (init := base.names) Ixon.RawEnv.addNameComponents @@ -67,10 +69,10 @@ private def extEnv : DecompileEnv := Id.run do /-- With extensions installed, the virtual indices resolve and the original expression comes back. -/ -private def extAppendResolves : Bool := Id.run do - let (cnst, cm, arena, ty) := extFixture +private def extAppendResolves (_ : Unit) : Bool := Id.run do + let (cnst, cm, arena, ty) := mkExtFixture () let ctx := mkBlockCtx cnst #[] #[nU] arena cm - match DecompileM.run extEnv ctx {} (decompileExpr ty 2) with + match DecompileM.run (mkExtEnv ()) ctx {} (decompileExpr ty 2) with | .ok (e, _) => let expected := Ix.Expr.mkForallE nX (Ix.Expr.mkConst nB #[]) @@ -82,10 +84,10 @@ private def extAppendResolves : Bool := Id.run do /-- Without the metadata wrapper, the same indices are out of bounds — proving the append (not table size coincidence) made them resolve. -/ -private def extAppendTeeth : Bool := Id.run do - let (cnst, _, arena, ty) := extFixture +private def extAppendTeeth (_ : Unit) : Bool := Id.run do + let (cnst, _, arena, ty) := mkExtFixture () let ctx := mkBlockCtx cnst #[] #[nU] arena - match DecompileM.run extEnv ctx {} (decompileExpr ty 2) with + match DecompileM.run (mkExtEnv ()) ctx {} (decompileExpr ty 2) with | .ok _ => return false | .error e => return match e with @@ -111,7 +113,7 @@ open Ix.DecompileM Ixon private def nAx : Ix.Name := Ix.Name.mkStr Ix.Name.mkAnon "MS.ax" /-- The names the fixtures read. -/ -private def msEnv : DecompileEnv := +private def mkMsEnv (_ : Unit) : DecompileEnv := { ixonEnv := { names := Ixon.RawEnv.addNameComponents {} nAx } } /-- Primary entry 0. -/ @@ -130,15 +132,15 @@ private def isMetaShareErr {α : Type} (idx entry p q : Nat) : Except DecompileE | _ => false /-- Forward reference (`metaSharing[0]` → `metaSharing[1]`): rejected. -/ -private def msForward : Bool := +private def msForward (_ : Unit) : Bool := isMetaShareErr 2 0 1 2 (validateMetaSharing 1 #[.app (.share 2) (.var 3), .var 4]) /-- Self reference (`share p` in `metaSharing[0]`): rejected, not a loop. -/ -private def msSelf : Bool := +private def msSelf (_ : Unit) : Bool := isMetaShareErr 1 0 1 1 (validateMetaSharing 1 #[.app (.share 1) (.var 3)]) /-- `i ≥ p + q`: out of range. -/ -private def msOutOfRange : Bool := +private def msOutOfRange (_ : Unit) : Bool := let r := validateMetaSharing 1 #[.var 0, .app (.share 5) (.var 3)] isMetaShareErr 5 1 1 2 r && (match r with @@ -148,30 +150,30 @@ private def msOutOfRange : Bool := /-- Whole-constant path (`decompileAxiom` → `withFreshBlock`): the table check rejects a malformed entry that nothing reads, and the error names the constant. -/ -private def msAxiomUnreadEntryRejected : Bool := +private def msAxiomUnreadEntryRejected (_ : Unit) : Bool := let ax : Ixon.Axiom := ⟨false, 0, .sort 0⟩ let cnst : Ixon.Constant := ⟨.axio ax, #[prim0], #[], #[.zero], #[]⟩ -- Entry 2 references itself (`share 3 = p + 2`). let cm : ConstantMeta := { info := .axio nAx.getHash #[] ⟨#[.leaf]⟩ 0, metaSharing := #[sharedM0, sharedM1, .app (.share 3) (.var 0)] } - let r := (DecompileM.run msEnv default {} (decompileAxiom ax cnst cm)).map (·.1) + let r := (DecompileM.run (mkMsEnv ()) default {} (decompileAxiom ax cnst cm)).map (·.1) isMetaShareErr 3 2 1 3 r && match r with | .error (.invalidMetaShareIndex _ _ _ _ c) => c == nAx.pretty | _ => false /-- Tables without shares pass the check. -/ -private def msNoShares : Bool := +private def msNoShares (_ : Unit) : Bool := validateMetaSharing 0 #[plainM0, plainM1] matches .ok () /-- A valid shared table passes the check. -/ -private def msSharedTable : Bool := +private def msSharedTable (_ : Unit) : Bool := validateMetaSharing 1 #[sharedM0, sharedM1] matches .ok () /-- The table check visits each shared node once: the chain `e(k+1) = app e(k) e(k)` of depth 64 (2^64 nodes as a tree) validates, and the first violation inside it is still its leftmost leaf. -/ -private def msSharedChain : Bool := +private def msSharedChain (_ : Unit) : Bool := let chain := (List.range 64).foldl (fun e _ => Ixon.Expr.app e e) (Ixon.Expr.app (.share 0) (.var 0)) (validateMetaSharing 1 #[chain, chain] matches .ok ()) && @@ -179,19 +181,15 @@ private def msSharedChain : Bool := end MetaShare -public def unitSuite : List TestSeq := [ - test "extension append: virtual ref/univ indices resolve" - extAppendResolves - ++ test "extension append: absent metadata leaves indices OOB" - extAppendTeeth, - test "metadata share: forward reference rejected" msForward - ++ test "metadata share: self reference rejected" msSelf - ++ test "metadata share: i ≥ p + q rejected" msOutOfRange - ++ test "metadata share: unread malformed entry rejected" - msAxiomUnreadEntryRejected - ++ test "metadata share: tables without shares unchanged" msNoShares - ++ test "metadata share: a valid shared table passes" msSharedTable - ++ test "metadata share: shared subterms are checked once" msSharedChain -] +public def unitSuite : LSpec.Spec := do + itBool "extension append: virtual ref/univ indices resolve" (extAppendResolves ()) + itBool "extension append: absent metadata leaves indices OOB" (extAppendTeeth ()) + itBool "metadata share: forward reference rejected" (msForward ()) + itBool "metadata share: self reference rejected" (msSelf ()) + itBool "metadata share: i ≥ p + q rejected" (msOutOfRange ()) + itBool "metadata share: unread malformed entry rejected" (msAxiomUnreadEntryRejected ()) + itBool "metadata share: tables without shares unchanged" (msNoShares ()) + itBool "metadata share: a valid shared table passes" (msSharedTable ()) + itBool "metadata share: shared subterms are checked once" (msSharedChain ()) end Tests.Decompile diff --git a/Tests/Ix/EnvBody.lean b/Tests/Ix/EnvBody.lean index 777fc3d61f..5781b07227 100644 --- a/Tests/Ix/EnvBody.lean +++ b/Tests/Ix/EnvBody.lean @@ -23,12 +23,12 @@ namespace Tests.Ix.EnvBody `lake test` runs the `IxTests` executable. -/ def fixturePath : System.FilePath := "Tests/Ix/Fixtures/Export.lean" -public def suite : IO LSpec.TestSeq := do +public def suite : IO LSpec.Spec := do let env ← getFileEnv fixturePath - pure $ - LSpec.test "getFileEnv includes the file body (not just imports)" + return do + itBool "getFileEnv includes the file body (not just imports)" ((env.constants.find? `MyNat).isSome) - ++ LSpec.test "getFileEnv still includes imports" + itBool "getFileEnv still includes imports" ((env.constants.find? `Nat).isSome) end Tests.Ix.EnvBody diff --git a/Tests/Ix/HostAdmission.lean b/Tests/Ix/HostAdmission.lean index 426a481128..27c8b4c3ba 100644 --- a/Tests/Ix/HostAdmission.lean +++ b/Tests/Ix/HostAdmission.lean @@ -119,9 +119,8 @@ private def checks : IO Nat := do ensure (!(verify changed tierArtifact limits).isOk) "tier downgrade/partition tampering passed" return 2 -public def units : LSpec.TestSeq := - .individualIO "host admission: actual receipts, canonical identities and replay/tamper controls" none (do - let count ← checks - return (true, count, 0, none)) .done +public def units : LSpec.Spec := + it "host admission: actual receipts, canonical identities and replay/tamper controls" do + let _ ← checks end Tests.Ix.HostAdmission diff --git a/Tests/Ix/HostAdmissionCli.lean b/Tests/Ix/HostAdmissionCli.lean index bbffd41bd3..8f6d9f7854 100644 --- a/Tests/Ix/HostAdmissionCli.lean +++ b/Tests/Ix/HostAdmissionCli.lean @@ -241,9 +241,8 @@ private def checks : IO Nat := do finally IO.FS.removeDirAll dir -def suite : List LSpec.TestSeq := [ - .individualIO "host statement persistence, addressed replay and actual CLI refusals" none (do - let count ← checks - return (true, count, 0, none)) .done] +def suite : LSpec.Spec := + it "host statement persistence, addressed replay and actual CLI refusals" do + let _ ← checks end Tests.Ix.HostAdmissionCli diff --git a/Tests/Ix/IOIngress.lean b/Tests/Ix/IOIngress.lean index dfd5a91320..72eed6d3ab 100644 --- a/Tests/Ix/IOIngress.lean +++ b/Tests/Ix/IOIngress.lean @@ -88,14 +88,13 @@ def violations : IO (Array String) := do found := found.push s!"no function reads {channel}: the scanner no longer reads the sources" return found -def structural : TestSeq := - .individualIO "every IO byte the IxVM and multi-stark programs read is range-checked" none (do +def structural : LSpec.Spec := do + it "every IO byte the IxVM and multi-stark programs read is range-checked" do let found ← violations - let ok := found.isEmpty - return (ok, if ok then 1 else 0, 1, - if ok then none else some ("; ".intercalate found.toList))) .done + expect found.isEmpty ("; ".intercalate found.toList) -def suite : List TestSeq := [structural] +def suite : LSpec.Spec := do + structural /-! ## Execution -/ diff --git a/Tests/Ix/ImportIxe.lean b/Tests/Ix/ImportIxe.lean index 78cf5def0e..bcbde2890a 100644 --- a/Tests/Ix/ImportIxe.lean +++ b/Tests/Ix/ImportIxe.lean @@ -268,63 +268,57 @@ private def compileFixtureToFile (consts : List (Lean.Name × Lean.ConstantInfo) return (root, failures.toMap.size) /-- C6 parity, source root equality and fresh replay. -/ -private def roundtripTest : IO (Bool × Nat × Nat × Option String) := do +private def roundtripTest : AssertM Unit := do let dir ← IO.FS.createTempDir let path := (dir / "fixture.ixe").toString try let original ← buildFixtureConsts let (root1, ungrounded1) ← compileFixtureToFile original.toList path if ungrounded1 > 0 then - return (false, 0, 0, - some s!"fixture compile ungrounded: {ungrounded1}") + fail s!"fixture compile ungrounded: {ungrounded1}" -- C6 parity: materialize everything and compare per constant. Source -- import restores the complete original declaration set. let materialized ← Ix.ImportIxe.materializeIxe path let extra := materialized.filter fun (n, _) => !original.any (·.1 == n) let missing := original.filter fun (n, _) => !materialized.any (·.1 == n) if materialized.size != original.size || !missing.isEmpty || !extra.isEmpty then - return (false, 0, 0, some s!"materialized names: original \ -{original.size}, materialized {materialized.size}; extra {extra.map (·.1)}, missing {missing.map (·.1)}") + fail s!"materialized names: original \ +{original.size}, materialized {materialized.size}; extra {extra.map (·.1)}, missing {missing.map (·.1)}" let mut origMap : Lean.NameMap Lean.ConstantInfo := {} for (n, ci) in original do origMap := origMap.insert n ci let mut matMap : Lean.NameMap Lean.ConstantInfo := {} for (n, ci) in materialized do let some oci := origMap.find? n - | return (false, 0, 0, some s!"unexpected source constant {n}") + | fail s!"unexpected source constant {n}" if let some e := compareCI n oci ci then - return (false, 0, 0, some e) + fail e matMap := matMap.insert n ci -- Root equality: recompiling the complete materialized source output is -- a fixed point of the canonical root. let path2 := (dir / "rebuilt.ixe").toString let (root2, _) ← compileFixtureToFile materialized.toList path2 if root2 != root1 then - return (false, 0, 0, some s!"root drift: {root1.take 12}… → \ -{root2.take 12}…") + fail s!"root drift: {root1.take 12}… → {root2.take 12}…" -- Fresh kernel replay via the shared planner (import_ixe core). let matMapFrozen := matMap - let plan ← match Ix.Replay.planDeclarations matMap - matMapFrozen.find? with - | .ok plan => pure plan - | .error e => return (false, 0, 0, some s!"planDeclarations: {e}") + let plan ← expectOk ((Ix.Replay.planDeclarations matMap matMapFrozen.find?).mapError (s!"planDeclarations: {·}")) let emptyEnv ← Lean.mkEmptyEnvironment let mut kenv := emptyEnv.toKernelEnv for (key, decl) in plan do match kenv.addDecl {} decl with | .ok kenv' => kenv := kenv' | .error _ => - return (false, 0, 0, some s!"fresh kernel replay rejected {key}") + fail s!"fresh kernel replay rejected {key}" for (n, expected) in original do let some actual := kenv.constants.find? n - | return (false, 0, 0, some s!"fresh replay lost source constant {n}") + | fail s!"fresh replay lost source constant {n}" if let some e := compareCI n expected actual then - return (false, 0, 0, some s!"fresh replay: {e}") - return (true, original.size, 0, none) + fail s!"fresh replay: {e}" finally IO.FS.removeDirAll dir -private def closureTest : IO (Bool × Nat × Nat × Option String) := do +private def closureTest : AssertM Unit := do let dir ← IO.FS.createTempDir let path := (dir / "fixture.ixe").toString try @@ -341,9 +335,8 @@ private def closureTest : IO (Bool × Nat × Nat × Option String) := do ("axiom excluded", !names.contains `TIxImp.axm), ("theorem excluded", !names.contains `TIxImp.thm), ("proj fixture excluded", !names.contains `TIxImp.P) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, subset.size, 0, none) + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" finally IO.FS.removeDirAll dir @@ -380,20 +373,21 @@ private def getConsumerEnv : IO Lean.Environment := do /-- C8: a consumer file `import_ixe`s the fixture artifact through the real command elaborator (in-process frontend + interpreter) and defines a term over the materialized constants. -/ -private def elabTest : IO (Bool × Nat × Nat × Option String) := do - try - let env ← getConsumerEnv - let checks : List (String × Bool) := [ - ("consumer def elaborated", env.contains `Consumer.uses), - ("consumer theorem elaborated", env.contains `Consumer.alsoUses), - ("materialized inductive present", env.contains nN), - ("materialized recursor present", env.contains nRec), - ("materialized defn present", env.contains `TIxImp.dbl) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, 0, 0, none) - catch e => - return (false, 0, 0, some s!"consumer elaboration failed: {e}") +private def elabTest : AssertM Unit := do + let envRes : Except String Lean.Environment ← liftM (m := IO) do + try + pure (.ok (← getConsumerEnv)) + catch e => + pure (.error s!"consumer elaboration failed: {e}") + let env ← expectOk envRes + let checks : List (String × Bool) := [ + ("consumer def elaborated", env.contains `Consumer.uses), + ("consumer theorem elaborated", env.contains `Consumer.alsoUses), + ("materialized inductive present", env.contains nN), + ("materialized recursor present", env.contains nRec), + ("materialized defn present", env.contains `TIxImp.dbl) ] + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" /-- C9: the ZkVoting consumption pattern against an imported artifact — `import_ixe` the fixture, commit a private value of an imported @@ -402,7 +396,7 @@ private def elabTest : IO (Bool × Nat × Nat × Option String) := do (`Ix.Commit.evalClaim`) — all with a closure-scoped compile, so cost tracks the claim, not the environment. (Proving the claim is `ix prove`'s job; the IxVM eval arm is still landing.) -/ -private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do +private def zkPatternTest : AssertM Unit := do let env ← getConsumerEnv -- Closure-scoped compile env over what the claim touches. let mut seen : Lean.NameSet := {} @@ -414,7 +408,7 @@ private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do if seen.contains n then continue seen := seen.insert n let some ci := env.find? n - | return (false, 0, 0, some s!"consumer env missing {n}") + | fail s!"consumer env missing {n}" closure := (n, ci) :: closure for r in Ix.Replay.constantInfoReferences ci do unless seen.contains r do @@ -433,12 +427,12 @@ private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do let (chained, env2) ← IO.ofExcept (Ix.Commit.compileDef env1 [] k2Ty k2Val) let (alone, _) ← IO.ofExcept (Ix.Commit.compileDef compileEnv [] k2Ty k2Val) unless chained == alone do - return (false, 0, 0, some "a chained anonymous definition has another address than alone") + fail "a chained anonymous definition has another address than alone" let some bytes := env2.constants.get? chained - | return (false, 0, 0, some "compileDef stored no record") + | fail "compileDef stored no record" let defn ← IO.ofExcept (Ixon.deConstantAt bytes 0 bytes.size) if defn.binders.isEmpty || defn.binders.any (·.nodes.any (·.isUndecided)) then - return (false, 0, 0, some "a definition compiled over the input has no decided binder data") + fail "a definition compiled over the input has no decided binder data" -- Commit a private value of the imported type. let voteType := Lean.Expr.const nN [] let vote := Lean.Expr.app (.const nSucc []) (.const nZero []) @@ -446,8 +440,7 @@ private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do Ix.Commit.commitDef compileEnv env [] voteType vote let commitName := Address.toUniqueName commitAddr unless env'.contains commitName do - return (false, 0, 0, - some "commitDef did not register the commitment constant") + fail "commitDef did not register the commitment constant" -- Claim: an imported function applied to the commitment evaluates -- to the public result. let input := Lean.mkApp (.const `TIxImp.dbl []) (.const commitName []) @@ -455,25 +448,18 @@ private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do (Lean.mkApp (.const nSucc []) (.const nZero [])) let ctx : Ix.ClaimContext := { spec := default, binding := default, axioms := none } - let claim ← match Ix.Commit.evalClaim ctx compileEnv' [] input output - voteType with - | .ok claim => pure claim - | .error e => return (false, 0, 0, some s!"evalClaim failed: {e}") + let claim ← expectOk ((Ix.Commit.evalClaim ctx compileEnv' [] input output voteType).mapError (s!"evalClaim failed: {·}")) match claim with | .eval _ i o _ => if i == o then - return (false, 0, 0, some "degenerate claim: input addr = output addr") - return (true, 0, 0, none) - | _ => return (false, 0, 0, some "expected an eval claim") + fail "degenerate claim: input addr = output addr" + | _ => fail "expected an eval claim" -def suite : List TestSeq := [ - .individualIO "materialize ∘ compile is exact and root-stable" none - roundtripTest .done, - .individualIO "only-scoped materialization returns the closure" none - closureTest .done, - .individualIO "import_ixe elaborates a consumer file (C8)" none - elabTest .done, - .individualIO "commit + eval claim over imported constants (C9)" none - zkPatternTest .done ] +def suite : LSpec.Spec := do + it "materialize ∘ compile is exact and root-stable" roundtripTest + it "only-scoped materialization returns the closure" closureTest + sequential do + it "import_ixe elaborates a consumer file (C8)" elabTest + it "commit + eval claim over imported constants (C9)" zkPatternTest end Tests.Ix.ImportIxe diff --git a/Tests/Ix/InitStd.lean b/Tests/Ix/InitStd.lean index 4774515f96..19fe0c2356 100644 --- a/Tests/Ix/InitStd.lean +++ b/Tests/Ix/InitStd.lean @@ -167,7 +167,9 @@ def tail (out : IO.Process.Output) : String := s!"{(out.stdout.takeEnd 2000).toString}\n{(out.stderr.takeEnd 2000).toString}" def reportChecks (name : String) (checks : Array (String × Bool)) : IO UInt32 := - LSpec.lspecIO (.ofList [(name, checks.toList.map fun (label, ok) => LSpec.test label ok)]) [] + LSpec.lspecMain (LSpec.describe name do + for (label, ok) in checks do + LSpec.itCheck label (fun () => ok)) [] /-- `initstd-reference`. -/ def reference : IO UInt32 := do @@ -268,7 +270,7 @@ def fidelity : IO UInt32 := do reportChecks "fidelity-initstd" #[ ("ix validate-lean on Init+Std exits 0", out.exitCode == 0), ("its report has the five phases, every one passed", - match verdict with | .ok n => n ≥ 5 | .error _ => false)] + match verdict with | .ok n => decide (n ≥ 5) | .error _ => false)] finally IO.FS.removeDirAll dir diff --git a/Tests/Ix/IxVM/Eval.lean b/Tests/Ix/IxVM/Eval.lean index d92bff15c6..c87a0518d7 100644 --- a/Tests/Ix/IxVM/Eval.lean +++ b/Tests/Ix/IxVM/Eval.lean @@ -528,15 +528,15 @@ normalizer. Closed numeric examples additionally pin a hand-computed result. Neutral terms deliberately avoid arithmetic, where Lean and IxVM choose different representations for stuck primitives. -/ def difficultTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) - (env : Ixon.Env) (r : Tests.Ix.IxVM.Runner) : IO TestSeq := do - let mut seq : TestSeq := .done + (env : Ixon.Env) (r : Tests.Ix.IxVM.Runner) : IO Spec := do + let mut checks : Array (String × Bool) := #[] for name in difficultNumeric.map Prod.fst ++ difficultNeutral do let some (.defnInfo info) := leanEnv.find? name | throw <| IO.userError s!"expected definition: {name}" let expected ← runMeta (Lean.Meta.withTransparency .all (Lean.Meta.reduceAll info.value)) leanEnv if let some (_, n) := difficultNumeric.find? (fun p => p.1 == name) then - seq := seq ++ test s!"Lean oracle agrees with pinned result: {name}" - (expected == .lit (.natVal n)) + checks := checks.push (s!"Lean oracle agrees with pinned result: {name}", + expected == .lit (.natVal n)) let input ← lookupAddr env name let (fixture, obj) ← compiledOutput base env info.levelParams info.type expected r.build <| execute s!"Lean differential: {name}" (← witness fixture input obj) @@ -550,8 +550,8 @@ def difficultTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) let input ← lookupAddr env ``Fixtures.wellFoundedTree let (fixture, output) ← natOutput env 15 let opaqueId ← lookupAddr env ``Lean.opaqueId - seq := seq ++ test "generated WF fixture contains the opaqueId dependency" - ((closureFrom env input).contains opaqueId) + checks := checks.push ("generated WF fixture contains the opaqueId dependency", + (closureFrom env input).contains opaqueId) r.build <| execute "opaque accessibility proof blocks kernel evaluation" (← witness fixture input output) (some "result does not match") -- This explicit proof does expose constructors to Acc.rec. Meta keeps its @@ -578,7 +578,9 @@ def difficultTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) let input ← lookupAddr env ``Fixtures.openZero r.build <| execute "symbolic Nat addition exposes zero after argument reduction" (← witness env input (definition natArrow (.leanLam (.ref 0 #[]) (.var 0)) #[nat] 0 #[])) - return seq + return do + for (label, ok) in checks do + itBool label ok private structure GenState where seed : UInt64 := 0x4958564d @@ -621,18 +623,18 @@ private def genNat (fuel : Nat) (locals : List Nat) : def differentialTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) (sharedEnv : Ixon.Env) (r : Tests.Ix.IxVM.Runner) - (count : Nat := 24) : IO TestSeq := do + (count : Nat := 24) : IO Spec := do let ty := Lean.mkConst ``Nat let mut state : GenState := {} - let mut seq : TestSeq := .done + let mut checks : Array (String × Bool) := #[] for i in [:count] do let seed := state.seed let ((value, answer), next) := (genNat 4 []).run state state := next let label := s!"generated arithmetic {i}, seed {seed}" let nf ← runMeta (Lean.Meta.withTransparency .all (Lean.Meta.reduceAll value)) leanEnv - seq := seq ++ test s!"Lean agrees with independent numeric oracle: {label}" - (nf == .lit (.natVal answer)) + checks := checks.push (s!"Lean agrees with independent numeric oracle: {label}", + nf == .lit (.natVal answer)) let (input, cache) ← IO.ofExcept (Ix.Commit.compileDef base [] ty value) let some bytes := cache.constants[input]? | throw <| IO.userError "missing generated input" let c : Ixon.Constant ← IO.ofExcept (Ixon.de bytes) @@ -644,9 +646,11 @@ def differentialTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEn r.build <| execute s!"mutated output: {label}" (← witness fixture input wrong) (some "result does not match") if count ≥ 24 then - seq := seq ++ test "generated corpus covers add/mul/sub/let/beta/div/mod" - (state.coverage.all (· > 0)) - return seq + checks := checks.push ("generated corpus covers add/mul/sub/let/beta/div/mod", + state.coverage.all (· > 0)) + return do + for (label, ok) in checks do + itBool label ok private def packBundle (env : Ixon.Env) (root : Address) : IO Ixon.Env := do let name := Ix.Name.mkStr Ix.Name.mkAnon "_obj" @@ -665,7 +669,7 @@ private def packBundle (env : Ixon.Env) (root : Address) : IO Ixon.Env := do /-- Check the command's printed claim against an independent construction, transport both endpoints through ordinary bundles, then execute the claim. -/ def commandTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) - (sharedEnv : Ixon.Env) (r : Tests.Ix.IxVM.Runner) : IO TestSeq := do + (sharedEnv : Ixon.Env) (r : Tests.Ix.IxVM.Runner) : IO Spec := do let (claim, cache) ← IO.ofExcept (Ix.Commit.evalClaimWithEnv evalCtx base [] (Lean.mkConst ``Fixtures.arithmetic) (.lit (.natVal 42)) (Lean.mkConst ``Nat)) let .eval _ input output _ := claim | throw <| IO.userError "expected Eval claim" @@ -690,33 +694,33 @@ def commandTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) let messages ← state.messages.toList.mapM fun msg => do pure (msg.severity, ← msg.data.toString) let expected := s!"42\n{claim}\ndigest {Address.blake3 (Ix.Claim.ser claim)}" - let seq := test "command prints the expected result, Eval claim, and digest" - (messages == [(.information, expected)]) + let msgOk := messages == [(.information, expected)] let inputBundle ← packBundle env input let outputBundle ← packBundle env output - let seq := seq ++ test "bundles retain the claim's individual constant addresses" - (inputBundle.main == some input && outputBundle.main == some output) - ++ test "output bundle prunes the input and display metadata" - (!outputBundle.consts.contains input && outputBundle.named.isEmpty) + let retainOk := inputBundle.main == some input && outputBundle.main == some output + let pruneOk := !outputBundle.consts.contains input && outputBundle.named.isEmpty let transported := { inputBundle with consts := outputBundle.consts.fold (fun m k v => m.insert k v) inputBundle.consts blobs := outputBundle.blobs.fold (fun m k v => m.insert k v) inputBundle.blobs anonHints := outputBundle.anonHints.fold (fun m k v => m.insert k v) inputBundle.anonHints } let w ← IO.ofExcept (buildClaimWitness transported claim) r.build (execute "command claim after bundle transport" w (exactPin := true)) - return seq + return do + itBool "command prints the expected result, Eval claim, and digest" msgOk + itBool "bundles retain the claim's individual constant addresses" retainOk + itBool "output bundle prunes the input and display metadata" pruneOk /-- IxCK's reader on the same Nat literal blobs as the program: the compiler's `[0]` and `[42]` are read, a trailing zero byte and the empty blob are refused (`Ix.Kernel.Reader.canonicalNatural`), each output record through the certified entry under the default table. -/ -def natBlobParity (env : Ixon.Env) : IO TestSeq := do +def natBlobParity (env : Ixon.Env) : IO Spec := do let some binding := Ix.Kernel.Admission.defaultBinding.toOption - | return test "the default role table loads" false + | return itBool "the default role table loads" false let limits : Ix.Kernel.Admission.Limits := { maxRecords := 1 <<< 22, maxBlobs := 1 <<< 22, maxTotalBytes := 1 <<< 34, maxRecordBytes := 1 <<< 28, maxRecordUnivNodes := 1 <<< 26 } - let mut tests := TestSeq.done + let mut checks : Array (String × Bool) := #[] for (label, blob, canonical) in [("[0]", ByteArray.mk #[0], true), ("[42]", ByteArray.mk #[42], true), ("[42, 0]", ByteArray.mk #[42, 0], false), ("[]", ByteArray.empty, false)] do let (_, c) ← natBlobOutput env blob @@ -727,16 +731,19 @@ def natBlobParity (env : Ixon.Env) : IO TestSeq := do | .ok _, true => true | .error e, false => ((toString e).splitOn "natural literal blob is not canonical").length > 1 | _, _ => false - tests := tests ++ test s!"IxCK's reader {if canonical then "reads" else "refuses"} the Nat literal blob {label}" - (ok && Ix.Kernel.Reader.canonicalNatural blob == canonical) - return tests + checks := checks.push ( + s!"IxCK's reader {if canonical then "reads" else "refuses"} the Nat literal blob {label}", + ok && Ix.Kernel.Reader.canonicalNatural blob == canonical) + return do + for (label, ok) in checks do + itBool label ok /-- Run the evaluation suite: `full = false` (PR `ci:ixvm`) runs all handcrafted, compiled, difficult, command, and parity cases plus 6 generated arithmetic pairs and 4 boundary truncation offsets; `full = true` (`ci:nightly`) runs all 24 generated arithmetic pairs (`0..23`) and verifies every FFT pin in `evalFftCosts`. -/ def runWith (leanEnv : Lean.Environment) (suiteName : String) (full : Bool) : IO UInt32 := do - let oracles ← IO.mkRef TestSeq.done + let oracles ← IO.mkRef (pure () : Spec) let genCount := if full then 24 else 6 -- Compile all Eval fixtures once and attach default role binding & models once. let allNames := @@ -755,7 +762,7 @@ def runWith (leanEnv : Lean.Environment) (suiteName : String) (full : Bool) : IO let generated ← differentialTests leanEnv base sharedEnv r (count := genCount) let command ← commandTests leanEnv base sharedEnv r let parity ← natBlobParity sharedEnv - oracles.set (difficult ++ generated ++ command ++ parity) + oracles.set (do difficult; generated; command; parity) let labels ← r.labels.get for (name, _) in evalFftCosts do if !full && name.startsWith "generated arithmetic " then @@ -763,7 +770,7 @@ def runWith (leanEnv : Lean.Environment) (suiteName : String) (full : Bool) : IO if idx?.any (· ≥ genCount) then continue unless labels.contains s!"eval accepts {name}" do r.fail s!"unused evaluation FFT pin: {name}" - let lean ← lspecIO (.ofList [(s!"{suiteName} oracles", [← oracles.get])]) [] + let lean ← lspecMain (describe s!"{suiteName} oracles" (← oracles.get)) [] return if code == 0 && lean == 0 then 0 else 1 /-- PR fast evaluation suite. -/ diff --git a/Tests/Ix/IxVM/Exploits.lean b/Tests/Ix/IxVM/Exploits.lean index 1c1da4be47..9b0a5c2549 100644 --- a/Tests/Ix/IxVM/Exploits.lean +++ b/Tests/Ix/IxVM/Exploits.lean @@ -2293,7 +2293,7 @@ def nativeEvaluationNames : List Lean.Name := claim seeds as well as their uses), and the check that an environment declaring the compiler-trust axioms lists no user axiom. -/ def axiomPolicyCases (ctx : Ix.ClaimContext) (env : Ixon.Env) : - IO (Array ExploitCase × TestSeq) := do + IO (Array ExploitCase × Spec) := do -- Check IxCK over just the native-evaluation + uses closure sliced out of the shared compiled env. -- Include `True.rec` in the sliced scope because `Lean.trustCompiler : True` references `True` -- (which is not in `RoleData.prelude`) and IxCK requires every non-prelude inductive block's recursor. @@ -2324,14 +2324,15 @@ def axiomPolicyCases (ctx : Ix.ClaimContext) (env : Ixon.Env) : | some ("blocked", r) => (true, false, s!"blocked behind {r}") | some (o, r) => (true, false, s!"reject ({o}: {(r.take 120).toString})") | none => (false, false, "no IxCK verdict") - let declTests := nativeEvaluationNames.foldl (init := .done) fun acc n => + let mut ixcChecks : Array (String × Bool) := #[] + for n in nativeEvaluationNames do let (present, accepted, label) := verdictOf n - acc ++ test s!"IxCK tolerates inert compiler-trust declaration {n} ({label})" - (present && accepted) - let ixcTests := nativeUses.foldl (init := declTests) fun acc n => + ixcChecks := ixcChecks.push (s!"IxCK tolerates inert compiler-trust declaration {n} ({label})", + present && accepted) + for n in nativeUses do let (present, accepted, label) := verdictOf n - acc ++ test s!"IxCK refuses use of inert compiler-trust axiom {n} ({label})" - (present && !accepted) + ixcChecks := ixcChecks.push (s!"IxCK refuses use of inert compiler-trust axiom {n} ({label})", + present && !accepted) let mut out : Array ExploitCase := #[] for n in nativeEvaluationNames do let addr ← IxVM.ClaimHarness.lookupAddr env n @@ -2349,8 +2350,9 @@ def axiomPolicyCases (ctx : Ix.ClaimContext) (env : Ixon.Env) : -- An environment that declares the compiler-trust axioms names no user axiom: -- the default table binds them as inert roles. let envCtx ← IO.ofExcept (Ix.ClaimContext.ofEnv env true) - let treeTest := test "an environment declaring the compiler-trust axioms has no user axioms tree" - (envCtx.axioms.isNone && (Ix.ClaimContext.userAxioms env).isEmpty) + ixcChecks := ixcChecks.push ( + "an environment declaring the compiler-trust axioms has no user axioms tree", + envCtx.axioms.isNone && (Ix.ClaimContext.userAxioms env).isEmpty) let (axEnv, axAddr) := storeAt env propAxiom out := out.push { name := "axiom-arbitrary" intent := "an arbitrary safe axiom (`axiom _ : Prop`) declared in a \ @@ -2376,7 +2378,10 @@ def axiomPolicyCases (ctx : Ix.ClaimContext) (env : Ixon.Env) : declares the compiler-trust axioms, in the context `ClaimContext.ofEnv` \ gives it (no user axioms), which must be accepted" env, claim := .check envCtx boolFalseA none, expectAccept := true } - return (out, ixcTests ++ treeTest) + let ixcSpec : Spec := do + for (label, ok) in ixcChecks do + itBool label ok + return (out, ixcSpec) /-! ## Runner -/ @@ -2638,7 +2643,7 @@ def ExploitCase.toCase (c : ExploitCase) : Except String Tests.Ix.IxVM.Case := d /-- Every case, through the production claim entry point (`verify_claim`): each exploit must be rejected and each control accepted. -/ -def exploitCases (leanEnv : Lean.Environment) : IO (Array ExploitCase × TestSeq) := do +def exploitCases (leanEnv : Lean.Environment) : IO (Array ExploitCase × Spec) := do -- Compile all Lean fixtures into one shared Ixon environment once. let allNames := #[``String, ``True, ``True.intro, ``True.rec, ``False, ``Eq, ``Eq.refl, ``Bool, ``Bool.rec, ``Nat.beq, @@ -2702,14 +2707,14 @@ controls, and one fast-failing `.binding` smoke. -/ def run (leanEnv : Lean.Environment) : IO UInt32 := do let (cases, ixcTests) ← exploitCases leanEnv let fast := cases.filter keepInFastExploits - let ixc ← lspecIO (.ofList [("ixvm-exploits IxCK", [ixcTests])]) [] + let ixc ← lspecMain (describe "ixvm-exploits IxCK" ixcTests) [] let ixvm ← Tests.Ix.IxVM.runCases "ixvm-exploits" (fast.map fun c _ => c.toCase) return if ixc == 0 && ixvm == 0 then 0 else 1 /-- Full nightly suite: every exploit and control, including all `.binding` cases. -/ def runFull (leanEnv : Lean.Environment) : IO UInt32 := do let (cases, ixcTests) ← exploitCases leanEnv - let ixc ← lspecIO (.ofList [("ixvm-exploits IxCK", [ixcTests])]) [] + let ixc ← lspecMain (describe "ixvm-exploits IxCK" ixcTests) [] let ixvm ← Tests.Ix.IxVM.runCases "ixvm-exploits-full" (cases.map fun c _ => c.toCase) return if ixc == 0 && ixvm == 0 then 0 else 1 diff --git a/Tests/Ix/IxVM/TagN.lean b/Tests/Ix/IxVM/TagN.lean index e9bd5be545..1874626587 100644 --- a/Tests/Ix/IxVM/TagN.lean +++ b/Tests/Ix/IxVM/TagN.lean @@ -210,25 +210,24 @@ def fieldOfWidth (f : Nat) : Field := if f == 0 then .lvls else if f == 2 then . /-- The host writes the expected bytes, and `Canonical.deConstant` accepts every valid rewritten constant in `expectedVectors` and `boundaryCases` (rejecting only level counts `≥ Ixon.maxLevelCount`). -/ -def expectedHostTests : TestSeq := - let encodingTests := expectedVectors.foldl (init := .done) fun acc (f, flag, v, bytes) => +def expectedHostTests : LSpec.Spec := do + for (f, flag, v, bytes) in expectedVectors do let field := fieldOfWidth f let effFlag := if field == .type && !(flags .type v).contains flag then 0x1 else flag let enc : ByteArray := if field == .type then tagNBytes 4 effFlag v else ⟨bytes⟩ let rewritten := rewrite field enc let expectOk := field != .lvls || v < Ixon.maxLevelCount - acc ++ test s!"host TagN f={f} flag={flag} writes {v} as {bytes}" + itBool s!"host TagN f={f} flag={flag} writes {v} as {bytes}" (tagNBytes f flag v == ⟨bytes⟩) - ++ test s!"host Canonical.deConstant accepts={expectOk} expected f={f} value={v}" - ((Ixon.Canonical.deConstant rewritten.size Ixon.loadMaxUnivNodes rewritten).isOk == expectOk) - let boundaryDecodeTests := fields.foldl (init := .done) fun acc field => - (boundaries field.width).foldl (init := acc) fun acc v => - (flags field v).foldl (init := acc) fun acc flag => + itBool s!"host Canonical.deConstant accepts={expectOk} expected f={f} value={v}" + ((Ixon.Canonical.deConstant rewritten.size Ixon.loadMaxUnivNodes rewritten).isOk == expectOk) + for field in fields do + for v in boundaries field.width do + for flag in flags field v do let rewritten := rewrite field (encodingOf field flag v) let expectOk := field != .lvls || v < Ixon.maxLevelCount - acc ++ test s!"host Canonical.deConstant accepts={expectOk} boundary f={field.width} flag={flag} value={v}" + itBool s!"host Canonical.deConstant accepts={expectOk} boundary f={field.width} flag={flag} value={v}" ((Ixon.Canonical.deConstant rewritten.size Ixon.loadMaxUnivNodes rewritten).isOk == expectOk) - encodingTests ++ boundaryDecodeTests /-- The expected encodings in their field. A flag the field gives no free value (an expression of another kind) is read under the field's own flag. -/ @@ -389,7 +388,7 @@ def invalidCodeSample (_ : Unit) : Array Builder := Id.run do /-- PR fast suite: host checks, all expected/rejected/boundary/level-count/parity/ universe-variable cases, and a boundary sample of invalid codes. -/ def run : IO UInt32 := do - let host ← lspecIO (.ofList [("ixvm-tagn host", [expectedHostTests])]) [] + let host ← lspecMain (describe "ixvm-tagn host" expectedHostTests) [] let cases := expectedCases () ++ rejectedCases () ++ boundaryCases () ++ invalidCodeSample () ++ levelCountCases () ++ levelCountParityCases () ++ universeVariableCases () -- The universe-variable cases are decided by the circuit's range check, so diff --git a/Tests/Ix/Ixon.lean b/Tests/Ix/Ixon.lean index 9623c52cf4..c69084c29d 100644 --- a/Tests/Ix/Ixon.lean +++ b/Tests/Ix/Ixon.lean @@ -10,9 +10,11 @@ public import Tests.Ix.RolePacking public import Tests.Ix.HostAdmission public import Tests.Ix.CircuitMeta -open LSpec SlimCheck Gen Ixon +open LSpec LSpec.Prop Ixon open Tests.FFI.Ixon (rsEqUnivSerialization rsEqExprSerialization rsEqConstantSerialization rsEqEnvSerialization) +set_option compiler.extract_closed false + /-! ## Roundtrip Tests for New Format Types -/ @@ -58,7 +60,7 @@ def envSerde (raw : RawEnv) : Bool := ## Unit Tests for New Format Types -/ -def univUnits : TestSeq := +def univUnits : LSpec.Spec := do let cases : List Univ := [ .zero, .var 0, @@ -76,10 +78,9 @@ def univUnits : TestSeq := .imax (.var 1) .zero, .max (.succ .zero) (.succ (.succ .zero)), ] - cases.foldl (init := .done) fun acc u => - acc ++ test s!"Univ roundtrip: {repr u}" (univSerde u) ++ - test s!"Univ Lean==Rust bytes: {repr u}" - (rsEqUnivSerialization u (serUniv u)) + for u in cases do + itBool s!"Univ roundtrip: {repr u}" (univSerde u) + itBool s!"Univ Lean==Rust bytes: {repr u}" (rsEqUnivSerialization u (serUniv u)) def univPrefixAccepts (bytes : ByteArray) : Bool := match runGet getUniv bytes with @@ -91,14 +92,15 @@ def univExactRejects (bytes : ByteArray) : Bool := | .error _ => true | .ok _ => false -def univExactUnits : TestSeq := - let bytes := serUniv Univ.zero ++ [0].toByteArray - test "Univ prefix runner may leave trailing bytes" - (univPrefixAccepts bytes) ++ - test "Univ full-buffer decoder rejects trailing bytes" - (univExactRejects bytes) +def univExactUnits : LSpec.Spec := do + it "Univ prefix runner may leave trailing bytes" do + let bytes := serUniv Univ.zero ++ [0].toByteArray + expect (univPrefixAccepts bytes) + it "Univ full-buffer decoder rejects trailing bytes" do + let bytes := serUniv Univ.zero ++ [0].toByteArray + expect (univExactRejects bytes) -def exprUnits : TestSeq := +def exprUnits : LSpec.Spec := do let cases : List Expr := [ .sort 0, .var 0, @@ -122,10 +124,9 @@ def exprUnits : TestSeq := .letE true .borrow (.sort 0) (.var 0) (.var 1), .prj 0 1 (.var 0), ] - cases.foldl (init := .done) fun acc e => - acc ++ test s!"Expr roundtrip: {repr e}" (exprSerde e) ++ - test s!"Expr Lean==Rust bytes: {repr e}" - (rsEqExprSerialization e (serExpr e)) + for e in cases do + itBool s!"Expr roundtrip: {repr e}" (exprSerde e) + itBool s!"Expr Lean==Rust bytes: {repr e}" (rsEqExprSerialization e (serExpr e)) def exprPrefixAccepts (bytes : ByteArray) : Bool := match runGet getExpr bytes with @@ -137,12 +138,13 @@ def exprExactRejects (bytes : ByteArray) : Bool := | .error _ => true | .ok _ => false -def exprExactUnits : TestSeq := - let bytes := serExpr (.sort 0) ++ [0].toByteArray - test "Expr prefix runner may leave trailing bytes" - (exprPrefixAccepts bytes) ++ - test "Expr full-buffer decoder rejects trailing bytes" - (exprExactRejects bytes) +def exprExactUnits : LSpec.Spec := do + it "Expr prefix runner may leave trailing bytes" do + let bytes := serExpr (.sort 0) ++ [0].toByteArray + expect (exprPrefixAccepts bytes) + it "Expr full-buffer decoder rejects trailing bytes" do + let bytes := serExpr (.sort 0) ++ [0].toByteArray + expect (exprExactRejects bytes) def exprPrefixRejects (bytes : Array UInt8) : Bool := match runGet getExpr (ByteArray.mk bytes) with @@ -153,13 +155,13 @@ def exprPrefixRejects (bytes : Array UInt8) : Bool := `runGet getExpr` so rejection comes from the grammar itself rather than trailing bytes. Reserved let codes and additional malformed vectors are covered by `Tests.IxonGolden.rejectedExprCases`. -/ -def strictExprUnits : TestSeq := - test "rejects empty app spine" (exprPrefixRejects #[0x70]) ++ - test "rejects nested app base" - (exprPrefixRejects #[0x71, 0x71, 0x10, 0x11, 0x12]) ++ - test "rejects nested lambda body" - (exprPrefixRejects #[0x81, 0x00, 0x81, 0x00, 0x10]) ++ - test "rejects nested forall codomain" +def strictExprUnits : LSpec.Spec := do + itBool "rejects empty app spine" (exprPrefixRejects #[0x70]) + itBool "rejects nested app base" + (exprPrefixRejects #[0x71, 0x71, 0x10, 0x11, 0x12]) + itBool "rejects nested lambda body" + (exprPrefixRejects #[0x81, 0x00, 0x81, 0x00, 0x10]) + itBool "rejects nested forall codomain" (exprPrefixRejects #[0x91, 0x00, 0x91, 0x00, 0x10]) /-! ## TagN integer code -/ @@ -199,83 +201,82 @@ def tagNShortCanonical (f : Nat) : Bool := Id.run do if runPut (putTagN f t.flag t.value) != two then return false return true -def tagNUnits : TestSeq := - let perF (f : Nat) : TestSeq := +def tagNUnits : LSpec.Spec := do + for f in [0, 2, 4] do let flags : List UInt8 := [0, (2 ^ f - 1).toUInt8] - let cases := flags.flatMap fun flag => (tagNBoundaries f).map (flag, ·) - cases.foldl (init := .done) fun acc (flag, v) => - acc ++ test s!"TagN f={f} flag={flag} value={v}: width and roundtrip" - (tagNRoundtrip f flag v) - perF 0 ++ perF 2 ++ perF 4 ++ - test "TagN rung ends f=0" ([tagNEnd1 0, tagNEnd2 0, tagNEnd3 0, tagNEnd4 0, tagNEnd5 0] - == [128, 16512, 82048, 16859264, 4311826560]) ++ - test "TagN rung ends f=2" ([tagNEnd1 2, tagNEnd2 2, tagNEnd3 2, tagNEnd4 2, tagNEnd5 2] - == [32, 4128, 69664, 16846880, 4311814176]) ++ - test "TagN rung ends f=4" ([tagNEnd1 4, tagNEnd2 4, tagNEnd3 4, tagNEnd4 4, tagNEnd5 4] - == [8, 1032, 66568, 16843784, 4311811080]) ++ - test "TagN f=4 bytes: 7" (tagNEncodes 4 0xA 7 #[0xA7]) ++ - test "TagN f=4 bytes: 8" (tagNEncodes 4 0xA 8 #[0xA8, 0x00]) ++ - test "TagN f=4 bytes: 1031" (tagNEncodes 4 0x1 1031 #[0x1B, 0xFF]) ++ - test "TagN f=4 bytes: 1032" (tagNEncodes 4 0 1032 #[0x0C, 0x00, 0x00]) ++ - test "TagN f=4 bytes: 66567" (tagNEncodes 4 0 66567 #[0x0C, 0xFF, 0xFF]) ++ - test "TagN f=4 bytes: 66568" (tagNEncodes 4 0 66568 #[0x0D, 0, 0, 0]) ++ - test "TagN f=4 bytes: 16843783" (tagNEncodes 4 0 16843783 #[0x0D, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=4 bytes: 16843784" (tagNEncodes 4 0 16843784 #[0x0E, 0, 0, 0, 0]) ++ - test "TagN f=4 bytes: 4311811079" - (tagNEncodes 4 0 4311811079 #[0x0E, 0xFF, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=4 bytes: 4311811080" - (tagNEncodes 4 0 4311811080 #[0x0F, 0, 0, 0, 0, 0, 0, 0, 0]) ++ - test "TagN f=0 bytes: 127" (tagNEncodes 0 0 127 #[0x7F]) ++ - test "TagN f=0 bytes: 128" (tagNEncodes 0 0 128 #[0x80, 0x00]) ++ - test "TagN f=0 bytes: 16512" (tagNEncodes 0 0 16512 #[0xC0, 0x00, 0x00]) ++ - test "TagN f=0 bytes: 82047" (tagNEncodes 0 0 82047 #[0xC0, 0xFF, 0xFF]) ++ - test "TagN f=0 bytes: 82048" (tagNEncodes 0 0 82048 #[0xC1, 0, 0, 0]) ++ - test "TagN f=0 bytes: 16859263" (tagNEncodes 0 0 16859263 #[0xC1, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=0 bytes: 16859264" (tagNEncodes 0 0 16859264 #[0xC2, 0, 0, 0, 0]) ++ - test "TagN f=0 bytes: 4311826560" - (tagNEncodes 0 0 4311826560 #[0xC3, 0, 0, 0, 0, 0, 0, 0, 0]) ++ - test "TagN f=0 bytes: 2^64 - 1" - (tagNEncodes 0 0 (2 ^ 64 - 1) #[0xC3, 0x7F, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=2 bytes: 32" (tagNEncodes 2 3 32 #[0xE0, 0x00]) ++ - test "TagN f=2 bytes: 4128" (tagNEncodes 2 3 4128 #[0xF0, 0x00, 0x00]) ++ - test "TagN f=2 bytes: 69663" (tagNEncodes 2 3 69663 #[0xF0, 0xFF, 0xFF]) ++ - test "TagN f=2 bytes: 69664" (tagNEncodes 2 3 69664 #[0xF1, 0, 0, 0]) ++ - test "TagN f=2 bytes: 16846879" (tagNEncodes 2 3 16846879 #[0xF1, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=2 bytes: 16846880" (tagNEncodes 2 3 16846880 #[0xF2, 0, 0, 0, 0]) ++ - test "TagN f=2 bytes: 4311814176" - (tagNEncodes 2 3 4311814176 #[0xF3, 0, 0, 0, 0, 0, 0, 0, 0]) ++ - test "TagN f=2 rejects code 4" (tagNRejects 2 #[0x34]) ++ - test "TagN f=2 rejects code 15" (tagNRejects 2 #[0x3F]) ++ - test "TagN f=0 rejects code 4" (tagNRejects 0 #[0xC4]) ++ - test "TagN f=0 rejects code 63" (tagNRejects 0 #[0xFF]) ++ - test "TagN f=4 rejects overflow" - (tagNRejects 4 #[0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=0 rejects overflow" - (tagNRejects 0 #[0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) ++ + for flag in flags do + for v in tagNBoundaries f do + itBool s!"TagN f={f} flag={flag} value={v}: width and roundtrip" + (tagNRoundtrip f flag v) + itBool "TagN rung ends f=0" ([tagNEnd1 0, tagNEnd2 0, tagNEnd3 0, tagNEnd4 0, tagNEnd5 0] + == [128, 16512, 82048, 16859264, 4311826560]) + itBool "TagN rung ends f=2" ([tagNEnd1 2, tagNEnd2 2, tagNEnd3 2, tagNEnd4 2, tagNEnd5 2] + == [32, 4128, 69664, 16846880, 4311814176]) + itBool "TagN rung ends f=4" ([tagNEnd1 4, tagNEnd2 4, tagNEnd3 4, tagNEnd4 4, tagNEnd5 4] + == [8, 1032, 66568, 16843784, 4311811080]) + itBool "TagN f=4 bytes: 7" (tagNEncodes 4 0xA 7 #[0xA7]) + itBool "TagN f=4 bytes: 8" (tagNEncodes 4 0xA 8 #[0xA8, 0x00]) + itBool "TagN f=4 bytes: 1031" (tagNEncodes 4 0x1 1031 #[0x1B, 0xFF]) + itBool "TagN f=4 bytes: 1032" (tagNEncodes 4 0 1032 #[0x0C, 0x00, 0x00]) + itBool "TagN f=4 bytes: 66567" (tagNEncodes 4 0 66567 #[0x0C, 0xFF, 0xFF]) + itBool "TagN f=4 bytes: 66568" (tagNEncodes 4 0 66568 #[0x0D, 0, 0, 0]) + itBool "TagN f=4 bytes: 16843783" (tagNEncodes 4 0 16843783 #[0x0D, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=4 bytes: 16843784" (tagNEncodes 4 0 16843784 #[0x0E, 0, 0, 0, 0]) + itBool "TagN f=4 bytes: 4311811079" + (tagNEncodes 4 0 4311811079 #[0x0E, 0xFF, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=4 bytes: 4311811080" + (tagNEncodes 4 0 4311811080 #[0x0F, 0, 0, 0, 0, 0, 0, 0, 0]) + itBool "TagN f=0 bytes: 127" (tagNEncodes 0 0 127 #[0x7F]) + itBool "TagN f=0 bytes: 128" (tagNEncodes 0 0 128 #[0x80, 0x00]) + itBool "TagN f=0 bytes: 16512" (tagNEncodes 0 0 16512 #[0xC0, 0x00, 0x00]) + itBool "TagN f=0 bytes: 82047" (tagNEncodes 0 0 82047 #[0xC0, 0xFF, 0xFF]) + itBool "TagN f=0 bytes: 82048" (tagNEncodes 0 0 82048 #[0xC1, 0, 0, 0]) + itBool "TagN f=0 bytes: 16859263" (tagNEncodes 0 0 16859263 #[0xC1, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=0 bytes: 16859264" (tagNEncodes 0 0 16859264 #[0xC2, 0, 0, 0, 0]) + itBool "TagN f=0 bytes: 4311826560" + (tagNEncodes 0 0 4311826560 #[0xC3, 0, 0, 0, 0, 0, 0, 0, 0]) + itBool "TagN f=0 bytes: 2^64 - 1" + (tagNEncodes 0 0 (2 ^ 64 - 1) #[0xC3, 0x7F, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=2 bytes: 32" (tagNEncodes 2 3 32 #[0xE0, 0x00]) + itBool "TagN f=2 bytes: 4128" (tagNEncodes 2 3 4128 #[0xF0, 0x00, 0x00]) + itBool "TagN f=2 bytes: 69663" (tagNEncodes 2 3 69663 #[0xF0, 0xFF, 0xFF]) + itBool "TagN f=2 bytes: 69664" (tagNEncodes 2 3 69664 #[0xF1, 0, 0, 0]) + itBool "TagN f=2 bytes: 16846879" (tagNEncodes 2 3 16846879 #[0xF1, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=2 bytes: 16846880" (tagNEncodes 2 3 16846880 #[0xF2, 0, 0, 0, 0]) + itBool "TagN f=2 bytes: 4311814176" + (tagNEncodes 2 3 4311814176 #[0xF3, 0, 0, 0, 0, 0, 0, 0, 0]) + itBool "TagN f=2 rejects code 4" (tagNRejects 2 #[0x34]) + itBool "TagN f=2 rejects code 15" (tagNRejects 2 #[0x3F]) + itBool "TagN f=0 rejects code 4" (tagNRejects 0 #[0xC4]) + itBool "TagN f=0 rejects code 63" (tagNRejects 0 #[0xFF]) + itBool "TagN f=4 rejects overflow" + (tagNRejects 4 #[0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=0 rejects overflow" + (tagNRejects 0 #[0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) -- The smallest overflowing rung-6 payloads: 2^64 - R5 for each f, one past -- the payload of 2^64 - 1 (R5 = 0x1_0101_4080, 0x1_0101_1020, 0x1_0101_0408). - test "TagN f=0 rejects the smallest overflow" - (tagNRejects 0 #[0xC3, 0x80, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=2 accepts 2^64 - 1" - (tagNEncodes 2 0 (2 ^ 64 - 1) #[0x33, 0xDF, 0xEF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=2 rejects the smallest overflow" - (tagNRejects 2 #[0x33, 0xE0, 0xEF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=4 accepts 2^64 - 1" - (tagNEncodes 4 0 (2 ^ 64 - 1) #[0x0F, 0xF7, 0xFB, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=4 rejects the smallest overflow" - (tagNRejects 4 #[0x0F, 0xF8, 0xFB, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ + itBool "TagN f=0 rejects the smallest overflow" + (tagNRejects 0 #[0xC3, 0x80, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=2 accepts 2^64 - 1" + (tagNEncodes 2 0 (2 ^ 64 - 1) #[0x33, 0xDF, 0xEF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=2 rejects the smallest overflow" + (tagNRejects 2 #[0x33, 0xE0, 0xEF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=4 accepts 2^64 - 1" + (tagNEncodes 4 0 (2 ^ 64 - 1) #[0x0F, 0xF7, 0xFB, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=4 rejects the smallest overflow" + (tagNRejects 4 #[0x0F, 0xF8, 0xFB, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) -- An invalid code followed by as many bytes as a valid rung would read: -- a reader that kept only the low two code bits would accept these. - test "TagN f=0 rejects code 4 with two following bytes" (tagNRejects 0 #[0xC4, 0x00, 0x00]) ++ - test "TagN f=2 rejects code 4 with two following bytes" (tagNRejects 2 #[0x34, 0x00, 0x00]) ++ - test "TagN rejects truncated rung 2" (tagNRejects 4 #[0x08]) ++ - test "TagN rejects truncated rung 4" (tagNRejects 4 #[0x0D, 0x00, 0x00]) ++ - test "TagN rejects truncated rung 5" (tagNRejects 4 #[0x0E, 0x00, 0x00, 0x00]) ++ - test "TagN rejects truncated rung 6" (tagNRejects 4 #[0x0F, 0x00, 0x00, 0x00]) ++ - test "TagN rejects trailing byte" (tagNRejects 4 #[0x07, 0x00]) ++ - test "TagN f=0 short strings canonical" (tagNShortCanonical 0) ++ - test "TagN f=2 short strings canonical" (tagNShortCanonical 2) ++ - test "TagN f=4 short strings canonical" (tagNShortCanonical 4) + itBool "TagN f=0 rejects code 4 with two following bytes" (tagNRejects 0 #[0xC4, 0x00, 0x00]) + itBool "TagN f=2 rejects code 4 with two following bytes" (tagNRejects 2 #[0x34, 0x00, 0x00]) + itBool "TagN rejects truncated rung 2" (tagNRejects 4 #[0x08]) + itBool "TagN rejects truncated rung 4" (tagNRejects 4 #[0x0D, 0x00, 0x00]) + itBool "TagN rejects truncated rung 5" (tagNRejects 4 #[0x0E, 0x00, 0x00, 0x00]) + itBool "TagN rejects truncated rung 6" (tagNRejects 4 #[0x0F, 0x00, 0x00, 0x00]) + itBool "TagN rejects trailing byte" (tagNRejects 4 #[0x07, 0x00]) + itBool "TagN f=0 short strings canonical" (tagNShortCanonical 0) + itBool "TagN f=2 short strings canonical" (tagNShortCanonical 2) + itBool "TagN f=4 short strings canonical" (tagNShortCanonical 4) /-! ## ExprMeta arena wire format @@ -284,16 +285,16 @@ explicit TagN backward deltas); the same vectors are pinned in Rust (`ixon::metadata::tests::arena_vector_*`). Name indices are 0 and 1 (one byte in every integer code). -/ -def arenaVecNames : Address × Address × NameIndex × NameReverseIndex := +def arenaVecNames (_ : Unit) : Address × Address × NameIndex × NameReverseIndex := let a := Address.blake3 (ByteArray.mk #[1]) let b := Address.blake3 (ByteArray.mk #[2]) (a, b, (({} : NameIndex).insert a 0).insert b 1, #[a, b]) def arenaBytes (arena : ExprMetaArena) : ByteArray := - runPut (putExprMetaArenaIndexed arena arenaVecNames.2.2.1) + runPut (putExprMetaArenaIndexed arena (arenaVecNames ()).2.2.1) def arenaFrom (bytes : Array UInt8) : Except String ExprMetaArena := - runGetExact (getExprMetaArenaIndexed arenaVecNames.2.2.2) (ByteArray.mk bytes) + runGetExact (getExprMetaArenaIndexed (arenaVecNames ()).2.2.2) (ByteArray.mk bytes) /-- The arena writes exactly `bytes`, and `bytes` read back to the arena. -/ def arenaVector (arena : ExprMetaArena) (bytes : Array UInt8) : Bool := @@ -307,57 +308,60 @@ def arenaRejects (bytes : Array UInt8) : Bool := | .error _ => true | .ok _ => false -def exprMetaArenaUnits : TestSeq := - let a := arenaVecNames.1 - let b := arenaVecNames.2.1 - -- `fun (x : T) => f x` in post-order: every child implicit. - let tree : ExprMetaArena := { nodes := #[ - .ref b, .ref a, .leaf, .app 1 2, .binder a .default 0 3] } - -- Shared nodes: explicit backward deltas next to implicit slots. - let dag : ExprMetaArena := { nodes := #[ - .leaf, .app 0 0, .letBinder a 0 1 0, .prj b 1, .mdata #[] 3] } - -- A forward reference wraps. - let forward : ExprMetaArena := { nodes := #[.leaf, .leaf, .leaf, .prj a 7] } - test "arena: a post-order tree writes no references" - (arenaVector tree #[0x05, 0x38, 0x01, 0x38, 0x00, 0x00, 0x0B, 0x13, 0x00]) ++ - test "arena: shared nodes are explicit backward deltas" - (arenaVector dag #[0x05, 0x00, 0x0A, 0x00, 0x32, 0x00, 0x01, 0x01, 0x40, - 0x01, 0x01, 0x49, 0x00]) ++ - test "arena: a forward reference wraps" - (arenaVector forward #[0x04, 0x00, 0x00, 0x00, - 0x40, 0x00, 0xC3, 0x7B, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "arena: rejects the retired call-site kinds 10 and 11" +def exprMetaArenaUnits : LSpec.Spec := do + it "arena: a post-order tree writes no references" do + let (a, b, _, _) := arenaVecNames () + -- `fun (x : T) => f x` in post-order: every child implicit. + let tree : ExprMetaArena := { nodes := #[ + .ref b, .ref a, .leaf, .app 1 2, .binder a .default 0 3] } + expect (arenaVector tree #[0x05, 0x38, 0x01, 0x38, 0x00, 0x00, 0x0B, 0x13, 0x00]) + it "arena: shared nodes are explicit backward deltas" do + let (a, b, _, _) := arenaVecNames () + -- Shared nodes: explicit backward deltas next to implicit slots. + let dag : ExprMetaArena := { nodes := #[ + .leaf, .app 0 0, .letBinder a 0 1 0, .prj b 1, .mdata #[] 3] } + expect (arenaVector dag #[0x05, 0x00, 0x0A, 0x00, 0x32, 0x00, 0x01, 0x01, 0x40, + 0x01, 0x01, 0x49, 0x00]) + it "arena: a forward reference wraps" do + let (a, _, _, _) := arenaVecNames () + -- A forward reference wraps. + let forward : ExprMetaArena := { nodes := #[.leaf, .leaf, .leaf, .prj a 7] } + expect (arenaVector forward #[0x04, 0x00, 0x00, 0x00, + 0x40, 0x00, 0xC3, 0x7B, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "arena: rejects the retired call-site kinds 10 and 11" (arenaRejects #[0x01, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00] && - arenaRejects #[0x01, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00]) ++ - test "arena: rejects an explicit slot at the implicit position" - (arenaRejects #[0x02, 0x00, 0x08, 0x00, 0x00]) ++ - test "arena: rejects an implicit slot with no preceding node" - (arenaRejects #[0x01, 0x09, 0x00]) ++ - test "arena: rejects mask bits beyond the kind's slots" + arenaRejects #[0x01, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00]) + itBool "arena: rejects an explicit slot at the implicit position" + (arenaRejects #[0x02, 0x00, 0x08, 0x00, 0x00]) + itBool "arena: rejects an implicit slot with no preceding node" + (arenaRejects #[0x01, 0x09, 0x00]) + itBool "arena: rejects mask bits beyond the kind's slots" (arenaRejects #[0x01, 0x01] && arenaRejects #[0x02, 0x00, 0x0C] && - arenaRejects #[0x01, 0x39, 0x00]) ++ - test "arena: rejects unknown kinds" (arenaRejects #[0x01, 0x60]) ++ - test "arena: rejects every truncation" + arenaRejects #[0x01, 0x39, 0x00]) + itBool "arena: rejects unknown kinds" (arenaRejects #[0x01, 0x60]) + itBool "arena: rejects every truncation" (let bytes : Array UInt8 := #[0x05, 0x38, 0x01, 0x38, 0x00, 0x00, 0x0B, 0x13, 0x00] - (List.range bytes.size).all fun n => arenaRejects (bytes.extract 0 n)) ++ - test "arena: the canonical form of a rejected vector is accepted" + (List.range bytes.size).all fun n => arenaRejects (bytes.extract 0 n)) + itBool "arena: the canonical form of a rejected vector is accepted" (arenaVector { nodes := #[.leaf, .app 0 0] } #[0x02, 0x00, 0x0A, 0x00]) -def constantUnits : TestSeq := - let defn := Definition.mk .defn .safe {} 0 (.sort 0) (.var 0) - let c := Constant.mk - (.defn defn) - #[.var 0, .sort 1] -- sharing - #[⟨(Blake3.Rust.hash "ref".toUTF8).val⟩] -- refs - #[.zero, .succ .zero] -- univs - #[] -- binder data - test "Constant roundtrip" (constantSerde c) - -def commUnits : TestSeq := - let addr1 : Address := ⟨(Blake3.Rust.hash "secret".toUTF8).val⟩ - let addr2 : Address := ⟨(Blake3.Rust.hash "payload".toUTF8).val⟩ - let c := Comm.mk addr1 addr2 - test "Comm roundtrip" (commSerde c) +def constantUnits : LSpec.Spec := do + it "Constant roundtrip" do + let defn := Definition.mk .defn .safe {} 0 (.sort 0) (.var 0) + let c := Constant.mk + (.defn defn) + #[.var 0, .sort 1] -- sharing + #[⟨(Blake3.Rust.hash "ref".toUTF8).val⟩] -- refs + #[.zero, .succ .zero] -- univs + #[] -- binder data + expect (constantSerde c) + +def commUnits : LSpec.Spec := do + it "Comm roundtrip" do + let addr1 : Address := ⟨(Blake3.Rust.hash "secret".toUTF8).val⟩ + let addr2 : Address := ⟨(Blake3.Rust.hash "payload".toUTF8).val⟩ + let c := Comm.mk addr1 addr2 + expect (commSerde c) /-! ## Env Unit Tests -/ @@ -372,80 +376,84 @@ def envSerdeUnit (env : Env) : Bool := | .error _ => false | .error _ => false -def envUnitTests : TestSeq := - -- Test 1: Empty env - let emptyEnv : Env := {} - -- Test 2: Env with only a blob. Blob addresses must be the content - -- hash of the bytes — readers verify per entry. - let blobBytes := ByteArray.mk #[4, 5, 6] - let blobAddr := Address.blake3 blobBytes - let envWithBlob : Env := { blobs := ({} : Std.HashMap _ _).insert blobAddr blobBytes } - -- Test 3: Env with a simple name (no named entry) - let testName := Ix.Name.mkStr Ix.Name.mkAnon "test" - let testNameAddr := testName.getHash - let envWithName : Env := { names := ({} : Std.HashMap _ _).insert testNameAddr testName } - -- Test 4: Env with named entry and empty metadata. §5 keys the - -- entry's constant by §2 rank, so the target must be a stored - -- constant (content-addressed — readers verify per entry). - let namedDef : Definition := { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 - } - let namedConst : Constant := { - info := .defn namedDef, sharing := #[], refs := #[], univs := #[] - } - let constAddr := Address.blake3 (serConstant namedConst) - let envWithNamed : Env := Id.run do - let mut env : Env := {} - env := env.storeConst constAddr namedConst - env := { env with names := RawEnv.addNameComponents env.names testName } - env := env.registerName testName { addr := constAddr, constMeta := .empty } - return env - -- Test 5: Env with nested name and named entry, plus an `original` - -- edge whose address is deliberately NOT a stored constant — the §5 - -- original address stays raw on the wire (it may reference an - -- assumed constant), so this must roundtrip. - let nestedName := Ix.Name.mkStr (Ix.Name.mkNat testName 42) "bar" - let envWithNestedName : Env := Id.run do - let mut env : Env := {} - env := env.storeConst constAddr namedConst - env := { env with names := RawEnv.addNameComponents env.names nestedName } - env := env.registerName nestedName - { addr := constAddr, constMeta := .empty, - original := some (Address.blake3 (ByteArray.mk #[99]), .empty) } - return env - -- Test 6: Env with blob and comm - let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) - let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) - let commAddr := Address.blake3 (ByteArray.mk #[16, 17, 18]) - let envWithBlobAndComm : Env := { - blobs := ({} : Std.HashMap _ _).insert blobAddr blobBytes, - comms := ({} : Std.HashMap _ _).insert commAddr (Comm.mk secretAddr payloadAddr) - } - -- Test 7: Bundle env — main + assumptions + anonHints exercise the - -- bundle header and §3. - let bundleDef : Definition := { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 - } - let bundleConst : Constant := { - info := .defn bundleDef, sharing := #[], refs := #[], univs := #[] - } - let bundleConstAddr := Address.blake3 (serConstant bundleConst) - let bundleEnv : Env := Id.run do - let mut env : Env := {} - env := env.storeConst bundleConstAddr bundleConst - return { env with - main := some bundleConstAddr - assumptions := ({} : Std.HashSet Address) - |>.insert (Address.blake3 (ByteArray.mk #[42])) - |>.insert (Address.blake3 (ByteArray.mk #[43])) - anonHints := ({} : Std.HashMap _ _).insert bundleConstAddr (.regular 5) } - test "Empty env roundtrip" (envSerdeUnit emptyEnv) ++ - test "Env with blob roundtrip" (envSerdeUnit envWithBlob) ++ - test "Env with name roundtrip" (envSerdeUnit envWithName) ++ - test "Env with named (empty meta) roundtrip" (envSerdeUnit envWithNamed) ++ - test "Env with nested name roundtrip" (envSerdeUnit envWithNestedName) ++ - test "Env with blob+comm roundtrip" (envSerdeUnit envWithBlobAndComm) ++ - test "Bundle env (main/assumptions/hints) roundtrip" (envSerdeUnit bundleEnv) +def envUnitTests : LSpec.Spec := do + it "Empty env roundtrip" do + let emptyEnv : Env := {} + expect (envSerdeUnit emptyEnv) + it "Env with blob roundtrip" do + let blobBytes := ByteArray.mk #[4, 5, 6] + let blobAddr := Address.blake3 blobBytes + let envWithBlob : Env := { blobs := ({} : Std.HashMap _ _).insert blobAddr blobBytes } + expect (envSerdeUnit envWithBlob) + it "Env with name roundtrip" do + let testName := Ix.Name.mkStr Ix.Name.mkAnon "test" + let testNameAddr := testName.getHash + let envWithName : Env := { names := ({} : Std.HashMap _ _).insert testNameAddr testName } + expect (envSerdeUnit envWithName) + it "Env with named (empty meta) roundtrip" do + let testName := Ix.Name.mkStr Ix.Name.mkAnon "test" + let namedDef : Definition := { + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 + } + let namedConst : Constant := { + info := .defn namedDef, sharing := #[], refs := #[], univs := #[] + } + let constAddr := Address.blake3 (serConstant namedConst) + let envWithNamed : Env := Id.run do + let mut env : Env := {} + env := env.storeConst constAddr namedConst + env := { env with names := RawEnv.addNameComponents env.names testName } + env := env.registerName testName { addr := constAddr, constMeta := .empty } + return env + expect (envSerdeUnit envWithNamed) + it "Env with nested name roundtrip" do + let testName := Ix.Name.mkStr Ix.Name.mkAnon "test" + let namedDef : Definition := { + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 + } + let namedConst : Constant := { + info := .defn namedDef, sharing := #[], refs := #[], univs := #[] + } + let constAddr := Address.blake3 (serConstant namedConst) + let nestedName := Ix.Name.mkStr (Ix.Name.mkNat testName 42) "bar" + let envWithNestedName : Env := Id.run do + let mut env : Env := {} + env := env.storeConst constAddr namedConst + env := { env with names := RawEnv.addNameComponents env.names nestedName } + env := env.registerName nestedName + { addr := constAddr, constMeta := .empty, + original := some (Address.blake3 (ByteArray.mk #[99]), .empty) } + return env + expect (envSerdeUnit envWithNestedName) + it "Env with blob+comm roundtrip" do + let blobBytes := ByteArray.mk #[4, 5, 6] + let blobAddr := Address.blake3 blobBytes + let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) + let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) + let commAddr := Address.blake3 (ByteArray.mk #[16, 17, 18]) + let envWithBlobAndComm : Env := { + blobs := ({} : Std.HashMap _ _).insert blobAddr blobBytes, + comms := ({} : Std.HashMap _ _).insert commAddr (Comm.mk secretAddr payloadAddr) + } + expect (envSerdeUnit envWithBlobAndComm) + it "Bundle env (main/assumptions/hints) roundtrip" do + let bundleDef : Definition := { + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 + } + let bundleConst : Constant := { + info := .defn bundleDef, sharing := #[], refs := #[], univs := #[] + } + let bundleConstAddr := Address.blake3 (serConstant bundleConst) + let bundleEnv : Env := Id.run do + let mut env : Env := {} + env := env.storeConst bundleConstAddr bundleConst + return { env with + main := some bundleConstAddr + assumptions := ({} : Std.HashSet Address) + |>.insert (Address.blake3 (ByteArray.mk #[42])) + |>.insert (Address.blake3 (ByteArray.mk #[43])) + anonHints := ({} : Std.HashMap _ _).insert bundleConstAddr (.regular 5) } + expect (envSerdeUnit bundleEnv) /-! ## Cross-implementation serialization comparison tests -/ @@ -494,117 +502,101 @@ def envSerdeAndRustParity (raw : RawEnv) : Bool := leanRoundtrip && rustParity /-- Unit tests for Lean==Rust serialization comparison -/ -def envSerializationUnitTests : TestSeq := - -- Test 1: Empty env - let emptyRaw : RawEnv := { consts := #[], named := #[], blobs := #[], comms := #[] } - -- Test 2: Env with one blob (content-addressed: readers verify). - let blobBytes := ByteArray.mk #[4, 5, 6] - let blobAddr := Address.blake3 blobBytes - let blobRaw : RawEnv := { - consts := #[], named := #[], - blobs := #[{ addr := blobAddr, bytes := blobBytes }], - comms := #[] - } - -- Test 3: Env with one comm - let commAddr := Address.blake3 (ByteArray.mk #[7, 8, 9]) - let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) - let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) - let commRaw : RawEnv := { - consts := #[], named := #[], - blobs := #[], - comms := #[{ addr := commAddr, comm := Comm.mk secretAddr payloadAddr }] - } - -- Test 4: Env with blob + comm - let blobCommRaw : RawEnv := { - consts := #[], named := #[], - blobs := #[{ addr := blobAddr, bytes := blobBytes }], - comms := #[{ addr := commAddr, comm := Comm.mk secretAddr payloadAddr }] - } - -- Test 5: Bundle env — the directed cross-language vector for the - -- bundle header (main/assumptions) and §3 anon_hints. - let bundleDef : Definition := { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 - } - let bundleConst : Constant := { - info := .defn bundleDef, sharing := #[], refs := #[], univs := #[] - } - let bundleConstAddr := Address.blake3 (serConstant bundleConst) - let bundleRaw : RawEnv := { - consts := #[{ addr := bundleConstAddr, const := bundleConst }], - named := #[], blobs := #[], comms := #[], - main := some bundleConstAddr, - assumptions := #[ - Address.blake3 (ByteArray.mk #[42]), - Address.blake3 (ByteArray.mk #[43])], - anonHints := #[(bundleConstAddr, .regular 5)] - } - -- Test 6: Named entry + hints — the directed cross-language vector - -- for the index-keyed §5 (name §4-index + const §2 rank) and §3 - -- (delta-coded ranks + fused hints). Unlike `RawEnv.toEnv`, the Rust - -- FFI side does not auto-add name components for named entries, so - -- `names` carries the leaf explicitly (ancestors are emitted by both - -- topological sorts from the parent chain). - let namedName := Ix.Name.mkStr Ix.Name.mkAnon "MyDef" - let namedRaw : RawEnv := { - consts := #[{ addr := bundleConstAddr, const := bundleConst }], - named := #[{ name := namedName, addr := bundleConstAddr, - constMeta := .empty, hints := some (.regular 7) }], - blobs := #[], comms := #[], - names := #[{ addr := namedName.getHash, name := namedName }], - anonHints := #[(bundleConstAddr, .abbrev)] - } - -- Test 7: Metadata-bearing named entries — the directed cross-language - -- byte vector for the FULL metadata wire grammar: an arena over the - -- kinds 0-9 (indexed names, binder info, an app, a ref, mdata), the - -- extension tables (sharing exprs, raw refs, univs, univ patches), and - -- a muts entry with the nested-aux `auxLayout` sidecar. Every indexed - -- name address is a registered name component. (Before call-site metadata was retired, the arena - -- also carried a call-site surgery node, kinds 10/11, now retired.) - let surgName := Ix.Name.mkStr Ix.Name.mkAnon "surg" - let blkName := Ix.Name.mkStr Ix.Name.mkAnon "blk" - let anonAddr := Ix.Name.mkAnon.getHash - let surgArena : ExprMetaArena := { nodes := #[ - .leaf, - .binder anonAddr .implicit 0 0, - .ref surgName.getHash, - .app 2 1, - .mdata #[#[(blkName.getHash, .ofName surgName.getHash)]] 3 - ] } - let surgMeta : ConstantMeta := { - info := .defn surgName.getHash #[anonAddr] #[surgName.getHash] #[] - surgArena 0 4, - metaSharing := #[.app (.share 1) (.var 2), .sort 0], - metaRefs := #[bundleConstAddr], - metaUnivs := #[.succ (.var 0), .max .zero (.var 1)], - univPatches := #[⟨1, #[0, 2]⟩, ⟨4, #[3]⟩] - } - let mutsMeta : ConstantMeta := .new - (.muts #[#[surgName.getHash], #[blkName.getHash]] - (some { perm := #[1, 0], sourceCtorCounts := #[2, 3], - evaporated := #[0, 0] })) - let metaRaw : RawEnv := { - consts := #[{ addr := bundleConstAddr, const := bundleConst }], - named := #[ - { name := surgName, addr := bundleConstAddr, constMeta := surgMeta, - hints := some (.regular 3) }, - { name := blkName, addr := bundleConstAddr, constMeta := mutsMeta }], - blobs := #[], comms := #[], - names := #[ - { addr := surgName.getHash, name := surgName }, - { addr := blkName.getHash, name := blkName }] - } - test "Empty env Lean==Rust" (envSerializationMatches emptyRaw) ++ - test "Blob env Lean==Rust" (envSerializationMatches blobRaw) ++ - test "Comm env Lean==Rust" (envSerializationMatches commRaw) ++ - test "Blob+Comm env Lean==Rust" (envSerializationMatches blobCommRaw) ++ - test "Bundle env Lean==Rust" (envSerializationMatches bundleRaw) ++ - test "Named env Lean==Rust" (envSerializationMatches namedRaw) ++ - test "Empty env bytes Lean==Rust" (envBytesMatchRust emptyRaw) ++ - test "Blob env bytes Lean==Rust" (envBytesMatchRust blobRaw) ++ - test "Bundle env bytes Lean==Rust" (envBytesMatchRust bundleRaw) ++ - test "Named env bytes Lean==Rust" (envBytesMatchRust namedRaw) ++ - test "Metadata env bytes Lean==Rust" (envBytesMatchRust metaRaw) ++ - test "Metadata env pure serde" (envSerde metaRaw) +def envSerializationUnitTests : LSpec.Spec := do + let mkEmptyRaw (_ : Unit) : RawEnv := + { consts := #[], named := #[], blobs := #[], comms := #[] } + let mkBlobRaw (_ : Unit) : RawEnv := + let blobBytes := ByteArray.mk #[4, 5, 6] + let blobAddr := Address.blake3 blobBytes + { consts := #[], named := #[], + blobs := #[{ addr := blobAddr, bytes := blobBytes }], + comms := #[] } + let mkCommRaw (_ : Unit) : RawEnv := + let commAddr := Address.blake3 (ByteArray.mk #[7, 8, 9]) + let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) + let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) + { consts := #[], named := #[], blobs := #[], + comms := #[{ addr := commAddr, comm := Comm.mk secretAddr payloadAddr }] } + let mkBlobCommRaw (_ : Unit) : RawEnv := + let blobBytes := ByteArray.mk #[4, 5, 6] + let blobAddr := Address.blake3 blobBytes + let commAddr := Address.blake3 (ByteArray.mk #[7, 8, 9]) + let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) + let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) + { consts := #[], named := #[], + blobs := #[{ addr := blobAddr, bytes := blobBytes }], + comms := #[{ addr := commAddr, comm := Comm.mk secretAddr payloadAddr }] } + let mkBundleConst (_ : Unit) : Address × Constant := + let bundleDef : Definition := { + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 + } + let bundleConst : Constant := { + info := .defn bundleDef, sharing := #[], refs := #[], univs := #[] + } + (Address.blake3 (serConstant bundleConst), bundleConst) + let mkBundleRaw (_ : Unit) : RawEnv := + let (bundleConstAddr, bundleConst) := mkBundleConst () + { consts := #[{ addr := bundleConstAddr, const := bundleConst }], + named := #[], blobs := #[], comms := #[], + main := some bundleConstAddr, + assumptions := #[ + Address.blake3 (ByteArray.mk #[42]), + Address.blake3 (ByteArray.mk #[43])], + anonHints := #[(bundleConstAddr, .regular 5)] } + let mkNamedRaw (_ : Unit) : RawEnv := + let (bundleConstAddr, bundleConst) := mkBundleConst () + let namedName := Ix.Name.mkStr Ix.Name.mkAnon "MyDef" + { consts := #[{ addr := bundleConstAddr, const := bundleConst }], + named := #[{ name := namedName, addr := bundleConstAddr, + constMeta := .empty, hints := some (.regular 7) }], + blobs := #[], comms := #[], + names := #[{ addr := namedName.getHash, name := namedName }], + anonHints := #[(bundleConstAddr, .abbrev)] } + let mkMetaRaw (_ : Unit) : RawEnv := + let (bundleConstAddr, bundleConst) := mkBundleConst () + let surgName := Ix.Name.mkStr Ix.Name.mkAnon "surg" + let blkName := Ix.Name.mkStr Ix.Name.mkAnon "blk" + let anonAddr := Ix.Name.mkAnon.getHash + let surgArena : ExprMetaArena := { nodes := #[ + .leaf, + .binder anonAddr .implicit 0 0, + .ref surgName.getHash, + .app 2 1, + .mdata #[#[(blkName.getHash, .ofName surgName.getHash)]] 3 + ] } + let surgMeta : ConstantMeta := { + info := .defn surgName.getHash #[anonAddr] #[surgName.getHash] #[] + surgArena 0 4, + metaSharing := #[.app (.share 1) (.var 2), .sort 0], + metaRefs := #[bundleConstAddr], + metaUnivs := #[.succ (.var 0), .max .zero (.var 1)], + univPatches := #[⟨1, #[0, 2]⟩, ⟨4, #[3]⟩] + } + let mutsMeta : ConstantMeta := .new + (.muts #[#[surgName.getHash], #[blkName.getHash]] + (some { perm := #[1, 0], sourceCtorCounts := #[2, 3], + evaporated := #[0, 0] })) + { consts := #[{ addr := bundleConstAddr, const := bundleConst }], + named := #[ + { name := surgName, addr := bundleConstAddr, constMeta := surgMeta, + hints := some (.regular 3) }, + { name := blkName, addr := bundleConstAddr, constMeta := mutsMeta }], + blobs := #[], comms := #[], + names := #[ + { addr := surgName.getHash, name := surgName }, + { addr := blkName.getHash, name := blkName }] } + itBool "Empty env Lean==Rust" (envSerializationMatches (mkEmptyRaw ())) + itBool "Blob env Lean==Rust" (envSerializationMatches (mkBlobRaw ())) + itBool "Comm env Lean==Rust" (envSerializationMatches (mkCommRaw ())) + itBool "Blob+Comm env Lean==Rust" (envSerializationMatches (mkBlobCommRaw ())) + itBool "Bundle env Lean==Rust" (envSerializationMatches (mkBundleRaw ())) + itBool "Named env Lean==Rust" (envSerializationMatches (mkNamedRaw ())) + itBool "Empty env bytes Lean==Rust" (envBytesMatchRust (mkEmptyRaw ())) + itBool "Blob env bytes Lean==Rust" (envBytesMatchRust (mkBlobRaw ())) + itBool "Bundle env bytes Lean==Rust" (envBytesMatchRust (mkBundleRaw ())) + itBool "Named env bytes Lean==Rust" (envBytesMatchRust (mkNamedRaw ())) + itBool "Metadata env bytes Lean==Rust" (envBytesMatchRust (mkMetaRaw ())) + itBool "Metadata env pure serde" (envSerde (mkMetaRaw ())) /-! ## Canonical env merkle root: Lean vs. Rust agreement -/ @@ -614,36 +606,35 @@ def envMerkleRootMatches (raw : RawEnv) : Bool := /-- Both pure-Lean and Rust FFI agree on the merkle root over the env's consts addresses. Distinct tests for various const-set shapes. -/ -def envMerkleRootUnitTests : TestSeq := - -- Empty env: no root. - let emptyRaw : RawEnv := - { consts := #[], named := #[], blobs := #[], comms := #[] } - -- Single-const env. - let constAddr := Address.blake3 (ByteArray.mk #[42]) +def envMerkleRootUnitTests : LSpec.Spec := do let oneConst : Constant := { info := .axio { isUnsafe := false, lvls := 0, typ := .sort 0 }, sharing := #[], refs := #[], univs := #[] } - let singleRaw : RawEnv := + let mkEmpty (_ : Unit) : RawEnv := + { consts := #[], named := #[], blobs := #[], comms := #[] } + let mkSingle (_ : Unit) : RawEnv := + let constAddr := Address.blake3 (ByteArray.mk #[42]) { consts := #[{ addr := constAddr, const := oneConst }], named := #[], blobs := #[], comms := #[] } - -- Two-const env, inserted in different orders to check sort invariance. - let addrA := Address.blake3 "a".toUTF8 - let addrB := Address.blake3 "b".toUTF8 - let raw_ab : RawEnv := + let mkAB (_ : Unit) : RawEnv := + let addrA := Address.blake3 "a".toUTF8 + let addrB := Address.blake3 "b".toUTF8 { consts := #[{ addr := addrA, const := oneConst }, { addr := addrB, const := oneConst }], named := #[], blobs := #[], comms := #[] } - let raw_ba : RawEnv := + let mkBA (_ : Unit) : RawEnv := + let addrA := Address.blake3 "a".toUTF8 + let addrB := Address.blake3 "b".toUTF8 { consts := #[{ addr := addrB, const := oneConst }, { addr := addrA, const := oneConst }], named := #[], blobs := #[], comms := #[] } - test "empty env merkle root is none" (emptyRaw.merkleRoot == none) ++ - test "empty env: Lean==Rust" (envMerkleRootMatches emptyRaw) ++ - test "single const: Lean==Rust" (envMerkleRootMatches singleRaw) ++ - test "two consts (a,b): Lean==Rust" (envMerkleRootMatches raw_ab) ++ - test "two consts (b,a): Lean==Rust" (envMerkleRootMatches raw_ba) ++ - test "(a,b) and (b,a) same root" - (raw_ab.merkleRoot == raw_ba.merkleRoot) + itBool "empty env merkle root is none" ((mkEmpty ()).merkleRoot == none) + itBool "empty env: Lean==Rust" (envMerkleRootMatches (mkEmpty ())) + itBool "single const: Lean==Rust" (envMerkleRootMatches (mkSingle ())) + itBool "two consts (a,b): Lean==Rust" (envMerkleRootMatches (mkAB ())) + itBool "two consts (b,a): Lean==Rust" (envMerkleRootMatches (mkBA ())) + itBool "(a,b) and (b,a) same root" + ((mkAB ()).merkleRoot == (mkBA ()).merkleRoot) /-! ## Checked format 4 and versioned storage envelopes -/ @@ -660,18 +651,19 @@ private def versionRejected {α : Type} (r : Except String α) (got : Nat) : Boo | .error e => (e.splitOn s!"unsupported .ixe envelope version {got}").length > 1 -def envHeaderUnits : TestSeq := - let bytes := match serEnv ({} : Env) with | .ok b => b | .error _ => .empty - test "env header is TagN(4, 0xE, 4) = 0xE4" (bytes.data[0]? == some 0xE4) - ++ test "wireFormatId is ixon-v5" (wireFormatId == "ixon-v5") - ++ test "checked object-format byte remains 4" (Env.OBJECT_FORMAT == 4) - ++ test "Lean reader accepts the version 4 header" ((deEnv bytes).toOption.isSome) - ++ test "Lean reader rejects a version 3 header" - (versionRejected (deEnv (emptyEnvWithHeader 0xE3)) 3) - ++ test "Lean streaming reader rejects a version 3 header" - (versionRejected (deEnvVerifiedLazy (emptyEnvWithHeader 0xE3)) 3) - ++ test "Rust reader rejects a version 3 header" - (versionRejected (deEnvAnon (emptyEnvWithHeader 0xE3)) 3) +def envHeaderUnits : LSpec.Spec := do + let mkEmptyBytes (_ : Unit) : ByteArray := + match serEnv ({} : Env) with | .ok b => b | .error _ => .empty + itBool "env header is TagN(4, 0xE, 4) = 0xE4" ((mkEmptyBytes ()).data[0]? == some 0xE4) + itBool "wireFormatId is ixon-v5" (wireFormatId == "ixon-v5") + itBool "checked object-format byte remains 4" (Env.OBJECT_FORMAT == 4) + itBool "Lean reader accepts the version 4 header" ((deEnv (mkEmptyBytes ())).toOption.isSome) + itBool "Lean reader rejects a version 3 header" + (versionRejected (deEnv (emptyEnvWithHeader 0xE3)) 3) + itBool "Lean streaming reader rejects a version 3 header" + (versionRejected (deEnvVerifiedLazy (emptyEnvWithHeader 0xE3)) 3) + itBool "Rust reader rejects a version 3 header" + (versionRejected (deEnvAnon (emptyEnvWithHeader 0xE3)) 3) /-! ## Envelope versions @@ -726,12 +718,10 @@ private def envelopeChecks (definition : Definition) : Except String Unit := do /-- Keep the fixture as a parameter so the compiler cannot initialize the entire closed FFI computation before the selected test runs. -/ -private def envelopeUnits (definition : Definition) : TestSeq := - .individualIO "envelope: v4 bytes, both writers and readers, malformed controls" none (do - let result ← IO.lazyPure fun _ => envelopeChecks definition - return match result with - | .ok _ => (true, 0, 0, none) - | .error e => (false, 0, 0, some e)) .done +private def envelopeUnits (definition : Definition) : Spec := + it "envelope: v4 bytes, both writers and readers, malformed controls" do + let result ← liftM (m := IO) (IO.lazyPure fun _ => envelopeChecks definition) + discard <| expectOk result /-! ## The binder-data section @@ -766,7 +756,7 @@ def canonicalRead (c : Constant) : Bool := (Canonical.deConstant bytes.size loadMaxUnivNodes bytes).toOption == some c /-- Each form still round-trips; the canonical (local) form rejects it. -/ -def noncanonicalSections : List (String × Array BinderBlock) := +def noncanonicalSections (_ : Unit) : List (String × Array BinderBlock) := let b := binderFixture.binders [("blocks out of order", #[b[1]!, b[0]!, b[2]!, b[3]!]), ("a repeated key", b.push b[3]!), @@ -779,7 +769,7 @@ def noncanonicalSections : List (String × Array BinderBlock) := /-- Each form is canonical (local) and round-trips; only the complete form rejects it. -/ -def incompleteSections : List (String × Array BinderBlock) := +def incompleteSections (_ : Unit) : List (String × Array BinderBlock) := let b := binderFixture.binders [("a variant no share node names", b.push ⟨true, 0, 2, #[.never {}]⟩), ("a missing root block", #[b[0]!, b[2]!, b[3]!]), @@ -799,92 +789,96 @@ def projectionWithSection (node : BinderNode) : Constant := { info := .dPrj ⟨0, Address.blake3 "block".toUTF8⟩, sharing := #[], refs := #[], univs := #[], binders := #[⟨false, 0, 0, #[node]⟩] } -def binderSectionUnits : TestSeq := - let bytes := serConstant binderFixture - let badTag := bytes.set! (bytes.size - binderFixtureSection.size + 5) 5 - let badKind := bytes.set! (bytes.size - binderFixtureSection.size + 1) 2 - test "section bytes" ((runPut (putBinders binderFixture.binders)).data == binderFixtureSection) - ++ test "the empty section is 0x00" ((runPut (putBinders #[])).data == #[0]) - ++ test "a record ends with its section" - ((bytes.extract (bytes.size - binderFixtureSection.size) bytes.size).data - == binderFixtureSection) - ++ test "record with a section round-trips" (constantSerde binderFixture) - ++ test "record without a section round-trips" (constantSerde { binderFixture with binders := #[] }) - ++ test "the fixture's section is canonical" binderFixture.bindersCanonical - ++ test "the fixture's section is complete" binderFixture.bindersComplete - ++ test "the canonical decoder accepts it" (canonicalRead binderFixture) - ++ test "a record without binders and no section is canonical and complete" - (let c := { binderFixture with - info := .defn (Definition.mk .defn .safe {} 0 (.sort 0) (.sort 0)), sharing := #[], binders := #[] } - canonicalRead c && c.bindersComplete) - ++ noncanonicalSections.foldl (init := .done) (fun acc (label, blocks) => - let c := { binderFixture with binders := blocks } - acc ++ test s!"{label}: round-trips" (constantSerde c) - ++ test s!"{label}: not canonical" (!c.bindersCanonical && !canonicalRead c)) - ++ incompleteSections.foldl (init := .done) (fun acc (label, blocks) => - let c := { binderFixture with binders := blocks } - acc ++ test s!"{label}: round-trips" (constantSerde c) - ++ test s!"{label}: canonical but not complete" - (c.bindersCanonical && canonicalRead c && !c.bindersComplete)) - ++ test "a projection with a parameter is not canonical" - (!canonicalRead (projectionWithSection (.ifAllZero #[0] {}))) - ++ test "a projection with any section is not canonical" - (!canonicalRead (projectionWithSection (.never {}))) - ++ test "a level count below 2^32 is canonical; 2^32 round-trips and is not" - (let withLvls (n : Nat) : Constant := - { info := .defn (Definition.mk .defn .safe {} n.toUInt64 (.sort 0) (.sort 0)), - sharing := #[], refs := #[], univs := #[.zero], binders := #[] } - canonicalRead (withLvls (maxLevelCount - 1)) && constantSerde (withLvls maxLevelCount) && - !(withLvls maxLevelCount).bindersCanonical && !canonicalRead (withLvls maxLevelCount)) - ++ test "an unknown node tag is rejected" ((deConstant badTag).toOption.isNone) - ++ test "a block kind other than 0 or 1 is rejected" ((deConstant badKind).toOption.isNone) - ++ test "a truncated section is rejected" - ((deConstantExact (bytes.extract 0 (bytes.size - 1))).toOption.isNone) - ++ test "section serialization Lean==Rust" (constantSerializationMatches binderFixture) +def binderSectionUnits : LSpec.Spec := do + itBool "section bytes" ((runPut (putBinders binderFixture.binders)).data == binderFixtureSection) + itBool "the empty section is 0x00" ((runPut (putBinders #[])).data == #[0]) + it "a record ends with its section" do + let bytes := serConstant binderFixture + expect ((bytes.extract (bytes.size - binderFixtureSection.size) bytes.size).data + == binderFixtureSection) + itBool "record with a section round-trips" (constantSerde binderFixture) + itBool "record without a section round-trips" (constantSerde { binderFixture with binders := #[] }) + itBool "the fixture's section is canonical" binderFixture.bindersCanonical + itBool "the fixture's section is complete" binderFixture.bindersComplete + itBool "the canonical decoder accepts it" (canonicalRead binderFixture) + itBool "a record without binders and no section is canonical and complete" + (let c := { binderFixture with + info := .defn (Definition.mk .defn .safe {} 0 (.sort 0) (.sort 0)), sharing := #[], binders := #[] } + canonicalRead c && c.bindersComplete) + for (label, blocks) in noncanonicalSections () do + let c := { binderFixture with binders := blocks } + itBool s!"{label}: round-trips" (constantSerde c) + itBool s!"{label}: not canonical" (!c.bindersCanonical && !canonicalRead c) + for (label, blocks) in incompleteSections () do + let c := { binderFixture with binders := blocks } + itBool s!"{label}: round-trips" (constantSerde c) + itBool s!"{label}: canonical but not complete" + (c.bindersCanonical && canonicalRead c && !c.bindersComplete) + itBool "a projection with a parameter is not canonical" + (!canonicalRead (projectionWithSection (.ifAllZero #[0] {}))) + itBool "a projection with any section is not canonical" + (!canonicalRead (projectionWithSection (.never {}))) + itBool "a level count below 2^32 is canonical; 2^32 round-trips and is not" + (let withLvls (n : Nat) : Constant := + { info := .defn (Definition.mk .defn .safe {} n.toUInt64 (.sort 0) (.sort 0)), + sharing := #[], refs := #[], univs := #[.zero], binders := #[] } + canonicalRead (withLvls (maxLevelCount - 1)) && constantSerde (withLvls maxLevelCount) && + !(withLvls maxLevelCount).bindersCanonical && !canonicalRead (withLvls maxLevelCount)) + it "an unknown node tag is rejected" do + let bytes := serConstant binderFixture + let badTag := bytes.set! (bytes.size - binderFixtureSection.size + 5) 5 + expect (deConstant badTag).toOption.isNone + it "a block kind other than 0 or 1 is rejected" do + let bytes := serConstant binderFixture + let badKind := bytes.set! (bytes.size - binderFixtureSection.size + 1) 2 + expect (deConstant badKind).toOption.isNone + it "a truncated section is rejected" do + let bytes := serConstant binderFixture + expect (deConstantExact (bytes.extract 0 (bytes.size - 1))).toOption.isNone + itBool "section serialization Lean==Rust" (constantSerializationMatches binderFixture) /-! ## Test Suite (property-based) -/ -public def Tests.Ixon.suite : List TestSeq := [ - envHeaderUnits, - Tests.Ix.RoleGeneration.units .natDiv, - Tests.Ix.RoleGeneration.artifactUnits .natDiv, - Tests.Ix.RoleArtifactConsumer.units, - Tests.Ix.RolePacking.units, - Tests.Ix.HostAdmission.units, - Tests.Ix.CircuitMeta.units, +public def Tests.Ixon.suite : LSpec.Spec := do + envHeaderUnits + Tests.Ix.RoleGeneration.units .natDiv + Tests.Ix.RoleGeneration.artifactUnits .natDiv + Tests.Ix.RoleArtifactConsumer.units + Tests.Ix.RolePacking.units + Tests.Ix.HostAdmission.units + Tests.Ix.CircuitMeta.units Tests.Ix.RoleBinding.units { sharing := #[], refs := #[], univs := #[.zero], info := .defn { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } }, + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } } Tests.Ix.RolePublication.units { sharing := #[], refs := #[], univs := #[.zero], info := .defn { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } }, + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } } envelopeUnits { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 }, - univExactUnits, - univUnits, - exprExactUnits, - exprUnits, - strictExprUnits, - tagNUnits, - exprMetaArenaUnits, - binderSectionUnits, + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } + univExactUnits + univUnits + exprExactUnits + exprUnits + strictExprUnits + tagNUnits + exprMetaArenaUnits + binderSectionUnits -- Env unit tests (for debugging serialization) - envUnitTests, + envUnitTests -- Env serialization comparison unit tests - envSerializationUnitTests, + envSerializationUnitTests -- Env merkle root agreement (Lean vs. Rust FFI) - envMerkleRootUnitTests, + envMerkleRootUnitTests -- Pure Lean serde roundtrips - checkIO "Univ serde roundtrips" (∀ u : Univ, univSerde u), - checkIO "Expr serde roundtrips" (∀ e : Expr, exprSerde e), - checkIO "Constant serde roundtrips" (∀ c : Constant, constantSerde c), - checkIO "Comm serde roundtrips" (∀ c : Comm, commSerde c), + prop "Univ serde roundtrips" fun (u : Univ) => univSerde u + prop "Expr serde roundtrips" fun (e : Expr) => exprSerde e + prop "Constant serde roundtrips" fun (c : Constant) => constantSerde c + prop "Comm serde roundtrips" fun (c : Comm) => commSerde c -- Cross-implementation serialization comparison (Lean == Rust) - checkIO "Univ serialization Lean==Rust" (∀ u : Univ, univSerializationMatches u), - checkIO "Expr serialization Lean==Rust" (∀ e : Expr, exprSerializationMatches e), - checkIO "Constant serialization Lean==Rust" (∀ c : Constant, constantSerializationMatches c), + prop "Univ serialization Lean==Rust" fun (u : Univ) => univSerializationMatches u + prop "Expr serialization Lean==Rust" fun (e : Expr) => exprSerializationMatches e + prop "Constant serialization Lean==Rust" fun (c : Constant) => constantSerializationMatches c -- Combined Env serde roundtrip + Lean==Rust decode and strict byte equality -- (generated named entries carry full metadata: arena nodes, extension -- tables, auxLayout — keeping the metadata wire format in sync). - checkIO "Env serde roundtrips and Lean==Rust bytes" (∀ raw : RawEnv, envSerdeAndRustParity raw), -] + prop "Env serde roundtrips and Lean==Rust bytes" fun (raw : RawEnv) => envSerdeAndRustParity raw diff --git a/Tests/Ix/IxonRejectParity.lean b/Tests/Ix/IxonRejectParity.lean index 910cc1954a..e41534a6e9 100644 --- a/Tests/Ix/IxonRejectParity.lean +++ b/Tests/Ix/IxonRejectParity.lean @@ -84,74 +84,88 @@ def parseCases (text : String) : Except String (Array Case) := do def maxRecordBytes : Nat := 1 <<< 28 def maxRecordUnivNodes : Nat := 1 <<< 26 -/-- The readers of a kind, each with whether it accepts `bytes`. -/ -def readers (kind : String) (bytes : ByteArray) : Option (List (String × Bool)) := - let canonical := ("Canonical.deConstant", +/-- The readers of a kind, each as `(name, acceptsFn)`. -/ +def readerFns (kind : String) : Option (List (String × (ByteArray → Bool))) := + let canonical := ("Canonical.deConstant", fun bytes => (Ixon.Canonical.deConstant maxRecordBytes maxRecordUnivNodes bytes).isOk) match kind with | "record" => some [canonical, - ("deConstantLoaded", (Ixon.Env.deConstantLoaded bytes).isOk), - ("deConstantAt", (Ixon.deConstantAt bytes 0 bytes.size).isOk), - ("refsAt", (Ix.Cert.RecordRefs.refsAt bytes 0 bytes.size).isSome)] + ("deConstantLoaded", fun bytes => (Ixon.Env.deConstantLoaded bytes).isOk), + ("deConstantAt", fun bytes => (Ixon.deConstantAt bytes 0 bytes.size).isOk), + ("refsAt", fun bytes => (Ix.Cert.RecordRefs.refsAt bytes 0 bytes.size).isSome)] | "noncanonical" | "canonical-rule" => some [canonical] - | "env" => some [("deEnv", (Ixon.deEnv bytes).isOk), - ("deEnvVerifiedLazy", (Ixon.deEnvVerifiedLazy bytes).isOk)] - | "ixes" => some [("parseIxesManifest", (Ix.Shard.parseIxesManifest bytes).isOk)] - | "tree" => some [("AssumptionTree.de", (Ix.AssumptionTree.de bytes).isOk)] - | "claim" => some [("Claim.de", (Ix.Claim.de bytes).isOk)] + | "env" => some [("deEnv", fun bytes => (Ixon.deEnv bytes).isOk), + ("deEnvVerifiedLazy", fun bytes => (Ixon.deEnvVerifiedLazy bytes).isOk)] + | "ixes" => some [("parseIxesManifest", fun bytes => (Ix.Shard.parseIxesManifest bytes).isOk)] + | "tree" => some [("AssumptionTree.de", fun bytes => (Ix.AssumptionTree.de bytes).isOk)] + | "claim" => some [("Claim.de", fun bytes => (Ix.Claim.de bytes).isOk)] | _ => none +/-- The readers of a kind, each with whether it accepts `bytes`. -/ +def readers (kind : String) (bytes : ByteArray) : Option (List (String × Bool)) := + (readerFns kind).map fun rs => rs.map fun (name, f) => (name, f bytes) + /-- The same small table at its exact aggregate budget and one node below. The offset control also exercises a record embedded between unrelated bytes. -/ -def budgetTests : TestSeq := Id.run do - let c : Ixon.Constant := { - info := .axio { isUnsafe := false, lvls := 0, typ := .sort 0 } - sharing := #[], refs := #[], univs := #[.succ .zero, .zero] } - let bytes := Ixon.serConstant c - let window := ByteArray.mk #[255] ++ bytes ++ ByteArray.mk #[255] - let noUnivs := { c with univs := #[] } - let noUnivBytes := Ixon.serConstant noUnivs - let block : Ix.CompileM.BlockResult := { - block := c, blockBytes := bytes, blockAddr := default } - let projected : Ix.CompileM.BlockResult := - { block with block := noUnivs, projections := #[(Ix.Name.anonymous default, c, .empty)] } - return test "lazy window accepts the exact aggregate universe budget" - ((Ixon.deConstantAt window 1 bytes.size 3).toOption == some c) ++ - test "lazy window refuses a universe table one node over budget" - (!(Ixon.deConstantAt window 1 bytes.size 2).isOk) ++ - test "refs-only reader accepts the exact aggregate universe budget" - (Ix.Cert.RecordRefs.refsAt window 1 bytes.size 3 == some (#[], none)) ++ - test "refs-only reader shares the budget across universe entries" - ((Ix.Cert.RecordRefs.refsAt window 1 bytes.size 2).isNone) ++ - test "empty universe tables accept a zero budget" - ((Ixon.deConstantAt noUnivBytes 0 noUnivBytes.size 0).toOption == some noUnivs) ++ - test "compiler accepts a block at the loader budget" - (Ix.CompileM.blockUnivsFit block 3) ++ - test "compiler refuses a block above the loader budget" - (!Ix.CompileM.blockUnivsFit block 2) ++ - test "compiler checks projection records against the loader budget" - (!Ix.CompileM.blockUnivsFit projected 2) +def budgetTests : LSpec.Spec := do + let mkFixture := fun () => + let c : Ixon.Constant := { + info := .axio { isUnsafe := false, lvls := 0, typ := .sort 0 } + sharing := #[], refs := #[], univs := #[.succ .zero, .zero] } + let bytes := Ixon.serConstant c + let window := ByteArray.mk #[255] ++ bytes ++ ByteArray.mk #[255] + let noUnivs := { c with univs := #[] } + let noUnivBytes := Ixon.serConstant noUnivs + let block : Ix.CompileM.BlockResult := { + block := c, blockBytes := bytes, blockAddr := default } + let projected : Ix.CompileM.BlockResult := + { block with block := noUnivs, projections := #[(Ix.Name.anonymous default, c, .empty)] } + (c, bytes, window, noUnivs, noUnivBytes, block, projected) + it "lazy window accepts the exact aggregate universe budget" do + let (c, bytes, window, _, _, _, _) := mkFixture () + expect ((Ixon.deConstantAt window 1 bytes.size 3).toOption == some c) + it "lazy window refuses a universe table one node over budget" do + let (_, bytes, window, _, _, _, _) := mkFixture () + expect (!(Ixon.deConstantAt window 1 bytes.size 2).isOk) + it "refs-only reader accepts the exact aggregate universe budget" do + let (_, bytes, window, _, _, _, _) := mkFixture () + expect (Ix.Cert.RecordRefs.refsAt window 1 bytes.size 3 == some (#[], none)) + it "refs-only reader shares the budget across universe entries" do + let (_, bytes, window, _, _, _, _) := mkFixture () + expect (Ix.Cert.RecordRefs.refsAt window 1 bytes.size 2).isNone + it "empty universe tables accept a zero budget" do + let (_, _, _, noUnivs, noUnivBytes, _, _) := mkFixture () + expect ((Ixon.deConstantAt noUnivBytes 0 noUnivBytes.size 0).toOption == some noUnivs) + it "compiler accepts a block at the loader budget" do + let (_, _, _, _, _, block, _) := mkFixture () + expect (Ix.CompileM.blockUnivsFit block 3) + it "compiler refuses a block above the loader budget" do + let (_, _, _, _, _, block, _) := mkFixture () + expect (!Ix.CompileM.blockUnivsFit block 2) + it "compiler checks projection records against the loader budget" do + let (_, _, _, _, _, _, projected) := mkFixture () + expect (!Ix.CompileM.blockUnivsFit projected 2) /-- Every case of the fixture, every reader of its kind: a control accepted, any other case refused. -/ -def suite : IO (List TestSeq) := do +def suite : IO Spec := do let cases ← IO.ofExcept (parseCases (← IO.FS.readFile fixturePath)) - let mut tests : TestSeq := budgetTests - for case in cases do - let (kind, accepted) := match case.kind.dropSuffix? "-accept" with - | some kind => (kind.toString, true) - | none => (case.kind, false) - match readers kind case.bytes with - | none => tests := tests ++ test s!"{case.kind} {case.name}: known kind" false - | some results => - for (reader, result) in results do - let verb := if accepted then "accepts" else "refuses" - tests := tests ++ test s!"{reader} {verb} {case.kind} {case.name}" (result == accepted) - -- a record rule beyond the codec: the codec reads the bytes either way - if kind == "canonical-rule" then - tests := tests ++ test s!"the codec reads {case.kind} {case.name}" - (Ixon.runGetExact Ixon.getConstant case.bytes).isOk - return [tests] + return do + budgetTests + for case in cases do + let (kind, accepted) := match case.kind.dropSuffix? "-accept" with + | some kind => (kind.toString, true) + | none => (case.kind, false) + match readerFns kind with + | none => itBool s!"{case.kind} {case.name}: known kind" false + | some fns => + for (reader, check) in fns do + let verb := if accepted then "accepts" else "refuses" + itBool s!"{reader} {verb} {case.kind} {case.name}" (check case.bytes == accepted) + -- a record rule beyond the codec: the codec reads the bytes either way + if kind == "canonical-rule" then + itBool s!"the codec reads {case.kind} {case.name}" + (Ixon.runGetExact Ixon.getConstant case.bytes).isOk end Tests.Ix.IxonRejectParity diff --git a/Tests/Ix/IxonRustParity.lean b/Tests/Ix/IxonRustParity.lean index 746cf3f6ff..b41973a75b 100644 --- a/Tests/Ix/IxonRustParity.lean +++ b/Tests/Ix/IxonRustParity.lean @@ -68,165 +68,173 @@ private def reqNat (j : Json) (k : String) : Except String Nat := private def reqArr (j : Json) (k : String) : Except String (Array Json) := do (← j.getObjVal? k).getArr? -def suite : IO (List TestSeq) := do +def suite : IO Spec := do let raw ← IO.FS.readFile fixturePath let root ← IO.ofExcept (Json.parse raw) - let mut tests : TestSeq := .done - - -- 1. Claims (20 positive vectors) let claims ← IO.ofExcept (reqArr root "claims") - tests := tests ++ test "claims count ≥ 15" (claims.size ≥ 15) - for c in claims do + let proofs ← IO.ofExcept (reqArr root "proofs") + let trees ← IO.ofExcept (reqArr root "assumption_trees") + let comms ← IO.ofExcept (reqArr root "comms") + let univs ← IO.ofExcept (reqArr root "univs") + let exprs ← IO.ofExcept (reqArr root "exprs") + let consts ← IO.ofExcept (reqArr root "constants") + let b3s ← IO.ofExcept (reqArr root "blake3") + let negs ← IO.ofExcept (reqArr root "negative_claims") + + let parseClaimVec (c : Json) : IO (String × ByteArray × String × Nat) := do let name ← IO.ofExcept (reqStr c "name") let hex ← IO.ofExcept (reqStr c "hex") let blake ← IO.ofExcept (reqStr c "blake3") let byteLen ← IO.ofExcept (reqNat c "byte_len") let bytes ← IO.ofExcept (parseHex hex) - let lenOk := bytes.size == byteLen - let hashOk := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake - let rtOk := match Ix.Claim.de bytes with - | .ok val => Ix.Claim.ser val == bytes - | .error _ => false - tests := tests ++ test s!"claim/{name}: len+blake3+roundtrip" (lenOk && hashOk && rtOk) - - -- 2. Proofs (7 positive vectors) - let proofs ← IO.ofExcept (reqArr root "proofs") - tests := tests ++ test "proofs count ≥ 7" (proofs.size ≥ 7) - for p in proofs do - let name ← IO.ofExcept (reqStr p "name") - let hex ← IO.ofExcept (reqStr p "hex") - let blake ← IO.ofExcept (reqStr p "blake3") + return (name, bytes, blake, byteLen) + let parseHexVec (v : Json) (hexKey : String := "hex") : IO (String × ByteArray × String) := do + let name ← IO.ofExcept (reqStr v "name") + let hex ← IO.ofExcept (reqStr v hexKey) + let blake ← IO.ofExcept (reqStr v "blake3") let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake - let rtOk := match Ixon.Proof.de bytes with - | .ok val => Ixon.Proof.ser val == bytes - | .error _ => false - tests := tests ++ test s!"proof/{name}: blake3+roundtrip" (hashOk && rtOk) - - -- 3. AssumptionTrees (5 vectors + root hash) - let trees ← IO.ofExcept (reqArr root "assumption_trees") - tests := tests ++ test "assumption_trees count ≥ 5" (trees.size ≥ 5) - for t in trees do + return (name, bytes, blake) + let parseTreeVec (t : Json) : IO (String × ByteArray × String × String) := do let name ← IO.ofExcept (reqStr t "name") let hex ← IO.ofExcept (reqStr t "hex") let blake ← IO.ofExcept (reqStr t "blake3") let rootBlake ← IO.ofExcept (reqStr t "root_blake3") let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake - let rtOk := match Ix.AssumptionTree.de bytes with - | .ok val => Ix.AssumptionTree.ser val == bytes && addrHex val.root == rootBlake - | .error _ => false - tests := tests ++ test s!"tree/{name}: blake3+roundtrip+root" (hashOk && rtOk) - - -- 4. Comms (2 vectors: untagged, tagged, commitment digest) - let comms ← IO.ofExcept (reqArr root "comms") - tests := tests ++ test "comms count ≥ 2" (comms.size ≥ 2) - for cm in comms do + return (name, bytes, blake, rootBlake) + let parseCommVec (cm : Json) : IO (String × ByteArray × ByteArray × String) := do let name ← IO.ofExcept (reqStr cm "name") let untaggedHex ← IO.ofExcept (reqStr cm "untagged_hex") let taggedHex ← IO.ofExcept (reqStr cm "tagged_hex") let commitBlake ← IO.ofExcept (reqStr cm "commit_blake3") let untagged ← IO.ofExcept (parseHex untaggedHex) let tagged ← IO.ofExcept (parseHex taggedHex) - let rtOk := match Ixon.deComm untagged with - | .ok val => - Ixon.serComm val == untagged && - Ixon.serCommTagged val == tagged && - addrHex val.commit == commitBlake - | .error _ => false - tests := tests ++ test s!"comm/{name}: untagged+tagged+commit" (rtOk == true) - - -- 5. Univs (7 vectors) - let univs ← IO.ofExcept (reqArr root "univs") - tests := tests ++ test "univs count ≥ 7" (univs.size ≥ 7) - for u in univs do - let name ← IO.ofExcept (reqStr u "name") - let hex ← IO.ofExcept (reqStr u "hex") - let blake ← IO.ofExcept (reqStr u "blake3") - let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake - let rtOk := match Ixon.deUniv bytes with - | .ok val => Ixon.serUniv val == bytes - | .error _ => false - tests := tests ++ test s!"univ/{name}: blake3+roundtrip" (hashOk && rtOk) - - -- 6. Exprs (22 vectors) - let exprs ← IO.ofExcept (reqArr root "exprs") - tests := tests ++ test "exprs count ≥ 20" (exprs.size ≥ 20) - for e in exprs do - let name ← IO.ofExcept (reqStr e "name") - let hex ← IO.ofExcept (reqStr e "hex") - let blake ← IO.ofExcept (reqStr e "blake3") - let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake - let rtOk := match Ixon.deExpr bytes with - | .ok val => Ixon.serExpr val == bytes - | .error _ => false - tests := tests ++ test s!"expr/{name}: blake3+roundtrip" (hashOk && rtOk) - - -- 7. Constants (11 vectors) - let consts ← IO.ofExcept (reqArr root "constants") - tests := tests ++ test "constants count ≥ 11" (consts.size ≥ 11) - for k in consts do - let name ← IO.ofExcept (reqStr k "name") - let hex ← IO.ofExcept (reqStr k "hex") - let blake ← IO.ofExcept (reqStr k "blake3") - let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake - let rtOk := match Ixon.deConstant bytes with - | .ok val => Ixon.serConstant val == bytes - | .error _ => false - tests := tests ++ test s!"constant/{name}: blake3+roundtrip" (hashOk && rtOk) - - -- 8. BLAKE3 (6 vectors across block & chunk boundaries) - let b3s ← IO.ofExcept (reqArr root "blake3") - tests := tests ++ test "blake3 count ≥ 6" (b3s.size ≥ 6) - for b in b3s do - let name ← IO.ofExcept (reqStr b "name") - let inputHex ← IO.ofExcept (reqStr b "input_hex") - let blake ← IO.ofExcept (reqStr b "blake3") - let bytes ← IO.ofExcept (parseHex inputHex) - let ok := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake - tests := tests ++ test s!"blake3/{name}: ffi+pure match Rust" ok - - -- 9. Negative Claim Controls (17 vectors: ALL rejected by Claim.de, DynamicLink cases round-trip in Codec) - let negs ← IO.ofExcept (reqArr root "negative_claims") - tests := tests ++ test "negative_claims count ≥ 17" (negs.size ≥ 17) - for n in negs do + return (name, untagged, tagged, commitBlake) + let parseNegVec (n : Json) : IO (String × ByteArray × String) := do let name ← IO.ofExcept (reqStr n "name") let hex ← IO.ofExcept (reqStr n "hex") let dlKind ← IO.ofExcept (reqStr n "dynamic_link_kind") let bytes ← IO.ofExcept (parseHex hex) - let rejectedByClaim := !(Ix.Claim.de bytes).isOk - tests := tests ++ test s!"neg/{name}: Claim.de rejects" rejectedByClaim - -- For the canonical DynamicLink wire vectors (non-scope-prefix probes), verify Lean Codec round-trip - if dlKind == "dynamic_link" && !name.endsWith "_scope_prefix_0403" then - let dlOk := match Ix.DynamicLink.deDynamicLink bytes with - | .ok s => Ix.DynamicLink.serDynamicLink s == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deDynamicLink roundtrips" (dlOk == true) - else if dlKind == "eval_assumption" && !name.endsWith "_scope_prefix_0403" then - let eaOk := match Ix.DynamicLink.deEvalAssumption bytes with - | .ok e => Ix.DynamicLink.serEvalAssumption e == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deEvalAssumption roundtrips" (eaOk == true) - else if dlKind == "eval_assumed_claim" then - let eacOk := match Ix.DynamicLink.deEvalAssumedClaim bytes with - | .ok c => Ix.DynamicLink.serEvalAssumedClaim c == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deEvalAssumedClaim roundtrips" (eacOk == true) - else if dlKind == "linked_circuit_entry" then - let lceOk := match Ix.DynamicLink.deLinkedCircuitEntry bytes with - | .ok e => Ix.DynamicLink.serLinkedCircuitEntry e == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deLinkedCircuitEntry roundtrips" (lceOk == true) - else if dlKind == "linked_claim" then - let lcOk := match Ix.DynamicLink.deLinkedClaim bytes with - | .ok c => Ix.DynamicLink.serLinkedClaim c == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deLinkedClaim roundtrips" (lcOk == true) - - return [tests] + return (name, bytes, dlKind) + + let claimVecs ← claims.mapM parseClaimVec + let proofVecs ← proofs.mapM parseHexVec + let treeVecs ← trees.mapM parseTreeVec + let commVecs ← comms.mapM parseCommVec + let univVecs ← univs.mapM parseHexVec + let exprVecs ← exprs.mapM parseHexVec + let constVecs ← consts.mapM parseHexVec + let b3Vecs ← b3s.mapM (parseHexVec · "input_hex") + let negVecs ← negs.mapM parseNegVec + + return do + -- 1. Claims (20 positive vectors) + itBool "claims count ≥ 15" (decide (claimVecs.size ≥ 15)) + for (name, bytes, blake, byteLen) in claimVecs do + itBool s!"claim/{name}: len+blake3+roundtrip" ( + let lenOk := bytes.size == byteLen + let hashOk := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake + let rtOk := match Ix.Claim.de bytes with + | .ok val => Ix.Claim.ser val == bytes + | .error _ => false + lenOk && hashOk && rtOk) + + -- 2. Proofs (7 positive vectors) + itBool "proofs count ≥ 7" (decide (proofVecs.size ≥ 7)) + for (name, bytes, blake) in proofVecs do + itBool s!"proof/{name}: blake3+roundtrip" ( + let hashOk := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake + let rtOk := match Ixon.Proof.de bytes with + | .ok val => Ixon.Proof.ser val == bytes + | .error _ => false + hashOk && rtOk) + + -- 3. AssumptionTrees (5 vectors + root hash) + itBool "assumption_trees count ≥ 5" (decide (treeVecs.size ≥ 5)) + for (name, bytes, blake, rootBlake) in treeVecs do + itBool s!"tree/{name}: blake3+roundtrip+root" ( + let hashOk := addrHex (Address.blake3 bytes) == blake + let rtOk := match Ix.AssumptionTree.de bytes with + | .ok val => Ix.AssumptionTree.ser val == bytes && addrHex val.root == rootBlake + | .error _ => false + hashOk && rtOk) + + -- 4. Comms (2 vectors: untagged, tagged, commitment digest) + itBool "comms count ≥ 2" (decide (commVecs.size ≥ 2)) + for (name, untagged, tagged, commitBlake) in commVecs do + itBool s!"comm/{name}: untagged+tagged+commit" ( + match Ixon.deComm untagged with + | .ok val => + Ixon.serComm val == untagged && + Ixon.serCommTagged val == tagged && + addrHex val.commit == commitBlake + | .error _ => false) + + -- 5. Univs (7 vectors) + itBool "univs count ≥ 7" (decide (univVecs.size ≥ 7)) + for (name, bytes, blake) in univVecs do + itBool s!"univ/{name}: blake3+roundtrip" ( + let hashOk := addrHex (Address.blake3 bytes) == blake + let rtOk := match Ixon.deUniv bytes with + | .ok val => Ixon.serUniv val == bytes + | .error _ => false + hashOk && rtOk) + + -- 6. Exprs (22 vectors) + itBool "exprs count ≥ 20" (decide (exprVecs.size ≥ 20)) + for (name, bytes, blake) in exprVecs do + itBool s!"expr/{name}: blake3+roundtrip" ( + let hashOk := addrHex (Address.blake3 bytes) == blake + let rtOk := match Ixon.deExpr bytes with + | .ok val => Ixon.serExpr val == bytes + | .error _ => false + hashOk && rtOk) + + -- 7. Constants (11 vectors) + itBool "constants count ≥ 11" (decide (constVecs.size ≥ 11)) + for (name, bytes, blake) in constVecs do + itBool s!"constant/{name}: blake3+roundtrip" ( + let hashOk := addrHex (Address.blake3 bytes) == blake + let rtOk := match Ixon.deConstant bytes with + | .ok val => Ixon.serConstant val == bytes + | .error _ => false + hashOk && rtOk) + + -- 8. BLAKE3 (6 vectors across block & chunk boundaries) + itBool "blake3 count ≥ 6" (decide (b3Vecs.size ≥ 6)) + for (name, bytes, blake) in b3Vecs do + itBool s!"blake3/{name}: ffi+pure match Rust" + (addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake) + + -- 9. Negative Claim Controls (17 vectors: ALL rejected by Claim.de, DynamicLink cases round-trip in Codec) + itBool "negative_claims count ≥ 17" (decide (negVecs.size ≥ 17)) + for (name, bytes, dlKind) in negVecs do + itBool s!"neg/{name}: Claim.de rejects" (!(Ix.Claim.de bytes).isOk) + -- For the canonical DynamicLink wire vectors (non-scope-prefix probes), verify Lean Codec round-trip + if dlKind == "dynamic_link" && !name.endsWith "_scope_prefix_0403" then + itBool s!"neg/{name}: DynamicLink.deDynamicLink roundtrips" ( + match Ix.DynamicLink.deDynamicLink bytes with + | .ok s => Ix.DynamicLink.serDynamicLink s == bytes + | .error _ => false) + else if dlKind == "eval_assumption" && !name.endsWith "_scope_prefix_0403" then + itBool s!"neg/{name}: DynamicLink.deEvalAssumption roundtrips" ( + match Ix.DynamicLink.deEvalAssumption bytes with + | .ok e => Ix.DynamicLink.serEvalAssumption e == bytes + | .error _ => false) + else if dlKind == "eval_assumed_claim" then + itBool s!"neg/{name}: DynamicLink.deEvalAssumedClaim roundtrips" ( + match Ix.DynamicLink.deEvalAssumedClaim bytes with + | .ok c => Ix.DynamicLink.serEvalAssumedClaim c == bytes + | .error _ => false) + else if dlKind == "linked_circuit_entry" then + itBool s!"neg/{name}: DynamicLink.deLinkedCircuitEntry roundtrips" ( + match Ix.DynamicLink.deLinkedCircuitEntry bytes with + | .ok e => Ix.DynamicLink.serLinkedCircuitEntry e == bytes + | .error _ => false) + else if dlKind == "linked_claim" then + itBool s!"neg/{name}: DynamicLink.deLinkedClaim roundtrips" ( + match Ix.DynamicLink.deLinkedClaim bytes with + | .ok c => Ix.DynamicLink.serLinkedClaim c == bytes + | .error _ => false) end Tests.Ix.IxonRustParity diff --git a/Tests/Ix/IxonSyntax.lean b/Tests/Ix/IxonSyntax.lean index b6e9c9ead1..9ffa97c06c 100644 --- a/Tests/Ix/IxonSyntax.lean +++ b/Tests/Ix/IxonSyntax.lean @@ -20,7 +20,9 @@ public import LSpec public import Ix.IxonSyntax public import Tests.Gen.IxonSyntax -open LSpec Ixon.Syntax +open LSpec LSpec.Prop Ixon.Syntax + +set_option compiler.extract_closed false namespace Tests.IxonSyntax @@ -43,10 +45,10 @@ def roundtripFile (src : String) : Except String String := do else if f1.decls.size != f2.decls.size then throw "decl count changed" else return p1 -/-- Render an `Except String` check as a test. -/ -def checkExcept (name : String) : Except String α → TestSeq - | .ok _ => test name true - | .error e => test s!"{name}: {e}" false +/-- Render an `Except String` check as a deferred test. -/ +def checkExcept (name : String) (f : Unit → Except String α) : Spec := + it name do + discard <| expectOk (f ()) /-- Does the result satisfy the predicate? (`test` needs applied Bool functions, not literal `match` bodies, for `Testable`.) -/ @@ -123,9 +125,9 @@ def termCorpus : List String := [ "x!? y" ] -def termRoundtrips : TestSeq := - termCorpus.foldl (init := .done) fun acc src => - acc ++ checkExcept s!"roundtrip {repr src}" (roundtripTerm src) +def termRoundtrips : LSpec.Spec := do + for src in termCorpus do + checkExcept s!"roundtrip {repr src}" fun () => roundtripTerm src def isPinnedRef : Term → Bool | .ref r => r.hash.isSome @@ -139,46 +141,42 @@ def isLet (nonDep : Bool) : Term → Bool | .letE contract .. => contract.nonDep == nonDep | _ => false -def adjacencyIsSignificant : TestSeq := - let pinned := parseTerm "f#abcd" - let applied := parseTerm "f #abcd" - test "f#abcd is a pinned ref" (isOk pinned isPinnedRef) - ++ test "f #abcd is an application" (isOk applied isUnaryApp) - ++ test "pinned prints f#abcd" (printsTo pinned "f#abcd") - ++ test "applied prints f #abcd" (printsTo applied "f #abcd") +def adjacencyIsSignificant : LSpec.Spec := do + itBool "f#abcd is a pinned ref" (isOk (parseTerm "f#abcd") isPinnedRef) + itBool "f #abcd is an application" (isOk (parseTerm "f #abcd") isUnaryApp) + itBool "pinned prints f#abcd" (printsTo (parseTerm "f#abcd") "f#abcd") + itBool "applied prints f #abcd" (printsTo (parseTerm "f #abcd") "f #abcd") -def typeArgumentIsGreedy : TestSeq := - test "f Type 1 takes 1 as universe arg" +def typeArgumentIsGreedy : LSpec.Spec := do + itBool "f Type 1 takes 1 as universe arg" (isOk (parseTerm "f Type 1") isUnaryApp) - ++ test "f (Type) 1 canonical" (rtEq "f (Type) 1" "f (Type) 1") - ++ test "f Type 1 canonical" (rtEq "f Type 1" "f (Type 1)") + itBool "f (Type) 1 canonical" (rtEq "f (Type) 1" "f (Type) 1") + itBool "f Type 1 canonical" (rtEq "f Type 1" "f (Type 1)") -def letVsHave : TestSeq := - test "let is dependent" +def letVsHave : LSpec.Spec := do + itBool "let is dependent" (isOk (parseTerm "let x : N := v; x") (isLet false)) - ++ test "have is non-dependent" + itBool "have is non-dependent" (isOk (parseTerm "have x : N := v; x") (isLet true)) /-- The acceptance fixture: hand-formatted input normalizes to the SAME canonical bytes the Rust printer emits (shared golden). -/ -def acceptanceFixture : TestSeq := - let src := "ixon 3\n" - ++ "import #9c41aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9c41\n" - ++ "\n" - ++ "def : String → Except PatchError String :=\n" - ++ " fun (s : String) => Except.ok PatchError String s\n" - let canonical := - "ixon 3\n\nimport #9c41aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9c41\n" - ++ "\n" - ++ "def : String → Except PatchError String := " - ++ "fun (s : String) => Except.ok PatchError String s\n" - match roundtripFile src with - | .error e => test s!"acceptance fixture: {e}" false - | .ok printed => - test "acceptance fixture prints the shared canonical golden" - (printed == canonical) - -def kitchenSink : TestSeq := +def acceptanceFixture : LSpec.Spec := do + it "acceptance fixture prints the shared canonical golden" do + let src := "ixon 3\n" + ++ "import #9c41aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9c41\n" + ++ "\n" + ++ "def : String → Except PatchError String :=\n" + ++ " fun (s : String) => Except.ok PatchError String s\n" + let canonical := + "ixon 3\n\nimport #9c41aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9c41\n" + ++ "\n" + ++ "def : String → Except PatchError String := " + ++ "fun (s : String) => Except.ok PatchError String s\n" + let printed ← expectOk (roundtripFile src) + shouldBe printed canonical + +def kitchenSink : LSpec.Spec := do let src := "ixon 3 import #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa @@ -216,8 +214,8 @@ cprj Nat'.succ := #dddd 0 1 ⊢ even (succ zero) : Bool " - checkExcept "kitchen sink roundtrip" (roundtripFile src) - ++ test "kitchen sink has a main expression" + checkExcept "kitchen sink roundtrip" fun () => roundtripFile src + itBool "kitchen sink has a main expression" (isOk (parseFile src) (·.main.isSome)) def rtFileEq (src expect : String) : Bool := @@ -225,7 +223,7 @@ def rtFileEq (src expect : String) : Bool := | .ok p => p == expect | .error _ => false -def mainExpression : TestSeq := +def mainExpression : LSpec.Spec := do let cases : List (String × String) := [ ("⊢ 1 : Nat\n", "⊢ 1 : Nat\n"), ("|- 1 : Nat\n", "⊢ 1 : Nat\n"), @@ -236,96 +234,95 @@ def mainExpression : TestSeq := "⊢ (fun (s : String) => Except.ok PatchError String s) : String → Except PatchError String\n"), ("import #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\nfun (x : Nat) => x : Nat → Nat\n", "import #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\n⊢ (fun (x : Nat) => x) : Nat → Nat\n")] - let formats := cases.foldl (init := .done) fun tests (src, expected) => - tests ++ test s!"v3 main {repr src}" + for (src, expected) in cases do + itBool s!"v3 main {repr src}" (rtFileEq ("ixon 3\n" ++ src) ("ixon 3\n\n" ++ expected)) - formats - ++ test "the annotation is mandatory" + itBool "the annotation is mandatory" (errKind (parseFile "ixon 3\n⊢ 1\n") fun k => match k with | .unexpectedToken .. => true | _ => false) - ++ test "after a declaration the turnstile is required" + itBool "after a declaration the turnstile is required" (errKind (parseFile "ixon 3\ndef x : N := v\n1 : Nat\n") fun k => match k with | .unexpectedToken .. => true | _ => false) - ++ test "at most one main expression" + itBool "at most one main expression" (errKind (parseFile "ixon 3\n⊢ 1 : Nat ⊢ 2 : Nat\n") (· == .mainExprNotLast)) - ++ test "main expression must be last" + itBool "main expression must be last" (errKind (parseFile "ixon 3\n⊢ 1 : Nat def x : A := b\n") (· == .mainExprNotLast)) -def mainAfterTermFinalDecl : TestSeq := +def mainAfterTermFinalDecl : LSpec.Spec := do -- Regression (found by quickcheck on the Rust side): the turnstile -- stops the preceding declaration's application spine. - checkExcept "main after where-less inductive" - (roundtripFile - "ixon 3\ninductive N (params := 0) (indices := 0) : Prop\n\n⊢ Prop : Prop\n") - ++ checkExcept "|- after a ctor block is not eaten by the bar" - (roundtripFile + checkExcept "main after where-less inductive" fun () => + roundtripFile + "ixon 3\ninductive N (params := 0) (indices := 0) : Prop\n\n⊢ Prop : Prop\n" + checkExcept "|- after a ctor block is not eaten by the bar" fun () => + roundtripFile ("ixon 3\ninductive N (params := 0) (indices := 0) : Prop where\n" - ++ " | c (params := 0) (fields := 0) : N\n|- c : N\n")) + ++ " | c (params := 0) (fields := 0) : N\n|- c : N\n") -def versionGate : TestSeq := - ([1, 2, 4] : List Nat).foldl (init := - test "version header required" (errKind (parseFile "⊢ 1 : Nat\n") (fun _ => true))) - fun tests version => tests ++ test s!"ixon {version} rejected" +def versionGate : LSpec.Spec := do + itBool "version header required" (errKind (parseFile "⊢ 1 : Nat\n") (fun _ => true)) + for version in ([1, 2, 4] : List Nat) do + itBool s!"ixon {version} rejected" (errKind (parseFile s!"ixon {version}\n") (· == .unknownVersion version 3)) -def importHashLength : TestSeq := - test "short import hash rejected" +def importHashLength : LSpec.Spec := do + itBool "short import hash rejected" (errKind (parseFile "ixon 3\nimport #abcd\n") fun k => k == .importHashLength 4) -def errorShapes : TestSeq := - test "missing => positioned" +def errorShapes : LSpec.Spec := do + itBool "missing => positioned" (errKind (parseTerm "fun (x : Nat) x") fun k => match k with | .unexpectedToken expected _ => (expected.splitOn "=>").length > 1 | _ => false) - ++ test "uppercase hash rejected" + itBool "uppercase hash rejected" (errKind (parseTerm "#DEAD") fun k => match k with | .invalidHash _ => true | _ => false) - ++ test "placeholder is not a term" + itBool "placeholder is not a term" (errKind (parseTerm "f _") (· == .placeholder)) - ++ test "(x : Nat) without arrow is committed" + itBool "(x : Nat) without arrow is committed" (errKind (parseTerm "(x : Nat)") fun k => match k with | .unexpectedToken expected _ => (expected.splitOn "→").length > 1 | _ => false) - ++ test "empty levels" + itBool "empty levels" (errKind (parseTerm "Nat.{}") (· == .emptyLevels)) - ++ test "line/col are 1-based" + itBool "line/col are 1-based" (errLine (parseFile "ixon 3\ndef x : Nat :=\n") 3) -def depthCap : TestSeq := - let limits : Limits := { maxDepth := 16 } - let deep := "".pushn '(' 64 ++ "x" ++ "".pushn ')' 64 - test "depth cap is a structured error" - (errKind (parseTerm deep limits) fun k => +def depthCap : LSpec.Spec := do + it "depth cap is a structured error" do + let limits : Limits := { maxDepth := 16 } + let deep := "".pushn '(' 64 ++ "x" ++ "".pushn ')' 64 + expect (errKind (parseTerm deep limits) fun k => match k with | .capExceeded .depth _ => true | _ => false) -def byteCap : TestSeq := - let limits : Limits := { maxBytes := 8 } - test "byte cap is a structured error" - (errKind (parseTerm "f x y z w" limits) fun k => +def byteCap : LSpec.Spec := do + it "byte cap is a structured error" do + let limits : Limits := { maxBytes := 8 } + expect (errKind (parseTerm "f x y z w" limits) fun k => match k with | .capExceeded .bytes _ => true | _ => false) -def commentsAndWhitespace : TestSeq := - test "comments are skipped" +def commentsAndWhitespace : LSpec.Spec := do + itBool "comments are skipped" (printsTo (parseTerm "f -- line comment\n /- block /- nested -/ -/ x") "f x") - ++ test "unterminated block comment" + itBool "unterminated block comment" (errKind (parseTerm "f /- open") (· == .unterminatedComment)) -def reservedComponentsEscape : TestSeq := - test "Nat.«def» roundtrips" +def reservedComponentsEscape : LSpec.Spec := do + itBool "Nat.«def» roundtrips" (printsTo (parseTerm "Nat.«def»") "Nat.«def»") - ++ test "«123» stays Str" + itBool "«123» stays Str" (printsTo (parseTerm "Foo.«123»") "Foo.«123»") - ++ test "bare 123 is Num" + itBool "bare 123 is Num" (printsTo (parseTerm "Foo.123") "Foo.123") /-! ## Properties (mirror `props.rs`) -/ @@ -383,28 +380,26 @@ def mutatedTotal (t : Term) (m : Muts) : Bool := end Tests.IxonSyntax -open Tests.IxonSyntax Tests.Gen.IxonSyntax in -public def Tests.IxonSyntax.suite : List LSpec.TestSeq := [ - termRoundtrips, - adjacencyIsSignificant, - typeArgumentIsGreedy, - letVsHave, - acceptanceFixture, - kitchenSink, - mainExpression, - mainAfterTermFinalDecl, - versionGate, - importHashLength, - errorShapes, - depthCap, - byteCap, - commentsAndWhitespace, - reservedComponentsEscape, - checkIO "term print∘parse∘print fixpoint" (∀ t : Term, termFixpoint t), - checkIO "file print∘parse∘print fixpoint" (∀ f : File, fileFixpoint f), - checkIO "node count ≤ printed bytes" (∀ t : Term, nodeCountBounded t), - checkIO "parse total on fuzz strings" (∀ f : Fuzz, parseTotal f), - checkIO "parse total under tiny limits" (∀ f : Fuzz, tinyLimitsTotal f), - checkIO "mutated canonical text total" - (∀ (t : Term) (m : Muts), mutatedTotal t m) -] +open Tests.IxonSyntax Tests.Gen.IxonSyntax LSpec LSpec.Prop in +public def Tests.IxonSyntax.suite : LSpec.Spec := do + termRoundtrips + adjacencyIsSignificant + typeArgumentIsGreedy + letVsHave + acceptanceFixture + kitchenSink + mainExpression + mainAfterTermFinalDecl + versionGate + importHashLength + errorShapes + depthCap + byteCap + commentsAndWhitespace + reservedComponentsEscape + prop "term print∘parse∘print fixpoint" fun (t : Term) => termFixpoint t + prop "file print∘parse∘print fixpoint" fun (f : File) => fileFixpoint f + prop "node count ≤ printed bytes" fun (t : Term) => nodeCountBounded t + prop "parse total on fuzz strings" fun (f : Fuzz) => parseTotal f + prop "parse total under tiny limits" fun (f : Fuzz) => tinyLimitsTotal f + prop "mutated canonical text total" fun (t : Term) (m : Muts) => mutatedTotal t m diff --git a/Tests/Ix/IxonUniverse.lean b/Tests/Ix/IxonUniverse.lean index bfc6772b94..07b9653d28 100644 --- a/Tests/Ix/IxonUniverse.lean +++ b/Tests/Ix/IxonUniverse.lean @@ -12,7 +12,9 @@ slip conditions, bounds and rule vectors retain their original definitions. namespace Tests.Ix.IxonUniverse open LSpec -def canonUnivSweep : +set_option compiler.extract_closed false + +def canonUnivSweep (_ : Unit) : Bool × Bool × Bool × Bool × Bool := Id.run do let mut p0 := true let mut p1 := true @@ -94,72 +96,94 @@ def checkCanon (params : Nat) (strict : Bool) (acc : CanonCheck) return acc /-- A `checkCanon` run as a test: no failures (the first three shown). -/ -def canonCheckTest (name : String) (r : CanonCheck) : TestSeq := - test s!"{name} ({r.count} levels, {r.slips} slip-skipped){ - if r.failures.isEmpty then "" else s!": {r.failures.toList.take 3}"}" - r.failures.isEmpty +def canonCheckTest (name : String) (getRes : IO CanonCheck) : Spec := + it name do + let r ← getRes + expect r.failures.isEmpty + s!"{name} ({r.count} levels, {r.slips} slip-skipped): {r.failures.toList.take 3}" /-- P0 on the smallest value-change witness and its family (strict), with the witness's representative pinned (`canon_univ.rs::tests::p0_witness` pins the same term), and on the biased random family. -/ -def canonUnivValueTests : TestSeq := - let (u, v, w) : Ixon.Univ × Ixon.Univ × Ixon.Univ := (.var 0, .var 1, .var 2) - let l : Ixon.Univ := .imax (.imax (.succ (.imax u w)) u) v - let σ : Nat → Nat := fun i => [0, 1, 2].getD i 0 - let witness := Tests.Gen.Ixon.univWitnessFamily.foldl (checkCanon 4 true) {} - let random := - (Tests.Gen.Ixon.biasedUnivFamily 3 10 4000 41).foldl (checkCanon 3 false) {} - let random4 := - (Tests.Gen.Ixon.biasedUnivFamily 4 12 1000 43).foldl (checkCanon 4 false) {} - test "canonUniv P0: imax (imax (imax u w + 1) u) v keeps its value 1 at (0, 1, 2)" - (Tests.Gen.Ixon.univEval σ l == 1 && Tests.Gen.Ixon.univEval σ (Ixon.canonUniv l) == 1) - ++ test "canonUniv: the witness's representative is pinned (Rust pins the same)" - (Ixon.canonUniv l == .max (.imax (.imax (.succ w) u) v) +def canonUnivValueTests : LSpec.Spec := do + it "canonUniv P0: imax (imax (imax u w + 1) u) v keeps its value 1 at (0, 1, 2)" do + let (u, v, w) : Ixon.Univ × Ixon.Univ × Ixon.Univ := (.var 0, .var 1, .var 2) + let l : Ixon.Univ := .imax (.imax (.succ (.imax u w)) u) v + let σ : Nat → Nat := fun i => [0, 1, 2].getD i 0 + expect (Tests.Gen.Ixon.univEval σ l == 1 && Tests.Gen.Ixon.univEval σ (Ixon.canonUniv l) == 1) + it "canonUniv: the witness's representative is pinned (Rust pins the same)" do + let (u, v, w) : Ixon.Univ × Ixon.Univ × Ixon.Univ := (.var 0, .var 1, .var 2) + let l : Ixon.Univ := .imax (.imax (.succ (.imax u w)) u) v + expect (Ixon.canonUniv l == .max (.imax (.imax (.succ w) u) v) (.imax (.imax (.imax (.succ u) w) u) v)) - ++ test "canonUniv: complete witness and seeded context counts" - (witness.count == 121 && random.count == 20000 && random4.count == 5000) - ++ canonCheckTest "canonUniv P0/P1/P2/P3/P6: the witness family" witness - ++ canonCheckTest "canonUniv P0/P1/P2/P3/P6: biased random, 3 params" random - ++ canonCheckTest "canonUniv P0/P1/P2/P3/P6: biased random, 4 params" random4 - -- The slip is rare; a jump here means the normal forms changed. - ++ test "canonUniv: subsumption slips stay rare (< 1 in 200)" - ((random.slips + random4.slips) * 200 < random.count + random4.count) - -def canonUnivVectors : TestSeq := + withResource { + description := "canonUniv witness and biased random families" + acquire := IO.lazyPure fun () => + let witness := Tests.Gen.Ixon.univWitnessFamily.foldl (checkCanon 4 true) {} + let random := + (Tests.Gen.Ixon.biasedUnivFamily 3 10 4000 41).foldl (checkCanon 3 false) {} + let random4 := + (Tests.Gen.Ixon.biasedUnivFamily 4 12 1000 43).foldl (checkCanon 4 false) {} + (witness, random, random4) + } fun getFamilies => do + it "canonUniv: complete witness and seeded context counts" do + let (witness, random, random4) ← getFamilies + expect (witness.count == 121 && random.count == 20000 && random4.count == 5000) + canonCheckTest "canonUniv P0/P1/P2/P3/P6: the witness family" (Prod.fst <$> getFamilies) + canonCheckTest "canonUniv P0/P1/P2/P3/P6: biased random, 3 params" ((·.2.1) <$> getFamilies) + canonCheckTest "canonUniv P0/P1/P2/P3/P6: biased random, 4 params" ((·.2.2) <$> getFamilies) + -- The slip is rare; a jump here means the normal forms changed. + it "canonUniv: subsumption slips stay rare (< 1 in 200)" do + let (_, random, random4) ← getFamilies + expect (decide ((random.slips + random4.slips) * 200 < random.count + random4.count)) + +def canonUnivVectors : LSpec.Spec := do let v : UInt64 → Ixon.Univ := .var let s : Ixon.Univ → Ixon.Univ := .succ let z : Ixon.Univ := .zero - test "canonUniv: commutative twins converge" + itBool "canonUniv: commutative twins converge" (Ixon.canonUniv (.max (v 1) (v 0)) == .max (v 0) (v 1)) - ++ test "canonUniv: reassociation converges" + itBool "canonUniv: reassociation converges" (Ixon.canonUniv (.max (.max (v 0) (v 1)) (v 2)) == .max (v 0) (.max (v 1) (v 2))) - ++ test "canonUniv: succ distributes over max" + itBool "canonUniv: succ distributes over max" (Ixon.canonUniv (s (.max (v 0) (v 1))) == .max (s (v 0)) (s (v 1))) - ++ test "canonUniv: WF eq_def shape reduces" + itBool "canonUniv: WF eq_def shape reduces" (Ixon.canonUniv (.imax (.imax (s z) (v 0)) (v 0)) == v 0) - ++ test "canonUniv: common spellings are fixpoints" + itBool "canonUniv: common spellings are fixpoints" ([z, s z, v 0, s (v 0), .max (v 0) (v 1), .imax (v 0) (v 1), .imax (s (v 1)) (v 0), .imax (.imax (s (v 0)) (v 1)) (v 2)].all fun u => Ixon.canonUniv u == u) - ++ test "reduceUniv: rule table (M1/M4/M7/I2/I4 spot checks)" + itBool "reduceUniv: rule table (M1/M4/M7/I2/I4 spot checks)" (Ixon.reduceUniv (.max (s z) (s (s z))) == s (s z) && Ixon.reduceUniv (.max (v 0) z) == v 0 && Ixon.reduceUniv (.max (s (v 0)) (s (s (v 0)))) == s (s (v 0)) && Ixon.reduceUniv (.imax (v 0) z) == z && Ixon.reduceUniv (.imax (s z) (v 0)) == v 0) -def canonUnivTests : TestSeq := - let (p0, p1, p2, p3, p6) := canonUnivSweep +def canonUnivTests : LSpec.Spec := do canonUnivVectors - ++ canonUnivValueTests - ++ test "canonUniv P0: value-preserving (exhaustive ≤6)" p0 - ++ test "canonUniv P1: idempotent (exhaustive ≤6)" p1 - ++ test "canonUniv P2: linearize∘normalize fixpoint (exhaustive ≤6)" p2 - ++ test "canonUniv P3: canonical forms are mk* fixpoints (exhaustive ≤6)" - p3 - ++ test "canonUniv P6: mk* rebuild absorbed (exhaustive ≤6)" p6 + canonUnivValueTests + withResource { + description := "canonUniv exhaustive sweep (size ≤ 6)" + acquire := IO.lazyPure fun () => canonUnivSweep () + } fun getSweep => do + it "canonUniv P0: value-preserving (exhaustive ≤6)" do + let (p0, _, _, _, _) ← getSweep + expect p0 + it "canonUniv P1: idempotent (exhaustive ≤6)" do + let (_, p1, _, _, _) ← getSweep + expect p1 + it "canonUniv P2: linearize∘normalize fixpoint (exhaustive ≤6)" do + let (_, _, p2, _, _) ← getSweep + expect p2 + it "canonUniv P3: canonical forms are mk* fixpoints (exhaustive ≤6)" do + let (_, _, _, p3, _) ← getSweep + expect p3 + it "canonUniv P6: mk* rebuild absorbed (exhaustive ≤6)" do + let (_, _, _, _, p6) ← getSweep + expect p6 /-! ## Long `imax` chains (canonUniv's normalizer memo) -/ @@ -182,36 +206,37 @@ def mixedChain (n : Nat) : Ixon.Univ := imaxChain of the normalizer (`2ⁿ` calls on these chains); the normalizer skips a repeated call (`CanonUniv.NState`), so chains of 64 finish. Checked by value (P0), idempotence (P1) and the `mk*` fixpoint (P3). -/ -def canonUnivChainTests : TestSeq := +def canonUnivChainTests : LSpec.Spec := do let ok (u : Ixon.Univ) : Bool := let c := Ixon.canonUniv u (Tests.Gen.Ixon.univDifferAt? 2 u c).isNone && Ixon.canonUniv c == c && Ixon.reduceUniv c == c - test "canonUniv: the Cutsat-shaped chain of 64 imax is `u` (0 at u = 0, else u)" + itBool "canonUniv: the Cutsat-shaped chain of 64 imax is `u` (0 at u = 0, else u)" (Ixon.canonUniv (cutsatChain 64) == .var 0) - ++ test "canonUniv P0, P1 and P3: imax chains of 0–10, 24, 40 and 64 links" + itBool "canonUniv P0, P1 and P3: imax chains of 0–10, 24, 40 and 64 links" (((List.range 11) ++ [24, 40, 64]).all fun n => ok (cutsatChain n) && ok (mixedChain n)) /-- `canonUniv` accumulates successor offsets in `Nat`: in `UInt64` an accumulator at `2^64 - 1` plus one successor wrapped to `0`, and the level lost its value. -/ -def canonUnivOffsetTests : TestSeq := - let init : Ixon.CanonUniv.NState := { acc := (∅ : Ixon.CanonUniv.CNorm).insert [] {} } - test "canonUniv offset past 2^64 is kept, not wrapped" - (((Ixon.CanonUniv.normalizeAux (.succ .zero) [] (2 ^ 64 - 1) init).acc.findD [] {}).constant +def canonUnivOffsetTests : LSpec.Spec := do + it "canonUniv offset past 2^64 is kept, not wrapped" do + let init : Ixon.CanonUniv.NState := { acc := (∅ : Ixon.CanonUniv.CNorm).insert [] {} } + expect (((Ixon.CanonUniv.normalizeAux (.succ .zero) [] (2 ^ 64 - 1) init).acc.findD [] {}).constant == 2 ^ 64) - ++ test "canonUniv offset past 2^64 on a variable is kept" - (((Ixon.CanonUniv.normalizeAux (.succ (.var 0)) [] (2 ^ 64 - 1) init).acc.findD [0] {}).vars + it "canonUniv offset past 2^64 on a variable is kept" do + let init : Ixon.CanonUniv.NState := { acc := (∅ : Ixon.CanonUniv.CNorm).insert [] {} } + expect (((Ixon.CanonUniv.normalizeAux (.succ (.var 0)) [] (2 ^ 64 - 1) init).acc.findD [0] {}).vars == #[(0, 2 ^ 64)]) -public def suite : List TestSeq := [ - test "canonUniv: exhaustive size classes 1–6 and total 3736" +public def suite : LSpec.Spec := do + itBool "canonUniv: exhaustive size classes 1–6 and total 3736" ((List.range 6).map (fun i => (Tests.Gen.Ixon.enumerateUniv (i + 1)).length - (Tests.Gen.Ixon.enumerateUniv i).length) == [4, 4, 36, 100, 708, 2884] && - (Tests.Gen.Ixon.enumerateUniv 6).length == 3736), - canonUnivTests, - canonUnivChainTests, - canonUnivOffsetTests] + (Tests.Gen.Ixon.enumerateUniv 6).length == 3736) + canonUnivTests + canonUnivChainTests + canonUnivOffsetTests end Tests.Ix.IxonUniverse diff --git a/Tests/Ix/Kernel/BuildPrimitives.lean b/Tests/Ix/Kernel/BuildPrimitives.lean index 18364ef922..b2f12bf890 100644 --- a/Tests/Ix/Kernel/BuildPrimitives.lean +++ b/Tests/Ix/Kernel/BuildPrimitives.lean @@ -121,8 +121,8 @@ def parseIxName (s : String) : Ix.Name := Id.run do /-- Dump the current `(name, hex)` table for every entry in `kernelPrimitives`. Pass iff every entry resolves; missing names are printed as `// MISSING:` comments so the output is still valid as-is for partial regeneration. -/ -def testBuildPrimitives : TestSeq := - .individualIO "build primitives dump" none (do +def testBuildPrimitives : Spec := + it "build primitives dump" do let leanEnv ← get_env! let filtered := primitiveClosure leanEnv @@ -157,10 +157,7 @@ def testBuildPrimitives : TestSeq := if !missing.isEmpty then IO.println s!"// Missing: {missing}" - let msg : Option String := - if missing.isEmpty then none else some s!"{missing.size} primitives missing from Ixon env" - return (missing.isEmpty, found, missing.size, msg) - ) .done + expect missing.isEmpty s!"{missing.size} primitives missing from Ixon env" /-- FFI: expose `PrimAddrs::new()` from Rust as `(lean_name, hex_address)` pairs in the same order as @@ -186,8 +183,8 @@ opaque rsPrimAddrsCanonicalFFI : IO (Array (String × String)) PrimAddrs value (`0xff…3`) intentionally diverges from its compiled content hash (which collides with `id`). Skip the check for it. -/ -def testPrimitivesParity : TestSeq := - .individualIO "primitive address parity (PrimAddrs vs live compile)" none (do +def testPrimitivesParity : Spec := + it "primitive address parity (PrimAddrs vs live compile)" do -- Reuse the same Lean → Ixon compile pipeline as testBuildPrimitives. let leanEnv ← get_env! let filtered := primitiveClosure leanEnv @@ -232,15 +229,12 @@ def testPrimitivesParity : TestSeq := IO.eprintln "Regenerate via `lake test -- --ignored rust-kernel-build-primitives` and paste into crates/common/src/prim_addrs.rs." let total_problems := missing.size + mismatches.size - let passed := kernelPrimitives.size - min total_problems kernelPrimitives.size - let msg : Option String := - if total_problems == 0 then none - else some s!"{mismatches.size} mismatch(es), {missing.size} missing" - return (total_problems == 0, passed, total_problems, msg) - ) .done + expect (total_problems == 0) s!"{mismatches.size} mismatch(es), {missing.size} missing" -def paritySuite : List TestSeq := [testPrimitivesParity] +def paritySuite : LSpec.Spec := do + testPrimitivesParity -def suite : List TestSeq := [testBuildPrimitives] +def suite : LSpec.Spec := do + testBuildPrimitives end Tests.Ix.Kernel.BuildPrimitives diff --git a/Tests/Ix/Kernel/BundleEvidence.lean b/Tests/Ix/Kernel/BundleEvidence.lean index 900a5cfdc2..f804d3f244 100644 --- a/Tests/Ix/Kernel/BundleEvidence.lean +++ b/Tests/Ix/Kernel/BundleEvidence.lean @@ -32,7 +32,7 @@ def operations : Array Lean.Name := /-- The bundle's evidence: no reason, the structural operations' entries, and each well-founded operation's theorems, in order, under their names. -/ -def shape : TestSeq := +def shape : LSpec.Spec := do let (ev, why) := Ix.RoleEvidence.bundleEvidenceReport () let structural := Ix.RoleEvidence.defeqRoles.all fun r => ev.any fun (r', es) => r' == r && es.length == (Ix.RoleEvidence.defeqEvidence (K := Unit) r).length && @@ -42,9 +42,9 @@ def shape : TestSeq := (es.zip thms).all fun (e, t) => match e with | .proof (k, _) => k == Ix.RoleEvidence.ofLeanName t | .defeq => false - test s!"the committed bundle reads ({why})" why.isEmpty $ - test "the structural operations: their defeq entries" structural $ - test "the well-founded operations: their certificate theorems, in order, by name" proved + itBool s!"the committed bundle reads ({why})" why.isEmpty + itBool "the structural operations: their defeq entries" structural + itBool "the well-founded operations: their certificate theorems, in order, by name" proved /-- The operations' closure in `Init` (no certificate theorem), checked group by group at the input's own evidence and at the bundle's, and all at once at @@ -75,13 +75,14 @@ def evaluate : IO (Array String × Array String) := do | .error e => errors := errors.push s!"checkSourceWith at the bundle's evidence: {e}" return (errors, lines) -def closureCheck : TestSeq := - .individualIO "the operations' Init closure, without certificates, at the bundle's evidence" none (do +def closureCheck : Spec := + it "the operations' Init closure, without certificates, at the bundle's evidence" do let (errors, lines) ← evaluate for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, operations.size, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) -def suite : List TestSeq := [shape, closureCheck] +def suite : LSpec.Spec := do + shape + closureCheck end Tests.Ix.Kernel.BundleEvidence diff --git a/Tests/Ix/Kernel/CheckCompPoly.lean b/Tests/Ix/Kernel/CheckCompPoly.lean index a64561060c..9dd944b80b 100644 --- a/Tests/Ix/Kernel/CheckCompPoly.lean +++ b/Tests/Ix/Kernel/CheckCompPoly.lean @@ -36,15 +36,15 @@ private def filterFocusConsts (names : Array Lean.Name) : IO (Array Lean.Name) : {filtered.size}/{names.size}" pure filtered -def testRustCheckCompPoly : TestSeq := - .individualIO s!"kernel check {focusConsts.size} CompPoly focus const(s)" none (do +def testRustCheckCompPoly : Spec := + it s!"kernel check {focusConsts.size} CompPoly focus const(s)" do unless (← ixePath.pathExists) do - return (false, 0, focusConsts.size, some s!"{ixePath} missing — build it with \ + fail s!"{ixePath} missing — build it with \ `lake exe ix compile Benchmarks/Compile/CompPoly.lean \ - --out comppoly.ixe --verbose`") + --out comppoly.ixe --verbose`" let names ← filterFocusConsts focusConsts if names.isEmpty then - return (false, 0, 0, some "IX_KERNEL_FOCUS_CONST matched no CompPoly canary") + fail "IX_KERNEL_FOCUS_CONST matched no CompPoly canary" let start ← IO.monoMsNow let expected := names.map fun _ => true let results ← rsCheckIxonFFI ixePath.toString names expected false "" @@ -57,12 +57,9 @@ def testRustCheckCompPoly : TestSeq := passed in {elapsed}ms" for (name, msg) in failures do IO.println s!" ✗ {name}: {msg}" - if failures.isEmpty then - return (true, names.size, names.size, none) - return (false, names.size - failures.size, names.size, - some s!"CompPoly focus check failed with {failures.size} failure(s)") - ) .done + expect failures.isEmpty s!"CompPoly focus check failed with {failures.size} failure(s)" -def suite : List TestSeq := [testRustCheckCompPoly] +def suite : LSpec.Spec := do + testRustCheckCompPoly end Tests.Ix.Kernel.CheckCompPoly diff --git a/Tests/Ix/Kernel/CheckLeanCli.lean b/Tests/Ix/Kernel/CheckLeanCli.lean index 2b8701fc92..a5127d82d0 100644 --- a/Tests/Ix/Kernel/CheckLeanCli.lean +++ b/Tests/Ix/Kernel/CheckLeanCli.lean @@ -64,7 +64,7 @@ private def check : IO Nat := do -- Keep the actual pin adapter's fresh-run/timing path executable on a small -- fixture; the historical corpus pin labels and budgets stay unchanged. let pin ← Tests.Tc.Pins.checkPin prepared { label := "CliAlias0", budgetMs := 60000 } - ensure ((← lspecIO (.ofList [("pin-adapter", [pin])]) []) == 0) "pin adapter failed" + ensure ((← lspecMain (describe "pin-adapter" pin) []) == 0) "pin adapter failed" let window := prepared.parts.env.consts[twice.addr]! let tampered := bytes.set! window.off (bytes[window.off]! ^^^ 1) for anon in [false, true] do @@ -244,9 +244,8 @@ private def check : IO Nat := do finally IO.FS.removeDirAll dir -def suite : List TestSeq := [ - .individualIO "authenticated IxCK CLI and repeatable prepared callers" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "authenticated IxCK CLI and repeatable prepared callers" do + let _ ← check end Tests.Ix.Kernel.CheckLeanCli diff --git a/Tests/Ix/Kernel/CheckLeanTargets.lean b/Tests/Ix/Kernel/CheckLeanTargets.lean index 82427b9c00..d2d17873ba 100644 --- a/Tests/Ix/Kernel/CheckLeanTargets.lean +++ b/Tests/Ix/Kernel/CheckLeanTargets.lean @@ -146,9 +146,8 @@ private def check : IO Nat := do IO.println s!"selected coverage: {labels.size} named at both modes; 5 aliases; caps, recursors, omitted projections and failures" return labels.size * 2 + 5 -def suite : List TestSeq := [ - .individualIO "selected labels require their actual producer and emitted key" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "selected labels require their actual producer and emitted key" do + let _ ← check end Tests.Ix.Kernel.CheckLeanTargets diff --git a/Tests/Ix/Kernel/CheckPrimeGaps.lean b/Tests/Ix/Kernel/CheckPrimeGaps.lean index 36272fdeeb..ba309ba316 100644 --- a/Tests/Ix/Kernel/CheckPrimeGaps.lean +++ b/Tests/Ix/Kernel/CheckPrimeGaps.lean @@ -32,16 +32,17 @@ private def filterFocusConsts (names : Array Lean.Name) : IO (Array Lean.Name) : {filtered.size}/{names.size}" pure filtered -def testLeanCheckPrimeGaps : TestSeq := - .individualIO s!"IxCK check {focusConsts.size} inlined PrimeGaps consts" none (do +def testLeanCheckPrimeGaps : Spec := + it s!"IxCK check {focusConsts.size} inlined PrimeGaps consts" do let names ← filterFocusConsts focusConsts let leanEnv ← get_env! IO.println s!"[check-primegaps/lean] compiling \ selected IxCK closure for {names.size} exact subject(s)" - Tests.Ix.Kernel.FocusedLeanCheck.checkClosure "check-primegaps/lean" + let (ok, _, _, msg) ← Tests.Ix.Kernel.FocusedLeanCheck.checkClosure "check-primegaps/lean" "primegaps-reduction" leanEnv names - ) .done + expect ok (msg.getD "PrimeGaps check failed") -def suite : List TestSeq := [testLeanCheckPrimeGaps] +def suite : LSpec.Spec := do + testLeanCheckPrimeGaps end Tests.Ix.Kernel.CheckPrimeGaps diff --git a/Tests/Ix/Kernel/CheckTauCeti.lean b/Tests/Ix/Kernel/CheckTauCeti.lean index 2a0b3db6aa..8d7b5f79a7 100644 --- a/Tests/Ix/Kernel/CheckTauCeti.lean +++ b/Tests/Ix/Kernel/CheckTauCeti.lean @@ -87,11 +87,11 @@ private def filterFocusConsts (names : Array Lean.Name) : IO (Array Lean.Name) : IO.println s!"[check-tauceti] IX_KERNEL_FOCUS_CONST={filter} matched {filtered.size}/{names.size}" pure filtered -def testRustCheckTauCetiConsts (names : Array Lean.Name := focusConsts) : TestSeq := - .individualIO s!"kernel check {names.size} TauCeti focus consts" none (do +def testRustCheckTauCetiConsts (names : Array Lean.Name := focusConsts) : Spec := + it s!"kernel check {names.size} TauCeti focus consts" do unless (← ixePath.pathExists) do - return (false, 0, names.size, some s!"{ixePath} missing — build it \ - with `ix compile Benchmarks/Compile/TauCeti.lean` (see module docstring)") + fail s!"{ixePath} missing — build it \ + with `ix compile Benchmarks/Compile/TauCeti.lean` (see module docstring)" let names ← filterFocusConsts names let expectPass : Array Bool := names.map expectedPass let start ← IO.monoMsNow @@ -129,14 +129,9 @@ def testRustCheckTauCetiConsts (names : Array Lean.Name := focusConsts) : TestSe for (name, msg) in failures do IO.println s!" ✗ {name}: {msg}" - let total := passed + failures.size - if failures.isEmpty then - return (true, passed, total, none) - else - return (false, passed, total, - some s!"TauCeti focus check failed with {failures.size} failure(s)") - ) .done + expect failures.isEmpty s!"TauCeti focus check failed with {failures.size} failure(s)" -def suite : List TestSeq := [testRustCheckTauCetiConsts] +def suite : LSpec.Spec := do + testRustCheckTauCetiConsts end Tests.Ix.Kernel.CheckTauCeti diff --git a/Tests/Ix/Kernel/CheckTauCetiReduction.lean b/Tests/Ix/Kernel/CheckTauCetiReduction.lean index 137e70fc61..c88a6379e1 100644 --- a/Tests/Ix/Kernel/CheckTauCetiReduction.lean +++ b/Tests/Ix/Kernel/CheckTauCetiReduction.lean @@ -23,17 +23,16 @@ def focusConsts : Array Lean.Name := #[ `Tests.Ix.Kernel.TauCetiReduction.composedSymmApply ] -def testLeanCheckTauCetiReduction : TestSeq := - .individualIO s!"IxCK check {focusConsts.size} inlined TauCeti reductions" none (do +def testLeanCheckTauCetiReduction : Spec := + it s!"IxCK check {focusConsts.size} inlined TauCeti reductions" do let leanEnv ← get_env! IO.println s!"[check-tauceti-reduction/lean] compiling \ selected IxCK closure for {focusConsts.size} subject(s)" - Tests.Ix.Kernel.FocusedLeanCheck.checkClosure + let (ok, _, _, msg) ← Tests.Ix.Kernel.FocusedLeanCheck.checkClosure "check-tauceti-reduction/lean" "tauceti-reduction" leanEnv focusConsts - ) .done + expect ok (msg.getD "TauCeti reduction check failed") -def suite : List TestSeq := [ +def suite : LSpec.Spec := do testLeanCheckTauCetiReduction -] end Tests.Ix.Kernel.CheckTauCetiReduction diff --git a/Tests/Ix/Kernel/FastPaths.lean b/Tests/Ix/Kernel/FastPaths.lean index 44841e3cb6..bc7c598448 100644 --- a/Tests/Ix/Kernel/FastPaths.lean +++ b/Tests/Ix/Kernel/FastPaths.lean @@ -93,16 +93,16 @@ def ixcVerdicts (compiled : Ix.CompileM.CertifiedOut) (names : List Lean.Name) : /-- The check of one probe against one kernel's verdicts. -/ def checkProbe (kernel : String) (closure : List Lean.Name) (verdicts : Verdicts) - (p : Probe) : TestSeq := + (p : Probe) : Spec := do let missing := closure.filter (!verdicts.contains ·) let failures := closure.filter fun n => !(verdicts.getD n .accept).isAccept - let describe (ns : List Lean.Name) : String := + let describeVerdicts (ns : List Lean.Name) : String := ", ".intercalate (ns.map fun n => s!"{n}: {(verdicts.getD n .accept).label}") - let complete := test s!"{kernel}: every member of {p.name}'s closure has a verdict \ + itBool s!"{kernel}: every member of {p.name}'s closure has a verdict \ (missing: {missing.take 5})" missing.isEmpty match p.expect with | .accept => - complete ++ test s!"{kernel} accepts the closure of {p.name} ({describe failures})" + itBool s!"{kernel} accepts the closure of {p.name} ({describeVerdicts failures})" failures.isEmpty | .reject culprit => let culpritRejected := (verdicts.getD culprit .accept).isReject @@ -110,11 +110,10 @@ def checkProbe (kernel : String) (closure : List Lean.Name) (verdicts : Verdicts -- trusted) or blocked behind the culprit, never rejected on its own let probeOk := p.name == culprit || !(verdicts.getD p.name .accept).isReject let others := failures.filter fun n => n != culprit && n != p.name - complete - ++ test s!"{kernel} rejects {culprit}, so the closure of {p.name} \ - ({(verdicts.getD culprit .accept).label})" culpritRejected - ++ test s!"{kernel}: {p.name} fails only through {culprit} ({describe others})" - (probeOk && others.isEmpty) + itBool s!"{kernel} rejects {culprit}, so the closure of {p.name} \ + ({(verdicts.getD culprit .accept).label})" culpritRejected + itBool s!"{kernel}: {p.name} fails only through {culprit} ({describeVerdicts others})" + (probeOk && others.isEmpty) def run : IO UInt32 := do let leanEnv ← get_env! @@ -137,10 +136,10 @@ def run : IO UInt32 := do let ixc ← ixcVerdicts compiled names let t2 ← IO.monoMsNow IO.println s!"[kernel-fast-paths] compile {t1 - t0} ms, IxCK {t2 - t1} ms" - let mut seq : TestSeq := .done - for (kernel, verdicts) in [("IxCK", ixc)] do - for p in probes do - seq := seq ++ checkProbe kernel (closures.getD p.name []) verdicts p - lspecIO (.ofList [("kernel-fast-paths", [seq])]) [] + let spec : Spec := describe "kernel-fast-paths" do + for (kernel, verdicts) in [("IxCK", ixc)] do + for p in probes do + checkProbe kernel (closures.getD p.name []) verdicts p + lspecMain spec [] end Tests.Ix.Kernel.FastPaths diff --git a/Tests/Ix/Kernel/FidelityAccess.lean b/Tests/Ix/Kernel/FidelityAccess.lean index ebaaf6e46b..464bcdf46b 100644 --- a/Tests/Ix/Kernel/FidelityAccess.lean +++ b/Tests/Ix/Kernel/FidelityAccess.lean @@ -100,9 +100,8 @@ private def check : IO Nat := do IO.println s!"projection access: {baseline.blocks} blocks, {baseline.compiled} projections; eager/lazy parity and strict faults" return baseline.compiled -def suite : List TestSeq := [ - .individualIO "lazy projection fidelity preserves exact reports and refuses access faults" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "lazy projection fidelity preserves exact reports and refuses access faults" do + let _ ← check end Tests.Ix.Kernel.FidelityAccess diff --git a/Tests/Ix/Kernel/Pins.lean b/Tests/Ix/Kernel/Pins.lean index a63ed225c5..9cb7e3d656 100644 --- a/Tests/Ix/Kernel/Pins.lean +++ b/Tests/Ix/Kernel/Pins.lean @@ -55,22 +55,22 @@ def pins : List Pin := [ /-- Check a fresh supporting closure over shared authenticated preparation. The existing per-subject budget measures its actual producer's checker time; input, preparation, reading and support checking are reported separately. -/ -public def checkPin (prepared : Ix.Cli.CheckLeanCmd.PreparedInput) (pin : Pin) : IO TestSeq := do +public def checkPin (prepared : Ix.Cli.CheckLeanCmd.PreparedInput) (pin : Pin) : IO Spec := do let expected ← match Ix.Cli.CheckLeanTargets.findCandidate prepared.inventory pin.label with | .ok c => pure c - | .error _ => return test s!"{pin.label}: resolves unambiguously in the input" false + | .error _ => return itBool s!"{pin.label}: resolves unambiguously in the input" false let cfg : Ix.Cli.CheckLeanCmd.CheckCfg := { workers := 1, silent := true, progressMs := 0, slowMs := 0 } match ← Ix.Cli.CheckLeanCmd.runPrepared prepared cfg (.only #[pin.label]) with - | .error e => return test s!"{pin.label}: driver failed: {e.message}" false + | .error e => return itBool s!"{pin.label}: driver failed: {e.message}" false | .ok report => if report.targets.size != 1 || report.targets.any (fun r => r.target.label != expected.label || r.target.address != expected.address || r.outcome != "accept") then - return test s!"{pin.label}: exact accepted coverage (got {report.failures})" false + return itBool s!"{pin.label}: exact accepted coverage (got {report.failures})" false let subjectMs := report.subjectMicros / 1000 IO.println s!"tc-pins: {pin.label}: selected checker {subjectMs}ms; preparation {report.prepareMs}ms; \ reading {report.readMicros / 1000}ms; support checker {report.supportMicros / 1000}ms; run {report.elapsedMs}ms" - return test s!"{pin.label}: producer checked in {subjectMs}ms (budget {pin.budgetMs}ms)" - (report.subjectMicros ≤ pin.budgetMs * 1000) + return itBool s!"{pin.label}: producer checked in {subjectMs}ms (budget {pin.budgetMs}ms)" + (decide (report.subjectMicros ≤ pin.budgetMs * 1000)) public def run : IO UInt32 := do IO.println "tc-pins" @@ -89,11 +89,13 @@ public def run : IO UInt32 := do activePins := activePins.push pin let tasks ← activePins.mapM fun pin => IO.asTask (prio := .dedicated) (checkPin prepared pin) - let mut seq : TestSeq := .done + let mut specs : Array Spec := #[] for task in tasks do match ← IO.wait task with - | .ok s => seq := seq ++ s + | .ok s => specs := specs.push s | .error e => throw e - lspecIO (.ofList [("tc-pins", [seq])]) [] + lspecMain (describe "tc-pins" do + for s in specs do + s) [] end Tests.Tc.Pins diff --git a/Tests/Ix/Kernel/PreludeFidelity.lean b/Tests/Ix/Kernel/PreludeFidelity.lean index ccf76fd838..6cc40989db 100644 --- a/Tests/Ix/Kernel/PreludeFidelity.lean +++ b/Tests/Ix/Kernel/PreludeFidelity.lean @@ -91,9 +91,8 @@ private def check : IO Nat := do {borrowed.constants} borrowed-owner source comparisons and explicit setup reader failure" return baseline.constants -def suite : List TestSeq := [ - .individualIO "setup-only prelude preserves source coverage and every input/error refusal" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "setup-only prelude preserves source coverage and every input/error refusal" do + let _ ← check end Tests.Ix.Kernel.PreludeFidelity diff --git a/Tests/Ix/Kernel/PrimAddrs.lean b/Tests/Ix/Kernel/PrimAddrs.lean index 96de687ee0..f526902f3c 100644 --- a/Tests/Ix/Kernel/PrimAddrs.lean +++ b/Tests/Ix/Kernel/PrimAddrs.lean @@ -104,15 +104,15 @@ def problems (fns : Array Tests.Ix.IxVM.Sources.Function) : Array String := Id.r out := out.push s!"{f.name} reads the default role binding" return out -def literalGuard : TestSeq := - .individualIO "the IxVM program's only address literals are the specification digest, \ - the debug entry points' default binding and the basis pin's default bindings" none (do +def literalGuard : Spec := + it "the IxVM program's only address literals are the specification digest, \ + the debug entry points' default binding and the basis pin's default bindings" do let found := problems (Tests.Ix.IxVM.Sources.functions (← Tests.Ix.IxVM.programSources)) - let ok := found.isEmpty - return (ok, if ok then 1 else 0, 1, - if ok then none else some ("; ".intercalate found.toList))) .done + expect found.isEmpty ("; ".intercalate found.toList) -def suite : List TestSeq := [literalGuard] ++ Tests.Ix.Kernel.PrimitiveTable.suite +def suite : LSpec.Spec := do + literalGuard + Tests.Ix.Kernel.PrimitiveTable.suite /-- A dotted Lean name as an `Ix.Name` (string components only). -/ private def ixNameOf (s : String) : Ix.Name := diff --git a/Tests/Ix/Kernel/PrimitiveTable.lean b/Tests/Ix/Kernel/PrimitiveTable.lean index ea94d99900..2a93460f69 100644 --- a/Tests/Ix/Kernel/PrimitiveTable.lean +++ b/Tests/Ix/Kernel/PrimitiveTable.lean @@ -11,24 +11,20 @@ open LSpec _root_.Ix @[extern "rs_prim_addrs_canonical"] private opaque rsPrimAddrsCanonicalFFI : IO (Array (String × String)) -def primsParity : TestSeq := - .individualIO "PrimAddrs.canonical parity vs Rust PrimAddrs::new()" none (do +def primsParity : Spec := + it "PrimAddrs.canonical parity vs Rust PrimAddrs::new()" do let rust ← rsPrimAddrsCanonicalFFI let lean := PrimAddrs.leanParityTable - if rust.size != lean.size then - return (false, rust.size, lean.size, - some s!"size mismatch: rust {rust.size} vs lean {lean.size}") + expect (rust.size == lean.size) s!"size mismatch: rust {rust.size} vs lean {lean.size}" let mut bad : Array String := #[] for ((rn, rh), (ln, la)) in rust.zip lean do if rn != ln then bad := bad.push s!"order mismatch: {rn} vs {ln}" else if toString la != rh then bad := bad.push s!"{rn}: rust {rh} != lean {toString la}" - if bad.isEmpty then - return (true, rust.size, rust.size, none) - return (false, bad.size, rust.size, - some (String.intercalate "; " bad.toList))) .done + expect bad.isEmpty (String.intercalate "; " bad.toList) -public def suite : List TestSeq := [primsParity] +public def suite : LSpec.Spec := do + primsParity end Tests.Ix.Kernel.PrimitiveTable diff --git a/Tests/Ix/Kernel/ReaderRoundtrip.lean b/Tests/Ix/Kernel/ReaderRoundtrip.lean index 58be0dd1f6..097a1f923b 100644 --- a/Tests/Ix/Kernel/ReaderRoundtrip.lean +++ b/Tests/Ix/Kernel/ReaderRoundtrip.lean @@ -243,14 +243,14 @@ def evaluate : IO (Report × Array String × Array String) := do let (lines, egressErrors) ← evaluateEgress inp return (report, lines, readerErrors ++ egressErrors) -def suiteIO : TestSeq := - .individualIO "reader fidelity and egress: compiled fixture closure against Lean" none (do +def suiteIO : Spec := + it "reader fidelity and egress: compiled fixture closure against Lean" do let (report, lines, errors) ← evaluate IO.println report.summary for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, report.constants, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) -def suite : List TestSeq := [suiteIO] +def suite : LSpec.Spec := do + suiteIO end Tests.Ix.Kernel.ReaderRoundtrip diff --git a/Tests/Ix/Kernel/RecordCheck.lean b/Tests/Ix/Kernel/RecordCheck.lean index ff0c34d6b3..55e49e05b8 100644 --- a/Tests/Ix/Kernel/RecordCheck.lean +++ b/Tests/Ix/Kernel/RecordCheck.lean @@ -304,15 +304,11 @@ evaluated when the module initializes. -/ end StoreRefusals -def suite : List TestSeq := [ - .individualIO "actual anon/meta outcomes, rollback, tiers and worker replay" none (do - let n ← check - return (true, n, 0, none)) .done, +def suite : LSpec.Spec := do + it "actual anon/meta outcomes, rollback, tiers and worker replay" do + let _ ← check -- 769 records: at 256 tasks the parallel decoder's chunks are four records long - .individualIO "record store: orphan, noncanonical and oversized records, phase precedence, cache" - none (do - return match StoreRefusals.checks (← StoreRefusals.atRunTime Nat 769) with - | .ok n => (true, n, 0, none) - | .error message => (false, 0, 0, some message)) .done] + it "record store: orphan, noncanonical and oversized records, phase precedence, cache" do + let _ ← expectOk (StoreRefusals.checks (← StoreRefusals.atRunTime Nat 769)) end Tests.Ix.Kernel.RecordCheck diff --git a/Tests/Ix/Kernel/SourceIngress.lean b/Tests/Ix/Kernel/SourceIngress.lean index 5628bb1b7b..851f93f136 100644 --- a/Tests/Ix/Kernel/SourceIngress.lean +++ b/Tests/Ix/Kernel/SourceIngress.lean @@ -148,7 +148,7 @@ def nm (s : String) : Ix.Name := .mkStr anon s /-- The numbering of a constant with no level parameters. -/ def noParams : Numbering := ⟨#[], false⟩ -def refusals : TestSeq := +def refusals : LSpec.Spec := do let fv := Ix.Expr.mkFVar (nm "x") let mv := Ix.Expr.mkMVar (nm "m") let lv := Ix.Expr.mkSort (Ix.Level.mkMvar (nm "u")) @@ -156,9 +156,9 @@ def refusals : TestSeq := match ingressExprs noParams.pos [Ix.Expr.mkApp (Ix.Expr.mkBVar 0) e] with | .error err => k err | .ok _ => false - test "free variable refused" (refused fv fun | .fvar _ => true | _ => false) ++ - test "metavariable refused" (refused mv fun | .mvar _ => true | _ => false) ++ - test "level metavariable refused" (refused lv fun | .levelMVar _ => true | _ => false) + itBool "free variable refused" (refused fv fun | .fvar _ => true | _ => false) + itBool "metavariable refused" (refused mv fun | .mvar _ => true | _ => false) + itBool "level metavariable refused" (refused lv fun | .levelMVar _ => true | _ => false) def sameResult : Except ExprError (List KExpr) → Except ExprError (List KExpr) → Bool | .ok a, .ok b => a == b @@ -168,13 +168,13 @@ def lamDropped : Except ExprError (List KExpr) → Bool | .ok [.lam (.const n []) (.bvar 0) m] => n == Ix.Kernel.roleKey .nat && m == { pw := .never } | _ => false -def erasure : TestSeq := +def erasure : LSpec.Spec := do let body := Ix.Expr.mkConst (nm "Nat") #[] let withData := Ix.Expr.mkMData #[(nm "k", .ofBool true)] body let lam := Ix.Expr.mkLam (nm "x") body (.mkBVar 0) .implicit - test "mdata erased" - (sameResult (ingressExprs noParams.pos [withData]) (ingressExprs noParams.pos [body])) ++ - test "binder name and info dropped, pw never" (lamDropped (ingressExprs noParams.pos [lam])) + itBool "mdata erased" + (sameResult (ingressExprs noParams.pos [withData]) (ingressExprs noParams.pos [body])) + itBool "binder name and info dropped, pw never" (lamDropped (ingressExprs noParams.pos [lam])) /-- `e` under the contract frame of `c`, as `Ix.Compile.CompileInput.prepare` writes it and `Ix.CanonM` keeps it. -/ @@ -206,7 +206,7 @@ def refusedWith (message : String) : Except ExprError (List KExpr) → Bool the binder it wraps, as the compiler lowers it; an unsupported contract mode, a frame not directly around a binder of its kind, or a malformed frame is refused. -/ -def contractFrames : TestSeq := +def contractFrames : LSpec.Spec := do let nat := Ix.Expr.mkConst (nm "Nat") #[] let lam := Ix.Expr.mkLam (nm "x") nat (.mkBVar 0) .default let pi := Ix.Expr.mkForallE (nm "x") nat nat .default @@ -225,38 +225,38 @@ def contractFrames : TestSeq := let misplaced := "semantic contract is not attached to its original binder" let key := Ix.Name.mkStr (nm "ix") "contract" let dag := Ix.Expr.mkApp (framed allC pi) (plain (framed lamC lam)) - test "a plain binder carries the never datum" - (binderOf (conv lam) == some { pw := .never }) ++ - test "an ordinary lam frame lowers to the plain binder" - (binderOf (conv (framed lamO lam)) == some { pw := .never }) ++ - test "an ordinary all frame lowers to the plain binder" - (binderOf (conv (framed allO pi)) == some { pw := .never }) ++ - test "a plain let carries Lean's nonDep" - (letOf (conv letE) == some { nonDep := false }) ++ - test "an ordinary let frame lowers to the plain let" - (letOf (conv (framed letO letE)) == some { nonDep := false }) ++ - test "plain metadata around an ordinary frame is erased" - (binderOf (conv (plain (framed lamO lam))) == some { pw := .never }) ++ - test "a valid annotated lam, all, let, field, or defAsserts frame lowers to the kernel term" + itBool "a plain binder carries the never datum" + (binderOf (conv lam) == some { pw := .never }) + itBool "an ordinary lam frame lowers to the plain binder" + (binderOf (conv (framed lamO lam)) == some { pw := .never }) + itBool "an ordinary all frame lowers to the plain binder" + (binderOf (conv (framed allO pi)) == some { pw := .never }) + itBool "a plain let carries Lean's nonDep" + (letOf (conv letE) == some { nonDep := false }) + itBool "an ordinary let frame lowers to the plain let" + (letOf (conv (framed letO letE)) == some { nonDep := false }) + itBool "plain metadata around an ordinary frame is erased" + (binderOf (conv (plain (framed lamO lam))) == some { pw := .never }) + itBool "a valid annotated lam, all, let, field, or defAsserts frame lowers to the kernel term" (binderOf (conv (framed lamC lam)) == some { pw := .never } && binderOf (conv (framed allC pi)) == some { pw := .never } && binderOf (conv (framed fieldC pi)) == some { pw := .never } && binderOf (conv (framed assertsC pi)) == some { pw := .never } && letOf (conv (framed letC letE)) == some { nonDep := false } && - binderOf (conv (plain (framed lamC lam))) == some { pw := .never }) ++ - test "a frame with reserved mode bits is refused" + binderOf (conv (plain (framed lamC lam))) == some { pw := .never }) + itBool "a frame with reserved mode bits is refused" (frameRefused (conv (Ix.Expr.mkMData #[(key, .ofNat 4), (Ix.Name.mkStr key "kind", .ofNat 0), - (Ix.Name.mkStr key "code", .ofNat 7)] lam))) ++ - test "a frame not directly around a binder of its kind is refused" + (Ix.Name.mkStr key "code", .ofNat 7)] lam))) + itBool "a frame not directly around a binder of its kind is refused" (refusedWith misplaced (conv (framed lamO (plain lam))) && refusedWith misplaced (conv (framed lamC pi)) && refusedWith misplaced (conv (framed allC nat)) && - refusedWith misplaced (conv (framed fieldC nat))) ++ - test "a malformed frame is refused" + refusedWith misplaced (conv (framed fieldC nat))) + itBool "a malformed frame is refused" (frameRefused (conv (Ix.Expr.mkMData #[(key, .ofNat 4)] lam)) && frameRefused (conv (Ix.Expr.mkMData #[(key, .ofNat 3), (Ix.Name.mkStr key "kind", .ofNat 0), - (Ix.Name.mkStr key "code", .ofNat 1)] lam))) ++ - test "the DAG walk is the tree walk on frames" + (Ix.Name.mkStr key "code", .ofNat 1)] lam))) + itBool "the DAG walk is the tree walk on frames" (sameTree (ingressExprsShared noParams.pos [dag]) (ingressExpr noParams.pos dag)) def sortOf : Except ExprError (List KExpr) → Option Ix.Kernel.Level @@ -265,15 +265,15 @@ def sortOf : Except ExprError (List KExpr) → Option Ix.Kernel.Level /-- Level parameters are positions: a constant's `i`-th is `i`, and a large eliminator's first, its elimination level, follows its block's. -/ -def numbering : TestSeq := +def numbering : LSpec.Spec := do let u := nm "u" let v := nm "v" let ty := Ix.Expr.mkSort (Ix.Level.mkMax (Ix.Level.mkParam u) (Ix.Level.mkParam v)) let large : Numbering := ⟨#[v, u], true⟩ - test "the i-th level parameter is position i" + itBool "the i-th level parameter is position i" (sortOf (ingressExprs (Numbering.mk #[u, v] false).pos [ty]) == - some (.max (.param 0) (.param 1))) ++ - test "a large eliminator's elimination level follows its block's parameters" + some (.max (.param 0) (.param 1))) + itBool "a large eliminator's elimination level follows its block's parameters" (sortOf (ingressExprs large.pos [ty]) == some (.max (.param 0) (.param 1)) && large.params == [1, 0]) @@ -282,7 +282,7 @@ reader reads a compiled universe: `Ixon.canonUniv` over the Lean index order (variable `i` is the constant's `i`-th Lean level parameter), back through `Reader.convUniv` (at a large eliminator through `Reader.recParam`, the elimination level first). -/ -def canonical : TestSeq := +def canonical : LSpec.Spec := do let u := nm "u" let v := nm "v" let plain : Numbering := ⟨#[u, v], false⟩ @@ -297,17 +297,17 @@ def canonical : TestSeq := (.max (.param 0) (.succ (.param 0)), .max (.var 0) (.succ (.var 0))), (.imax (.param 1) (.max (.param 0) (.param 1)), .imax (.var 1) (.max (.var 0) (.var 1))), (.succ (.max (.zero) (.param 1)), .succ (.max .zero (.var 1)))] - test "a member's level is the reader's reading of its compiled universe" - (cases.all fun (l, w) => canonLevel plain l == read (fun i => i) w) ++ - test "at a large eliminator the index order puts the elimination level first" + itBool "a member's level is the reader's reading of its compiled universe" + (cases.all fun (l, w) => canonLevel plain l == read (fun i => i) w) + itBool "at a large eliminator the index order puts the elimination level first" -- Source `max u v` is positions `max 0 1`; compiled, `u` is variable 1 (canonLevel large (.max (.param 0) (.param 1)) == read recP (.max (.var 1) (.var 0)) && - canonLevel large (.imax (.param 1) (.param 0)) == read recP (.imax (.var 0) (.var 1))) ++ - test "canonical forms do not depend on the order of a max" - (canonLevel plain (.max (.param 0) (.param 1)) == canonLevel plain (.max (.param 1) (.param 0))) ++ - test "canonicalizing is idempotent" - (cases.all fun (l, _) => canonLevel plain (canonLevel plain l) == canonLevel plain l) ++ - test "mapLevels' executed walk is the structural map" + canonLevel large (.imax (.param 1) (.param 0)) == read recP (.imax (.var 0) (.var 1))) + itBool "canonical forms do not depend on the order of a max" + (canonLevel plain (.max (.param 0) (.param 1)) == canonLevel plain (.max (.param 1) (.param 0))) + itBool "canonicalizing is idempotent" + (cases.all fun (l, _) => canonLevel plain (canonLevel plain l) == canonLevel plain l) + itBool "mapLevels' executed walk is the structural map" (let e : KExpr := .app (.sort (.max (.param 1) (.param 0))) (.const (ingressKey (nm "f")) [.max (.param 1) (.param 0)]) mapLevelsList (canonLevel plain) [e, e] == @@ -329,9 +329,9 @@ def agrees : Except ExprError (List KExpr) → Except ExprError KExpr → Bool | .ok [a], .ok b => decide (a = b) && treeSize b == 2 ^ 13 - 1 | _, _ => false -def sharing : TestSeq := - test "a 2^64-leaf DAG converts" ((ingressExprs noParams.pos [sharedDag 64]).isOk) ++ - test "the DAG walk is the tree walk at depth 12" +def sharing : LSpec.Spec := do + itBool "a 2^64-leaf DAG converts" ((ingressExprs noParams.pos [sharedDag 64]).isOk) + itBool "the DAG walk is the tree walk at depth 12" (agrees (ingressExprsShared noParams.pos [sharedDag 12]) (ingressExpr noParams.pos (sharedDag 12))) /-! ## The fixtures -/ @@ -401,12 +401,11 @@ def evaluate : IO (Array String × Array String) := do | .error e => errors := errors.push s!"checkSourceTiered on the accepted closure and spin: {e}" return (errors, lines) -def fixtures : TestSeq := - .individualIO "source mode: fixture closure, group by group and all at once" none (do +def fixtures : Spec := + it "source mode: fixture closure, group by group and all at once" do let (errors, lines) ← evaluate for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, expected.length, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) /-! ## Quotient Source @@ -586,12 +585,11 @@ def evaluateQuotient : IO (Array String × Array String) := do | .error e, _ => errors := errors.push s!"quotient: prelude check: {what}: {e}" return (errors, lines) -def quotient : TestSeq := - .individualIO "quotient source: alias fibers collapsed, mismatches refused, role aliases, canonical levels" none (do +def quotient : Spec := + it "quotient source: alias fibers collapsed, mismatches refused, role aliases, canonical levels" do let (errors, lines) ← evaluateQuotient for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, 6, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) /-! ## The `.indDecl` shape guard @@ -625,24 +623,24 @@ def withU : Ix.Kernel.Key .source → Option (Ix.Kernel.ConstantInfo .source) := def noneEnv : Ix.Kernel.Key .source → Option (Ix.Kernel.ConstantInfo .source) := fun _ => none -def shapeUnits : TestSeq := - test "a block naming only its formers passes" - (Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.b" (.app (sconst "T") (sconst "T"))]) $ - test "a mutual block's constructor may name another former" - (Ix.Kernel.indShapeOk noneEnv [sind "A" sty, sind "B" sty, sctor "A.a" (.app (sconst "A") (sconst "B"))]) $ - test "a constructor naming an earlier constructor is refused" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.b" (.app (sconst "T") (sconst "T.a"))]) $ - test "a constructor naming a later constructor is refused" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (.app (sconst "T") (sconst "T.b")), sctor "T.b" (sconst "T")]) $ - test "a former naming an unknown constant is refused, and passes once it is declared" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" (sconst "U")] && Ix.Kernel.indShapeOk withU [sind "T" (sconst "U")]) $ - test "a constructor name already declared is refused" - (!Ix.Kernel.indShapeOk withU [sind "T" sty, sctor "U" (sconst "T")]) $ - test "a constructor named as a former is refused" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T" (sconst "T")]) $ - test "a constructor name declared twice is refused" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.a" (sconst "T")]) $ - test "a literal needs its support" +def shapeUnits : LSpec.Spec := do + itBool "a block naming only its formers passes" + (Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.b" (.app (sconst "T") (sconst "T"))]) + itBool "a mutual block's constructor may name another former" + (Ix.Kernel.indShapeOk noneEnv [sind "A" sty, sind "B" sty, sctor "A.a" (.app (sconst "A") (sconst "B"))]) + itBool "a constructor naming an earlier constructor is refused" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.b" (.app (sconst "T") (sconst "T.a"))]) + itBool "a constructor naming a later constructor is refused" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (.app (sconst "T") (sconst "T.b")), sctor "T.b" (sconst "T")]) + itBool "a former naming an unknown constant is refused, and passes once it is declared" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" (sconst "U")] && Ix.Kernel.indShapeOk withU [sind "T" (sconst "U")]) + itBool "a constructor name already declared is refused" + (!Ix.Kernel.indShapeOk withU [sind "T" sty, sctor "U" (sconst "T")]) + itBool "a constructor named as a former is refused" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T" (sconst "T")]) + itBool "a constructor name declared twice is refused" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.a" (sconst "T")]) + itBool "a literal needs its support" (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (.app (sconst "T") (.lit (.natVal 0)))]) /-! ## Repeated names in a lowered block @@ -669,12 +667,12 @@ def lowersTo (rb : Ix.Kernel.Reader.BlockRead .source) (ks : List String) : Bool | .ok r => r.decls.size == 1 && r.decls.toList.flatMap (·.names) == ks.map skey | .error _ => false -def repeatedNames : TestSeq := - test "a block with distinct names lowers to its declaration" - (lowersTo (blockWith ["T.a", "T.b"]) ["T", "T.a", "T.b"]) $ - test "a block declaring a constructor name twice is declined" - (declinesRepeat (blockWith ["T.a", "T.b", "T.a"]) "T.a") $ - test "a block naming a constructor as its type is declined" +def repeatedNames : LSpec.Spec := do + itBool "a block with distinct names lowers to its declaration" + (lowersTo (blockWith ["T.a", "T.b"]) ["T", "T.a", "T.b"]) + itBool "a block declaring a constructor name twice is declined" + (declinesRepeat (blockWith ["T.a", "T.b", "T.a"]) "T.a") + itBool "a block naming a constructor as its type is declined" (declinesRepeat (blockWith ["T"]) "T") /-- The lowered declarations with `Args.cons`'s declared type naming `Tm.var`. -/ @@ -712,14 +710,23 @@ def evaluateShape : IO (Array String × Array String) := do errors := errors.push s!"shape: refused, but not by the shape guard: {msg}" return (errors, lines) -def shapeGuard : TestSeq := - .individualIO "the shape guard refuses a modeled block's constructor naming an earlier one" none (do +def shapeGuard : Spec := + it "the shape guard refuses a modeled block's constructor naming an earlier one" do let (errors, lines) ← evaluateShape for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, 2, 0, msg)) .done - -def suite : List TestSeq := [refusals, erasure, contractFrames, numbering, canonical, sharing, fixtures, - quotient, shapeUnits, repeatedNames, shapeGuard] + expect errors.isEmpty ("\n".intercalate errors.toList) + +def suite : LSpec.Spec := do + refusals + erasure + contractFrames + numbering + canonical + sharing + fixtures + quotient + shapeUnits + repeatedNames + shapeGuard end Tests.Ix.Kernel.SourceIngress diff --git a/Tests/Ix/Kernel/SourceIngressMain.lean b/Tests/Ix/Kernel/SourceIngressMain.lean index 0355003a80..dce8a00c80 100644 --- a/Tests/Ix/Kernel/SourceIngressMain.lean +++ b/Tests/Ix/Kernel/SourceIngressMain.lean @@ -75,7 +75,7 @@ partial def parse (a : Args) : List String → Except String Args def main (args : List String) : IO UInt32 := do if args == ["--fixture"] then - return ← LSpec.lspecIO (.ofList [("kernel-source-ingress", Tests.Ix.Kernel.SourceIngress.suite)]) [] + return ← LSpec.lspecMain (LSpec.describe "kernel-source-ingress" Tests.Ix.Kernel.SourceIngress.suite) [] let a ← IO.ofExcept (parse {} args) let modules := if a.modules.isEmpty then #[`Init] else a.modules let t0 ← IO.monoMsNow diff --git a/Tests/Ix/Kernel/TierInd.lean b/Tests/Ix/Kernel/TierInd.lean index f56c7bcdf0..0beebf4cb5 100644 --- a/Tests/Ix/Kernel/TierInd.lean +++ b/Tests/Ix/Kernel/TierInd.lean @@ -253,13 +253,13 @@ def evaluate : IO (Array String × Array String) := do (errors, lines) := expectDecline s!"Poly, {label} levels" bad fe₀ why errors lines return (errors, lines) -def tierInd : TestSeq := - .individualIO "the tier's typing-only inductive install and its answer view" none (do +def tierInd : Spec := + it "the tier's typing-only inductive install and its answer view" do let (errors, lines) ← evaluate for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, lines.size, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) -def suite : List TestSeq := [tierInd] +def suite : LSpec.Spec := do + tierInd end Tests.Ix.Kernel.TierInd diff --git a/Tests/Ix/Kernel/Tutorial.lean b/Tests/Ix/Kernel/Tutorial.lean index 3cade4f579..0146d60400 100644 --- a/Tests/Ix/Kernel/Tutorial.lean +++ b/Tests/Ix/Kernel/Tutorial.lean @@ -164,8 +164,8 @@ def rsCheckMalformedRecRuleIxonFFI | some (outcome, reason) => return some (.kernelException s!"{outcome}: {reason}") | none => return some (.kernelException s!"missing verdict for {recName}") -def testTutorialConsts : TestSeq := - .individualIO "kernel tutorial checks" none (do +def testTutorialConsts : Spec := + it "kernel tutorial checks" do let leanEnv ← get_env! let testCases := TutorialMeta.getTestCases leanEnv @@ -500,12 +500,9 @@ def testTutorialConsts : TestSeq := IO.println e IO.println s!"[kernel-tutorial] {passed} passed, {failed} failed" - if failed == 0 then - return (true, passed, 0, none) - else - return (false, passed, passed + failed, some s!"{failed} checks failed") - ) .done + expect (failed == 0) s!"{failed} checks failed" -def suite : List TestSeq := [testTutorialConsts] +def suite : LSpec.Spec := do + testTutorialConsts end Tests.Ix.Kernel.Tutorial diff --git a/Tests/Ix/Kernel/UserAxioms.lean b/Tests/Ix/Kernel/UserAxioms.lean index 1a5394668b..9001fedf2e 100644 --- a/Tests/Ix/Kernel/UserAxioms.lean +++ b/Tests/Ix/Kernel/UserAxioms.lean @@ -146,16 +146,12 @@ def gateChecks : Except String Unit := do (env.consts.length == env'.consts.length) | _, _ => throw "the prelude through the entry does not accept under both policies" -private def unit (label : String) (check : Unit → Except String Unit) : LSpec.TestSeq := - .individualIO label none (do - let result ← IO.lazyPure check - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done - -def suite : List LSpec.TestSeq := [ - unit "the fold under each axiom policy: user axioms, axiom role specifications, T1" (fun _ => foldChecks), +private def unit (label : String) (check : Unit → Except String Unit) : LSpec.Spec := + it label do + let _ ← LSpec.expectOk (check ()) + +def suite : LSpec.Spec := do + unit "the fold under each axiom policy: user axioms, axiom role specifications, T1" (fun _ => foldChecks) unit "the role table's admission under each axiom policy" (fun _ => gateChecks) -] end Tests.Ix.Kernel.UserAxioms diff --git a/Tests/Ix/Kernel/ValidateReaderCli.lean b/Tests/Ix/Kernel/ValidateReaderCli.lean index 6567eb5719..f3e1a40015 100644 --- a/Tests/Ix/Kernel/ValidateReaderCli.lean +++ b/Tests/Ix/Kernel/ValidateReaderCli.lean @@ -135,9 +135,8 @@ private def check : IO Nat := do {report.constants} direct source comparisons and visible expected declines" return 12 -def suite : List TestSeq := [ - .individualIO "validate-lean source fidelity keeps coverage, declines, failures and lazy/eager reports" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "validate-lean source fidelity keeps coverage, declines, failures and lazy/eager reports" do + let _ ← check end Tests.Ix.Kernel.ValidateReaderCli diff --git a/Tests/Ix/LeanExport.lean b/Tests/Ix/LeanExport.lean index 8e27ec9493..71caa3539e 100644 --- a/Tests/Ix/LeanExport.lean +++ b/Tests/Ix/LeanExport.lean @@ -37,6 +37,9 @@ public section namespace Tests.Ix.LeanExport open _root_.Ix.LeanExport (importString environment) +open LSpec + +set_option compiler.extract_closed false private def require (ok : Bool) (message : String) : IO Unit := unless ok do throw (IO.userError message) @@ -62,43 +65,43 @@ private def withMData (data : String) : String := export_ ["{\"ie\":1,\"mdata\":{\"data\":" ++ data ++ ",\"expr\":0}}"] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":1}}" -def readerTests : LSpec.TestSeq := +def readerTests : LSpec.Spec := do let dropped (text : String) : Option Nat := (importString text).toOption.map (·.droppedSyntaxMData) - LSpec.test "a well-formed export is read" ((importString (export_ [])).toOption.any fun im => - im.constants.size == 1 && im.exportMeta.leanVersion == "4.34.1") ++ - LSpec.test "another format version is refused" (refuses ((export_ []).replace metaLine (metaLine "3.0.0"))) ++ - LSpec.test "an export without its meta record is refused" - (refuses ("\n".intercalate ((export_ []).splitOn "\n" |>.drop 1))) ++ - LSpec.test "a second meta record is refused" (refuses (export_ [metaLine])) ++ - LSpec.test "a name index out of sequence is refused" - (refuses (export_ ["{\"in\":3,\"str\":{\"pre\":0,\"str\":\"U\"}}"])) ++ - LSpec.test "a reference to an expression not yet defined is refused" - (refuses (export_ [] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":7}}")) ++ - LSpec.test "an extra field is refused" - (refuses (export_ [] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":0,\"x\":1}}")) ++ - LSpec.test "a missing field is refused" - (refuses (export_ [] "{\"axiom\":{\"levelParams\":[],\"name\":1,\"type\":0}}")) ++ - LSpec.test "a name declared twice is refused" - (refuses (export_ ["{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":0}}"])) ++ - LSpec.test "an unknown record is refused" (refuses (export_ ["{\"universe\":0}"])) ++ - LSpec.test "an unknown binder info is refused" - (refuses (export_ ["{\"ie\":1,\"lam\":{\"binderInfo\":\"auto\",\"body\":0,\"name\":1,\"type\":0}}"])) ++ - LSpec.test "a canonical numeral is read" - (accepts (export_ ["{\"ie\":1,\"natVal\":\"120\"}"])) ++ - LSpec.test "a numeral that is not canonical is refused" - (refuses (export_ ["{\"ie\":1,\"natVal\":\"0120\"}"])) ++ - LSpec.test "a metadata value that reads back is kept" - (dropped (withMData "{\"noImplicitLambda\":\"Lean.DataValue.ofBool true\"}") == some 0) ++ - LSpec.test "a name-valued metadata entry is kept" - (dropped (withMData "{\"k\":\"Lean.DataValue.ofName `Nat.add\"}") == some 0) ++ - LSpec.test "a name written in constructor form is kept" + itBool "a well-formed export is read" ((importString (export_ [])).toOption.any fun im => + im.constants.size == 1 && im.exportMeta.leanVersion == "4.34.1") + itBool "another format version is refused" (refuses ((export_ []).replace metaLine (metaLine "3.0.0"))) + itBool "an export without its meta record is refused" + (refuses ("\n".intercalate ((export_ []).splitOn "\n" |>.drop 1))) + itBool "a second meta record is refused" (refuses (export_ [metaLine])) + itBool "a name index out of sequence is refused" + (refuses (export_ ["{\"in\":3,\"str\":{\"pre\":0,\"str\":\"U\"}}"])) + itBool "a reference to an expression not yet defined is refused" + (refuses (export_ [] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":7}}")) + itBool "an extra field is refused" + (refuses (export_ [] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":0,\"x\":1}}")) + itBool "a missing field is refused" + (refuses (export_ [] "{\"axiom\":{\"levelParams\":[],\"name\":1,\"type\":0}}")) + itBool "a name declared twice is refused" + (refuses (export_ ["{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":0}}"])) + itBool "an unknown record is refused" (refuses (export_ ["{\"universe\":0}"])) + itBool "an unknown binder info is refused" + (refuses (export_ ["{\"ie\":1,\"lam\":{\"binderInfo\":\"auto\",\"body\":0,\"name\":1,\"type\":0}}"])) + itBool "a canonical numeral is read" + (accepts (export_ ["{\"ie\":1,\"natVal\":\"120\"}"])) + itBool "a numeral that is not canonical is refused" + (refuses (export_ ["{\"ie\":1,\"natVal\":\"0120\"}"])) + itBool "a metadata value that reads back is kept" + (dropped (withMData "{\"noImplicitLambda\":\"Lean.DataValue.ofBool true\"}") == some 0) + itBool "a name-valued metadata entry is kept" + (dropped (withMData "{\"k\":\"Lean.DataValue.ofName `Nat.add\"}") == some 0) + itBool "a name written in constructor form is kept" (dropped (withMData ("{\"k\":" ++ (Lean.Json.str (reprStr (Lean.DataValue.ofName - (.num (.str (.num `h 4) "_hyg") 17)))).compress ++ "}")) == some 0) ++ - LSpec.test "a syntax-valued metadata entry is dropped and counted" - (dropped (withMData "{\"_recApp\":\"Lean.DataValue.ofSyntax\\n (Lean.Syntax.missing)\"}") == some 1) ++ - LSpec.test "a metadata value that does not read back is refused" - (refuses (withMData "{\"k\":\"Lean.DataValue.ofBool maybe\"}")) ++ - LSpec.test "a metadata value in another form is refused" + (.num (.str (.num `h 4) "_hyg") 17)))).compress ++ "}")) == some 0) + itBool "a syntax-valued metadata entry is dropped and counted" + (dropped (withMData "{\"_recApp\":\"Lean.DataValue.ofSyntax\\n (Lean.Syntax.missing)\"}") == some 1) + itBool "a metadata value that does not read back is refused" + (refuses (withMData "{\"k\":\"Lean.DataValue.ofBool maybe\"}")) + itBool "a metadata value in another form is refused" (refuses (withMData "{\"k\":\"Lean.DataValue.ofNat 3\"}")) /-! ## Fidelity on ix's own toolchain -/ @@ -164,17 +167,17 @@ def compileBound (env : Lean.Environment) : IO Ixon.Env := do Ix.RoleBinding.Compile.finalize (Ix.RoleBinding.Compile.certifiedBackend 8) env (pure env) input out.env Ix.Typing.typingLimits out.existing? -def fidelity : IO (Bool × Nat × Nat × Option String) := do - let exported ← IO.ofExcept (importString (← readFixture Lean.versionString)) - require (exported.exportMeta.leanVersion == Lean.versionString) +def fidelity : AssertM Unit := do + let exported ← expectOk (importString (← readFixture Lean.versionString)) + expect (exported.exportMeta.leanVersion == Lean.versionString) s!"the fixture comes from Lean {exported.exportMeta.leanVersion}, the test runs on {Lean.versionString}" let native ← getCompileEnv #[`IxCK.Kernel.PinGen.Certs, `Tests.Fixtures.toolchains.Primitives] let mut nativeDecls : Array (Lean.Name × Lean.ConstantInfo) := #[] let mut binderDiffs := 0 for (name, ci) in exported.constants do let some nci := native.find? name - | throw (IO.userError s!"{name} is exported but not in the native environment") - require (sameDeclaration ci nci) s!"{name}: the exported declaration differs from the native one" + | fail s!"{name} is exported but not in the native environment" + expect (sameDeclaration ci nci) s!"{name}: the exported declaration differs from the native one" unless sameBinders ci nci do binderDiffs := binderDiffs + 1 nativeDecls := nativeDecls.push (name, nci) let fromNative ← compileBound (← environment nativeDecls) @@ -184,9 +187,8 @@ def fidelity : IO (Bool × Nat × Nat × Option String) := do IO.println s!"[lean-export] {exported.constants.size} declarations; {binderDiffs} differ from the \ native ones in binder names or info; {exported.droppedSyntaxMData} syntax-valued metadata entries dropped" for line in report do IO.println s!"[lean-export] {line}" - require fromNative.roleBinding.isSome "the native compile has no role binding" - require c.contentExact s!"the export's compile differs in content: {report}" - return (true, 0, 0, none) + expect fromNative.roleBinding.isSome "the native compile has no role binding" + expect c.contentExact s!"the export's compile differs in content: {report}" /-! ## Another toolchain's roles -/ @@ -201,45 +203,43 @@ its `Nat.xor` does too. is finalized. Its binding binds the role at the address the export publishes it at, which is not the default table's. `finalize`'s own check of the published role names against that binding passed. -/ -def foreignRoles (version : String) (role : _root_.Ix.Kernel.Role) : - IO (Bool × Nat × Nat × Option String) := do - let exported ← IO.ofExcept (importString (← readFixture version)) +def foreignRoles (version : String) (role : _root_.Ix.Kernel.Role) : AssertM Unit := do + let exported ← expectOk (importString (← readFixture version)) let env ← environment exported.constants let constants := env.constants.toList match ← Ix.CompileM.compileCertified env constants 8 with | .ok _ => - throw (IO.userError s!"{version}: the compile at the default role table accepted {repr role}") + fail s!"{version}: the compile at the default role table accepted {repr role}" | .error e => - require (e.startsWith "role check failed") s!"{version}: refused for another reason: {e}" + expect (e.startsWith "role check failed") s!"{version}: refused for another reason: {e}" let artifact ← match ← Ix.CompileM.compileAndFinalize env constants 8 (allowPartial := false) (certSource := pure env) (defaultRoles := false) with | .ok (_, .done artifact _) => pure artifact | .ok (out, .refused) => - throw (IO.userError s!"{version}: {out.failures.toMap.size} constants failed to compile") - | .ok (_, .failed e) => throw (IO.userError s!"{version}: finalization failed: {e}") - | .error e => throw (IO.userError s!"{version}: the compile failed: {e}") + fail s!"{version}: {out.failures.toMap.size} constants failed to compile" + | .ok (_, .failed e) => fail s!"{version}: finalization failed: {e}" + | .error e => fail s!"{version}: the compile failed: {e}" let some binding := artifact.roleBinding - | throw (IO.userError s!"{version}: the artifact carries no role binding") + | fail s!"{version}: the artifact carries no role binding" let some table := _root_.Ix.Kernel.RoleTable.ofBytes binding.bytes - | throw (IO.userError s!"{version}: the role binding does not decode") - let published := (← IO.ofExcept (_root_.Ix.RoleBinding.sourceAddresses artifact))[role.leanName]? + | fail s!"{version}: the role binding does not decode" + let published := (← expectOk (_root_.Ix.RoleBinding.sourceAddresses artifact))[role.leanName]? let atDefault := (_root_.Ix.Cert.roleTableBound.find? (·.1 == role)).map (·.2) - require (published.isSome && table.addressOf? role == published) + expect (published.isSome && table.addressOf? role == published) s!"{version}: {repr role} is published at {published}, bound at {table.addressOf? role}" - require (published != atDefault) + expect (published != atDefault) s!"{version}: {repr role} is published at the default table's address {atDefault}" IO.println s!"[lean-export] {version}: {repr role} bound at {published}; the default table \ binds it at {atDefault}" - return (true, 0, 0, none) - -def suite : List LSpec.TestSeq := [ - readerTests, - .individualIO "a 4.34.1 export compiles to exactly the native content, role binding included" none - fidelity .done, - .individualIO "a 4.35.0 export binds its own Int.decLt, which the default role table refuses" - none (foreignRoles "4.35.0" .intDecLt) .done, - .individualIO "a 4.33.1 export binds its own Nat.xor, which the default role table refuses" - none (foreignRoles "4.33.1" .natXor) .done] + +def suite : LSpec.Spec := do + readerTests + it "a 4.34.1 export compiles to exactly the native content, role binding included" + fidelity + it "a 4.35.0 export binds its own Int.decLt, which the default role table refuses" + (foreignRoles "4.35.0" .intDecLt) + it "a 4.33.1 export binds its own Nat.xor, which the default role table refuses" + (foreignRoles "4.33.1" .natXor) end Tests.Ix.LeanExport diff --git a/Tests/Ix/Merkle.lean b/Tests/Ix/Merkle.lean index 969df07834..61301f7269 100644 --- a/Tests/Ix/Merkle.lean +++ b/Tests/Ix/Merkle.lean @@ -10,109 +10,113 @@ public import LSpec open LSpec open Ix.Merkle +set_option compiler.extract_closed false + private def addr (seed : String) : Address := Address.blake3 seed.toUTF8 /-! ## Canonical builder -/ -private def canonicalUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - test "canonical_empty → none" (merkleRootCanonical #[] == none) - ++ test "canonical_single = leafHash" - (merkleRootCanonical #[a] == some (leafHash a)) - ++ test "canonical_sort_invariant [a,b] = [b,a]" - (merkleRootCanonical #[a, b] == merkleRootCanonical #[b, a]) - ++ test "canonical_dedup [a,a,b] = [a,b]" - (merkleRootCanonical #[a, a, b] == merkleRootCanonical #[a, b]) - ++ test "canonical_distinguishes [a] ≠ [a,b]" - (!(merkleRootCanonical #[a] == merkleRootCanonical #[a, b])) - ++ test "canonical_three_leaves nonempty" - ((merkleRootCanonical #[a, b, c]).isSome) - ++ test "canonical_no_malleability" - -- [a, a] post-dedup is [a], yielding leafHash a. - -- A two-leaf tree node_hash(leaf_hash(a), leaf_hash(a)) is different. - (merkleRootCanonical #[a, a] - == some (leafHash a) - && !(merkleRootCanonical #[a, a] - == some (nodeHash (leafHash a) (leafHash a)))) +private def canonicalUnits : LSpec.Spec := do + itBool "canonical_empty → none" (merkleRootCanonical #[] == none) + itBool "canonical_single = leafHash" + (let a := addr "a"; merkleRootCanonical #[a] == some (leafHash a)) + itBool "canonical_sort_invariant [a,b] = [b,a]" + (let a := addr "a"; let b := addr "b" + merkleRootCanonical #[a, b] == merkleRootCanonical #[b, a]) + itBool "canonical_dedup [a,a,b] = [a,b]" + (let a := addr "a"; let b := addr "b" + merkleRootCanonical #[a, a, b] == merkleRootCanonical #[a, b]) + itBool "canonical_distinguishes [a] ≠ [a,b]" + (let a := addr "a"; let b := addr "b" + !(merkleRootCanonical #[a] == merkleRootCanonical #[a, b])) + itBool "canonical_three_leaves nonempty" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + (merkleRootCanonical #[a, b, c]).isSome) + itBool "canonical_no_malleability" + -- [a, a] post-dedup is [a], yielding leafHash a. + -- A two-leaf tree node_hash(leaf_hash(a), leaf_hash(a)) is different. + (let a := addr "a" + merkleRootCanonical #[a, a] == some (leafHash a) + && !(merkleRootCanonical #[a, a] == some (nodeHash (leafHash a) (leafHash a)))) /-! ## Domain separation -/ -private def domainSepUnits : TestSeq := - let a := addr "a" - test "leaf_vs_node_disjoint" - (!(leafHash a == nodeHash a zeroAddress)) +private def domainSepUnits : LSpec.Spec := do + itBool "leaf_vs_node_disjoint" + (let a := addr "a"; !(leafHash a == nodeHash a zeroAddress)) /-! ## Free-form (merkleJoin) -/ -private def joinUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - test "join_is_node_hash" (merkleJoin a b == nodeHash a b) - ++ test "join_non_commutative" (!(merkleJoin a b == merkleJoin b a)) - ++ test "join_canonical_inequal" - -- Free-form tree of {a,b}{c} ≠ canonical tree of {a,b,c}. - (let left := (merkleRootCanonical #[a, b]).get! - let right := (merkleRootCanonical #[c]).get! - let joined := merkleJoin left right - let canon := (merkleRootCanonical #[a, b, c]).get! - !(joined == canon)) +private def joinUnits : LSpec.Spec := do + itBool "join_is_node_hash" + (let a := addr "a"; let b := addr "b"; merkleJoin a b == nodeHash a b) + itBool "join_non_commutative" + (let a := addr "a"; let b := addr "b"; !(merkleJoin a b == merkleJoin b a)) + itBool "join_canonical_inequal" + -- Free-form tree of {a,b}{c} ≠ canonical tree of {a,b,c}. + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let left := (merkleRootCanonical #[a, b]).get! + let right := (merkleRootCanonical #[c]).get! + let joined := merkleJoin left right + let canon := (merkleRootCanonical #[a, b, c]).get! + !(joined == canon)) /-! ## Membership proofs -/ -private def membershipUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - let leaves := #[a, b, c] - let root := (merkleRootCanonical leaves).get! - test "proof_single_leaf empty path" - ((merkleProofCanonical #[a] a).get!.isEmpty - && verifyMerkleProof (leafHash a) a #[]) - ++ test "proof_two_leaves roundtrip" - (let leaves := #[a, b] - let root := (merkleRootCanonical leaves).get! - let path_a := (merkleProofCanonical leaves a).get! - let path_b := (merkleProofCanonical leaves b).get! - verifyMerkleProof root a path_a && verifyMerkleProof root b path_b) - ++ test "proof_three_leaves all members" - (let path_a := (merkleProofCanonical leaves a).get! - let path_b := (merkleProofCanonical leaves b).get! - let path_c := (merkleProofCanonical leaves c).get! - verifyMerkleProof root a path_a - && verifyMerkleProof root b path_b - && verifyMerkleProof root c path_c) - ++ test "proof_rejects_nonmember_direct" - ((merkleProofCanonical #[a, b] (addr "x")) == none) +private def membershipUnits : LSpec.Spec := do + itBool "proof_single_leaf empty path" + (let a := addr "a" + (merkleProofCanonical #[a] a).get!.isEmpty + && verifyMerkleProof (leafHash a) a #[]) + itBool "proof_two_leaves roundtrip" + (let a := addr "a"; let b := addr "b" + let leaves := #[a, b] + let root := (merkleRootCanonical leaves).get! + let path_a := (merkleProofCanonical leaves a).get! + let path_b := (merkleProofCanonical leaves b).get! + verifyMerkleProof root a path_a && verifyMerkleProof root b path_b) + itBool "proof_three_leaves all members" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let leaves := #[a, b, c] + let root := (merkleRootCanonical leaves).get! + let path_a := (merkleProofCanonical leaves a).get! + let path_b := (merkleProofCanonical leaves b).get! + let path_c := (merkleProofCanonical leaves c).get! + verifyMerkleProof root a path_a + && verifyMerkleProof root b path_b + && verifyMerkleProof root c path_c) + itBool "proof_rejects_nonmember_direct" + (let a := addr "a"; let b := addr "b" + (merkleProofCanonical #[a, b] (addr "x")) == none) /-! ## Join composes membership -/ -private def joinMembershipUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - let leftLeaves := #[a, b] - let rightLeaves := #[c] - let leftRoot := (merkleRootCanonical leftLeaves).get! - let rightRoot := (merkleRootCanonical rightLeaves).get! - let joined := merkleJoin leftRoot rightRoot - test "join_composes_left" - (let path := (merkleProofCanonical leftLeaves a).get! +private def joinMembershipUnits : LSpec.Spec := do + itBool "join_composes_left" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let leftLeaves := #[a, b] + let rightLeaves := #[c] + let leftRoot := (merkleRootCanonical leftLeaves).get! + let rightRoot := (merkleRootCanonical rightLeaves).get! + let joined := merkleJoin leftRoot rightRoot + let path := (merkleProofCanonical leftLeaves a).get! verifyMerkleProof joined a (path.push (rightRoot, false))) - ++ test "join_composes_right" - (let path := (merkleProofCanonical rightLeaves c).get! - verifyMerkleProof joined c (path.push (leftRoot, true))) + itBool "join_composes_right" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let leftLeaves := #[a, b] + let rightLeaves := #[c] + let leftRoot := (merkleRootCanonical leftLeaves).get! + let rightRoot := (merkleRootCanonical rightLeaves).get! + let joined := merkleJoin leftRoot rightRoot + let path := (merkleProofCanonical rightLeaves c).get! + verifyMerkleProof joined c (path.push (leftRoot, true))) /-! ## Suite -/ -public def Tests.Merkle.suite : List TestSeq := [ - canonicalUnits, - domainSepUnits, - joinUnits, - membershipUnits, - joinMembershipUnits, -] - +public def Tests.Merkle.suite : LSpec.Spec := do + canonicalUnits + domainSepUnits + joinUnits + membershipUnits + joinMembershipUnits diff --git a/Tests/Ix/MetaEnv.lean b/Tests/Ix/MetaEnv.lean index d351c7e958..31395c0e80 100644 --- a/Tests/Ix/MetaEnv.lean +++ b/Tests/Ix/MetaEnv.lean @@ -40,21 +40,20 @@ private def constKind : Lean.ConstantInfo → String | .inductInfo _ => "an inductive" | .ctorInfo _ => "a constructor" | .recInfo _ => "a recursor" | .quotInfo _ => "a quotient primitive" -/-- Load a tmpdir fixture with `getFileEnvCore` and run `check` on the result -(the fixture file is gone by the time the TestSeq is folded, so checks run -eagerly here). -/ +/-- Load a tmpdir fixture with `getFileEnvCore` and run `check` on the result. -/ private def withFixture (name source : String) - (check : FilePath → FileEnv → IO (Bool × Option String)) - : IO (Bool × Nat × Nat × Option String) := do + (check : FilePath → FileEnv → AssertM Unit) : AssertM Unit := do let dir ← IO.FS.createTempDir let path := dir / name IO.FS.writeFile path source try - let fe ← getFileEnvCore path - let (ok, err?) ← check path fe - return (ok, 0, 0, err?) - catch e => - return (false, 0, 0, some s!"getFileEnvCore failed: {e}") + let feRes : Except String FileEnv ← liftM (m := IO) do + try + pure (.ok (← getFileEnvCore path)) + catch e => + pure (.error s!"getFileEnvCore failed: {e}") + let fe ← expectOk feRes + check path fe finally IO.FS.removeDirAll dir @@ -82,56 +81,51 @@ private def checkFullContent (env : Lean.Environment) (marker : Lean.Name) | some ci => some s!"Nat.add_comm is {constKind ci}, expected a theorem with a proof" | none => some "Nat.add_comm missing from env" -def moduleFileTest : TestSeq := - .individualIO "module header: full content + isModule flag" none - (withFixture "ModFixture.lean" moduleSource fun _ fe => do - if !fe.isModule then - return (false, some "isModule = false for a `module` header") +def moduleFileTest : LSpec.Spec := do + it "module header: full content + isModule flag" do + withFixture "ModFixture.lean" moduleSource fun _ fe => do + expect fe.isModule "isModule = false for a `module` header" -- The env must also carry private transitive imports (absent entirely -- at exported level). let privCount := fe.env.constants.toList.countP fun (n, _) => isPrivateName n - if privCount == 0 then - return (false, some "no _private.* constants — exported-level trim suspected") - match checkFullContent fe.env `TestsMetaEnv.modMarker with - | some e => return (false, some e) - | none => return (true, none)) .done - -def classicFileTest : TestSeq := - .individualIO "classic header: full content + isModule flag" none - (withFixture "ClassicFixture.lean" classicSource fun _ fe => do - if fe.isModule then - return (false, some "isModule = true for a classic header") - match checkFullContent fe.env `TestsMetaEnv.classicMarker with - | some e => return (false, some e) - | none => return (true, none)) .done + expect (privCount != 0) "no _private.* constants — exported-level trim suspected" + if let some e := checkFullContent fe.env `TestsMetaEnv.modMarker then + fail e + +def classicFileTest : LSpec.Spec := do + it "classic header: full content + isModule flag" do + withFixture "ClassicFixture.lean" classicSource fun _ fe => do + expectFalse fe.isModule "isModule = true for a classic header" + if let some e := checkFullContent fe.env `TestsMetaEnv.classicMarker then + fail e /-- Scoping: `defaultConstList` on a module-mode file must (a) keep the file's own definitions, (b) keep module-visible imports, (c) pull in referenced `_private.*` proof auxiliaries through the closure — with their full-content `ConstantInfo`s (theorems stay theorems) — and (d) still exclude some of the full env (the unreferenced foreign privates the `module` header conceals). -/ -def scopedListTest : TestSeq := - .individualIO "module header: defaultConstList scopes names, not content" none - (withFixture "ScopeFixture.lean" moduleSource fun path fe => do +def scopedListTest : LSpec.Spec := do + it "module header: defaultConstList scopes names, not content" do + withFixture "ScopeFixture.lean" moduleSource fun path fe => do let closed ← defaultConstList fe path.toString let full := fe.env.constants.toList.length let names : Std.HashSet Lean.Name := .ofList (closed.map (·.1)) - if !names.contains `TestsMetaEnv.modMarker then - return (false, some "local definition missing from scoped list") + expect (names.contains `TestsMetaEnv.modMarker) + "local definition missing from scoped list" let addComm := closed.find? fun (n, _) => n == `Nat.add_comm match addComm with | some (_, .thmInfo _) => pure () | some (_, ci) => - return (false, some s!"scoped Nat.add_comm is {constKind ci}, expected a theorem") - | none => return (false, some "Nat.add_comm missing from scoped list") + fail s!"scoped Nat.add_comm is {constKind ci}, expected a theorem" + | none => fail "Nat.add_comm missing from scoped list" let privCount := closed.countP fun (n, _) => isPrivateName n - if privCount == 0 then - return (false, some "closure pulled in no _private.* proof auxiliaries") - if closed.length ≥ full then - return (false, some s!"scoped list ({closed.length}) does not exclude \ -anything from the full env ({full})") - return (true, none)) .done - -def suite : List TestSeq := [moduleFileTest, classicFileTest, scopedListTest] + expect (privCount != 0) "closure pulled in no _private.* proof auxiliaries" + expect (decide (closed.length < full)) + s!"scoped list ({closed.length}) does not exclude anything from the full env ({full})" + +def suite : LSpec.Spec := do + moduleFileTest + classicFileTest + scopedListTest end Tests.Ix.MetaEnv diff --git a/Tests/Ix/MultiStarkVerifier.lean b/Tests/Ix/MultiStarkVerifier.lean index 70b0d58a56..76fd9037d4 100644 --- a/Tests/Ix/MultiStarkVerifier.lean +++ b/Tests/Ix/MultiStarkVerifier.lean @@ -106,17 +106,18 @@ private def fixtures : List (String × System.FilePath × Bool) := [ /-- Every committed fixture key decodes under `StarkSystem.fromBytes` and satisfies the full production static check (`Ix.Cert.MultiStark.checkSystem`), matching the security floor and structural invariants enforced in-circuit by `MultiStark.recursionProgram`. -/ -def admissibilitySuite : IO (List TestSeq) := do - let mut tests : TestSeq := .done - for (name, dir, _) in fixtures do +def admissibilitySuite : IO Spec := do + let loaded ← fixtures.mapM fun (name, dir, _) => do let sys ← IO.FS.readBinFile (dir / "system.bin") - match Ix.Cert.MultiStark.StarkSystem.fromBytes sys with - | .ok s => - tests := tests ++ test s!"{name}: key decodes and satisfies checkSystem" - (Ix.Cert.MultiStark.checkSystem s) - | .error e => - tests := tests ++ test s!"{name}: Lean decoder accepts the fixture key ({e})" false - return [tests] + return (name, sys) + return do + for (name, sys) in loaded do + match Ix.Cert.MultiStark.StarkSystem.fromBytes sys with + | .ok s => + itBool s!"{name}: key decodes and satisfies checkSystem" + (Ix.Cert.MultiStark.checkSystem s) + | .error e => + itBool s!"{name}: Lean decoder accepts the fixture key ({e})" false section DecoderParity @@ -215,339 +216,340 @@ private def expectOkCheck (bytes : ByteArray) (pred : StarkSystem → Bool) : Bo /-- Parity and negative-control suite for the Lean verifying-key decoder (`StarkSystem.fromBytes`), static system validator (`checkSystem` / `checkSystemWithFloor`), transcript shape binding (`observeShape`), and executable `LookupsPlain` checker (`checkLookupsPlain`). -/ -def decoderParitySuite : IO (List TestSeq) := do - let mut tests : TestSeq := .done - - -- 1. Positive checks on all 5 real Rust fixtures (including `prep_first`) - for (name, dir, hasInactivePrep) in fixtures do +def decoderParitySuite : IO Spec := do + let fixtureData ← fixtures.mapM fun (name, dir, hasInactivePrep) => do let sysBytes ← IO.FS.readBinFile (dir / "system.bin") let clmBytes ← IO.FS.readBinFile (dir / "claims.bin") let prfBytes ← IO.FS.readBinFile (dir / "proof.bin") - match StarkSystem.fromBytes sysBytes with - | .error e => - tests := tests ++ test s!"{name}: StarkSystem.fromBytes accepts fixture ({e})" false - | .ok s => - tests := tests ++ test s!"{name}: toBytes round-trips byte-identically" - (s.toBytes == sysBytes) - tests := tests ++ test s!"{name}: vkDigest matches recomputed computeVkDigest" - (s.vkDigest == computeVkDigest s.circuits) - tests := tests ++ test s!"{name}: passes checkSystemWithFloor(allowBelowFloor=true)" - (checkSystemWithFloor s true) - tests := tests ++ test s!"{name}: all circuits pass checkLookupsPlain" - (s.circuits.all checkLookupsPlain) - let sFloor := { s with params := floorParams } - tests := tests ++ test s!"{name}: passes StarkSystem.fromBytes and checkSystem at production floor" - (expectOkCheck sFloor.toBytes fun s2 => checkSystem s2 && s2 == sFloor) - tests := tests ++ test s!"{name}: verifyBatchBytesWithFloor matches expected acceptance" - (verifyBatchBytesWithFloor sysBytes clmBytes prfBytes none true hasInactivePrep) - if hasInactivePrep then - tests := tests ++ test s!"{name}: strict active-preprocessed rejects inactive fixed table" - (!verifyBatchBytesWithFloor sysBytes clmBytes prfBytes none true false) - - -- Load grouped_prep_1shard as base production-floor key for single-invariant mutations + return (name, hasInactivePrep, sysBytes, clmBytes, prfBytes) let baseBytes ← IO.FS.readBinFile (System.FilePath.mk "Tests/Fixtures/MultiStark" / "system.bin") - let .ok baseToy := StarkSystem.fromBytes baseBytes - | return [tests ++ test "base fixture decode" false] - let base := { baseToy with params := floorParams } - let baseFloorBytes := base.toBytes - tests := tests ++ test "base production-floor key decodes and passes checkSystem" - (expectOkCheck baseFloorBytes checkSystem) - - -- 2. Header downgrades, vk_digest mismatch, and transcript binding - tests := tests ++ test "negative: Protocol v5 header rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 0 5)) "Protocol v6") - tests := tests ++ test "negative: Fp^2 extension_degree rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 2 2)) "cubic extension") - tests := tests ++ test "negative: FriBatching::Horner tag rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 4 0)) "Tensor") - tests := tests ++ test "negative: tampered vk_digest rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (flipByte baseFloorBytes 6)) "vk_digest") - let badDigestSys := { base with vkDigest := default } - tests := tests ++ test "negative: mismatched vkDigest rejected by checkSystem" - (!checkSystem badDigestSys) - tests := tests ++ test "transcript: observeShape absorbs recomputed vkDigest regardless of stale field" - (observeShape (initialChallenger base.params) base == - observeShape (initialChallenger base.params) badDigestSys) - let altCirc := { base.circuits[0]! with nodes := base.circuits[0]!.nodes.push (.const Goldilocks.one) } - let altSys := { base with circuits := base.circuits.set! 0 altCirc } - tests := tests ++ test "transcript: observeShape changes when circuit graph changes even with fixed vkDigest" - (observeShape (initialChallenger base.params) base != - observeShape (initialChallenger base.params) altSys) - - -- 3. Lookup roots outside lookupPrefixLen - let c0 := base.circuits[0]! - let badPrefixC0 := { c0 with lookupPrefixLen := c0.lookupPrefixLen - 1 } - let badPrefixSys := makeSelfConsistent floorParams (base.circuits.set! 0 badPrefixC0) - base.preprocessedCommit base.preprocessedIndices - tests := tests ++ test "negative: lookup root outside lookupPrefixLen rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badPrefixSys.toBytes) "lookup") - tests := tests ++ test "negative: lookup root outside lookupPrefixLen rejected by checkSystem" - (!checkSystem badPrefixSys) - tests := tests ++ test "negative: lookup root outside lookupPrefixLen rejected by checkLookupsPlain" - (!checkLookupsPlain badPrefixC0) - let oobPrefixC0 := { c0 with lookupPrefixLen := c0.nodes.size + 1 } - let oobPrefixSys := makeSelfConsistent floorParams (base.circuits.set! 0 oobPrefixC0) - base.preprocessedCommit base.preprocessedIndices - tests := tests ++ test "negative: lookupPrefixLen > nodes.size rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobPrefixSys.toBytes) "lookup_prefix_len") - tests := tests ++ test "negative: lookupPrefixLen > nodes.size rejected by checkSystem" - (!checkSystem oobPrefixSys) - -- Separate multiplicity vs argument root outside lookupPrefixLen - let badMultCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 1 - nodes := #[.var .main .current 0, .const Goldilocks.one] - zeros := #[], lookups := #[{ multiplicity := 1, args := #[0] }] - } - let badMultSys := makeSelfConsistent floorParams #[badMultCirc] - tests := tests ++ test "negative: lookup multiplicity outside lookupPrefixLen rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badMultSys.toBytes) "multiplicity") - tests := tests ++ test "negative: lookup multiplicity outside lookupPrefixLen rejected by checkLookupsPlain" - (!checkLookupsPlain badMultCirc) - - -- 4. Derived maxConstraintDegree mismatch, blowup budget, and mul-DAG degree overflow - let badDegHiC0 := { c0 with maxConstraintDegree := c0.maxConstraintDegree + 1 } - let badDegHiSys := makeSelfConsistent floorParams (base.circuits.set! 0 badDegHiC0) - base.preprocessedCommit base.preprocessedIndices - tests := tests ++ test "negative: inflated maxConstraintDegree rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badDegHiSys.toBytes) "max_constraint_degree") - tests := tests ++ test "negative: inflated maxConstraintDegree rejected by checkSystem" - (!checkSystem badDegHiSys) - let badDegLoC0 := { c0 with maxConstraintDegree := c0.maxConstraintDegree - 1 } - let badDegLoSys := makeSelfConsistent floorParams (base.circuits.set! 0 badDegLoC0) - base.preprocessedCommit base.preprocessedIndices - tests := tests ++ test "negative: deflated maxConstraintDegree rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badDegLoSys.toBytes) "max_constraint_degree") - tests := tests ++ test "negative: deflated maxConstraintDegree rejected by checkSystem" - (!checkSystem badDegLoSys) - let deg4Circ : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 4, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .main .current 0, .mul 0 0, .mul 1 1] - zeros := #[2], lookups := #[] - } - let lowBlowupParams := { floorParams with logBlowup := 1, numQueries := 238 } - let blowupExceedSys := makeSelfConsistent lowBlowupParams #[deg4Circ] - let blowupOkSys := makeSelfConsistent floorParams #[deg4Circ] - tests := tests ++ test "negative: degree exceeding blowup budget rejected by fromBytes" - (expectErr (StarkSystem.fromBytes blowupExceedSys.toBytes) "blowup") - tests := tests ++ test "negative: degree exceeding blowup budget rejected by checkSystem" - (!checkSystem blowupExceedSys) - tests := tests ++ test "positive: degree within blowup budget accepted by fromBytes and checkSystem" - (expectOkCheck blowupOkSys.toBytes checkSystem) - let overflowNodes : Array GraphNode := Id.run do - let mut ns : Array GraphNode := #[.var .main .current 0] - for i in [0:32] do - ns := ns.push (.mul i i) - return ns - let overflowCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := overflowNodes, zeros := #[32], lookups := #[] - } - let overflowSys := makeSelfConsistent floorParams #[overflowCirc] - tests := tests ++ test "negative: mul-DAG degree overflow rejected by fromBytes" - (expectErr (StarkSystem.fromBytes overflowSys.toBytes) "overflow") - tests := tests ++ test "negative: mul-DAG degree overflow rejected by checkSystem" - (!checkSystem overflowSys) - - -- 5. lookupGroupSize bounds (0 and 9 > MAX_LOOKUP_GROUP = 8; 8 accepted) - let trivialCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .main .current 0], zeros := #[0], lookups := #[] - } - let grp0Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 0 }] - let grp9Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 9 }] - let grp8Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 8 }] - tests := tests ++ test "negative: lookupGroupSize = 0 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes grp0Sys.toBytes) "lookup group size") - tests := tests ++ test "negative: lookupGroupSize = 0 rejected by checkSystem" - (!checkSystem grp0Sys) - tests := tests ++ test "negative: lookupGroupSize = 9 (> MAX_LOOKUP_GROUP) rejected by fromBytes" - (expectErr (StarkSystem.fromBytes grp9Sys.toBytes) "lookup group size") - tests := tests ++ test "negative: lookupGroupSize = 9 (> MAX_LOOKUP_GROUP) rejected by checkSystem" - (!checkSystem grp9Sys) - tests := tests ++ test "positive: lookupGroupSize = 8 (MAX_LOOKUP_GROUP) accepted" - (expectOkCheck grp8Sys.toBytes checkSystem) - - -- 6. Compiler-context parity (lookup prefix forbidden nodes & stage-2 reachable from zeros) - let forbiddenPrefixNodes : List (String × GraphNode) := [ - ("Public(0)", .publicInput 0), - ("IsFirstRow", .isFirstRow), - ("IsLastRow", .isLastRow), - ("IsTransition", .isTransition), - ("Var(Stage2)", .var .stage2 .current 0) - ] - for (label, badNode) in forbiddenPrefixNodes do - let rawBadCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 2 - nodes := #[.const Goldilocks.one, badNode] - zeros := #[], lookups := #[{ multiplicity := 0, args := #[1] }] - } - let degs := sweepDegreesTotal rawBadCirc.nodes - let expectedDeg := deriveLookupDegree degs rawBadCirc.lookups rawBadCirc.lookupGroupSize - let badCirc := { rawBadCirc with maxConstraintDegree := expectedDeg } - let badSys := makeSelfConsistent floorParams #[badCirc] - tests := tests ++ test s!"negative: {label} in lookup prefix rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badSys.toBytes) "lookup prefix") - tests := tests ++ test s!"negative: {label} in lookup prefix rejected by checkSystem" - (!checkSystem badSys) - tests := tests ++ test s!"negative: {label} in lookup prefix rejected by checkLookupsPlain" - (!checkLookupsPlain badCirc) - let s2ZeroDirect : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .stage2 .current 0], zeros := #[0], lookups := #[] - } - let s2DirectSys := makeSelfConsistent floorParams #[s2ZeroDirect] - tests := tests ++ test "negative: stage-2 directly in zero constraint rejected by fromBytes" - (expectErr (StarkSystem.fromBytes s2DirectSys.toBytes) "stage-2") - tests := tests ++ test "negative: stage-2 directly in zero constraint rejected by checkSystem" - (!checkSystem s2DirectSys) - let s2ZeroIndirect : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .stage2 .current 0, .mul 0 0, .neg 1], zeros := #[2], lookups := #[] - } - let s2IndirectSys := makeSelfConsistent floorParams #[s2ZeroIndirect] - tests := tests ++ test "negative: stage-2 reachable from zero constraint rejected by fromBytes" - (expectErr (StarkSystem.fromBytes s2IndirectSys.toBytes) "stage-2") - tests := tests ++ test "negative: stage-2 reachable from zero constraint rejected by checkSystem" - (!checkSystem s2IndirectSys) - let selPubZeroCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .main .current 0, .isFirstRow, .mul 0 1, .publicInput 0, .add 2 3] - zeros := #[4], lookups := #[] - } - let selPubSys := makeSelfConsistent floorParams #[selPubZeroCirc] - tests := tests ++ test "positive: selectors and publics in zero constraints accepted" - (expectOkCheck selPubSys.toBytes checkSystem) - - -- 7. Preprocessed width/height consistency & power-of-two height - let badPrepW : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 0 } - let badPrepWSys := makeSelfConsistent floorParams #[badPrepW] - tests := tests ++ test "negative: preprocessedWidth > 0 with preprocessedHeight == 0 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badPrepWSys.toBytes) "preprocessed_width") - tests := tests ++ test "negative: preprocessedWidth > 0 with preprocessedHeight == 0 rejected by checkSystem" - (!checkSystem badPrepWSys) - let dummyRoot : D := base.vkDigest - let badPrepH : SysCircuit := { trivialCirc with preprocessedWidth := 0, preprocessedHeight := 4 } - let badPrepHSys := makeSelfConsistent floorParams #[badPrepH] (some #[dummyRoot]) #[some 0] - tests := tests ++ test "negative: preprocessedWidth == 0 with preprocessedHeight > 0 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badPrepHSys.toBytes) "preprocessed_width") - tests := tests ++ test "negative: preprocessedWidth == 0 with preprocessedHeight > 0 rejected by checkSystem" - (!checkSystem badPrepHSys) - let nonPotPrepH : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 3 } - let nonPotSys := makeSelfConsistent floorParams #[nonPotPrepH] (some #[dummyRoot]) #[some 0] - tests := tests ++ test "negative: non-power-of-two preprocessedHeight rejected by fromBytes" - (expectErr (StarkSystem.fromBytes nonPotSys.toBytes) "power of two") - tests := tests ++ test "negative: non-power-of-two preprocessedHeight rejected by checkSystem" - (!checkSystem nonPotSys) - - -- 8. Canonical ConstBig encodings - for badVal in ([0, 1, 0xFFFF, Goldilocks.order, Goldilocks.order + 1, 0xFFFFFFFFFFFFFFFF] : List Nat) do - let badBytes := rawSingleNodeConstBigKey badVal false - tests := tests ++ test s!"negative: non-canonical ConstBig {badVal} rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badBytes) "non-canonical") - for goodVal in ([0x10000, Goldilocks.order - 1] : List Nat) do - let goodBytes := rawSingleNodeConstBigKey goodVal true - tests := tests ++ test s!"positive: canonical ConstBig {goodVal} accepted and round-trips" - (expectOkCheck goodBytes fun s => checkSystem s && s.toBytes == goodBytes) - - -- 9. Node index bounds, topological order, trailer, nonzero capHeight LDE check, PoW cap, EOF - let oobPubSys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.publicInput 12], zeros := #[] }] - tests := tests ++ test "negative: OOB Public(12) rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobPubSys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB Public(12) rejected by checkSystem" - (!checkSystem oobPubSys) - let oobMainSys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.var .main .current 1], zeros := #[] }] - tests := tests ++ test "negative: OOB Main var rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobMainSys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB Main var rejected by checkSystem" - (!checkSystem oobMainSys) - let oobPrepSys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.var .preprocessed .current 0], zeros := #[] }] - tests := tests ++ test "negative: OOB Preprocessed var rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobPrepSys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB Preprocessed var rejected by checkSystem" - (!checkSystem oobPrepSys) - let oobS2Sys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.var .stage2 .current 3], zeros := #[] }] - tests := tests ++ test "negative: OOB Stage2 var rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobS2Sys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB Stage2 var rejected by checkSystem" - (!checkSystem oobS2Sys) - let oobZeroSys := makeSelfConsistent floorParams - #[{ trivialCirc with zeros := #[5] }] - tests := tests ++ test "negative: OOB zero root rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobZeroSys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB zero root rejected by checkSystem" - (!checkSystem oobZeroSys) - let nonTopoSys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.neg 0], zeros := #[] }] - tests := tests ++ test "negative: non-topological node rejected by fromBytes" - (expectErr (StarkSystem.fromBytes nonTopoSys.toBytes) "topological") - tests := tests ++ test "negative: non-topological node rejected by checkSystem" - (!checkSystem nonTopoSys) - - let missingCommitSys := { base with preprocessedCommit := none } - tests := tests ++ test "negative: missing preprocessed commitment rejected by fromBytes" - (expectErr (StarkSystem.fromBytes missingCommitSys.toBytes) "missing preprocessed commitment") - tests := tests ++ test "negative: missing preprocessed commitment rejected by checkSystem" - (!checkSystem missingCommitSys) - let extraCommitSys := makeSelfConsistent floorParams #[trivialCirc] (some #[dummyRoot]) #[none] - tests := tests ++ test "negative: extraneous preprocessed commitment rejected by fromBytes" - (expectErr (StarkSystem.fromBytes extraCommitSys.toBytes) "no preprocessed circuits") - tests := tests ++ test "negative: extraneous preprocessed commitment rejected by checkSystem" - (!checkSystem extraCommitSys) - let badRankSys := { base with preprocessedIndices := #[none, some 1] } - tests := tests ++ test "negative: non-canonical preprocessed rank rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badRankSys.toBytes) "rank") - tests := tests ++ test "negative: non-canonical preprocessed rank rejected by checkSystem" - (!checkSystem badRankSys) - let missingIdxSys := { base with preprocessedIndices := #[none, none] } - tests := tests ++ test "negative: missing preprocessed index rejected by fromBytes" - (expectErr (StarkSystem.fromBytes missingIdxSys.toBytes) "preprocessed_height") - tests := tests ++ test "negative: missing preprocessed index rejected by checkSystem" - (!checkSystem missingIdxSys) - for capN in ([0, 2, 3] : List Nat) do - let badCapSys := { base with preprocessedCommit := some (Array.replicate capN dummyRoot) } - tests := tests ++ test s!"negative: malformed preprocessed cap len {capN} rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badCapSys.toBytes) "roots") - tests := tests ++ test s!"negative: malformed preprocessed cap len {capN} rejected by checkSystem" - (!checkSystem badCapSys) - - -- Nonzero cap_height LDE root count check (height 2, logBlowup 2 => LDE log 3, capHeight 2 => 4 roots) - let prep2Circ : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 2 } - let cap2Params := { floorParams with capHeight := 2 } - let cap2GoodSys := makeSelfConsistent cap2Params #[prep2Circ] (some (Array.replicate 4 dummyRoot)) #[some 0] - let cap2BadSys := makeSelfConsistent cap2Params #[prep2Circ] (some (Array.replicate 2 dummyRoot)) #[some 0] - tests := tests ++ test "nonzero capHeight validates against preprocessed LDE height (4 roots ok, checkSystem rejects)" - (expectOkCheck cap2GoodSys.toBytes fun s => !checkSystem s) - tests := tests ++ test "negative: nonzero capHeight with unblown root count (2 roots) rejected by fromBytes" - (expectErr (StarkSystem.fromBytes cap2BadSys.toBytes) "roots") - - let badCommitPowSys := { base with params := { base.params with commitPowBits := 33 } } - let badQueryPowSys := { base with params := { base.params with queryPowBits := 33 } } - tests := tests ++ test "negative: commitPowBits > 32 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badCommitPowSys.toBytes) "exceeds") - tests := tests ++ test "negative: commitPowBits > 32 rejected by checkSystemWithFloor(true)" - (!checkSystemWithFloor badCommitPowSys true) - tests := tests ++ test "negative: queryPowBits > 32 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badQueryPowSys.toBytes) "exceeds") - tests := tests ++ test "negative: queryPowBits > 32 rejected by checkSystemWithFloor(true)" - (!checkSystemWithFloor badQueryPowSys true) - tests := tests ++ test "negative: trailing byte rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (baseFloorBytes.push 0)) "trailing") - tests := tests ++ test "negative: truncated key rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (baseFloorBytes.extract 0 (baseFloorBytes.size - 1))) "eof") - - return [tests] + return do + -- 1. Positive checks on all 5 real Rust fixtures (including `prep_first`) + for (name, hasInactivePrep, sysBytes, clmBytes, prfBytes) in fixtureData do + match StarkSystem.fromBytes sysBytes with + | .error e => + itBool s!"{name}: StarkSystem.fromBytes accepts fixture ({e})" false + | .ok s => + itBool s!"{name}: toBytes round-trips byte-identically" + (s.toBytes == sysBytes) + itBool s!"{name}: vkDigest matches recomputed computeVkDigest" + (s.vkDigest == computeVkDigest s.circuits) + itBool s!"{name}: passes checkSystemWithFloor(allowBelowFloor=true)" + (checkSystemWithFloor s true) + itBool s!"{name}: all circuits pass checkLookupsPlain" + (s.circuits.all checkLookupsPlain) + let sFloor := { s with params := floorParams } + itBool s!"{name}: passes StarkSystem.fromBytes and checkSystem at production floor" + (expectOkCheck sFloor.toBytes fun s2 => checkSystem s2 && s2 == sFloor) + itBool s!"{name}: verifyBatchBytesWithFloor matches expected acceptance" + (verifyBatchBytesWithFloor sysBytes clmBytes prfBytes none true hasInactivePrep) + if hasInactivePrep then + itBool s!"{name}: strict active-preprocessed rejects inactive fixed table" + (!verifyBatchBytesWithFloor sysBytes clmBytes prfBytes none true false) + + -- Load grouped_prep_1shard as base production-floor key for single-invariant mutations + match StarkSystem.fromBytes baseBytes with + | .error _ => + itBool "base fixture decode" false + | .ok baseToy => + let base := { baseToy with params := floorParams } + let baseFloorBytes := base.toBytes + itBool "base production-floor key decodes and passes checkSystem" + (expectOkCheck baseFloorBytes checkSystem) + + -- 2. Header downgrades, vk_digest mismatch, and transcript binding + itBool "negative: Protocol v5 header rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 0 5)) "Protocol v6") + itBool "negative: Fp^2 extension_degree rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 2 2)) "cubic extension") + itBool "negative: FriBatching::Horner tag rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 4 0)) "Tensor") + itBool "negative: tampered vk_digest rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (flipByte baseFloorBytes 6)) "vk_digest") + let badDigestSys := { base with vkDigest := default } + itBool "negative: mismatched vkDigest rejected by checkSystem" + (!checkSystem badDigestSys) + itBool "transcript: observeShape absorbs recomputed vkDigest regardless of stale field" + (observeShape (initialChallenger base.params) base == + observeShape (initialChallenger base.params) badDigestSys) + let altCirc := { base.circuits[0]! with nodes := base.circuits[0]!.nodes.push (.const Goldilocks.one) } + let altSys := { base with circuits := base.circuits.set! 0 altCirc } + itBool "transcript: observeShape changes when circuit graph changes even with fixed vkDigest" + (observeShape (initialChallenger base.params) base != + observeShape (initialChallenger base.params) altSys) + + -- 3. Lookup roots outside lookupPrefixLen + let c0 := base.circuits[0]! + let badPrefixC0 := { c0 with lookupPrefixLen := c0.lookupPrefixLen - 1 } + let badPrefixSys := makeSelfConsistent floorParams (base.circuits.set! 0 badPrefixC0) + base.preprocessedCommit base.preprocessedIndices + itBool "negative: lookup root outside lookupPrefixLen rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badPrefixSys.toBytes) "lookup") + itBool "negative: lookup root outside lookupPrefixLen rejected by checkSystem" + (!checkSystem badPrefixSys) + itBool "negative: lookup root outside lookupPrefixLen rejected by checkLookupsPlain" + (!checkLookupsPlain badPrefixC0) + let oobPrefixC0 := { c0 with lookupPrefixLen := c0.nodes.size + 1 } + let oobPrefixSys := makeSelfConsistent floorParams (base.circuits.set! 0 oobPrefixC0) + base.preprocessedCommit base.preprocessedIndices + itBool "negative: lookupPrefixLen > nodes.size rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobPrefixSys.toBytes) "lookup_prefix_len") + itBool "negative: lookupPrefixLen > nodes.size rejected by checkSystem" + (!checkSystem oobPrefixSys) + -- Separate multiplicity vs argument root outside lookupPrefixLen + let badMultCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 1 + nodes := #[.var .main .current 0, .const Goldilocks.one] + zeros := #[], lookups := #[{ multiplicity := 1, args := #[0] }] + } + let badMultSys := makeSelfConsistent floorParams #[badMultCirc] + itBool "negative: lookup multiplicity outside lookupPrefixLen rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badMultSys.toBytes) "multiplicity") + itBool "negative: lookup multiplicity outside lookupPrefixLen rejected by checkLookupsPlain" + (!checkLookupsPlain badMultCirc) + + -- 4. Derived maxConstraintDegree mismatch, blowup budget, and mul-DAG degree overflow + let badDegHiC0 := { c0 with maxConstraintDegree := c0.maxConstraintDegree + 1 } + let badDegHiSys := makeSelfConsistent floorParams (base.circuits.set! 0 badDegHiC0) + base.preprocessedCommit base.preprocessedIndices + itBool "negative: inflated maxConstraintDegree rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badDegHiSys.toBytes) "max_constraint_degree") + itBool "negative: inflated maxConstraintDegree rejected by checkSystem" + (!checkSystem badDegHiSys) + let badDegLoC0 := { c0 with maxConstraintDegree := c0.maxConstraintDegree - 1 } + let badDegLoSys := makeSelfConsistent floorParams (base.circuits.set! 0 badDegLoC0) + base.preprocessedCommit base.preprocessedIndices + itBool "negative: deflated maxConstraintDegree rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badDegLoSys.toBytes) "max_constraint_degree") + itBool "negative: deflated maxConstraintDegree rejected by checkSystem" + (!checkSystem badDegLoSys) + let deg4Circ : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 4, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .main .current 0, .mul 0 0, .mul 1 1] + zeros := #[2], lookups := #[] + } + let lowBlowupParams := { floorParams with logBlowup := 1, numQueries := 238 } + let blowupExceedSys := makeSelfConsistent lowBlowupParams #[deg4Circ] + let blowupOkSys := makeSelfConsistent floorParams #[deg4Circ] + itBool "negative: degree exceeding blowup budget rejected by fromBytes" + (expectErr (StarkSystem.fromBytes blowupExceedSys.toBytes) "blowup") + itBool "negative: degree exceeding blowup budget rejected by checkSystem" + (!checkSystem blowupExceedSys) + itBool "positive: degree within blowup budget accepted by fromBytes and checkSystem" + (expectOkCheck blowupOkSys.toBytes checkSystem) + let overflowNodes : Array GraphNode := Id.run do + let mut ns : Array GraphNode := #[.var .main .current 0] + for i in [0:32] do + ns := ns.push (.mul i i) + return ns + let overflowCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := overflowNodes, zeros := #[32], lookups := #[] + } + let overflowSys := makeSelfConsistent floorParams #[overflowCirc] + itBool "negative: mul-DAG degree overflow rejected by fromBytes" + (expectErr (StarkSystem.fromBytes overflowSys.toBytes) "overflow") + itBool "negative: mul-DAG degree overflow rejected by checkSystem" + (!checkSystem overflowSys) + + -- 5. lookupGroupSize bounds (0 and 9 > MAX_LOOKUP_GROUP = 8; 8 accepted) + let trivialCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .main .current 0], zeros := #[0], lookups := #[] + } + let grp0Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 0 }] + let grp9Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 9 }] + let grp8Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 8 }] + itBool "negative: lookupGroupSize = 0 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes grp0Sys.toBytes) "lookup group size") + itBool "negative: lookupGroupSize = 0 rejected by checkSystem" + (!checkSystem grp0Sys) + itBool "negative: lookupGroupSize = 9 (> MAX_LOOKUP_GROUP) rejected by fromBytes" + (expectErr (StarkSystem.fromBytes grp9Sys.toBytes) "lookup group size") + itBool "negative: lookupGroupSize = 9 (> MAX_LOOKUP_GROUP) rejected by checkSystem" + (!checkSystem grp9Sys) + itBool "positive: lookupGroupSize = 8 (MAX_LOOKUP_GROUP) accepted" + (expectOkCheck grp8Sys.toBytes checkSystem) + + -- 6. Compiler-context parity (lookup prefix forbidden nodes & stage-2 reachable from zeros) + let forbiddenPrefixNodes : List (String × GraphNode) := [ + ("Public(0)", .publicInput 0), + ("IsFirstRow", .isFirstRow), + ("IsLastRow", .isLastRow), + ("IsTransition", .isTransition), + ("Var(Stage2)", .var .stage2 .current 0) + ] + for (label, badNode) in forbiddenPrefixNodes do + let rawBadCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 2 + nodes := #[.const Goldilocks.one, badNode] + zeros := #[], lookups := #[{ multiplicity := 0, args := #[1] }] + } + let degs := sweepDegreesTotal rawBadCirc.nodes + let expectedDeg := deriveLookupDegree degs rawBadCirc.lookups rawBadCirc.lookupGroupSize + let badCirc := { rawBadCirc with maxConstraintDegree := expectedDeg } + let badSys := makeSelfConsistent floorParams #[badCirc] + itBool s!"negative: {label} in lookup prefix rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badSys.toBytes) "lookup prefix") + itBool s!"negative: {label} in lookup prefix rejected by checkSystem" + (!checkSystem badSys) + itBool s!"negative: {label} in lookup prefix rejected by checkLookupsPlain" + (!checkLookupsPlain badCirc) + let s2ZeroDirect : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .stage2 .current 0], zeros := #[0], lookups := #[] + } + let s2DirectSys := makeSelfConsistent floorParams #[s2ZeroDirect] + itBool "negative: stage-2 directly in zero constraint rejected by fromBytes" + (expectErr (StarkSystem.fromBytes s2DirectSys.toBytes) "stage-2") + itBool "negative: stage-2 directly in zero constraint rejected by checkSystem" + (!checkSystem s2DirectSys) + let s2ZeroIndirect : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .stage2 .current 0, .mul 0 0, .neg 1], zeros := #[2], lookups := #[] + } + let s2IndirectSys := makeSelfConsistent floorParams #[s2ZeroIndirect] + itBool "negative: stage-2 reachable from zero constraint rejected by fromBytes" + (expectErr (StarkSystem.fromBytes s2IndirectSys.toBytes) "stage-2") + itBool "negative: stage-2 reachable from zero constraint rejected by checkSystem" + (!checkSystem s2IndirectSys) + let selPubZeroCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .main .current 0, .isFirstRow, .mul 0 1, .publicInput 0, .add 2 3] + zeros := #[4], lookups := #[] + } + let selPubSys := makeSelfConsistent floorParams #[selPubZeroCirc] + itBool "positive: selectors and publics in zero constraints accepted" + (expectOkCheck selPubSys.toBytes checkSystem) + + -- 7. Preprocessed width/height consistency & power-of-two height + let badPrepW : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 0 } + let badPrepWSys := makeSelfConsistent floorParams #[badPrepW] + itBool "negative: preprocessedWidth > 0 with preprocessedHeight == 0 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badPrepWSys.toBytes) "preprocessed_width") + itBool "negative: preprocessedWidth > 0 with preprocessedHeight == 0 rejected by checkSystem" + (!checkSystem badPrepWSys) + let dummyRoot : D := base.vkDigest + let badPrepH : SysCircuit := { trivialCirc with preprocessedWidth := 0, preprocessedHeight := 4 } + let badPrepHSys := makeSelfConsistent floorParams #[badPrepH] (some #[dummyRoot]) #[some 0] + itBool "negative: preprocessedWidth == 0 with preprocessedHeight > 0 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badPrepHSys.toBytes) "preprocessed_width") + itBool "negative: preprocessedWidth == 0 with preprocessedHeight > 0 rejected by checkSystem" + (!checkSystem badPrepHSys) + let nonPotPrepH : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 3 } + let nonPotSys := makeSelfConsistent floorParams #[nonPotPrepH] (some #[dummyRoot]) #[some 0] + itBool "negative: non-power-of-two preprocessedHeight rejected by fromBytes" + (expectErr (StarkSystem.fromBytes nonPotSys.toBytes) "power of two") + itBool "negative: non-power-of-two preprocessedHeight rejected by checkSystem" + (!checkSystem nonPotSys) + + -- 8. Canonical ConstBig encodings + for badVal in ([0, 1, 0xFFFF, Goldilocks.order, Goldilocks.order + 1, 0xFFFFFFFFFFFFFFFF] : List Nat) do + let badBytes := rawSingleNodeConstBigKey badVal false + itBool s!"negative: non-canonical ConstBig {badVal} rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badBytes) "non-canonical") + for goodVal in ([0x10000, Goldilocks.order - 1] : List Nat) do + let goodBytes := rawSingleNodeConstBigKey goodVal true + itBool s!"positive: canonical ConstBig {goodVal} accepted and round-trips" + (expectOkCheck goodBytes fun s => checkSystem s && s.toBytes == goodBytes) + + -- 9. Node index bounds, topological order, trailer, nonzero capHeight LDE check, PoW cap, EOF + let oobPubSys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.publicInput 12], zeros := #[] }] + itBool "negative: OOB Public(12) rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobPubSys.toBytes) "out of bounds") + itBool "negative: OOB Public(12) rejected by checkSystem" + (!checkSystem oobPubSys) + let oobMainSys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.var .main .current 1], zeros := #[] }] + itBool "negative: OOB Main var rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobMainSys.toBytes) "out of bounds") + itBool "negative: OOB Main var rejected by checkSystem" + (!checkSystem oobMainSys) + let oobPrepSys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.var .preprocessed .current 0], zeros := #[] }] + itBool "negative: OOB Preprocessed var rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobPrepSys.toBytes) "out of bounds") + itBool "negative: OOB Preprocessed var rejected by checkSystem" + (!checkSystem oobPrepSys) + let oobS2Sys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.var .stage2 .current 3], zeros := #[] }] + itBool "negative: OOB Stage2 var rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobS2Sys.toBytes) "out of bounds") + itBool "negative: OOB Stage2 var rejected by checkSystem" + (!checkSystem oobS2Sys) + let oobZeroSys := makeSelfConsistent floorParams + #[{ trivialCirc with zeros := #[5] }] + itBool "negative: OOB zero root rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobZeroSys.toBytes) "out of bounds") + itBool "negative: OOB zero root rejected by checkSystem" + (!checkSystem oobZeroSys) + let nonTopoSys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.neg 0], zeros := #[] }] + itBool "negative: non-topological node rejected by fromBytes" + (expectErr (StarkSystem.fromBytes nonTopoSys.toBytes) "topological") + itBool "negative: non-topological node rejected by checkSystem" + (!checkSystem nonTopoSys) + + let missingCommitSys := { base with preprocessedCommit := none } + itBool "negative: missing preprocessed commitment rejected by fromBytes" + (expectErr (StarkSystem.fromBytes missingCommitSys.toBytes) "missing preprocessed commitment") + itBool "negative: missing preprocessed commitment rejected by checkSystem" + (!checkSystem missingCommitSys) + let extraCommitSys := makeSelfConsistent floorParams #[trivialCirc] (some #[dummyRoot]) #[none] + itBool "negative: extraneous preprocessed commitment rejected by fromBytes" + (expectErr (StarkSystem.fromBytes extraCommitSys.toBytes) "no preprocessed circuits") + itBool "negative: extraneous preprocessed commitment rejected by checkSystem" + (!checkSystem extraCommitSys) + let badRankSys := { base with preprocessedIndices := #[none, some 1] } + itBool "negative: non-canonical preprocessed rank rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badRankSys.toBytes) "rank") + itBool "negative: non-canonical preprocessed rank rejected by checkSystem" + (!checkSystem badRankSys) + let missingIdxSys := { base with preprocessedIndices := #[none, none] } + itBool "negative: missing preprocessed index rejected by fromBytes" + (expectErr (StarkSystem.fromBytes missingIdxSys.toBytes) "preprocessed_height") + itBool "negative: missing preprocessed index rejected by checkSystem" + (!checkSystem missingIdxSys) + for capN in ([0, 2, 3] : List Nat) do + let badCapSys := { base with preprocessedCommit := some (Array.replicate capN dummyRoot) } + itBool s!"negative: malformed preprocessed cap len {capN} rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badCapSys.toBytes) "roots") + itBool s!"negative: malformed preprocessed cap len {capN} rejected by checkSystem" + (!checkSystem badCapSys) + + -- Nonzero cap_height LDE root count check (height 2, logBlowup 2 => LDE log 3, capHeight 2 => 4 roots) + let prep2Circ : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 2 } + let cap2Params := { floorParams with capHeight := 2 } + let cap2GoodSys := makeSelfConsistent cap2Params #[prep2Circ] (some (Array.replicate 4 dummyRoot)) #[some 0] + let cap2BadSys := makeSelfConsistent cap2Params #[prep2Circ] (some (Array.replicate 2 dummyRoot)) #[some 0] + itBool "nonzero capHeight validates against preprocessed LDE height (4 roots ok, checkSystem rejects)" + (expectOkCheck cap2GoodSys.toBytes fun s => !checkSystem s) + itBool "negative: nonzero capHeight with unblown root count (2 roots) rejected by fromBytes" + (expectErr (StarkSystem.fromBytes cap2BadSys.toBytes) "roots") + + let badCommitPowSys := { base with params := { base.params with commitPowBits := 33 } } + let badQueryPowSys := { base with params := { base.params with queryPowBits := 33 } } + itBool "negative: commitPowBits > 32 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badCommitPowSys.toBytes) "exceeds") + itBool "negative: commitPowBits > 32 rejected by checkSystemWithFloor(true)" + (!checkSystemWithFloor badCommitPowSys true) + itBool "negative: queryPowBits > 32 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badQueryPowSys.toBytes) "exceeds") + itBool "negative: queryPowBits > 32 rejected by checkSystemWithFloor(true)" + (!checkSystemWithFloor badQueryPowSys true) + itBool "negative: trailing byte rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (baseFloorBytes.push 0)) "trailing") + itBool "negative: truncated key rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (baseFloorBytes.extract 0 (baseFloorBytes.size - 1))) "eof") end DecoderParity @@ -560,75 +562,78 @@ height assertion of `StarkVerifier::ood_loop` before any other circuit's out-of-domain check. -/ private def prepFirstHeightMutants : List Nat := [0, 1, 3, 4] -def suite : IO (List TestSeq) := do +def suite : IO Spec := do let system ← loadRecursionSystem - let mut tests : TestSeq := .done - for (name, dir, hasInactivePrep) in fixtures do + let loaded ← fixtures.mapM fun (name, dir, hasInactivePrep) => do let sys ← IO.FS.readBinFile (dir / "system.bin") let prf ← IO.FS.readBinFile (dir / "proof.bin") let clm ← IO.FS.readBinFile (dir / "claims.bin") - if hasInactivePrep then - -- Strict active-preprocessed invariant: `select_active_prep` rejects shards that - -- deactivate a circuit with a fixed preprocessed table. - let ok ← checkProof system sys clm prf - tests := tests ++ test s!"{name}: strict active-preprocessed check rejects inactive fixed table" - (!ok) - else - let ok ← checkProof system sys clm prf - tests := tests ++ test s!"{name}: valid Protocol v6 Fp^3 Rust proof accepted by Aiur verifier" ok - -- Negative control 1: flip a byte near the end of the proof (FRI/MMCS payload) - let badPrf1 := flipByte prf (prf.size - 17) - tests := tests ++ test s!"{name}: tampered proof tail rejected" - (!(← checkProof system sys clm badPrf1)) - -- Negative control 2: flip a byte in the proof header/length prefix - let badPrf2 := flipByte prf (min 12 (prf.size - 1)) - tests := tests ++ test s!"{name}: tampered proof header rejected" - (!(← checkProof system sys clm badPrf2)) - -- Negative control 3: flip a byte in claims.bin - let badClm := flipByte clm (clm.size - 1) - tests := tests ++ test s!"{name}: tampered claims rejected" - (!(← checkProof system sys badClm prf)) - -- Negative control 4: truncated proof rejected without panicking - let truncPrf := prf.extract 0 (prf.size / 2) - tests := tests ++ test s!"{name}: truncated proof rejected" - (!(← checkProof system sys clm truncPrf)) - -- Negative control 5: Protocol v5 header downgrade rejected fail-closed - let v5Sys := setU16LE sys 0 5 - tests := tests ++ test s!"{name}: Protocol v5 downgrade rejected fail-closed" - (!(← checkProof system v5Sys clm prf)) - -- Negative control 6: Fp^2 (extension_degree = 2) header downgrade rejected fail-closed - let fp2Sys := setU16LE sys 2 2 - tests := tests ++ test s!"{name}: Fp^2 (ext_degree=2) downgrade rejected fail-closed" - (!(← checkProof system fp2Sys clm prf)) - -- Negative control 7: FriBatching::Horner (tag 0) downgrade rejected fail-closed - let hornerSys := setU16LE sys 4 0 - tests := tests ++ test s!"{name}: FriBatching::Horner downgrade rejected fail-closed" - (!(← checkProof system hornerSys clm prf)) - -- Negative control 8: a fixed table at a height other than its own is rejected. + return (name, hasInactivePrep, sys, prf, clm) let pfDir : System.FilePath := "Tests/Fixtures/MultiStark/prep_first" let pfSys ← IO.FS.readBinFile (pfDir / "system.bin") let pfClm ← IO.FS.readBinFile (pfDir / "claims.bin") - for ld in prepFirstHeightMutants do + let pfMutants ← prepFirstHeightMutants.mapM fun ld => do let bad ← IO.FS.readBinFile (pfDir / s!"logdeg_{ld}" / "proof.bin") - tests := tests ++ test - s!"prep_first: fixed table of 4 rows at log degree {ld} rejected (height binding)" - (!(← checkProof system pfSys pfClm bad)) - -- Negative control 9: non-zero commit PoW witness when commit_pow_bits == 0 is rejected. + return (ld, bad) let npDir : System.FilePath := "Tests/Fixtures/MultiStark/single_no_prep" let npSys ← IO.FS.readBinFile (npDir / "system.bin") let npClm ← IO.FS.readBinFile (npDir / "claims.bin") let badCpowPrf ← IO.FS.readBinFile (npDir / "nonzero_cpow" / "proof.bin") - tests := tests ++ test - "single_no_prep: nonzero commit PoW witness when commit_pow_bits == 0 rejected" - (!(← checkProof system npSys npClm badCpowPrf)) - -- Negative control 10: natively valid below-floor proof rejected in-circuit. let lowDir : System.FilePath := npDir / "below_floor" let lowSys ← IO.FS.readBinFile (lowDir / "system.bin") let lowClm ← IO.FS.readBinFile (lowDir / "claims.bin") let lowPrf ← IO.FS.readBinFile (lowDir / "proof.bin") - tests := tests ++ test - "single_no_prep/below_floor: natively valid below-floor proof rejected in-circuit" - (!(← checkProof system lowSys lowClm lowPrf)) - return [tests] ++ (← admissibilitySuite) ++ (← decoderParitySuite) + let admissibility ← admissibilitySuite + let decoderParity ← decoderParitySuite + return do + for (name, hasInactivePrep, sys, prf, clm) in loaded do + if hasInactivePrep then + -- Strict active-preprocessed invariant: `select_active_prep` rejects shards that + -- deactivate a circuit with a fixed preprocessed table. + it s!"{name}: strict active-preprocessed check rejects inactive fixed table" do + expectFalse (← checkProof system sys clm prf) + else + it s!"{name}: valid Protocol v6 Fp^3 Rust proof accepted by Aiur verifier" do + expect (← checkProof system sys clm prf) + -- Negative control 1: flip a byte near the end of the proof (FRI/MMCS payload) + it s!"{name}: tampered proof tail rejected" do + let badPrf1 := flipByte prf (prf.size - 17) + expectFalse (← checkProof system sys clm badPrf1) + -- Negative control 2: flip a byte in the proof header/length prefix + it s!"{name}: tampered proof header rejected" do + let badPrf2 := flipByte prf (min 12 (prf.size - 1)) + expectFalse (← checkProof system sys clm badPrf2) + -- Negative control 3: flip a byte in claims.bin + it s!"{name}: tampered claims rejected" do + let badClm := flipByte clm (clm.size - 1) + expectFalse (← checkProof system sys badClm prf) + -- Negative control 4: truncated proof rejected without panicking + it s!"{name}: truncated proof rejected" do + let truncPrf := prf.extract 0 (prf.size / 2) + expectFalse (← checkProof system sys clm truncPrf) + -- Negative control 5: Protocol v5 header downgrade rejected fail-closed + it s!"{name}: Protocol v5 downgrade rejected fail-closed" do + let v5Sys := setU16LE sys 0 5 + expectFalse (← checkProof system v5Sys clm prf) + -- Negative control 6: Fp^2 (extension_degree = 2) header downgrade rejected fail-closed + it s!"{name}: Fp^2 (ext_degree=2) downgrade rejected fail-closed" do + let fp2Sys := setU16LE sys 2 2 + expectFalse (← checkProof system fp2Sys clm prf) + -- Negative control 7: FriBatching::Horner (tag 0) downgrade rejected fail-closed + it s!"{name}: FriBatching::Horner downgrade rejected fail-closed" do + let hornerSys := setU16LE sys 4 0 + expectFalse (← checkProof system hornerSys clm prf) + -- Negative control 8: a fixed table at a height other than its own is rejected. + for (ld, bad) in pfMutants do + it s!"prep_first: fixed table of 4 rows at log degree {ld} rejected (height binding)" do + expectFalse (← checkProof system pfSys pfClm bad) + -- Negative control 9: non-zero commit PoW witness when commit_pow_bits == 0 is rejected. + it "single_no_prep: nonzero commit PoW witness when commit_pow_bits == 0 rejected" do + expectFalse (← checkProof system npSys npClm badCpowPrf) + -- Negative control 10: natively valid below-floor proof rejected in-circuit. + it "single_no_prep/below_floor: natively valid below-floor proof rejected in-circuit" do + expectFalse (← checkProof system lowSys lowClm lowPrf) + admissibility + decoderParity end Tests.Ix.MultiStarkVerifier diff --git a/Tests/Ix/ResourceHints.lean b/Tests/Ix/ResourceHints.lean index e3ddf1a0d3..5863a0043f 100644 --- a/Tests/Ix/ResourceHints.lean +++ b/Tests/Ix/ResourceHints.lean @@ -89,16 +89,15 @@ def compiledVerdicts : IO (Array String × Array String) := do lines := lines ++ ls return (errors, lines) -def report (name : String) (action : IO (Array String × Array String)) : TestSeq := - .individualIO name none (do +def report (name : String) (action : IO (Array String × Array String)) : Spec := + it name do let (errors, lines) ← action for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate (errors.toList.take 20)) - return (errors.isEmpty, 1, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate (errors.toList.take 20)) -def suite : List TestSeq := [ - report "the typing half's verdict on the compiled fixtures" fixtureVerdict, +def suite : LSpec.Spec := do + report "the typing half's verdict on the compiled fixtures" fixtureVerdict report "actual typing verdicts: an ordinary contract input, an assumption axiom, unsafe inductives" - compiledVerdicts] + compiledVerdicts end Tests.ResourceHints diff --git a/Tests/Ix/ResourceModes.lean b/Tests/Ix/ResourceModes.lean index 797d90ff75..aca5dddbd1 100644 --- a/Tests/Ix/ResourceModes.lean +++ b/Tests/Ix/ResourceModes.lean @@ -38,7 +38,9 @@ such types (the mode-repair branch, V7). -/ namespace Tests.ResourceModes -open IxCK.Resource Ixon +open IxCK.Resource Ixon LSpec + +set_option compiler.extract_closed false /-! ## A small library -/ @@ -163,7 +165,7 @@ def noArgs : Heap × List Val := (({} : HB).heap, []) def noExtern : ExternOracle := fun _ _ _ => none -def outcomeName : Outcome → String +def outcomeName : IxCK.Resource.Outcome → String | .value .. => "a value" | .violation k => s!"violation {repr k}" | .stuck => "stuck" @@ -179,8 +181,8 @@ value, or the violation), and the checker accepts exactly when `accept`. -/ def runCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input : Heap × List Val) (run : Option Violation) (accept : Bool) (toCheck : List Ref := [entry]) (lim : Limits := {}) (ext : ExternOracle := noExtern) : - LSpec.TestSeq := - .individualIO label none (do + Spec := + it label do let P := prog defs let o := runR P ext 100000 entry input.1 input.2 let runOk := match o, run with @@ -194,20 +196,20 @@ def runCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input | .violation _ => false | _ => true let msg := s!"run: {outcomeName o}; checker: {verdictName verdict}" - return (runOk && checkOk && consistent, 0, 0, if runOk && checkOk && consistent then none else some msg)) .done + expect (runOk && checkOk && consistent) msg /-- Run `entry` on `input` (an ill-typed input): the run is stuck, which is not a violation, and the checker accepts exactly when `accept`. -/ def stuckCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input : Heap × List Val) - (accept : Bool) (toCheck : List Ref := [entry]) : LSpec.TestSeq := - .individualIO label none (do + (accept : Bool) (toCheck : List Ref := [entry]) : LSpec.Spec := + it label do let P := prog defs let o := runR P noExtern 100000 entry input.1 input.2 let runOk := match o with | .stuck => true | _ => false let verdict := checkBodies {} P toCheck let checkOk := verdict.isAccept == accept let msg := s!"run: {outcomeName o}; checker: {verdictName verdict}" - return (runOk && checkOk, 0, 0, if runOk && checkOk then none else some msg)) .done + expect (runOk && checkOk) msg /-! ### Erased binders and fields -/ @@ -221,19 +223,18 @@ def idOf := mem 103 -- `let (@erased x) := xs; len x` def eraseLet := mem 104 -def erasedCases : List LSpec.TestSeq := [ +def erasedCases : LSpec.Spec := do runCase "erased: reading an erased parameter" [(useErased, body [par .erased .leaf] - (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] useErased irrArg (some .erasedRead) false, + (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] useErased irrArg (some .erasedRead) false runCase "erased: an erased parameter never read" [(keepE, body [par .erased .leaf, par] - (v 0))] keepE irrAndList none true, + (v 0))] keepE irrAndList none true runCase "erased: projecting an erased field" [(leak, body [par] (.proj K 0 (v 0) .leaf) .shared .leaf)] - leak oneKey (some .erasedRead) false, + leak oneKey (some .erasedRead) false runCase "erased: projecting a kept field" [(idOf, body [par] (.proj K 1 (v 0) .leaf) .shared .leaf)] - idOf oneKey none true, + idOf oneKey none true runCase "erased: reading an erased let" [(eraseLet, body [par] (.letE (.value .erased) .val (v 0) (lenOf (v 0))) .shared .leaf)] eraseLet oneList (some .erasedRead) false -] /-! ### Unique transfer -/ @@ -248,45 +249,44 @@ def boxS := mem 117 def boxI := mem 118 def twiceN := mem 119 -def uniqueCases : List LSpec.TestSeq := [ +def uniqueCases : LSpec.Spec := do -- `twice (@unique xs) := consume xs + consume xs` runCase "unique: a binding transferred twice" [(twice, body [par .unique] (add (app (.const consumeR .val) [v 0] .leaf) (app (.const consumeR .val) [v 0] .leaf)) .shared .leaf)] - twice oneList (some .revokedUse) false, + twice oneList (some .revokedUse) false runCase "unique: a binding transferred once" [(once1, body [par .unique] - (app (.const consumeR .val) [v 0] .leaf) .shared .leaf)] once1 oneList none true, + (app (.const consumeR .val) [v 0] .leaf) .shared .leaf)] once1 oneList none true -- `share1 (xs : List) := consume xs`; `caller (xs) := share1 xs + len xs` runCase "unique: a shared parameter given away, then read by its caller" [(share1, body [par] (app (.const consumeR .val) [v 0] .leaf) .shared .leaf), (caller, body [par] (add (app (.const share1 .val) [v 0] .leaf) (lenOf (v 0))) .shared .leaf)] - caller oneList (some .revokedUse) false [share1, caller], + caller oneList (some .revokedUse) false [share1, caller] -- `headU (@unique xs) := match xs with | [] => 0 | _ :: t => len t` runCase "unique: a consuming match, the fields used" [(headU, body [par .unique] - (onList (v 0) (.natLit 0) (lenOf (v 0)) .val .leaf) .shared .leaf)] headU oneList none true, + (onList (v 0) (.natLit 0) (lenOf (v 0)) .val .leaf) .shared .leaf)] headU oneList none true -- `headBad (@unique xs) := match xs with | [] => 0 | _ :: _ => len xs` runCase "unique: a consumed major read in an alternative" [(headBad, body [par .unique] (onList (v 0) (.natLit 0) (lenOf (v 2)) .val .leaf) .shared .leaf)] headBad oneList - (some .revokedUse) false, + (some .revokedUse) false -- `deep (@unique xs) := match xs with | [] => 0 | h :: t => consume (h :: t) + len t` runCase "unique: deep transfer revokes the fields" [(deep, body [par .unique] (onList (v 0) (.natLit 0) (add (app (.const consumeR .val) [app (.const consR .val) [.irr, v 1, v 0]] .leaf) (lenOf (v 0))) .val .leaf) - .shared .leaf)] deep oneList (some .revokedUse) false, + .shared .leaf)] deep oneList (some .revokedUse) false -- `boxS (@unique x : List) := let s := ⟨x⟩ : S; consumeS s + len x` (a `@shared` field stops deep uniqueness; -- `x` must be `@unique`, not plain: a plain parameter may be caller-borrowed so `consumeS ⟨x⟩` would escape) runCase "unique: a @shared field stops deep uniqueness" [(boxS, body [par .unique] (.letE (.value .many) .val (app (.const sboxR .val) [v 0]) - (add (app (.const consumeSR .val) [v 0] .leaf) (lenOf (v 1)))) .shared .leaf)] boxS oneList none true, + (add (app (.const consumeSR .val) [v 0] .leaf) (lenOf (v 1)))) .shared .leaf)] boxS oneList none true -- `boxI (x : List) := let s := ⟨x⟩ : B; consumeB s + len x` (an inherited field) runCase "unique: an inherited field is transferred with its box" [(boxI, body [par] (.letE (.value .many) .val (app (.const boxR .val) [v 0]) (add (app (.const consumeBR .val) [v 0] .leaf) (lenOf (v 1)))) .shared .leaf)] boxI oneList - (some .revokedUse) false, + (some .revokedUse) false -- `twiceN (@unique n : Nat) := consumeN n + consumeN n` (a leaf is never unique) runCase "unique: a leaf transferred twice" [(twiceN, body [par .unique .leaf] (add (app (.const consumeNR .val) [v 0 .leaf] .leaf) (app (.const consumeNR .val) [v 0 .leaf] .leaf)) .shared .leaf)] twiceN oneNat none true -] /-! ### Borrows -/ @@ -303,58 +303,56 @@ def headN := mem 129 def storeN := mem 132 def shf := mem 133 -def borrowCases : List LSpec.TestSeq := [ +def borrowCases : LSpec.Spec := do runCase "borrow: a borrowed parameter returned" [(esc, body [par .borrowed] (v 0))] esc oneList - (some .borrowEscape) false, + (some .borrowEscape) false -- refused after repair A (the leaf-result refinement dropped, findings 1 to 3); accepted again -- under the leaf ruling L1 (a number is never confined): `len`'s leaf result carries no region. runCase "borrow: a borrowed parameter read" [(peek, body [par .borrowed] (lenOf (v 0)) .shared .leaf)] - peek oneList none true, + peek oneList none true runCase "borrow: a borrowed parameter returned borrowed" [(same, body [par .borrowed] (v 0) .borrowed)] - same oneList none true, + same oneList none true -- `stash (@borrowed b : List) : List := [b]` runCase "borrow: a borrowed parameter stored in a cell" [(stash, body [par .borrowed] (app (.const consR .val) [.irr, v 0, app (.const nilR .val) [.irr] .imm]))] stash oneList - (some .borrowEscape) false, + (some .borrowEscape) false runCase "borrow: a borrowed parameter given away" [(give, body [par .borrowed] - (app (.const consumeR .val) [v 0] .leaf) .shared .leaf)] give oneList (some .borrowEscape) false, + (app (.const consumeR .val) [v 0] .leaf) .shared .leaf)] give oneList (some .borrowEscape) false runCase "borrow: a let's loan returned" [(letEsc, body [par] (.letE .borrow .val (v 0) (v 0)))] - letEsc oneList (some .borrowEscape) false, + letEsc oneList (some .borrowEscape) false -- refused after repair A, accepted again under L1: `len x` carries no region of the let's. runCase "borrow: a let's loan read" [(letOk, body [par] (.letE .borrow .val (v 0) (lenOf (v 0))) - .shared .leaf)] letOk oneList none true, + .shared .leaf)] letOk oneList none true -- under L1 a borrowed number is not confined: the run returns it and the checker accepts -- (before L1, borrowEscape and a refusal) runCase "borrow: a borrowed leaf returned" [(escN, body [par .borrowed .leaf] (v 0 .leaf) .shared .leaf)] - escN oneNat none true, + escN oneNat none true runCase "borrow: arithmetic on a borrowed leaf" [(addN, body [par .borrowed .leaf] - (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] addN oneNat none true, + (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] addN oneNat none true -- `headN (@borrowed xs : List Nat) : Nat := match xs with | [] => 0 | h :: _ => h` runCase "borrow: a leaf read out of a borrowed container is not confined" [(headN, body [par .borrowed] - (onList (v 0) (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] headN oneList none true, + (onList (v 0) (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] headN oneList none true -- `storeN (@borrowed n : Nat) : Nat := match [n] with | [] => 0 | h :: _ => h` runCase "borrow: a borrowed leaf stored in a cell and read back is a counted value" [(storeN, body [par .borrowed .leaf] (onList (app (.const consR .val) [.irr, v 0 .leaf, app (.const nilR .val) [.irr] .imm]) - (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] storeN oneNat none true, + (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] storeN oneNat none true -- `shf (@borrowed b : List) : List := (⟨b⟩ : S).1` (a borrowed value in a `@shared` field) runCase "borrow: a borrowed value stored in a @shared field and returned" [(shf, body [par .borrowed] (.proj S 0 (app (.const sboxR .val) [v 0]) .val))] shf oneList (some .borrowEscape) false -] /-! ### Once -/ def twiceCall := mem 130 def onceCall := mem 131 -def onceCases : List LSpec.TestSeq := [ +def onceCases : LSpec.Spec := do runCase "once: a once parameter called twice" [(twiceCall, body [par .once .val arrowSk] (add (app (v 0) [.natLit 1] .leaf) (app (v 0) [.natLit 2] .leaf)) .shared .leaf)] twiceCall oneFun - (some .onceReentry) false, + (some .onceReentry) false runCase "once: a once parameter called once" [(onceCall, body [par .once .val arrowSk] (app (v 0) [.natLit 1] .leaf) .shared .leaf)] onceCall oneFun none true -] /-! ### Captures and partial applications -/ @@ -363,25 +361,24 @@ def capOuter := mem 141 def capPlain := mem 142 def papT := mem 143 -def captureCases : List LSpec.TestSeq := [ +def captureCases : LSpec.Spec := do -- `capOnce (@unique xs) := let g := fun u => consume xs; g 0 + g 1` runCase "capture: a closure consuming its capture called twice" [(capOnce, body [par .unique] (.letE (.value .many) .val (lam (par .many .leaf) (app (.const consumeR .val) [v 1] .leaf) .shared .leaf) (add (app (v 0) [.natLit 0] .leaf) (app (v 0) [.natLit 1] .leaf))) .shared .leaf)] capOnce oneList - (some .revokedUse) false, + (some .revokedUse) false -- `capOuter (@unique xs) := let g := fun u => len xs; len xs` runCase "capture: a unique binding captured, then read outside" [(capOuter, body [par .unique] (.letE (.value .many) .val (lam (par .many .leaf) (lenOf (v 1)) .shared .leaf) (lenOf (v 1))) - .shared .leaf)] capOuter oneList (some .revokedUse) false, + .shared .leaf)] capOuter oneList (some .revokedUse) false -- `capPlain (xs : List) := let g := fun u => len xs; g 0 + len xs` runCase "capture: a shared binding captured and read" [(capPlain, body [par] (.letE (.value .many) .val (lam (par .many .leaf) (lenOf (v 1)) .shared .leaf) - (add (app (v 0) [.natLit 0] .leaf) (lenOf (v 1)))) .shared .leaf)] capPlain oneList none true, + (add (app (v 0) [.natLit 0] .leaf) (lenOf (v 1)))) .shared .leaf)] capPlain oneList none true -- `papT (@unique xs) := let g := consume2 xs; len xs` runCase "capture: a partial application transfers its unique argument" [(papT, body [par .unique] (.letE (.value .many) .val (app (.const consume2R .val) [v 0]) (lenOf (v 1))) .shared .leaf)] papT oneList (some .revokedUse) false -] /-! ### Skeletons and statics -/ @@ -390,37 +387,36 @@ def callUseOk := mem 151 def badStatic := mem 152 def okStatic := mem 153 -def skeletonCases : List LSpec.TestSeq := [ +def skeletonCases : LSpec.Spec := do -- `callUse (xs) := use (fun (@unique y) => consume y) xs` runCase "skeleton: a closure with a unique binder at a plain arrow" [(callUse, body [par] (app (.const useR .val) [lam (par .unique) (app (.const consumeR .val) [v 0] .leaf) .shared .leaf, v 0] .leaf) - .shared .leaf)] callUse oneList (some .revokedUse) false, + .shared .leaf)] callUse oneList (some .revokedUse) false runCase "skeleton: a closure with a plain binder at a plain arrow" [(callUseOk, body [par] (app (.const useR .val) [lam (par .many) (lenOf (v 0)) .shared .leaf, v 0] .leaf) .shared .leaf)] - callUseOk oneList none true, + callUseOk oneList none true -- `badStatic := consume tbl + len tbl` runCase "static: a static given away, then read" [(badStatic, body [] (add (app (.const consumeR .val) [.const tblR .val] .leaf) (lenOf (.const tblR .val))) .shared .leaf)] badStatic - noArgs (some .revokedUse) false, + noArgs (some .revokedUse) false runCase "static: a static read twice" [(okStatic, body [] (add (lenOf (.const tblR .val)) (lenOf (.const tblR .val))) .shared .leaf)] okStatic noArgs none true -] /-! ### Limits and the fast path -/ /-- A step limit declines. -/ -def limitCase : LSpec.TestSeq := - .individualIO "limits: the step limit declines" none (do +def limitCase : LSpec.Spec := do + it "limits: the step limit declines" do let verdict := checkBodies { steps := 3 } (prog []) [lenR] let ok := match verdict with | .decline _ => true | _ => false - return (ok, 0, 0, if ok then none else some (verdictName verdict))) .done + expect ok (verdictName verdict) /-- A closure of default records is accepted without reading; an annotated axiom is read and refused outside the extern set, accepted inside it. -/ -def fastPathCase : LSpec.TestSeq := - .individualIO "fast path and externs: default records unread; an annotated axiom only as an extern" none (do +def fastPathCase : LSpec.Spec := do + it "fast path and externs: default records unread; an annotated axiom only as an extern" do let plain : Ixon.Constant := { info := .axio ⟨false, 0, .sort 0⟩, sharing := #[], refs := #[], univs := #[.zero] } let moded : Ixon.Constant := @@ -437,8 +433,7 @@ def fastPathCase : LSpec.TestSeq := let ok := (match v1 with | .accept 0 true => true | _ => false) && (match v2 with | .refuse _ w => (w.splitOn "not in the extern set").length > 1 | _ => false) && (match v3 with | .accept _ false => true | _ => false) - return (ok, 0, 0, if ok then none else - some s!"{verdictName v1}; {verdictName v2}; {verdictName v3}")) .done + expect ok s!"{verdictName v1}; {verdictName v2}; {verdictName v3}" /-! ### Must-reject cases: an erased field at an alternative -/ @@ -451,19 +446,18 @@ def altConst := mem 161 def secondOf := mem 162 def altLam := mem 163 -def alternativeCases : List LSpec.TestSeq := [ +def alternativeCases : LSpec.Spec := do -- `firstOf (a : List) (b : Nat) : List := a`; `altConst (k : Key) := Key.casesOn k firstOf` runCase "must-reject: an erased field passed to an alternative that is not a λ" [ (firstOf, body [par, par .many .leaf] (v 1)), (altConst, body [par] (.case caseK (v 0) #[.const firstOf .val] #[] .val))] - altConst oneKey (some .erasedRead) false, + altConst oneKey (some .erasedRead) false -- `secondOf (b : Nat) : Nat := b`; `altLam (k : Key) := Key.casesOn k (fun (@erased g) => secondOf)` runCase "erased: a λ alternative binds the erased field, the rest passed on" [ (secondOf, body [par .many .leaf] (v 0 .leaf) .shared .leaf), (altLam, body [par] (.case caseK (v 0) #[lam (par .erased) (.const secondOf .val) .shared .leaf] #[] .leaf) .shared .leaf)] altLam oneKey none true -] /-! ### Findings of the mode study (REPLY-2-TO-IXVM.md §4), with their controls @@ -984,8 +978,8 @@ are out of fuel up to some fuel and a value from there on (the evaluator spends fuel per step and does not change what it runs with it), and the checker accepts exactly when `accept`. -/ def fuelCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input : Heap × List Val) - (fuels : List Nat) (accept : Bool) (toCheck : List Ref := [entry]) : LSpec.TestSeq := - .individualIO label none (do + (fuels : List Nat) (accept : Bool) (toCheck : List Ref := [entry]) : LSpec.Spec := + it label do let P := prog defs let os := fuels.map fun f => runR P noExtern f entry input.1 input.2 let rest := os.dropWhile fun o => match o with | .outOfFuel => true | _ => false @@ -993,218 +987,217 @@ def fuelCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input let verdict := checkBodies {} P toCheck let checkOk := verdict.isAccept == accept let msg := s!"runs: {", ".intercalate (os.map outcomeName)}; checker: {verdictName verdict}" - return (runOk && checkOk, 0, 0, if runOk && checkOk then none else some msg)) .done + expect (runOk && checkOk) msg -def findingCases : List LSpec.TestSeq := [ +def findingCases : LSpec.Spec := do runCase "finding 1: a borrowed number through a call of `Nat → Nat` (its parameter read as no-leaf)" [idNDef true, (g4, body [par .borrowed .leaf] (app (.const idN .val) [v 0 .leaf] .leaf) .shared .leaf)] - g4 oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted + g4 oneNat none true -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 1, control: the parameter not read as no-leaf" [idNDef false, (g4, body [par .borrowed .leaf] (app (.const idN .val) [v 0 .leaf] .leaf) .shared .leaf)] - g4 oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted + g4 oneNat none true -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 1, control: the result returned borrowed" [idNDef true, (g4b, body [par .borrowed .leaf] (app (.const idN .val) [v 0 .leaf] .leaf) .borrowed .leaf)] - g4b oneNat none true, + g4b oneNat none true runCase "finding 2: a borrowed number captured by a closure passed at a function type" [app1Def true, (g3, body [par .borrowed .leaf] (app (.const app1 .val) [lam (par .many .leaf) (v 1 .leaf) .shared .leaf] .leaf) .shared .leaf)] - g3 oneNat none true [g3, app1], -- L1 W1: borrowEscape before -- L1: accepted + g3 oneNat none true [g3, app1] -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 2, control: the parameter not read as no-leaf" [app1Def false, (g3, body [par .borrowed .leaf] (app (.const app1 .val) [lam (par .many .leaf) (v 1 .leaf) .shared .leaf] .leaf) .shared .leaf)] - g3 oneNat none true [g3, app1], -- L1 W1: borrowEscape before -- L1: accepted + g3 oneNat none true [g3, app1] -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 2, control: the captured number not borrowed" [app1Def true, (g3p, body [par .many .leaf] (app (.const app1 .val) [lam (par .many .leaf) (v 1 .leaf) .shared .leaf] .leaf) .shared .leaf)] - g3p oneNat none true [g3p, app1], + g3p oneNat none true [g3p, app1] runCase "finding 3: a borrowed number cast to a list under an absurd hypothesis" (eqDefs ++ [(g2, body [par .many .irr, par .many .irr, par .borrowed .leaf] (app (.const bad3 .val) [.irr, .case caseEq .irr #[v 0 .leaf] #[] .val] .leaf) .shared .leaf)]) - g2 in3 none true [g2, bad3], -- L1 W1: borrowEscape before -- L1: accepted + g2 in3 none true [g2, bad3] -- L1 W1: borrowEscape before -- L1: accepted fuelCase "finding 7: a call of six arguments, the third erased, at every fuel from 0 to 12" - p7Defs gV in7 fuels0to12 true [gV, fV], - fuelCase "finding 7, control: the erased parameter first" p7xDefs gXV in7x fuels0to12 true [gXV, fXV], + p7Defs gV in7 fuels0to12 true [gV, fV] + fuelCase "finding 7, control: the erased parameter first" p7xDefs gXV in7x fuels0to12 true [gXV, fXV] runCase "finding 8: a unique list stored twice in one cell, the cell given away" [(dup, body [par .unique] (app (.const consumeR .val) [app (.const consR .val) [.irr, v 0, v 0]] .leaf) - .shared .leaf)] dup oneList (some .revokedUse) false, + .shared .leaf)] dup oneList (some .revokedUse) false runCase "finding 8: a unique list stored in a cell and in a cell inside it, the cell given away" [(dup2, body [par .unique] (app (.const consumeR .val) [app (.const consR .val) [.irr, v 0, app (.const consR .val) [.irr, v 0, app (.const nilR .val) [.irr] .imm]]] .leaf) .shared .leaf)] - dup2 oneList (some .revokedUse) false, + dup2 oneList (some .revokedUse) false runCase "finding 8, control: two unique lists in one cell, the cell given away" [(pairOk, body [par .unique, par .unique] (app (.const consumeR .val) [app (.const consR .val) [.irr, v 1, v 0]] .leaf) .shared .leaf)] - pairOk twoLists none true, + pairOk twoLists none true runCase "finding 9: a closure capturing a borrowed list, applied, its result returned" [(g5, body [par .borrowed] (.letE (.value .many) .val (lam (par .many .leaf) (v 1) .shared .val) - (app (v 0) [.natLit 0])))] g5 oneList (some .borrowEscape) false, + (app (v 0) [.natLit 0])))] g5 oneList (some .borrowEscape) false runCase "finding 9, control: the list not borrowed" [(g5p, body [par] (.letE (.value .many) .val (lam (par .many .leaf) (v 1) .shared .val) - (app (v 0) [.natLit 0])))] g5p oneList none true, + (app (v 0) [.natLit 0])))] g5p oneList none true runCase "finding 13: a function value applied to a borrowed list, then to its consumption" - p13Defs use13 in13 (some .revokedUse) false [use13, kk], + p13Defs use13 in13 (some .revokedUse) false [use13, kk] runCase "a partial application of a function value at a unique binder, called twice" (kcDefs ++ [(d1, body [par .many .val skU, par .unique] (.letE (.value .many) .val (app (v 1) [v 0] .val) (add (app (v 0) [.natLit 1] .leaf) (app (v 0) [.natLit 2] .leaf))) .shared .leaf)]) - d1 inD1 (some .revokedUse) false, + d1 inD1 (some .revokedUse) false runCase "a partial application of a once-only partial application, called twice" (kcDefs ++ [(d2, body [par .unique] (.letE (.value .many) .val (app (.const kc3 .val) [v 0] .val) (.letE (.value .many) .val (app (v 0) [.natLit 1] .val) (add (app (v 0) [.natLit 2] .leaf) (app (v 0) [.natLit 3] .leaf)))) .shared .leaf)]) - d2 oneList (some .revokedUse) false, + d2 oneList (some .revokedUse) false -- refused since repair D though the runs are clean: the result's aliases include the moved -- argument (d1h) or the consumed once-only binding (d2h) runCase "a function value at a unique binder applied to all its arguments (refused, runs clean)" (kcDefs ++ [(d1h, body [par .many .val skU, par .unique] (app (v 1) [v 0, .natLit 1] .leaf) .shared .leaf)]) - d1h inD1 none false, + d1h inD1 none false runCase "a once-only partial application applied to all its remaining arguments (refused, runs clean)" (kcDefs ++ [(d2h, body [par .unique] (.letE (.value .many) .val (app (.const kc3 .val) [v 0] .val) (app (v 0) [.natLit 1, .natLit 2] .leaf)) .shared .leaf)]) - d2h oneList none false, + d2h oneList none false runCase "a spine longer than the checker's depth left at it: a borrowed list stored in a @shared field" - s6Defs g6 oneList (some .borrowEscape) false [g6] { depth := 6 }, - runCase "the same at the default depth" s6Defs g6 oneList (some .borrowEscape) false, - runCase "the same, the list not borrowed, at depth 6" s6Defs g6p oneList none true [g6p] { depth := 6 }, + s6Defs g6 oneList (some .borrowEscape) false [g6] { depth := 6 } + runCase "the same at the default depth" s6Defs g6 oneList (some .borrowEscape) false + runCase "the same, the list not borrowed, at depth 6" s6Defs g6p oneList none true [g6p] { depth := 6 } runCase "finding 10: a closure consuming its capture, lent to a body that calls it twice" (onceDefs ++ [(bad10, body [par .unique] (app (.const callTwice .val) [consumeClo] .leaf) .shared .leaf)]) - bad10 oneList (some .revokedUse) false [bad10, callTwice], + bad10 oneList (some .revokedUse) false [bad10, callTwice] runCase "finding 10: a closure consuming its capture, aliased by a let, both called" [(alias10, body [par .unique] (.letE (.value .many) .val consumeClo (.letE (.value .many) .val (v 0) (add (app (v 0) [.natLit 0] .leaf) (app (v 1) [.natLit 0] .leaf)))) - .shared .leaf)] alias10 oneList (some .revokedUse) false, + .shared .leaf)] alias10 oneList (some .revokedUse) false runCase "finding 10, control: the closure passed to a once parameter" (onceDefs ++ [(ok10, body [par .unique] (app (.const callOnce .val) [consumeClo] .leaf) .shared .leaf)]) - ok10 oneList none true [ok10, callOnce], + ok10 oneList none true [ok10, callOnce] runCase "finding 11: a once parameter passed to a body that calls it twice" (onceDefs ++ [(h11, body [par .once .val arrowSk] (app (.const callTwice .val) [v 0] .leaf) .shared .leaf)]) - h11 oneFun (some .onceReentry) false [h11, callTwice], + h11 oneFun (some .onceReentry) false [h11, callTwice] runCase "finding 11, control: a once parameter passed to a once parameter" (onceDefs ++ [(ok11, body [par .once .val arrowSk] (app (.const callOnce .val) [v 0] .leaf) .shared .leaf)]) - ok11 oneFun none true [ok11, callOnce], + ok11 oneFun none true [ok11, callOnce] runCase "finding 12: a primitive's partial application holding a borrowed number, returned" [(addB, body [par .borrowed .leaf] (app (.const addR .val) [v 0 .leaf] .val) .shared .val arrowSk)] - addB oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted + addB oneNat none true -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 12, control: the number not borrowed" [(addP, body [par .many .leaf] (app (.const addR .val) [v 0 .leaf] .val) .shared .val arrowSk)] - addP oneNat none true, + addP oneNat none true runCase "finding 16: a case's two extra arguments, the second consuming the first" (p16Defs ++ [(use16, body [par .many .val sk16, par .unique, par .many .imm] (.case caseE (v 0 .imm) #[v 2, v 2] #[v 1, app (.const consumeR .val) [v 1] .leaf] .leaf) .shared .leaf)]) - use16 in16 (some .revokedUse) false [use16, kk16], + use16 in16 (some .revokedUse) false [use16, kk16] runCase "finding 16, control: the extra arguments a plain list and a number" (p16Defs ++ [(use16p, body [par .many .val sk16, par .many, par .many .imm] (.case caseE (v 0 .imm) #[v 2, v 2] #[v 1, .natLit 1] .leaf) .shared .leaf)]) - use16p in16 none true [use16p, kk16], + use16p in16 none true [use16p, kk16] runCase "a once parameter stored in a cell, the cell lent to a body that calls the field twice" [useBoxDef, (bad11b, body [par .once .val arrowSk] (app (.const useBox .val) [app (.const boxR .val) [v 0]] .leaf) - .shared .leaf)] bad11b oneFun (some .onceReentry) false [bad11b, useBox], + .shared .leaf)] bad11b oneFun (some .onceReentry) false [bad11b, useBox] runCase "the same, the parameter plain" [useBoxDef, (ok11b, body [par .many .val arrowSk] (app (.const useBox .val) [app (.const boxR .val) [v 0]] .leaf) - .shared .leaf)] ok11b oneFun none true [ok11b, useBox], + .shared .leaf)] ok11b oneFun none true [ok11b, useBox] runCase "a once parameter returned by a case alternative, the case's value lent to a body that calls it twice" (onceDefs ++ p16Defs ++ [(retAlt, body [par .once .val arrowSk, par .many .imm] retAltBody .shared .leaf)]) - retAlt funAndE0 (some .onceReentry) false, + retAlt funAndE0 (some .onceReentry) false runCase "the same, the parameter plain" (onceDefs ++ p16Defs ++ [(retAltP, body [par .many .val arrowSk, par .many .imm] retAltBody .shared .leaf)]) - retAltP funAndE0 none true, + retAltP funAndE0 none true runCase "a once parameter returned, the result called twice by the caller" [(retF, body [par .once .val arrowSk] (v 0) .shared .val arrowSk), (useRet, body [par .once .val arrowSk] (useRetBody retF) .shared .leaf)] - useRet oneFun (some .onceReentry) false [useRet, retF], + useRet oneFun (some .onceReentry) false [useRet, retF] runCase "the same, the parameter plain" [(retP, body [par .many .val arrowSk] (v 0) .shared .val arrowSk), (useRetP, body [par .many .val arrowSk] (useRetBody retP) .shared .leaf)] - useRetP oneFun none true [useRetP, retP], + useRetP oneFun none true [useRetP, retP] runCase "a once parameter passed to two once parameters" (onceDefs ++ [(twiceOnce, body [par .once .val arrowSk] twiceOnceBody .shared .leaf)]) - twiceOnce oneFun (some .onceReentry) false [twiceOnce, callOnce], + twiceOnce oneFun (some .onceReentry) false [twiceOnce, callOnce] runCase "the same, the parameter plain" (onceDefs ++ [(twiceOnceP, body [par .many .val arrowSk] twiceOnceBody .shared .leaf)]) - twiceOnceP oneFun none true [twiceOnceP, callOnce], - runCase "finding 17: a borrowed number bound at a unique let, returned" oDefs u17a oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted - runCase "finding 17, control: the number not borrowed" oDefs u17ap oneNat none true, + twiceOnceP oneFun none true [twiceOnceP, callOnce] + runCase "finding 17: a borrowed number bound at a unique let, returned" oDefs u17a oneNat none true -- L1 W1: borrowEscape before -- L1: accepted + runCase "finding 17, control: the number not borrowed" oDefs u17ap oneNat none true runCase "finding 17: a borrowed number through a unique result of class leaf" oDefs u17b oneNat - none true [u17b, idU], -- L1 W1: borrowEscape before -- L1: accepted + none true [u17b, idU] -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 17: a borrowed number through a polymorphic unique result" oDefs u17c oneNat - none true [u17c, idUP], -- L1 W1: borrowEscape before -- L1: accepted - runCase "finding 17, control: the number not borrowed" oDefs u17cp oneNat none true [u17cp, idUP], + none true [u17c, idUP] -- L1 W1: borrowEscape before -- L1: accepted + runCase "finding 17, control: the number not borrowed" oDefs u17cp oneNat none true [u17cp, idUP] runCase "finding 17: a borrowed wrapper of a number matched, its field bound unique and returned" oDefs u17d oneNat - none true, -- L1 W1: borrowEscape before -- L1: accepted - runCase "finding 17, control: the wrapper not borrowed" oDefs u17dp oneNat none true, + none true -- L1 W1: borrowEscape before -- L1: accepted + runCase "finding 17, control: the wrapper not borrowed" oDefs u17dp oneNat none true runCase "finding 18: a borrowed list stored in a @shared field by a callee, projected" - [mkSBDef, (leak18, body [par .borrowed] projSB)] leak18 oneList (some .borrowEscape) false [leak18, mkSB], + [mkSBDef, (leak18, body [par .borrowed] projSB)] leak18 oneList (some .borrowEscape) false [leak18, mkSB] runCase "finding 18, control: the list not borrowed" - [mkSBDef, (leak18p, body [par] projSB)] leak18p oneList none true [leak18p, mkSB], + [mkSBDef, (leak18p, body [par] projSB)] leak18p oneList none true [leak18p, mkSB] runCase "finding 18: the same field matched" - [mkSBDef, (leak18m, body [par .borrowed] matchSB)] leak18m oneList (some .borrowEscape) false [leak18m, mkSB], + [mkSBDef, (leak18m, body [par .borrowed] matchSB)] leak18m oneList (some .borrowEscape) false [leak18m, mkSB] runCase "finding 18, control: the list not borrowed" - [mkSBDef, (leak18mp, body [par] matchSB)] leak18mp oneList none true [leak18mp, mkSB], + [mkSBDef, (leak18mp, body [par] matchSB)] leak18mp oneList none true [leak18mp, mkSB] runCase "a borrowed list retained by a call whose result is unique" (uDefs ++ [(leakU, body [par .borrowed] isSBmk .shared .imm)]) leakU oneList (some .borrowEscape) false - [leakU, mkSBU, isSB], + [leakU, mkSBU, isSB] runCase "the same, the list unique (mkSBUU)" - (uDefs ++ [(leakUp, body [par .unique] isSBmkU .shared .imm)]) leakUp oneList none true [leakUp, mkSBUU, isSB], + (uDefs ++ [(leakUp, body [par .unique] isSBmkU .shared .imm)]) leakUp oneList none true [leakUp, mkSBUU, isSB] runCase "pre-proof Fix 2 (evil6): plain param wrapped in @shared field and consumed uniquely" - preProofDefs evil6 oneList (some .borrowEscape) false [evil6, inner6], + preProofDefs evil6 oneList (some .borrowEscape) false [evil6, inner6] runCase "pre-proof Repair U + extern (mkWeird): borrowed arg to .unique extern with @shared field" - preProofDefs leakWeirdU oneList (some .borrowEscape) false [leakWeirdU] {} extWeirdU, + preProofDefs leakWeirdU oneList (some .borrowEscape) false [leakWeirdU] {} extWeirdU runCase "pre-proof Repair U + extern control: @unique arg to .unique extern with @shared field" - preProofDefs okWeirdU oneList none true [okWeirdU] {} extWeirdU, + preProofDefs okWeirdU oneList none true [okWeirdU] {} extWeirdU runCase "pre-proof Fix 3 (evil10): closure returning unique capture at .unique called twice" - preProofDefs evil10 oneList (some .revokedUse) false [evil10], + preProofDefs evil10 oneList (some .revokedUse) false [evil10] runCase "pre-proof Fix 3 control: closure returning unique capture at .unique called once" - preProofDefs ok10r oneList none true [ok10r], + preProofDefs ok10r oneList none true [ok10r] runCase "pre-proof Fix 4 (evil5d): multi-arg PAP via applyValue loses onceOnly" - preProofDefs stepOnce5 inG3 (some .revokedUse) false [stepOnce5, g3Fix], + preProofDefs stepOnce5 inG3 (some .revokedUse) false [stepOnce5, g3Fix] runCase "pre-proof Fix 4 (evil5j): multi-arg @once PAP via applyValue called twice" - preProofDefs stepOnceF5 inGOnce (some .onceReentry) false [stepOnceF5, gOnce5], + preProofDefs stepOnceF5 inGOnce (some .onceReentry) false [stepOnceF5, gOnce5] runCase "pre-proof Fix 6a: .prim PAP on borrowed .val arg refused" - preProofDefs primPap6 oneList (some .borrowEscape) false [primPap6], + preProofDefs primPap6 oneList (some .borrowEscape) false [primPap6] runCase "pre-proof Fix 7 (anCase killSrc): once-only closure returned from case alt called again via binding" - preProofDefs evilCaseOnce7 inCaseOnce7 (some .revokedUse) false [evilCaseOnce7], + preProofDefs evilCaseOnce7 inCaseOnce7 (some .revokedUse) false [evilCaseOnce7] runCase "pre-proof Fix 7 control: once-only closure returned from case alt called once" - preProofDefs okCaseOnce7 inCaseOnce7 none true [okCaseOnce7], + preProofDefs okCaseOnce7 inCaseOnce7 none true [okCaseOnce7] runCase "pre-proof Fix 8 (anAlt borrowed rename): .borrowed alt lambda renames closing region" - preProofDefs evilAltBor8 oneNat (some .borrowEscape) false [evilAltBor8], + preProofDefs evilAltBor8 oneNat (some .borrowEscape) false [evilAltBor8] runCase "pre-proof Fix 8 control: .borrowed alt lambda returned @borrowed" - preProofDefs okAltBor8 oneNat none true [okAltBor8], + preProofDefs okAltBor8 oneNat none true [okAltBor8] runCase "pre-proof Fix 9a (applyValue valid after callResult): borrowed capture revoked by @unique arg" - preProofDefs evil9a oneList (some .revokedUse) false [evil9a, mkId2_9a], + preProofDefs evil9a oneList (some .revokedUse) false [evil9a, mkId2_9a] runCase "pre-proof Fix 9a (curried PAP): ((f0 0) u) u revoked by @unique arg" - preProofDefs evil9aPap oneList (some .revokedUse) false [evil9aPap, f0Curried9a], + preProofDefs evil9aPap oneList (some .revokedUse) false [evil9aPap, f0Curried9a] runCase "pre-proof Fix 9b (callResult post-loop valid): @borrowed precedes @unique on same binding" - preProofDefs evil9b oneList (some .revokedUse) false [evil9b, borUniq9b], + preProofDefs evil9b oneList (some .revokedUse) false [evil9b, borUniq9b] runCase "pre-proof Fix 9b (lendPlain): plain precedes @unique on same binding (leaf result)" - preProofDefs evil9bLend oneList (some .revokedUse) false [evil9bLend, plainUniq9b], + preProofDefs evil9bLend oneList (some .revokedUse) false [evil9bLend, plainUniq9b] runCase "pre-proof Fix 9b control: distinct bindings at plain + @unique params" - preProofDefs ok9b twoLists none true [ok9b, plainUniq9b], + preProofDefs ok9b twoLists none true [ok9b, plainUniq9b] runCase "pre-proof Fix 10 (evil11): 2-hop .arrow -> .unknown -> .data under @unique arrow" - preProofDefs pfSeed11 oneList (some .revokedUse) false [pfSeed11, pfEvil11, pfEvil11b, pfG2_11], + preProofDefs pfSeed11 oneList (some .revokedUse) false [pfSeed11, pfEvil11, pfEvil11b, pfG2_11] runCase "pre-proof Fix 10 (evil10): 2-hop .arrow -> .unknown -> .data through @once param" - preProofDefs pfSeed10 oneList (some .revokedUse) false [pfSeed10, pfEvil10a, pfEvil10b, pfG3_10], + preProofDefs pfSeed10 oneList (some .revokedUse) false [pfSeed10, pfEvil10a, pfEvil10b, pfG3_10] runCase "pre-proof Fix 10 (evil12): contravariant 2-hop .arrow -> .unknown -> .data in @once domain" - preProofDefs pfSeed12 oneList (some .revokedUse) false [pfSeed12, pfHop1_12, pfHop2_12, pfEvil10b, pfG3_10], + preProofDefs pfSeed12 oneList (some .revokedUse) false [pfSeed12, pfHop1_12, pfHop2_12, pfEvil10b, pfG3_10] runCase "pre-proof Fix 10 control: @once (Nat -> List) called with non-arrow-returning onceOnly closure" - preProofDefs pfOkOnce10 oneList none true [pfOkOnce10, pfEvil10b], + preProofDefs pfOkOnce10 oneList none true [pfOkOnce10, pfEvil10b] runCase "pre-proof Fix 11 (evil13): local shared dep dropped by anCase deps.filter demotes own" - preProofDefs pfEvil13 pfInBoolTrue (some .revokedUse) false [pfEvil13], + preProofDefs pfEvil13 pfInBoolTrue (some .revokedUse) false [pfEvil13] runCase "pre-proof Fix 11 control: distinct local bindings in Weird.mk" - preProofDefs pfOk13 pfInBoolTrue none true [pfOk13], + preProofDefs pfOk13 pfInBoolTrue none true [pfOk13] runCase "pre-proof Fix 11 control: anAlt @unique return clears killed deps" - preProofDefs pfOkAltUniq oneList none true [pfOkAltUniq], + preProofDefs pfOkAltUniq oneList none true [pfOkAltUniq] runCase "pre-proof Fix 12 (exploitProj): @shared projection keeps container deps across borrow lend" - preProofDefs pfEvil14Proj oneList (some .revokedUse) false [pfEvil14Proj, pfWrap14, pfMkWrap14], + preProofDefs pfEvil14Proj oneList (some .revokedUse) false [pfEvil14Proj, pfWrap14, pfMkWrap14] runCase "pre-proof Fix 12 (exploitCase): @shared caseField keeps container deps across borrow lend" - preProofDefs pfEvil14Case oneList (some .revokedUse) false [pfEvil14Case, pfWrap14, pfMkWrap14], + preProofDefs pfEvil14Case oneList (some .revokedUse) false [pfEvil14Case, pfWrap14, pfMkWrap14] runCase "pre-proof Fix 12 control: consuming match on @unique @shared-field struct" - preProofDefs pfOk14Consume oneList none true [pfOk14Consume, pfWrap14, pfMkWrap14], + preProofDefs pfOk14Consume oneList none true [pfOk14Consume, pfWrap14, pfMkWrap14] runCase "pre-proof Fix 13 (evil15): multi-field anCtor with outer .imm cls still returns .val" - preProofDefs pfEvil15 oneList (some .borrowEscape) false [pfEvil15], + preProofDefs pfEvil15 oneList (some .borrowEscape) false [pfEvil15] runCase "pre-proof Fix 13 control: distinct @unique fields in multi-field ctor" - preProofDefs pfOk15 twoLists none true [pfOk15], - stuckCase "finding 15: an input cell's Nat field holding a list, read by a case" p15Defs g15 in15 true [g15, mkK], + preProofDefs pfOk15 twoLists none true [pfOk15] + stuckCase "finding 15: an input cell's Nat field holding a list, read by a case" p15Defs g15 in15 true [g15, mkK] runCase "finding 15, control: a well-typed input" p15Defs g15 in15ok none true [g15, mkK] -] /-! ### Must-reject cases from records -/ @@ -1523,29 +1516,27 @@ def v8CensusOf (b : Built) : Nat × List String × List String × List String × else if pre != post then changed := changed ++ [nm] return (total, preList, postList, gained, lost, changed) -def recordCasesTest : LSpec.TestSeq := - .individualIO "must-reject cases from records: case definitions, primitives, recursors, quotients, \ - η-short interfaces" none (do - match ← buildFixture with - | .error e => return (false, 0, 0, some s!"the fixture: {e}") - | .ok b => - let mut allOk := true - let mut failed : Array String := #[] - for c in recordCases do - let (ok, line) := match runRecCase b c with - | .ok r => r - | .error e => (false, s!"{c.label}: {e}") - IO.println s!" {if ok then "ok" else "FAIL"} {line}" - unless ok do - allOk := false - failed := failed.push line - let (total, preL, postL, gained, lost, changed) := v8CensusOf b - let censusOk := lost.isEmpty && changed.isEmpty - IO.println s!" {if censusOk then "ok" else "FAIL"} V8 census (ResourceModesFixture): {total} refs, pre={preL.length} {preL}, post={postL.length} {postL}, +gained={gained}, -lost={lost}, ~changed={changed}" - unless censusOk do +def recordCasesTest : LSpec.Spec := do + it "must-reject cases from records: case definitions, primitives, recursors, quotients, \ + η-short interfaces" do + let b ← expectOk ((← buildFixture).mapError (s!"the fixture: {·}")) + let mut allOk := true + let mut failed : Array String := #[] + for c in recordCases do + let (ok, line) := match runRecCase b c with + | .ok r => r + | .error e => (false, s!"{c.label}: {e}") + IO.println s!" {if ok then "ok" else "FAIL"} {line}" + unless ok do allOk := false - failed := failed.push s!"V8 census (ResourceModesFixture): lost={lost} changed={changed}" - return (allOk, 0, 0, if allOk then none else some ("; ".intercalate failed.toList))) .done + failed := failed.push line + let (total, preL, postL, gained, lost, changed) := v8CensusOf b + let censusOk := lost.isEmpty && changed.isEmpty + IO.println s!" {if censusOk then "ok" else "FAIL"} V8 census (ResourceModesFixture): {total} refs, pre={preL.length} {preL}, post={postL.length} {postL}, +gained={gained}, -lost={lost}, ~changed={changed}" + unless censusOk do + allOk := false + failed := failed.push s!"V8 census (ResourceModesFixture): lost={lost} changed={changed}" + expect allOk ("; ".intercalate failed.toList) /-! ### Recursive, mutual, nested and indexed types from records (the mode-repair branch, V7 & V8) @@ -1588,28 +1579,26 @@ def recTypeCases : List RecCase := [ reads := true, accept := true, natValue := some 2 } ] -def recTypeCasesTest : LSpec.TestSeq := - .individualIO "recursive, mutual, nested and indexed types from records: the class oracle answers" none (do - match ← buildFixtureAt "Tests/Ix/ResourceModesRecFixture.lean" recFixtureSeeds with - | .error e => return (false, 0, 0, some s!"the fixture: {e}") - | .ok b => - let mut allOk := true - let mut failed : Array String := #[] - for c in recTypeCases do - let (ok, line) := match runRecCase b c with - | .ok r => r - | .error e => (false, s!"{c.label}: {e}") - IO.println s!" {if ok then "ok" else "FAIL"} {line}" - unless ok do - allOk := false - failed := failed.push line - let (total, preL, postL, gained, lost, changed) := v8CensusOf b - let censusOk := lost.isEmpty && changed.isEmpty && gained.any fun s => (s.splitOn "ModeRecFixture.V.casesOn").length > 1 - IO.println s!" {if censusOk then "ok" else "FAIL"} V8 census (ResourceModesRecFixture): {total} refs, pre={preL.length} {preL}, post={postL.length} {postL}, +gained={gained}, -lost={lost}, ~changed={changed}" - unless censusOk do +def recTypeCasesTest : LSpec.Spec := do + it "recursive, mutual, nested and indexed types from records: the class oracle answers" do + let b ← expectOk ((← buildFixtureAt "Tests/Ix/ResourceModesRecFixture.lean" recFixtureSeeds).mapError (s!"the fixture: {·}")) + let mut allOk := true + let mut failed : Array String := #[] + for c in recTypeCases do + let (ok, line) := match runRecCase b c with + | .ok r => r + | .error e => (false, s!"{c.label}: {e}") + IO.println s!" {if ok then "ok" else "FAIL"} {line}" + unless ok do allOk := false - failed := failed.push s!"V8 census (ResourceModesRecFixture): gained={gained} lost={lost} changed={changed}" - return (allOk, 0, 0, if allOk then none else some ("; ".intercalate failed.toList))) .done + failed := failed.push line + let (total, preL, postL, gained, lost, changed) := v8CensusOf b + let censusOk := lost.isEmpty && changed.isEmpty && gained.any fun s => (s.splitOn "ModeRecFixture.V.casesOn").length > 1 + IO.println s!" {if censusOk then "ok" else "FAIL"} V8 census (ResourceModesRecFixture): {total} refs, pre={preL.length} {preL}, post={postL.length} {postL}, +gained={gained}, -lost={lost}, ~changed={changed}" + unless censusOk do + allOk := false + failed := failed.push s!"V8 census (ResourceModesRecFixture): gained={gained} lost={lost} changed={changed}" + expect allOk ("; ".intercalate failed.toList) /-! ### Annotated Lean source compile, closure completeness, `DefAsserts`, and `0x04` diagnostics -/ @@ -1985,12 +1974,10 @@ def runAnnotatedCompileSuite : IO (Array String) := do errs := errs.push s!"readErased: expected erasedRead, got: {e}" return errs -def annotatedCompileCasesTest : LSpec.TestSeq := - .individualIO "annotated Lean source compile: positive modes, 2-variant shared λ, strip/apply, tier retry, must-rejects" - none (do - let errs ← runAnnotatedCompileSuite - return (errs.isEmpty, 0, 0, - if errs.isEmpty then none else some ("; ".intercalate errs.toList))) .done +def annotatedCompileCasesTest : LSpec.Spec := do + it "annotated Lean source compile: positive modes, 2-variant shared λ, strip/apply, tier retry, must-rejects" do + let errs ← runAnnotatedCompileSuite + expect errs.isEmpty ("; ".intercalate errs.toList) def runCompletenessAndAssertsSuite : IO (Array String) := do let mut errs : Array String := #[] @@ -2150,12 +2137,10 @@ def runCompletenessAndAssertsSuite : IO (Array String) := do | _ => errs := errs.push "ModeFixture.k was not a standalone .defn" return errs -def completenessAndAssertsTest : LSpec.TestSeq := - .individualIO "closure completeness (`bindersComplete`, `modesCanonical`) and `DefAsserts` placement" - none (do - let errs ← runCompletenessAndAssertsSuite - return (errs.isEmpty, 0, 0, - if errs.isEmpty then none else some ("; ".intercalate errs.toList))) .done +def completenessAndAssertsTest : LSpec.Spec := do + it "closure completeness (`bindersComplete`, `modesCanonical`) and `DefAsserts` placement" do + let errs ← runCompletenessAndAssertsSuite + expect errs.isEmpty ("; ".intercalate errs.toList) def runUndecidedRoleDiagnosticSuite : IO (Array String) := do let mut errs : Array String := #[] @@ -2206,16 +2191,26 @@ def runUndecidedRoleDiagnosticSuite : IO (Array String) := do | _ => errs := errs.push "compileAndFinalize for bound diagnostic fixture failed" return errs -def undecidedRoleDiagnosticTest : LSpec.TestSeq := - .individualIO "diagnostic when unannotated (`0x04`) records meet the role table (`Ix.Typing`, `Ix.ModeCheck`)" - none (do - let errs ← runUndecidedRoleDiagnosticSuite - return (errs.isEmpty, 0, 0, - if errs.isEmpty then none else some ("; ".intercalate errs.toList))) .done - -public def suite : List LSpec.TestSeq := - erasedCases ++ uniqueCases ++ borrowCases ++ onceCases ++ captureCases ++ skeletonCases ++ - alternativeCases ++ findingCases ++ [limitCase, fastPathCase, recordCasesTest, recTypeCasesTest, - annotatedCompileCasesTest, completenessAndAssertsTest, undecidedRoleDiagnosticTest] +def undecidedRoleDiagnosticTest : LSpec.Spec := do + it "diagnostic when unannotated (`0x04`) records meet the role table (`Ix.Typing`, `Ix.ModeCheck`)" do + let errs ← runUndecidedRoleDiagnosticSuite + expect errs.isEmpty ("; ".intercalate errs.toList) + +public def suite : LSpec.Spec := do + erasedCases + uniqueCases + borrowCases + onceCases + captureCases + skeletonCases + alternativeCases + findingCases + limitCase + fastPathCase + recordCasesTest + recTypeCasesTest + annotatedCompileCasesTest + completenessAndAssertsTest + undecidedRoleDiagnosticTest end Tests.ResourceModes diff --git a/Tests/Ix/RoleArtifactConsumer.lean b/Tests/Ix/RoleArtifactConsumer.lean index d607ea4ca1..9a54596c2b 100644 --- a/Tests/Ix/RoleArtifactConsumer.lean +++ b/Tests/Ix/RoleArtifactConsumer.lean @@ -55,13 +55,47 @@ private def withBadCheat (env : Env) (falseAddress : Address) : Env × Address : let (env, address) := insert env bad (publish env "badCheat" address, address) -/-- The user-axiom path: strict by default, `--allow-user-axioms` conditional, -listed and without a host statement, and a binding that leaves `sorryAx` -unbound refused. Library entry points first, then the `ix` and -`kernel-check-ixe` binaries over every driver path, the read cache's included. -/ -private def userAxiomChecks (env tierEnv : Env) (generated : _root_.Ix.RoleBinding.Generated) - (ix kernel dir : System.FilePath) : IO Nat := do - let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } +private structure Fixture where + env : Env + tierEnv : Env + badEnv : Env + cheatEnv : Env + tierCheatEnv : Env + badCheatEnv : Env + generated : _root_.Ix.RoleBinding.Generated + proofAddress : Address + proof : Constant + tierOwner : Address + tierAddress : Address + cheatAddress : Address + useAddress : Address + badAddress : Address + bytes : ByteArray + tierBytes : ByteArray + badBytes : ByteArray + cheatBytes : ByteArray + badCheatBytes : ByteArray + tierCheatBytes : ByteArray + noSorry : ByteArray + ix : System.FilePath + kernel : System.FilePath + dir : System.FilePath + path : System.FilePath + tierPath : System.FilePath + badPath : System.FilePath + cheatPath : System.FilePath + tierCheatPath : System.FilePath + noSorryPath : System.FilePath + boundPath : System.FilePath + +private def buildFixture : IO Fixture := do + let (env, generated) ← IO.ofExcept (Tests.Ix.RoleGeneration.completeArtifact .natDiv) + let some (proofAddress, proof) := generated.evidence[0]? + | throw (IO.userError "fixture has no proof") + let (tierEnv, tierOwner, tierAddress) ← IO.ofExcept (withTier env proof) + let .defn definition := proof.info | throw (IO.userError "proof kind changed") + let badProof := { proof with info := .defn { definition with value := .var 0 } } + let (badEnv, _) := insert env badProof let some falseAddress := generated.table.addressOf? .false | throw (IO.userError "fixture has no False") let (cheatEnv, cheatAddress, useAddress) := withCheat env falseAddress let (tierCheatEnv, _, _) := withCheat tierEnv falseAddress @@ -72,145 +106,65 @@ private def userAxiomChecks (env tierEnv : Env) (generated : _root_.Ix.RoleBindi let noSorryBytes := noSorryTable.toBytes let noSorryEnv := { cheatEnv with roleBinding := some ⟨Address.admissionHash noSorryBytes, noSorryBytes⟩ } let bytes ← IO.ofExcept (serEnv env) + let tierBytes ← IO.ofExcept (serEnv tierEnv) + let badBytes ← IO.ofExcept (serEnv badEnv) let cheatBytes ← IO.ofExcept (serEnv cheatEnv) let badCheatBytes ← IO.ofExcept (serEnv badCheatEnv) let tierCheatBytes ← IO.ofExcept (serEnv tierCheatEnv) let noSorry ← IO.ofExcept (serEnv noSorryEnv) - for anon in [false, true] do - let strict ← checked (← prepareInput cheatBytes anon) - let r ← checked (← runPrepared strict cfg .all) - ensure (!r.failures.isEmpty && r.artifactAdmission.isNone && r.conditionalOn.isEmpty && - runExit r true == _root_.Ix.Benchmark.Results.exitRejected) - "strict checking admitted a user axiom" - let p ← checked (← prepareInput cheatBytes anon (allowUserAxioms := true)) - let r ← checked (← runPrepared p cfg .all) - ensure (r.failures.isEmpty && r.hostStatement.isNone && - r.artifactAdmission == some (.conditional cheatEnv.consts.size none #[cheatAddress]) && - runExit r true == exitConditional && runExit r true true == _root_.Ix.Benchmark.Results.exitUsage && - runStatus r true == "conditional") - s!"the conditional whole run is not reported as conditional on cheat: {repr r.artifactAdmission}" - let r ← checked (← runPrepared p cfg (.only #[if anon then toString useAddress else "useCheat"])) - ensure (r.failures.isEmpty && r.userAxioms == #[cheatAddress] && runExit r false == exitConditional && - runStatus r false == "conditional") - "a selected run through a user axiom is not conditional on it" - -- a user axiom the run reads and then rejects admits nothing: the run lists - -- only the user axioms whose records it accepted (`admittedUserAxioms`) - let pBad ← checked (← prepareInput badCheatBytes anon (allowUserAxioms := true)) - let r ← checked (← runPrepared pBad cfg (.only (if anon then #[toString useAddress, toString badAddress] - else #["useCheat", "badCheat"]))) - let bad := r.targets.filter (·.target.address == badAddress) - ensure (bad.size == 1 && bad.all (fun t => t.outcome == "reject" && !t.reason.startsWith "reader:") && - r.failures.size == 1 && r.userAxioms == #[cheatAddress] && runStatus r false == "rejected") - s!"a rejected user axiom was listed as admitted: {r.userAxioms}, {bad.map (·.reason)}" - let natDiv := if anon then toString (generated.table.addressOf? .natDiv).get! else "Nat.div" - let r ← checked (← runPrepared p cfg (.only #[natDiv])) - ensure (r.failures.isEmpty && r.userAxioms.isEmpty && runExit r false == 0) - "a selected run that reads no user axiom became conditional" - -- with no user axiom among the declarations, the one run under the flag is - -- the certified entry's (T1, `ReceiptConditional.toReceipt`): the same - -- verdict and host statement as a strict run - let strict ← checked (← runPrepared (← checked (← prepareInput bytes anon)) cfg .all) - let p ← checked (← prepareInput bytes anon (allowUserAxioms := true)) - let r ← checked (← runPrepared p cfg .all) - ensure (r.artifactAdmission == some (.logical env.consts.size) && r.hostStatement.isSome && - r.hostStatement == strict.hostStatement && r.artifactAdmission == strict.artifactAdmission && - runExit r true true == 0) "the flag replaced the certified entry on an artifact without user axioms" - match ← prepareInput noSorry anon (allowUserAxioms := true) with - | .error (.artifact message) => - ensure (message.contains "leaves sorryAx unbound") s!"wrong refusal: {message}" - | _ => throw (IO.userError "a binding without sorryAx admitted user axioms") - let p ← checked (← prepareInput tierCheatBytes true (allowUserAxioms := true)) - let r ← checked (← runPrepared p cfg .all) - ensure (r.artifactAdmission == some (.conditional tierCheatEnv.consts.size (some 1) #[cheatAddress])) - s!"the tiered conditional entry did not run: {repr r.artifactAdmission}" - -- and the tiered entry with no user axiom: the certified tiered receipt - -- (`TierReceiptConditional.toTierReceipt`) and the strict run's statement - let tierBytes ← IO.ofExcept (serEnv tierEnv) - let strict ← checked (← runPrepared (← checked (← prepareInput tierBytes true)) cfg .all) - let r ← checked (← runPrepared (← checked (← prepareInput tierBytes true (allowUserAxioms := true))) cfg .all) - ensure (r.artifactAdmission == some (.tiered tierEnv.consts.size 1) && - r.artifactAdmission == strict.artifactAdmission && r.hostStatement.isSome && - r.hostStatement == strict.hostStatement) - s!"the flag replaced the certified tiered entry: {repr r.artifactAdmission} vs {repr strict.artifactAdmission}" - -- meta mode checks the published names against the binding even when strict - match ← prepareInput noSorry with - | .error (.artifact message) => - ensure (message.contains "role binding") s!"wrong meta refusal: {message}" - | _ => throw (IO.userError "a published sorryAx left unbound passed meta preparation") + let ix ← IO.FS.realPath ".lake/build/bin/ix" + let kernel ← IO.FS.realPath ".lake/build/bin/kernel-check-ixe" + let dir ← IO.FS.createTempDir + let path := dir / "bound.ixe" + let tierPath := dir / "tier.ixe" + let badPath := dir / "invalid.ixe" let cheatPath := dir / "cheat.ixe" let tierCheatPath := dir / "tier-cheat.ixe" let noSorryPath := dir / "no-sorry.ixe" let boundPath := dir / "bound-axioms.ixe" - let unused := dir / "conditional.ixhc" + IO.FS.writeBinFile path bytes + IO.FS.writeBinFile tierPath tierBytes + IO.FS.writeBinFile badPath badBytes IO.FS.writeBinFile cheatPath cheatBytes IO.FS.writeBinFile tierCheatPath tierCheatBytes IO.FS.writeBinFile noSorryPath noSorry IO.FS.writeBinFile boundPath bytes - let vars := #[("IX_KERNEL_CHECK_PROGRESS_MS", some "0"), ("IX_KERNEL_CHECK_SLOW_MS", some "0")] - let listed := s!"[check-lean] {cheatAddress}" - let mut calls := 0 - for (file, args, code, texts) in [ - (cheatPath, #[], 3, #[]), - (cheatPath, #["--anon"], 3, #[]), - (cheatPath, #["--allow-user-axioms"], exitConditional, - #["whole artifact: CONDITIONAL on 1 user axioms:", s!"{listed} cheat", "no host statement"]), - (cheatPath, #["--anon", "--allow-user-axioms"], exitConditional, - #["whole artifact: CONDITIONAL on 1 user axioms:", listed]), - (cheatPath, #["--allow-user-axioms", "--consts", "useCheat"], exitConditional, - #["selected checking: CONDITIONAL on 1 user axioms:", s!"{listed} cheat"]), - (tierCheatPath, #["--anon", "--allow-user-axioms"], exitConditional, - #["whole artifact: CONDITIONAL on 1 user axioms:", "conditional logical entry and typing tier"]), - (cheatPath, #["--allow-user-axioms", "--host-out", unused.toString], 2, - #["CONDITIONAL on 1 user axioms and issues no host statement"]), - (boundPath, #["--allow-user-axioms"], 0, #["whole artifact: logical entry accepted all"]), - (noSorryPath, #["--anon", "--allow-user-axioms"], 3, #["leaves sorryAx unbound"]), - (noSorryPath, #[], 3, #["role binding"])] do - calls := calls + 1 - let out ← IO.Process.output { cmd := ix.toString, args := #["check-lean", file.toString] ++ args, env := vars } - let text := out.stdout ++ out.stderr - ensure (out.exitCode == code && texts.all (fun t => text.contains t) && - (code == 0 || !out.stdout.contains "accepted all")) - s!"user-axiom CLI control {args} failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" - ensure (!(← unused.pathExists)) "a conditional run wrote a host statement" - -- kernel-check-ixe: strict by default and conditional with the flag, on the - -- streamed, eager, pooled and read-cache paths alike - let rowsOf := fun (rowsPath : System.FilePath) => do - let mut rows : Std.HashMap String String := {} - for line in (← IO.FS.readFile rowsPath).splitOn "\n" do - if line.isEmpty then continue - let row ← IO.ofExcept (Lean.Json.parse line) - rows := rows.insert (← IO.ofExcept (row.getObjValAs? String "address")) - (← IO.ofExcept (row.getObjValAs? String "outcome")) - return rows - let cache := dir / "read-cache" - for (args, cached) in [(#["--load", "stream"], false), (#["--load", "eager", "--jobs", "2"], false), - (#["--jobs", "2"], true), (#[], true), (#["--load", "eager"], true)] do - for allow in [true, false] do - calls := calls + 1 - let rowsPath := dir / "cheat.jsonl" - let result ← IO.Process.output { - cmd := kernel.toString - args := #[cheatPath.toString, rowsPath.toString] ++ args ++ (if allow then #["--allow-user-axioms"] else #[]) - env := #[("CHECK_IXE_ROOTS", none), ("CHECK_IXE_SKIP", none), - ("CHECK_IXE_READ_CACHE", if cached then some cache.toString else none)] } - let rows ← rowsOf rowsPath - let label := s!"kernel-check-ixe {args} allow={allow}" - ensure (result.exitCode == 0 && rows.contains (toString cheatAddress) && rows.contains (toString useAddress)) - s!"{label} failed: {result.exitCode}\n{result.stderr}" - if allow then - ensure (rows.toList.all (·.2 == "accept") && - result.stderr.contains s!"CONDITIONAL on 1 user axioms:\n {cheatAddress}") - s!"{label} did not admit and list the user axiom\n{result.stderr}" - else - ensure (rows[toString cheatAddress]? != some "accept" && rows[toString useAddress]? != some "accept" && - !result.stderr.contains "CONDITIONAL") - s!"{label} admitted a user axiom while strict\n{result.stderr}" - ensure (← cache.pathExists) "the read cache was never written" - let refused ← IO.Process.output { - cmd := kernel.toString, args := #[noSorryPath.toString, (dir / "no-sorry.jsonl").toString, "--allow-user-axioms"] } - ensure (refused.exitCode == 2 && refused.stderr.contains "leaves sorryAx unbound") - s!"kernel-check-ixe admitted user axioms under a binding without sorryAx\n{refused.stderr}" - return calls + 1 + return { + env, tierEnv, badEnv, cheatEnv, tierCheatEnv, badCheatEnv, generated, + proofAddress, proof, tierOwner, tierAddress, cheatAddress, useAddress, badAddress, + bytes, tierBytes, badBytes, cheatBytes, badCheatBytes, tierCheatBytes, noSorry, + ix, kernel, dir, path, tierPath, badPath, cheatPath, tierCheatPath, noSorryPath, boundPath + } + +private def rowsOf (rowsPath : System.FilePath) : IO (Std.HashMap String String) := do + let mut rows : Std.HashMap String String := {} + for line in (← IO.FS.readFile rowsPath).splitOn "\n" do + if line.isEmpty then continue + let row ← IO.ofExcept (Lean.Json.parse line) + rows := rows.insert (← IO.ofExcept (row.getObjValAs? String "address")) + (← IO.ofExcept (row.getObjValAs? String "outcome")) + return rows + +private def checkKernelIxeUserAxioms (fx : Fixture) (args : Array String) + (cache? : Option System.FilePath) (allow : Bool) (outName : String) : IO Unit := do + let rowsPath := fx.dir / outName + let result ← IO.Process.output { + cmd := fx.kernel.toString + args := #[fx.cheatPath.toString, rowsPath.toString] ++ args ++ (if allow then #["--allow-user-axioms"] else #[]) + env := #[("CHECK_IXE_ROOTS", none), ("CHECK_IXE_SKIP", none), + ("CHECK_IXE_READ_CACHE", cache?.map (·.toString))] } + let rows ← rowsOf rowsPath + let label := s!"kernel-check-ixe {args} allow={allow}" + ensure (result.exitCode == 0 && rows.contains (toString fx.cheatAddress) && rows.contains (toString fx.useAddress)) + s!"{label} failed: {result.exitCode}\n{result.stderr}" + if allow then + ensure (rows.toList.all (·.2 == "accept") && + result.stderr.contains s!"CONDITIONAL on 1 user axioms:\n {fx.cheatAddress}") + s!"{label} did not admit and list the user axiom\n{result.stderr}" + else + ensure (rows[toString fx.cheatAddress]? != some "accept" && rows[toString fx.useAddress]? != some "accept" && + !result.stderr.contains "CONDITIONAL") + s!"{label} admitted a user axiom while strict\n{result.stderr}" private def orderedChecks (env tierEnv badEnv : Env) : IO Unit := do let prepared ← IO.ofExcept ((prepareRecords env artifactLimits).mapError toString) @@ -249,149 +203,256 @@ private def orderedChecks (env tierEnv badEnv : Env) : IO Unit := do !(checkTieredAt badEnv artifactLimits badOrder).isOk) "explicit-order admission accepted an invalid logical theorem" -private def checks : IO Nat := do - let (env, generated) ← IO.ofExcept (Tests.Ix.RoleGeneration.completeArtifact .natDiv) - let some (proofAddress, proof) := generated.evidence[0]? - | throw (IO.userError "fixture has no proof") - let (tierEnv, tierOwner, tierAddress) ← IO.ofExcept (withTier env proof) - let receipt ← IO.ofExcept ((checkTiered tierEnv artifactLimits).mapError toString) +private def tierFenceChecks (fx : Fixture) : IO Unit := do + let receipt ← IO.ofExcept ((checkTiered fx.tierEnv artifactLimits).mapError toString) ensure (!receipt.logical.consts.isEmpty && receipt.tier.length == 1) "the actual logical/tier fold did not accept the nonempty fixture" - ensure (receipt.prepared.records.length == tierEnv.consts.size && - receipt.prepared.binding.bytes == generated.table.toBytes) + ensure (receipt.prepared.records.length == fx.tierEnv.consts.size && + receipt.prepared.binding.bytes == fx.generated.table.toBytes) "tier receipt changed the actual binding or original raw batch" - ensure (!(check tierEnv artifactLimits).isOk) "logical-only entry accepted a partial definition" - let input ← IO.ofExcept ((prepareRecords tierEnv artifactLimits).mapError toString) + ensure (!(check fx.tierEnv artifactLimits).isOk) "logical-only entry accepted a partial definition" + let input ← IO.ofExcept ((prepareRecords fx.tierEnv artifactLimits).mapError toString) let (logical, tier) := _root_.Ix.Kernel.Admission.partitionTier input.constants let keys := logical.map (·.1) ++ tier.toList.map (fun (_, a, _) => a) ensure (keys.length == input.constants.length && keys.eraseDups.length == keys.length && input.constants.all (fun (a, _) => keys.contains a)) "partition lost or duplicated an original record" - ensure (tier.size == 2 && tier.any (fun (_, a, _) => a == tierOwner) && - tier.any (fun (_, a, _) => a == tierAddress)) "tier projection was not partitioned with its owner" - ensure (!(receipt.prepared.preludeFor { generated.table with bound := #[] }).isOk) + ensure (tier.size == 2 && tier.any (fun (_, a, _) => a == fx.tierOwner) && + tier.any (fun (_, a, _) => a == fx.tierAddress)) "tier projection was not partitioned with its owner" + ensure (!(receipt.prepared.preludeFor { fx.generated.table with bound := #[] }).isOk) "tier prelude accepted a different canonical table" - let some tierRaw := tierEnv.consts[tierOwner]? | throw (IO.userError "tier owner missing") + let some tierRaw := fx.tierEnv.consts[fx.tierOwner]? | throw (IO.userError "tier owner missing") let badRaw := { tierRaw with buf := ByteArray.mk #[0], off := 0, len := 1 } - ensure (match checkTiered { tierEnv with consts := tierEnv.consts.insert tierOwner badRaw } artifactLimits with + ensure (match checkTiered { fx.tierEnv with consts := fx.tierEnv.consts.insert fx.tierOwner badRaw } artifactLimits with | .error (.preparation (.bytes (.mismatch _ _ _))) => true | _ => false) "tier bytes escaped the authentication of the complete input" - ensure (match checkTiered { tierEnv with consts := tierEnv.consts.erase proofAddress } artifactLimits with + ensure (match checkTiered { fx.tierEnv with consts := fx.tierEnv.consts.erase fx.proofAddress } artifactLimits with | .error (.preparation (.coverage _)) => true | _ => false) "missing proof was supplied by a default evidence store" - let .defn definition := proof.info | throw (IO.userError "proof kind changed") - let fenced : Constant := { proof with - refs := proof.refs.push tierAddress - info := .defn { definition with kind := .defn, value := .ref proof.refs.size.toUInt64 #[] } } - let (fencedEnv, _) := insert tierEnv fenced + let .defn definition := fx.proof.info | throw (IO.userError "proof kind changed") + let fenced : Constant := { fx.proof with + refs := fx.proof.refs.push fx.tierAddress + info := .defn { definition with kind := .defn, value := .ref fx.proof.refs.size.toUInt64 #[] } } + let (fencedEnv, _) := insert fx.tierEnv fenced ensure (match checkTiered fencedEnv artifactLimits with | .error (.admission (.fence _ _)) => true | _ => false) "logical reference to tier escaped the fence" +private def inProcessWholeCheck (fx : Fixture) (anon : Bool) : IO Unit := do let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } - let bytes ← IO.ofExcept (serEnv env) - let tierBytes ← IO.ofExcept (serEnv tierEnv) - for anon in [false, true] do - let p ← checked (← prepareInput bytes anon) - let logical ← checked (← runPrepared p cfg .all) - ensure (logical.failures.isEmpty && logical.artifactAdmission == some (.logical env.consts.size)) - "bound whole check did not run the actual logical entry" - ensure (logical.hostStatement.any (·.kind == .logical)) - "bound whole check omitted its receipt-derived host statement" - ensure (logical.rows.isEmpty && logical.execution == .serial) - "default quiet whole check did not take the single-pass checkWhole fast path" - let logicalFull ← checked (← runPrepared p { cfg with perRecord := true } .all) - ensure (logical.artifactAdmission == logicalFull.artifactAdmission && - logical.hostStatement == logicalFull.hostStatement && - logical.passed == logicalFull.passed && logical.typed == logicalFull.typed && - logical.targetsCovered == logicalFull.targetsCovered && - logical.roles == logicalFull.roles && !logicalFull.rows.isEmpty) - "single-pass whole check disagreed with per-record pool check" - let selected := if anon then toString (generated.table.addressOf? .natDiv).get! else "Nat.div" - let selected ← checked (← runPrepared p cfg (.only #[selected])) - ensure (selected.failures.isEmpty && selected.artifactAdmission.isNone && selected.hostStatement.isNone) - "selected proof-backed operation lost actual evidence or claimed whole admission" - let capped ← checked (← runPrepared p cfg .all (some 1)) - ensure (capped.artifactAdmission.isNone && capped.hostStatement.isNone) - "capped checking claimed complete artifact admission" - let tp ← checked (← prepareInput tierBytes anon) - let tr ← checked (← runPrepared tp cfg .all) - ensure (tr.failures.isEmpty && tr.artifactAdmission == some (.tiered tierEnv.consts.size 1)) - "bound whole check did not run the actual tiered entry" - ensure (tr.hostStatement.any (fun s => match s.kind with | .tiered .. => true | _ => false)) - "bound tier check omitted its receipt-derived partition commitments" - let thin := { env with assumptions := ({} : Std.HashSet Address).insert tierAddress } - let thin ← IO.ofExcept (serEnv thin) - let thin ← checked (← prepareInput thin anon) - ensure (match checkWhole thin .all none with - | .error (.artifact message) => message.contains "thin artifact" | _ => false) - "unresolved thin input obtained a whole receipt" + let p ← checked (← prepareInput fx.bytes anon) + let logical ← checked (← runPrepared p cfg .all) + ensure (logical.failures.isEmpty && logical.artifactAdmission == some (.logical fx.env.consts.size)) + "bound whole check did not run the actual logical entry" + ensure (logical.hostStatement.any (·.kind == .logical)) + "bound whole check omitted its receipt-derived host statement" + ensure (logical.rows.isEmpty && logical.execution == .serial) + "default quiet whole check did not take the single-pass checkWhole fast path" + let logicalFull ← checked (← runPrepared p { cfg with perRecord := true } .all) + ensure (logical.artifactAdmission == logicalFull.artifactAdmission && + logical.hostStatement == logicalFull.hostStatement && + logical.passed == logicalFull.passed && logical.typed == logicalFull.typed && + logical.targetsCovered == logicalFull.targetsCovered && + logical.roles == logicalFull.roles && !logicalFull.rows.isEmpty) + "single-pass whole check disagreed with per-record pool check" + let selected := if anon then toString (fx.generated.table.addressOf? .natDiv).get! else "Nat.div" + let selected ← checked (← runPrepared p cfg (.only #[selected])) + ensure (selected.failures.isEmpty && selected.artifactAdmission.isNone && selected.hostStatement.isNone) + "selected proof-backed operation lost actual evidence or claimed whole admission" + let capped ← checked (← runPrepared p cfg .all (some 1)) + ensure (capped.artifactAdmission.isNone && capped.hostStatement.isNone) + "capped checking claimed complete artifact admission" + let tp ← checked (← prepareInput fx.tierBytes anon) + let tr ← checked (← runPrepared tp cfg .all) + ensure (tr.failures.isEmpty && tr.artifactAdmission == some (.tiered fx.tierEnv.consts.size 1)) + "bound whole check did not run the actual tiered entry" + ensure (tr.hostStatement.any (fun s => match s.kind with | .tiered .. => true | _ => false)) + "bound tier check omitted its receipt-derived partition commitments" + let thin := { fx.env with assumptions := ({} : Std.HashSet Address).insert fx.tierAddress } + let thin ← IO.ofExcept (serEnv thin) + let thin ← checked (← prepareInput thin anon) + ensure (match checkWhole thin .all none with + | .error (.artifact message) => message.contains "thin artifact" | _ => false) + "unresolved thin input obtained a whole receipt" - -- An unnamed bad theorem is absent from the meta inventory. Whole checking - -- must still refuse it through the exact full artifact entry. - let badProof := { proof with info := .defn { definition with value := .var 0 } } - let (badEnv, _) := insert env badProof - let badBytes ← IO.ofExcept (serEnv badEnv) - let bad ← checked (← prepareInput badBytes) - ensure (match ← runPrepared bad cfg .all with | .error (.artifact _) => true | _ => false) - "an unnamed invalid record escaped bound whole checking" - orderedChecks env tierEnv badEnv - let ix ← IO.FS.realPath ".lake/build/bin/ix" - let dir ← IO.FS.createTempDir - try - let path := dir / "bound.ixe" - let tierPath := dir / "tier.ixe" - let badPath := dir / "invalid.ixe" - IO.FS.writeBinFile path bytes - IO.FS.writeBinFile tierPath tierBytes - IO.FS.writeBinFile badPath badBytes - let vars := #[("IX_KERNEL_CHECK_PROGRESS_MS", some "0"), ("IX_KERNEL_CHECK_SLOW_MS", some "0")] - for (file, args, code, text) in [ - (path, #[], 0, "whole artifact: logical entry accepted"), - (tierPath, #["--anon"], 0, "tier constants typed only"), - (path, #["--consts", "Nat.div"], 0, "selected checking only"), - (badPath, #[], 3, "artifact")] do - let out ← IO.Process.output { cmd := ix.toString, args := #["check-lean", file.toString] ++ args, env := vars } - ensure (out.exitCode == code && (out.stdout ++ out.stderr).contains text) - s!"bound CLI control failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" - let failures := dir / "aggregate-failures.txt" - let out ← IO.Process.output { - cmd := ix.toString - args := #["check-lean", badPath.toString, "--fail-out", failures.toString] - env := vars } - ensure (out.exitCode == 3 && out.stderr.contains "artifact") "aggregate refusal exit changed" - let lines := (← IO.FS.readFile failures).splitOn "\n" |>.map (·.trimAscii.toString) - ensure (lines.any (·.contains "artifact") && lines.all (fun line => line.isEmpty || line.startsWith "#")) - "aggregate refusal wrote a fabricated declaration selector" - let kernel ← IO.FS.realPath ".lake/build/bin/kernel-check-ixe" - let neutral := #["CHECK_IXE_ROOTS", "CHECK_IXE_SKIP", "CHECK_IXE_READ_CACHE"].map (·, none) - let mut previous : Option (Array (String × String × String)) := none - for mode in ["stream", "eager"] do - let rowsPath := dir / s!"{mode}.jsonl" - let result ← IO.Process.output { - cmd := kernel.toString - args := #[path.toString, rowsPath.toString, "--load", mode, "--jobs", "2"] - env := neutral } - ensure (result.exitCode == 0) s!"bound diagnostic {mode} failed: {result.stdout}\n{result.stderr}" - let mut rows : Array (String × String × String) := #[] - for line in (← IO.FS.readFile rowsPath).splitOn "\n" do - if line.isEmpty then continue - let row ← IO.ofExcept (Lean.Json.parse line) - rows := rows.push (← IO.ofExcept (row.getObjValAs? String "address"), - ← IO.ofExcept (row.getObjValAs? String "outcome"), ← IO.ofExcept (row.getObjValAs? String "reason")) - ensure (!rows.isEmpty && rows.all (·.2.1 == "accept")) "actual bound proof/operation records were refused" - for (address, lazy) in env.consts.toList do - let record ← IO.ofExcept lazy.get - let owner := toString (Ixon.CheckOrder.owner address record) - ensure (rows.any (·.1 == owner)) s!"bound diagnostic omitted owner {owner}" - let sorted := rows.qsort (fun a b => a.1 < b.1) - if let some earlier := previous then ensure (earlier == sorted) "stream/eager bound diagnostic rows differ" - previous := some sorted - return 7 + (← userAxiomChecks env tierEnv generated ix kernel dir) - finally - IO.FS.removeDirAll dir +private def inProcessUserAxiomCheck (fx : Fixture) (anon : Bool) : IO Unit := do + let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } + let strict ← checked (← prepareInput fx.cheatBytes anon) + let r ← checked (← runPrepared strict cfg .all) + ensure (!r.failures.isEmpty && r.artifactAdmission.isNone && r.conditionalOn.isEmpty && + runExit r true == _root_.Ix.Benchmark.Results.exitRejected) + "strict checking admitted a user axiom" + let p ← checked (← prepareInput fx.cheatBytes anon (allowUserAxioms := true)) + let r ← checked (← runPrepared p cfg .all) + ensure (r.failures.isEmpty && r.hostStatement.isNone && + r.artifactAdmission == some (.conditional fx.cheatEnv.consts.size none #[fx.cheatAddress]) && + runExit r true == exitConditional && runExit r true true == _root_.Ix.Benchmark.Results.exitUsage && + runStatus r true == "conditional") + s!"the conditional whole run is not reported as conditional on cheat: {repr r.artifactAdmission}" + let r ← checked (← runPrepared p cfg (.only #[if anon then toString fx.useAddress else "useCheat"])) + ensure (r.failures.isEmpty && r.userAxioms == #[fx.cheatAddress] && runExit r false == exitConditional && + runStatus r false == "conditional") + "a selected run through a user axiom is not conditional on it" + let pBad ← checked (← prepareInput fx.badCheatBytes anon (allowUserAxioms := true)) + let r ← checked (← runPrepared pBad cfg (.only (if anon then #[toString fx.useAddress, toString fx.badAddress] + else #["useCheat", "badCheat"]))) + let bad := r.targets.filter (·.target.address == fx.badAddress) + ensure (bad.size == 1 && bad.all (fun t => t.outcome == "reject" && !t.reason.startsWith "reader:") && + r.failures.size == 1 && r.userAxioms == #[fx.cheatAddress] && runStatus r false == "rejected") + s!"a rejected user axiom was listed as admitted: {r.userAxioms}, {bad.map (·.reason)}" + let natDiv := if anon then toString (fx.generated.table.addressOf? .natDiv).get! else "Nat.div" + let r ← checked (← runPrepared p cfg (.only #[natDiv])) + ensure (r.failures.isEmpty && r.userAxioms.isEmpty && runExit r false == 0) + "a selected run that reads no user axiom became conditional" + let strict ← checked (← runPrepared (← checked (← prepareInput fx.bytes anon)) cfg .all) + let p ← checked (← prepareInput fx.bytes anon (allowUserAxioms := true)) + let r ← checked (← runPrepared p cfg .all) + ensure (r.artifactAdmission == some (.logical fx.env.consts.size) && r.hostStatement.isSome && + r.hostStatement == strict.hostStatement && r.artifactAdmission == strict.artifactAdmission && + runExit r true true == 0) "the flag replaced the certified entry on an artifact without user axioms" + match ← prepareInput fx.noSorry anon (allowUserAxioms := true) with + | .error (.artifact message) => + ensure (message.contains "leaves sorryAx unbound") s!"wrong refusal: {message}" + | _ => throw (IO.userError "a binding without sorryAx admitted user axioms") -public def units : LSpec.TestSeq := - .individualIO "bound artifact consumers: whole logical/tier entries, the user-axiom path and actual CLI routing" none (do - let count ← checks - return (true, count, 0, none)) .done +private def inProcessTierUserAxiomChecks (fx : Fixture) : IO Unit := do + let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } + let p ← checked (← prepareInput fx.tierCheatBytes true (allowUserAxioms := true)) + let r ← checked (← runPrepared p cfg .all) + ensure (r.artifactAdmission == some (.conditional fx.tierCheatEnv.consts.size (some 1) #[fx.cheatAddress])) + s!"the tiered conditional entry did not run: {repr r.artifactAdmission}" + let strict ← checked (← runPrepared (← checked (← prepareInput fx.tierBytes true)) cfg .all) + let r ← checked (← runPrepared (← checked (← prepareInput fx.tierBytes true (allowUserAxioms := true))) cfg .all) + ensure (r.artifactAdmission == some (.tiered fx.tierEnv.consts.size 1) && + r.artifactAdmission == strict.artifactAdmission && r.hostStatement.isSome && + r.hostStatement == strict.hostStatement) + s!"the flag replaced the certified tiered entry: {repr r.artifactAdmission} vs {repr strict.artifactAdmission}" + match ← prepareInput fx.noSorry with + | .error (.artifact message) => + ensure (message.contains "role binding") s!"wrong meta refusal: {message}" + | _ => throw (IO.userError "a published sorryAx left unbound passed meta preparation") + +open LSpec in +public def units : LSpec.Spec := + LSpec.beforeAll buildFixture (fun fx => IO.FS.removeDirAll fx.dir) "role artifact consumer fixtures" fun getFx => do + let vars := #[("IX_KERNEL_CHECK_PROGRESS_MS", some "0"), ("IX_KERNEL_CHECK_SLOW_MS", some "0")] + it "bound artifact consumers: tier partition and fence checks" do + tierFenceChecks (← getFx) + it "bound artifact consumers: in-process whole checks (meta)" do + inProcessWholeCheck (← getFx) false + it "bound artifact consumers: in-process whole checks (anon)" do + inProcessWholeCheck (← getFx) true + it "bound artifact consumers: unnamed invalid record and ordered checks" do + let fx ← getFx + let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } + let bad ← checked (← prepareInput fx.badBytes) + ensure (match ← runPrepared bad cfg .all with | .error (.artifact _) => true | _ => false) + "an unnamed invalid record escaped bound whole checking" + orderedChecks fx.env fx.tierEnv fx.badEnv + it "bound artifact consumers: in-process user-axiom checks (meta)" do + inProcessUserAxiomCheck (← getFx) false + it "bound artifact consumers: in-process user-axiom checks (anon)" do + inProcessUserAxiomCheck (← getFx) true + it "bound artifact consumers: in-process tiered user-axiom checks" do + inProcessTierUserAxiomChecks (← getFx) + for (label, pickFile, args, code, text) in [ + ("whole logical CLI", (fun (fx : Fixture) => fx.path), #[], 0, "whole artifact: logical entry accepted"), + ("tier anon CLI", (fun (fx : Fixture) => fx.tierPath), #["--anon"], 0, "tier constants typed only"), + ("selected consts CLI", (fun (fx : Fixture) => fx.path), #["--consts", "Nat.div"], 0, "selected checking only"), + ("invalid artifact CLI", (fun (fx : Fixture) => fx.badPath), #[], 3, "artifact")] do + it s!"bound artifact consumers: ix check-lean {label}" do + let fx ← getFx + let out ← IO.Process.output { cmd := fx.ix.toString, args := #["check-lean", (pickFile fx).toString] ++ args, env := vars } + ensure (out.exitCode == code && (out.stdout ++ out.stderr).contains text) + s!"bound CLI control failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" + it "bound artifact consumers: ix check-lean aggregate fail-out" do + let fx ← getFx + let failures := fx.dir / "aggregate-failures.txt" + let out ← IO.Process.output { + cmd := fx.ix.toString + args := #["check-lean", fx.badPath.toString, "--fail-out", failures.toString] + env := vars } + ensure (out.exitCode == 3 && out.stderr.contains "artifact") "aggregate refusal exit changed" + let lines := (← IO.FS.readFile failures).splitOn "\n" |>.map (·.trimAscii.toString) + ensure (lines.any (·.contains "artifact") && lines.all (fun line => line.isEmpty || line.startsWith "#")) + "aggregate refusal wrote a fabricated declaration selector" + it "bound artifact consumers: kernel-check-ixe stream vs eager parity" do + let fx ← getFx + let neutral := #["CHECK_IXE_ROOTS", "CHECK_IXE_SKIP", "CHECK_IXE_READ_CACHE"].map (·, none) + let mut previous : Option (Array (String × String × String)) := none + for mode in ["stream", "eager"] do + let rowsPath := fx.dir / s!"{mode}.jsonl" + let result ← IO.Process.output { + cmd := fx.kernel.toString + args := #[fx.path.toString, rowsPath.toString, "--load", mode, "--jobs", "2"] + env := neutral } + ensure (result.exitCode == 0) s!"bound diagnostic {mode} failed: {result.stdout}\n{result.stderr}" + let mut rows : Array (String × String × String) := #[] + for line in (← IO.FS.readFile rowsPath).splitOn "\n" do + if line.isEmpty then continue + let row ← IO.ofExcept (Lean.Json.parse line) + rows := rows.push (← IO.ofExcept (row.getObjValAs? String "address"), + ← IO.ofExcept (row.getObjValAs? String "outcome"), ← IO.ofExcept (row.getObjValAs? String "reason")) + ensure (!rows.isEmpty && rows.all (·.2.1 == "accept")) "actual bound proof/operation records were refused" + for (address, lazy) in fx.env.consts.toList do + let record ← IO.ofExcept lazy.get + let owner := toString (Ixon.CheckOrder.owner address record) + ensure (rows.any (·.1 == owner)) s!"bound diagnostic omitted owner {owner}" + let sorted := rows.qsort (fun a b => a.1 < b.1) + if let some earlier := previous then ensure (earlier == sorted) "stream/eager bound diagnostic rows differ" + previous := some sorted + for (label, pickFile, args, code, mkTexts) in [ + ("strict meta", (fun (fx : Fixture) => fx.cheatPath), #[], 3, fun (_ : Fixture) => #[]), + ("strict anon", (fun (fx : Fixture) => fx.cheatPath), #["--anon"], 3, fun (_ : Fixture) => #[]), + ("conditional meta", (fun (fx : Fixture) => fx.cheatPath), #["--allow-user-axioms"], exitConditional, + fun (fx : Fixture) => #["whole artifact: CONDITIONAL on 1 user axioms:", s!"[check-lean] {fx.cheatAddress} cheat", "no host statement"]), + ("conditional anon", (fun (fx : Fixture) => fx.cheatPath), #["--anon", "--allow-user-axioms"], exitConditional, + fun (fx : Fixture) => #["whole artifact: CONDITIONAL on 1 user axioms:", s!"[check-lean] {fx.cheatAddress}"]), + ("conditional selected", (fun (fx : Fixture) => fx.cheatPath), #["--allow-user-axioms", "--consts", "useCheat"], exitConditional, + fun (fx : Fixture) => #["selected checking: CONDITIONAL on 1 user axioms:", s!"[check-lean] {fx.cheatAddress} cheat"]), + ("conditional tiered", (fun (fx : Fixture) => fx.tierCheatPath), #["--anon", "--allow-user-axioms"], exitConditional, + fun (_ : Fixture) => #["whole artifact: CONDITIONAL on 1 user axioms:", "conditional logical entry and typing tier"]), + ("clean artifact with flag", (fun (fx : Fixture) => fx.boundPath), #["--allow-user-axioms"], 0, + fun (_ : Fixture) => #["whole artifact: logical entry accepted all"]), + ("no-sorry anon", (fun (fx : Fixture) => fx.noSorryPath), #["--anon", "--allow-user-axioms"], 3, + fun (_ : Fixture) => #["leaves sorryAx unbound"]), + ("no-sorry meta", (fun (fx : Fixture) => fx.noSorryPath), #[], 3, + fun (_ : Fixture) => #["role binding"])] do + it s!"bound artifact consumers: user-axiom CLI ({label})" do + let fx ← getFx + let out ← IO.Process.output { cmd := fx.ix.toString, args := #["check-lean", (pickFile fx).toString] ++ args, env := vars } + let text := out.stdout ++ out.stderr + ensure (out.exitCode == code && (mkTexts fx).all (fun t => text.contains t) && + (code == 0 || !out.stdout.contains "accepted all")) + s!"user-axiom CLI control {args} failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" + it "bound artifact consumers: user-axiom CLI rejects --host-out" do + let fx ← getFx + let unused := fx.dir / "conditional.ixhc" + let out ← IO.Process.output { + cmd := fx.ix.toString + args := #["check-lean", fx.cheatPath.toString, "--allow-user-axioms", "--host-out", unused.toString] + env := vars } + let text := out.stdout ++ out.stderr + ensure (out.exitCode == 2 && text.contains "CONDITIONAL on 1 user axioms and issues no host statement" && + !out.stdout.contains "accepted all") + s!"user-axiom CLI --host-out control failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" + ensure (!(← unused.pathExists)) "a conditional run wrote a host statement" + for (tag, args) in [("stream", #["--load", "stream"]), ("eager-j2", #["--load", "eager", "--jobs", "2"])] do + for allow in [true, false] do + it s!"bound artifact consumers: kernel-check-ixe uncached {tag} allow={allow}" do + let fx ← getFx + checkKernelIxeUserAxioms fx args none allow s!"cheat-{tag}-{allow}.jsonl" + it "bound artifact consumers: kernel-check-ixe read-cache paths" do + let fx ← getFx + let cache := fx.dir / "read-cache" + for (tag, args) in [("j2", #["--jobs", "2"]), ("default", #[]), ("eager", #["--load", "eager"])] do + for allow in [true, false] do + checkKernelIxeUserAxioms fx args (some cache) allow s!"cheat-cache-{tag}-{allow}.jsonl" + ensure (← cache.pathExists) "the read cache was never written" + it "bound artifact consumers: kernel-check-ixe refuses no-sorry" do + let fx ← getFx + let refused ← IO.Process.output { + cmd := fx.kernel.toString + args := #[fx.noSorryPath.toString, (fx.dir / "no-sorry.jsonl").toString, "--allow-user-axioms"] } + ensure (refused.exitCode == 2 && refused.stderr.contains "leaves sorryAx unbound") + s!"kernel-check-ixe admitted user axioms under a binding without sorryAx\n{refused.stderr}" end Tests.Ix.RoleArtifactConsumer diff --git a/Tests/Ix/RoleBinding.lean b/Tests/Ix/RoleBinding.lean index 707d43d583..1a18371ae6 100644 --- a/Tests/Ix/RoleBinding.lean +++ b/Tests/Ix/RoleBinding.lean @@ -103,12 +103,9 @@ private def checks (_fixture : Constant) : Except String Unit := do need "every header reader rejects bad framing or hash" (!parsed.isOk) /-- The parameter keeps foreign calls out of module initialization. -/ -public def units (fixture : Constant) : LSpec.TestSeq := - .individualIO "role binding: exact v4/v5 bytes, all loaders, FFI and admission boundary" none (do - let result ← IO.lazyPure fun _ => checks fixture - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done +public def units (fixture : Constant) : LSpec.Spec := + it "role binding: exact v4/v5 bytes, all loaders, FFI and admission boundary" do + LSpec.expectOk (checks fixture) end Tests.Ix.RoleBinding diff --git a/Tests/Ix/RoleCompile.lean b/Tests/Ix/RoleCompile.lean index 518e37ada4..0e299efc96 100644 --- a/Tests/Ix/RoleCompile.lean +++ b/Tests/Ix/RoleCompile.lean @@ -120,10 +120,9 @@ private def check : IO Bool := IO.FS.withTempDir fun dir => do "a changed hint passed the finalized-artifact check" return true -public def suite : List LSpec.TestSeq := [ - .individualIO "production artifact bindings: source certificates, both compilers and certified checking" none (do +public def suite : LSpec.Spec := + it "production artifact bindings: source certificates, both compilers and certified checking" do let ok ← check - return (ok, 0, 0, none)) .done -] + LSpec.expect ok end Tests.Ix.RoleCompile diff --git a/Tests/Ix/RoleEquations.lean b/Tests/Ix/RoleEquations.lean index 1e7fa669ee..5f5a477444 100644 --- a/Tests/Ix/RoleEquations.lean +++ b/Tests/Ix/RoleEquations.lean @@ -108,16 +108,11 @@ def roleChecks : Except String Unit := do let missing ← checked #[.indDecl eqBasis 2, .indDecl natBasis 0] need "an absent operation is refused" (!(checkRole missing .intSub evidence).isOk) -private def unit (label : String) (check : Unit → Except String Unit) : LSpec.TestSeq := - .individualIO label none (do - let result ← IO.lazyPure check - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done - -public def suite : List LSpec.TestSeq := [ - unit "dependent equation terms and proof evidence pass the real checker" (fun _ => equationChecks), +private def unit (label : String) (check : Unit → Except String Unit) : LSpec.Spec := + LSpec.itThunk label fun () => LSpec.expectOk (check ()) + +public def suite : LSpec.Spec := do + unit "dependent equation terms and proof evidence pass the real checker" (fun _ => equationChecks) unit "definition behavior and evidence count satisfy the role specification" (fun _ => roleChecks) -] end Tests.Ix.RoleEquations diff --git a/Tests/Ix/RoleGeneration.lean b/Tests/Ix/RoleGeneration.lean index d229eec72e..00ce020474 100644 --- a/Tests/Ix/RoleGeneration.lean +++ b/Tests/Ix/RoleGeneration.lean @@ -207,12 +207,9 @@ private def checks (operation : Role) : Except String Unit := do need "certificate support cannot change an original reducibility hint" (!(strongerHint.emit limits originalHint).isOk) -public def units (operation : Role) : LSpec.TestSeq := - .individualIO "role generation: actual proof records, source bindings, emission and refusals" none (do - let result ← IO.lazyPure fun _ => checks operation - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done +public def units (operation : Role) : LSpec.Spec := + it "role generation: actual proof records, source bindings, emission and refusals" do + LSpec.expectOk (checks operation) private def artifactChecks (operation : Role) : Except String Unit := do let limits := Ix.Typing.typingLimits @@ -303,11 +300,8 @@ private def artifactChecks (operation : Role) : Except String Unit := do need "authenticated replacement proof fails the actual certified consumer" (!(Ix.RoleBinding.Artifact.check changedArtifact limits).isOk) -public def artifactUnits (operation : Role) : LSpec.TestSeq := - .individualIO "artifact consumer: real fold, exact binding, no fallback and evidence refusals" none (do - let result ← IO.lazyPure fun _ => artifactChecks operation - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done +public def artifactUnits (operation : Role) : LSpec.Spec := + it "artifact consumer: real fold, exact binding, no fallback and evidence refusals" do + LSpec.expectOk (artifactChecks operation) end Tests.Ix.RoleGeneration diff --git a/Tests/Ix/RolePacking.lean b/Tests/Ix/RolePacking.lean index 177382a4f7..d20b1bc408 100644 --- a/Tests/Ix/RolePacking.lean +++ b/Tests/Ix/RolePacking.lean @@ -90,9 +90,8 @@ private def checks : IO Nat := do return 6 return 3 -public def units : LSpec.TestSeq := - .individualIO "bound packing: all production pruners preserve actual reader/consumer support" none (do - let count ← checks - return (true, count, 0, none)) .done +public def units : LSpec.Spec := + it "bound packing: all production pruners preserve actual reader/consumer support" do + let _ ← checks end Tests.Ix.RolePacking diff --git a/Tests/Ix/RolePublication.lean b/Tests/Ix/RolePublication.lean index 6b21c6cf81..c006e3a205 100644 --- a/Tests/Ix/RolePublication.lean +++ b/Tests/Ix/RolePublication.lean @@ -80,11 +80,8 @@ private def checks (record : Constant) : Except String Unit := do need "missing owner fails before publication" (!(publication projected (fun a => if a == projectionAddress then some projection else none) [.nat]).isOk) -public def units (record : Constant) : LSpec.TestSeq := - .individualIO "role publication: structural names, aliases, explicit absence and actual prelude owners" none (do - let result ← IO.lazyPure fun _ => checks record - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done +public def units (record : Constant) : LSpec.Spec := + it "role publication: structural names, aliases, explicit absence and actual prelude owners" do + LSpec.expectOk (checks record) end Tests.Ix.RolePublication diff --git a/Tests/Ix/SharingComponents.lean b/Tests/Ix/SharingComponents.lean index c69122937c..cfcdab2d7a 100644 --- a/Tests/Ix/SharingComponents.lean +++ b/Tests/Ix/SharingComponents.lean @@ -113,12 +113,11 @@ private def componentControls (count : Nat) (wild : Bool) : IO Nat := do return tested /-- The comparison over `count` generated inputs. -/ -def suiteOf (count : Nat) (wild : Bool) : List TestSeq := [ - .individualIO s!"uncertain components match the original hashed grouping ({count} inputs)" none (do - let tested ← componentControls count wild - return (true, tested, 0, none)) .done] +def suiteOf (count : Nat) (wild : Bool) : Spec := + it s!"uncertain components match the original hashed grouping ({count} inputs)" do + let _ ← componentControls count wild /-- The primary run: 15 generated inputs and parent arrays within range. -/ -def suite : List TestSeq := suiteOf 15 false +def suite : Spec := suiteOf 15 false end Tests.SharingComponents diff --git a/Tests/Ix/SharingExact.lean b/Tests/Ix/SharingExact.lean index 6346969e16..8d665d8b6b 100644 --- a/Tests/Ix/SharingExact.lean +++ b/Tests/Ix/SharingExact.lean @@ -65,10 +65,10 @@ def u64LE (x : UInt64) : ByteArray := def cbytes (c : Constant) : Nat := (serConstant c).size -def withOk {α} (name : String) (x : Except SharingError α) (k : α → TestSeq) : TestSeq := +def withOk {α} (name : String) (x : Except SharingError α) (k : α → AssertM Unit) : AssertM Unit := match x with | .ok a => k a - | .error e => test s!"{name}: unexpected error {reprStr e}" false + | .error e => fail s!"{name}: unexpected error {reprStr e}" def isErr {α} (x : Except SharingError α) (p : SharingError → Bool) : Bool := match x with @@ -263,35 +263,35 @@ def boundaryValues : List Nat := [tagNEnd1 f, tagNEnd2 f, tagNEnd3 f, tagNEnd4 f, tagNEnd5 f].flatMap fun e => [e - 1, e, e + 1]) -def widthTests (_ : Unit) : TestSeq := - group "integer widths" <| - test "tag0Size = putTagN 0 length at every rung boundary" - (boundaryValues.all fun n => tag0Size n == (runPut (putTagN 0 0 n.toUInt64)).size) ++ - test "tag4Size = putTagN 4 length at every rung boundary" +def widthTests : Spec := + describe "integer widths" do + itBool "tag0Size = putTagN 0 length at every rung boundary" + (boundaryValues.all fun n => tag0Size n == (runPut (putTagN 0 0 n.toUInt64)).size) + itBool "tag4Size = putTagN 4 length at every rung boundary" (boundaryValues.all fun n => [0x7, 0x8, 0x9, 0xB].all fun (f : UInt8) => - tag4Size n == (runPut (putTagN 4 f n.toUInt64)).size) ++ - test "shareWidth = serialized Share length at every boundary" + tag4Size n == (runPut (putTagN 4 f n.toUInt64)).size) + itBool "shareWidth = serialized Share length at every boundary" (boundaryValues.all fun n => shareWidth n == (serExpr (.share n.toUInt64)).size && - exprSize (.share n.toUInt64) == shareWidth n) ++ - test "Share 7/8 → 1/2 bytes" (shareWidth 7 == 1 && shareWidth 8 == 2) ++ - test "Share 1031/1032 → 2/3 bytes" (shareWidth 1031 == 2 && shareWidth 1032 == 3) ++ - test "Share 66567/66568 → 3/4 bytes" (shareWidth 66567 == 3 && shareWidth 66568 == 4) ++ - test "Share 16843783/16843784 → 4/5 bytes" - (shareWidth 16843783 == 4 && shareWidth 16843784 == 5) ++ - test "Share 4311811079/4311811080 → 5/9 bytes" - (shareWidth 4311811079 == 5 && shareWidth 4311811080 == 9) ++ - test "Share 2^64-1 → 9 bytes" (shareWidth (2^64 - 1) == 9) ++ - test "TagN f=0 127/128 → 1/2 bytes, 16511/16512 → 2/3, 82047/82048 → 3/4, 16859263/16859264 → 4/5" + exprSize (.share n.toUInt64) == shareWidth n) + itBool "Share 7/8 → 1/2 bytes" (shareWidth 7 == 1 && shareWidth 8 == 2) + itBool "Share 1031/1032 → 2/3 bytes" (shareWidth 1031 == 2 && shareWidth 1032 == 3) + itBool "Share 66567/66568 → 3/4 bytes" (shareWidth 66567 == 3 && shareWidth 66568 == 4) + itBool "Share 16843783/16843784 → 4/5 bytes" + (shareWidth 16843783 == 4 && shareWidth 16843784 == 5) + itBool "Share 4311811079/4311811080 → 5/9 bytes" + (shareWidth 4311811079 == 5 && shareWidth 4311811080 == 9) + itBool "Share 2^64-1 → 9 bytes" (shareWidth (2^64 - 1) == 9) + itBool "TagN f=0 127/128 → 1/2 bytes, 16511/16512 → 2/3, 82047/82048 → 3/4, 16859263/16859264 → 4/5" (tag0Size 127 == 1 && tag0Size 128 == 2 && tag0Size 16511 == 2 && tag0Size 16512 == 3 && tag0Size 82047 == 3 && tag0Size 82048 == 4 && tag0Size 16859263 == 4 && - tag0Size 16859264 == 5) ++ - test "tag0BracketStart is the start of the count's TagN rung" + tag0Size 16859264 == 5) + itBool "tag0BracketStart is the start of the count's TagN rung" (boundaryValues.all fun k => tag0Size (tag0BracketStart k) == tag0Size k && - (tag0BracketStart k == 0 || tag0Size (tag0BracketStart k - 1) < tag0Size k)) ++ - test "tag0StepBound bounds the growth of the count's TagN width" + (tag0BracketStart k == 0 || decide (tag0Size (tag0BracketStart k - 1) < tag0Size k))) + itBool "tag0StepBound bounds the growth of the count's TagN width" ((boundaryValues.all fun n => n == 0 || decide (tag0Size n - tag0Size (n - 1) ≤ tag0StepBound n)) && tag0StepBound 82048 == 1 && tag0StepBound (tagNEnd5 0 - 1) == 1 && @@ -321,14 +321,14 @@ def genExprForSize : RGen Ixon.Expr := do | 2 => return .lam e (.share idx.toUInt64) | _ => return e -def exprSizeTests (_ : Unit) : TestSeq := - let gen := runGen 7 ((List.range 2000).mapM fun _ => genExprForSize) - group "exact expression length" <| - test "exprSize = serExpr size on telescope boundaries (1/2/7/8/9/255/256/257)" - (telescopeExprs.all fun e => exprSize e == (serExpr e).size) ++ - test "exprSize = serExpr size on 2000 generated expressions with boundary Shares" - (gen.all fun e => exprSize e == (serExpr e).size) ++ - test "App with 7/8 args uses 1/2 header bytes" +def exprSizeTests : Spec := + describe "exact expression length" do + itBool "exprSize = serExpr size on telescope boundaries (1/2/7/8/9/255/256/257)" + (telescopeExprs.all fun e => exprSize e == (serExpr e).size) + it "exprSize = serExpr size on 2000 generated expressions with boundary Shares" do + let gen := runGen 7 ((List.range 2000).mapM fun _ => genExprForSize) + expect (gen.all fun e => exprSize e == (serExpr e).size) + itBool "App with 7/8 args uses 1/2 header bytes" (let a7 := (List.range 7).foldl (fun f _ => .app f (.var 0)) (.var 1) let a8 := Ixon.Expr.app a7 (.var 0) (serExpr a7).size == 1 + 8 && (serExpr a8).size == 2 + 9) @@ -343,24 +343,24 @@ def decompositionHolds (c : Constant) : Bool := cbytes c == fixedConstantBytes c + exprsSize (constantInfoRoots c.info) + tag0Size c.sharing.size + exprsSize c.sharing -def decompositionTests (_ : Unit) : TestSeq := - let mkRoots (k : Nat) (n : Nat) : Array Ixon.Expr := - (Array.range n).map fun i => .app (.share (k - 1 - i % (max k 1)).toUInt64) (.var i.toUInt64) - let infos (rs : Array Ixon.Expr) : List ConstantInfo := - [ .defn ⟨.defn, .safe, {}, 0, rs[0]!, rs[1]!⟩, .axio ⟨false, 1, rs[0]!⟩, - .quot ⟨.lift, 2, rs[0]!⟩, - .recr ⟨true, false, 1, 2, 3, 4, 5, rs[0]!, #[⟨1, rs[1]!⟩, ⟨300, rs[2]!⟩]⟩, - .cPrj ⟨1, 2, testRefs[0]!⟩, .rPrj ⟨3, testRefs[1]!⟩, .iPrj ⟨200, testRefs[0]!⟩, - .dPrj ⟨0, testRefs[1]!⟩, - .muts #[.defn ⟨.thm, .part, {}, 0, rs[0]!, rs[1]!⟩, - .indc ⟨true, 1, 1, 0, rs[2]!, #[⟨false, 1, 0, 1, 2, .inherited, rs[3]!⟩, ⟨false, 1, 1, 1, 0, .inherited, rs[0]!⟩]⟩, - .recr ⟨false, true, 0, 0, 0, 0, 0, rs[1]!, #[⟨2, rs[2]!⟩]⟩] ] - let cases := [0, 1, 8, 9, 127, 128, 255, 256, 257, 1032, 1033].flatMap fun k => - (infos (mkRoots k 4)).map fun info => tableConstant info k - group "complete-Constant length decomposition" <| - test s!"serConstant size = fixed + roots + tag0(table) + table on {cases.length} constants (all kinds; tables 0/1/8/9/127/128/255/256/257/1032/1033)" - (cases.all decompositionHolds) ++ - test "Share 7/8 and 1031/1032 have widths 1/2 and 2/3" +def decompositionTests : Spec := + describe "complete-Constant length decomposition" do + it "serConstant size = fixed + roots + tag0(table) + table (all kinds; tables 0/1/8/9/127/128/255/256/257/1032/1033)" do + let mkRoots (k : Nat) (n : Nat) : Array Ixon.Expr := + (Array.range n).map fun i => .app (.share (k - 1 - i % (max k 1)).toUInt64) (.var i.toUInt64) + let infos (rs : Array Ixon.Expr) : List ConstantInfo := + [ .defn ⟨.defn, .safe, {}, 0, rs[0]!, rs[1]!⟩, .axio ⟨false, 1, rs[0]!⟩, + .quot ⟨.lift, 2, rs[0]!⟩, + .recr ⟨true, false, 1, 2, 3, 4, 5, rs[0]!, #[⟨1, rs[1]!⟩, ⟨300, rs[2]!⟩]⟩, + .cPrj ⟨1, 2, testRefs[0]!⟩, .rPrj ⟨3, testRefs[1]!⟩, .iPrj ⟨200, testRefs[0]!⟩, + .dPrj ⟨0, testRefs[1]!⟩, + .muts #[.defn ⟨.thm, .part, {}, 0, rs[0]!, rs[1]!⟩, + .indc ⟨true, 1, 1, 0, rs[2]!, #[⟨false, 1, 0, 1, 2, .inherited, rs[3]!⟩, ⟨false, 1, 1, 1, 0, .inherited, rs[0]!⟩]⟩, + .recr ⟨false, true, 0, 0, 0, 0, 0, rs[1]!, #[⟨2, rs[2]!⟩]⟩] ] + let cases := [0, 1, 8, 9, 127, 128, 255, 256, 257, 1032, 1033].flatMap fun k => + (infos (mkRoots k 4)).map fun info => tableConstant info k + expect (cases.all decompositionHolds) s!"decomposition failed on {cases.length} constants" + itBool "Share 7/8 and 1031/1032 have widths 1/2 and 2/3" (exprSize (.share 7) == 1 && exprSize (.share 8) == 2 && exprSize (.share 1031) == 2 && exprSize (.share 1032) == 3) @@ -370,161 +370,182 @@ def fixtureA : Ixon.Expr := arr P P def fixtureB : Ixon.Expr := arr P (.sort 1) def tiedMinimaRoot : Ixon.Expr := arr fixtureA (arr fixtureA (arr fixtureB fixtureB)) -def structuralIdTests (_ : Unit) : TestSeq := - let naiveAgree := runGen 11 do - let mut ok := true - for _ in [0:300] do - let roots ← genRoots 5 10 3 - match expandRoots roots with - | .ok ex => - let naive := naiveCanonical roots - let rootIdx := roots.map fun r => (naive.findIdx? (· == r)).getD 1000000 - ok := ok && ex.dag.toExprs == naive && ex.roots == rootIdx - | .error _ => ok := false - return ok - group "structural IDs" <| - withOk "tied-minima fixture" (expandRoots #[tiedMinimaRoot]) (fun ex => - test "ids: Sort0=0 Sort1=1 A=2 B=3 (B→B)=4 (A→B→B)=5 root=6" - (ex.dag.toExprs == #[P, .sort 1, fixtureA, fixtureB, arr fixtureB fixtureB, - arr fixtureA (arr fixtureB fixtureB), tiedMinimaRoot] && ex.roots == #[6])) ++ - withOk "witness" (expandRoots #[arr (chain 2) (chain 2)]) (fun ex => - test "ids: P=0 T1=1 T2=2 R=3" (ex.dag.toExprs == #[P, chain 1, chain 2, - arr (chain 2) (chain 2)])) ++ - test "canonical IDs equal an independent naive assignment on 300 generated inputs" - naiveAgree ++ - test "let modes are part of structural identity" +def structuralIdTests : Spec := + describe "structural IDs" do + it "tied-minima fixture: ids Sort0=0 Sort1=1 A=2 B=3 (B→B)=4 (A→B→B)=5 root=6" do + withOk "tied-minima fixture" (expandRoots #[tiedMinimaRoot]) fun ex => + expect (ex.dag.toExprs == #[P, .sort 1, fixtureA, fixtureB, arr fixtureB fixtureB, + arr fixtureA (arr fixtureB fixtureB), tiedMinimaRoot] && ex.roots == #[6]) + it "witness: ids P=0 T1=1 T2=2 R=3" do + withOk "witness" (expandRoots #[arr (chain 2) (chain 2)]) fun ex => + expect (ex.dag.toExprs == #[P, chain 1, chain 2, arr (chain 2) (chain 2)]) + it "canonical IDs equal an independent naive assignment on 300 generated inputs" do + let naiveAgree := runGen 11 do + let mut ok := true + for _ in [0:300] do + let roots ← genRoots 5 10 3 + match expandRoots roots with + | .ok ex => + let naive := naiveCanonical roots + let rootIdx := roots.map fun r => (naive.findIdx? (· == r)).getD 1000000 + ok := ok && ex.dag.toExprs == naive && ex.roots == rootIdx + | .error _ => ok := false + return ok + expect naiveAgree + itBool "let modes are part of structural identity" (distinctCount #[.lam P P, .all P P, .letE true (.value .many) P P P, .letE false (.value .many) P P P, .letE false .borrow P P P, - .letE false (.value .erased) P P P] == 7) ++ - test "lexCompare: proper prefix first, then numeric" + .letE false (.value .erased) P P P] == 7) + itBool "lexCompare: proper prefix first, then numeric" (lexCompare [1] [1, 0] == .lt && lexCompare [] [0] == .lt && - lexCompare [2] [10] == .lt && lexCompare [1, 0] [1] == .gt) ++ - test "compareBytes: unsigned, proper prefix first" + lexCompare [2] [10] == .lt && lexCompare [1, 0] [1] == .gt) + itBool "compareBytes: unsigned, proper prefix first" (compareBytes ⟨#[0x7f]⟩ ⟨#[0x80]⟩ == .lt && compareBytes ⟨#[1]⟩ ⟨#[1, 0]⟩ == .lt && compareBytes ⟨#[0xff]⟩ ⟨#[0x00, 0x00]⟩ == .gt) /-- The same AST in three pointer layouts: generated (pool-shared), fresh (deserialized, no sharing), and maximally shared (from the DAG). -/ -def representationTestsWith (count : Nat) (_ : Unit) : TestSeq := - let ok := runGen 13 do - let mut ok := true - for i in [0:count] do - let roots ← genRoots 5 10 3 - let c := wrapRoots roots i - let fresh := match deConstant (serConstant c) with - | .ok c' => c' - | .error _ => c - let dagShared := match expandConstantSharing c with - | .ok c' => c' - | .error _ => c - let alt := alternateOf c - let outs := [c, fresh, dagShared, alt].map fun x => - (normalizeConstantSharing x).toOption.map serConstant - let tiered := [c, fresh, dagShared, alt].map fun x => - (normalizeConstantSharingTiered .tagN x).toOption.map serConstant - ok := ok && outs.all (· == outs.head!) && outs.head!.isSome && - tiered.all (· == tiered.head!) && tiered.head!.isSome - return ok - group "representation independence" <| - test s!"pool-shared, deserialized, DAG-shared and uniform-w1-encoded inputs normalize to identical bytes, by the exact search and by the tiered construction ({count} inputs)" ok - -def representationTests (_ : Unit) : TestSeq := representationTestsWith 120 () -def representationTestsPR (_ : Unit) : TestSeq := representationTestsWith 50 () - -def cacheTests (_ : Unit) : TestSeq := - let empty : ExprCache Nat := {} - let key : ExprCache.Key := ⟨0, .var 3⟩ - let cached := empty.insert key 17 - let collision := cached.insert ⟨0, .var 4⟩ 29 - let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } - let source : Ixon.Expr := .app (.var 3) (.var 4) - let poisoned : IngestState := - { ptrCache := empty.insert ⟨(exprKey source).address, .sort 8⟩ 999 } - let ordinary := (ingestExpr {} context 0 source).run {} - let repaired := (ingestExpr {} context 0 source).run poisoned - let illegal : Ixon.Expr := .share 0 - let illegalState : IngestState := { ptrCache := empty.insert ⟨(exprKey illegal).address, .var 0⟩ 17 } - let dag : Ixon.Expr := (List.range 36).foldl (fun e _ => .app e e) (.var 3) - group "checked expression cache" <| - test "an exact key retrieves its cached ID" (cached.get? key == some 17) ++ - test "a colliding address with a different expression misses" - (cached.get? ⟨0, .var 4⟩ == none) ++ - test "collision replacement cannot return the evicted expression's ID" - (collision.get? key == none && collision.get? ⟨0, .var 4⟩ == some 29) ++ - test "equal expression structure can use the same candidate bucket" - ((empty.insert ⟨0, .app (.var 3) (.var 4)⟩ 17).get? ⟨0, source⟩ == some 17) ++ - test "let modes are checked before accepting a hit" - ((empty.insert ⟨0, .letE false (.value .many) P P P⟩ 17).get? - ⟨0, .letE false .borrow P P P⟩ == none) ++ - test "poisoning a pointer bucket cannot bypass actual ingestion" - (ordinary.toOption.map (fun (id, state) => (id, state.interner.nodes, state.visits)) == - repaired.toOption.map (fun (id, state) => (id, state.interner.nodes, state.visits)) && repaired.isOk) ++ - test "a colliding candidate cannot hide an illegal Share" - (isErr ((ingestExpr {} context 0 illegal).run illegalState) (· == .shareInExpandedInput 0 0)) ++ - test "fast re-expansion rejects the same colliding candidate" - (match ordinary with +def representationTestsWith (count : Nat) : Spec := + describe "representation independence" do + it s!"pool-shared, deserialized, DAG-shared and uniform-w1-encoded inputs normalize to identical bytes, by the exact search and by the tiered construction ({count} inputs)" do + let ok := runGen 13 do + let mut ok := true + for i in [0:count] do + let roots ← genRoots 5 10 3 + let c := wrapRoots roots i + let fresh := match deConstant (serConstant c) with + | .ok c' => c' + | .error _ => c + let dagShared := match expandConstantSharing c with + | .ok c' => c' + | .error _ => c + let alt := alternateOf c + let outs := [c, fresh, dagShared, alt].map fun x => + (normalizeConstantSharing x).toOption.map serConstant + let tiered := [c, fresh, dagShared, alt].map fun x => + (normalizeConstantSharingTiered .tagN x).toOption.map serConstant + ok := ok && outs.all (· == outs.head!) && outs.head!.isSome && + tiered.all (· == tiered.head!) && tiered.head!.isSome + return ok + expect ok + +def representationTests : Spec := representationTestsWith 120 +def representationTestsPR : Spec := representationTestsWith 50 + +def cacheTests : Spec := + describe "checked expression cache" do + it "an exact key retrieves its cached ID" do + let empty : ExprCache Nat := {} + let key : ExprCache.Key := ⟨0, .var 3⟩ + let cached := empty.insert key 17 + expect (cached.get? key == some 17) + it "a colliding address with a different expression misses" do + let empty : ExprCache Nat := {} + let cached := empty.insert ⟨0, .var 3⟩ 17 + expect (cached.get? ⟨0, .var 4⟩ == none) + it "collision replacement cannot return the evicted expression's ID" do + let empty : ExprCache Nat := {} + let key : ExprCache.Key := ⟨0, .var 3⟩ + let cached := empty.insert key 17 + let collision := cached.insert ⟨0, .var 4⟩ 29 + expect (collision.get? key == none && collision.get? ⟨0, .var 4⟩ == some 29) + it "equal expression structure can use the same candidate bucket" do + let empty : ExprCache Nat := {} + let source : Ixon.Expr := .app (.var 3) (.var 4) + expect ((empty.insert ⟨0, .app (.var 3) (.var 4)⟩ 17).get? ⟨0, source⟩ == some 17) + it "let modes are checked before accepting a hit" do + let empty : ExprCache Nat := {} + expect ((empty.insert ⟨0, .letE false (.value .many) P P P⟩ 17).get? + ⟨0, .letE false .borrow P P P⟩ == none) + it "poisoning a pointer bucket cannot bypass actual ingestion" do + let empty : ExprCache Nat := {} + let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } + let source : Ixon.Expr := .app (.var 3) (.var 4) + let poisoned : IngestState := + { ptrCache := empty.insert ⟨(exprKey source).address, .sort 8⟩ 999 } + let ordinary := (ingestExpr {} context 0 source).run {} + let repaired := (ingestExpr {} context 0 source).run poisoned + expect (ordinary.toOption.map (fun (id, state) => (id, state.interner.nodes, state.visits)) == + repaired.toOption.map (fun (id, state) => (id, state.interner.nodes, state.visits)) && repaired.isOk) + it "a colliding candidate cannot hide an illegal Share" do + let empty : ExprCache Nat := {} + let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } + let illegal : Ixon.Expr := .share 0 + let illegalState : IngestState := { ptrCache := empty.insert ⟨(exprKey illegal).address, .var 0⟩ 17 } + expect (isErr ((ingestExpr {} context 0 illegal).run illegalState) (· == .shareInExpandedInput 0 0)) + it "fast re-expansion rejects the same colliding candidate" do + let empty : ExprCache Nat := {} + let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } + let source : Ixon.Expr := .app (.var 3) (.var 4) + let poisoned : IngestState := + { ptrCache := empty.insert ⟨(exprKey source).address, .sort 8⟩ 999 } + let ordinary := (ingestExpr {} context 0 source).run {} + expect (match ordinary with | .ok (id, state) => let target : Dag := ⟨state.interner.nodes⟩ match reIngestExpr {} target (ReIndex.ofDag target) context 0 source poisoned.ptrCache 0 with | .ok actual _ _ => actual == id | _ => false - | .error _ => false : Bool) ++ - test "a 36-level shared DAG keeps linear ingestion work" - (match (ingestExpr {} context 0 dag).run {} with + | .error _ => false) + it "a 36-level shared DAG keeps linear ingestion work" do + let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } + let dag : Ixon.Expr := (List.range 36).foldl (fun e _ => .app e e) (.var 3) + expect (match (ingestExpr {} context 0 dag).run {} with | .ok (_, state) => state.interner.nodes.size == 37 && state.visits == 37 - | .error _ => false : Bool) - -def expansionTests (_ : Unit) : TestSeq := - let chainTable (k : Nat) : Array Ixon.Expr := - #[.var 0] ++ (Array.range (k - 1)).map fun i => .app (.share i.toUInt64) (.var 0) - let validTables := runGen 17 do - let mut ok := true - for _ in [0:100] do - -- A random valid backward table: entry i is a node over earlier Shares and leaves. - let k := 1 + (← rand 6) - let mut table : Array Ixon.Expr := #[] - for i in [0:k] do - let pick : RGen Ixon.Expr := do - if i > 0 && (← rand 2) == 0 then pure (.share (← rand i).toUInt64) else genLeaf - table := table.push (← genNode #[← pick, ← pick, ← pick]) - let roots := #[Ixon.Expr.app (.share (k - 1).toUInt64) (.share 0), .share (← rand k).toUInt64] - let info : ConstantInfo := .defn ⟨.defn, .safe, {}, 0, roots[0]!, roots[1]!⟩ - let c : Constant := { info, sharing := table, refs := #[], univs := #[] } - match expandConstantSharing c with - | .ok c' => ok := ok && constantInfoRoots c'.info == roots.map (naiveExpand table) - | .error _ => ok := false - return ok - group "bounded share expansion" <| - test "expansion equals direct substitution on 100 random backward tables" validTables ++ - test "forward reference is rejected" + | .error _ => false) + +def expansionTests : Spec := + describe "bounded share expansion" do + it "expansion equals direct substitution on 100 random backward tables" do + let validTables := runGen 17 do + let mut ok := true + for _ in [0:100] do + -- A random valid backward table: entry i is a node over earlier Shares and leaves. + let k := 1 + (← rand 6) + let mut table : Array Ixon.Expr := #[] + for i in [0:k] do + let pick : RGen Ixon.Expr := do + if i > 0 && (← rand 2) == 0 then pure (.share (← rand i).toUInt64) else genLeaf + table := table.push (← genNode #[← pick, ← pick, ← pick]) + let roots := #[Ixon.Expr.app (.share (k - 1).toUInt64) (.share 0), .share (← rand k).toUInt64] + let info : ConstantInfo := .defn ⟨.defn, .safe, {}, 0, roots[0]!, roots[1]!⟩ + let c : Constant := { info, sharing := table, refs := #[], univs := #[] } + match expandConstantSharing c with + | .ok c' => ok := ok && constantInfoRoots c'.info == roots.map (naiveExpand table) + | .error _ => ok := false + return ok + expect validTables + itBool "forward reference is rejected" (isErr (optimizeSharingTable #[.share 1, P] #[.share 0]) - (· == .nonBackwardShare 0 1)) ++ - test "self reference is rejected" + (· == .nonBackwardShare 0 1)) + itBool "self reference is rejected" (isErr (optimizeSharingTable #[.app (.share 0) P] #[.share 0]) - (· == .nonBackwardShare 0 0)) ++ - test "out-of-range root reference is rejected" - (isErr (optimizeSharingTable #[] #[.share 3]) (· == .shareOutOfRange none 3 0)) ++ - test "re-expanding the DAG's own roots gives their IDs; an encoding of another term (the fast path's fallback) gives it a fresh ID" + (· == .nonBackwardShare 0 0)) + itBool "out-of-range root reference is rejected" + (isErr (optimizeSharingTable #[] #[.share 3]) (· == .shareOutOfRange none 3 0)) + itBool "re-expanding the DAG's own roots gives their IDs; an encoding of another term (the fast path's fallback) gives it a fresh ID" (match expandRoots #[arr (chain 2) (chain 2)] with | .ok ex => (reexpand {} ex.dag #[] #[arr (chain 2) (chain 2)]).toOption.map (·.2.1) == some ex.roots && ((reexpand {} ex.dag #[] #[arr (chain 3) (chain 3)]).toOption.map - fun r => r.2.1.all (· ≥ ex.dag.size)) == some true - | .error _ => false : Bool) ++ - test "out-of-range entry reference is rejected" - (isErr (optimizeSharingTable #[.share 5] #[P]) (· == .shareOutOfRange (some 0) 5 1)) ++ - test "Share in an expanded-root input is rejected" - (isErr (optimizeSharing #[P, .share 0]) (· == .shareInExpandedInput 1 0)) ++ - test "stored depth limit" - (isErr (optimizeSharing #[chain 20] { maxDepth := 10 }) (exhausted .depth)) ++ - test "expanded height limit (shallow entries, deep expansion)" - (isErr (optimizeSharingTable (chainTable 40) #[.share 39] { maxDepth := 20 }) - (exhausted .depth)) ++ - test "distinct-node limit" - (isErr (optimizeSharing #[chain 30] { maxNodes := 10 }) (exhausted .nodes)) ++ - test "walk limit" - (isErr (optimizeSharing #[chain 30] { maxExprVisits := 10 }) (exhausted .exprVisits)) ++ - test "unreachable entries do not affect the result" + fun r => r.2.1.all (fun i => decide (i ≥ ex.dag.size))) == some true + | .error _ => false) + itBool "out-of-range entry reference is rejected" + (isErr (optimizeSharingTable #[.share 5] #[P]) (· == .shareOutOfRange (some 0) 5 1)) + itBool "Share in an expanded-root input is rejected" + (isErr (optimizeSharing #[P, .share 0]) (· == .shareInExpandedInput 1 0)) + itBool "stored depth limit" + (isErr (optimizeSharing #[chain 20] { maxDepth := 10 }) (exhausted .depth)) + itBool "expanded height limit (shallow entries, deep expansion)" + (let chainTable (k : Nat) : Array Ixon.Expr := + #[.var 0] ++ (Array.range (k - 1)).map fun i => .app (.share i.toUInt64) (.var 0) + isErr (optimizeSharingTable (chainTable 40) #[.share 39] { maxDepth := 20 }) + (exhausted .depth)) + itBool "distinct-node limit" + (isErr (optimizeSharing #[chain 30] { maxNodes := 10 }) (exhausted .nodes)) + itBool "walk limit" + (isErr (optimizeSharing #[chain 30] { maxExprVisits := 10 }) (exhausted .exprVisits)) + itBool "unreachable entries do not affect the result" (let c := axiomOf (arr (chain 2) (chain 2)) let garbage : Constant := { c with info := .axio ⟨false, 0, arr (.share 2) (.share 2)⟩, @@ -545,22 +566,22 @@ def sampleInfos : List ConstantInfo := .recr ⟨false, false, 0, 0, 0, 0, 0, e 13, #[⟨0, e 14⟩]⟩], .muts #[] ] -def rootApiTests (_ : Unit) : TestSeq := - let shift (rs : Array Ixon.Expr) := rs.map fun r => Ixon.Expr.app r (.var 99) - group "root extraction and reassembly" <| - test "constantInfoRoots = Ix.CompileM.constantInfoRootExprs on every kind" - (sampleInfos.all fun i => constantInfoRoots i == Ix.CompileM.constantInfoRootExprs i) ++ - test "withRoots consumes exactly the extracted roots in order" - (sampleInfos.all fun i => - let rs := shift (constantInfoRoots i) - match withRoots i rs with - | .ok i' => constantInfoRoots i' == rs && (withRoots i' (constantInfoRoots i)).toOption == some i - | .error _ => false) ++ - test "mapRoots f info = withRoots info ((constantInfoRoots info).map f) on every kind" +def rootApiTests : Spec := + describe "root extraction and reassembly" do + itBool "constantInfoRoots = Ix.CompileM.constantInfoRootExprs on every kind" + (sampleInfos.all fun i => constantInfoRoots i == Ix.CompileM.constantInfoRootExprs i) + itBool "withRoots consumes exactly the extracted roots in order" + (let shift (rs : Array Ixon.Expr) := rs.map fun r => Ixon.Expr.app r (.var 99) + sampleInfos.all fun i => + let rs := shift (constantInfoRoots i) + match withRoots i rs with + | .ok i' => constantInfoRoots i' == rs && (withRoots i' (constantInfoRoots i)).toOption == some i + | .error _ => false) + itBool "mapRoots f info = withRoots info ((constantInfoRoots info).map f) on every kind" (sampleInfos.all fun i => let g := fun r => Ixon.Expr.app r (.var 98) - (withRoots i ((constantInfoRoots i).map g)).toOption == some (mapRoots g i)) ++ - test "withRoots rejects one root too many / too few" + (withRoots i ((constantInfoRoots i).map g)).toOption == some (mapRoots g i)) + itBool "withRoots rejects one root too many / too few" (sampleInfos.all fun i => let rs := constantInfoRoots i isErr (withRoots i (rs.push P)) (· == .rootCountMismatch rs.size (rs.size + 1)) && @@ -648,85 +669,84 @@ def genSpines : RGen (Array Ixon.Expr) := do roots := roots.push (.app e e) return roots -def spineWalkTests (_ : Unit) : TestSeq := - let (checked, err) := runGen 53 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:200] do - if err.isSome then break - let roots ← genSpines - match expandRoots roots with - | .ok ex => - let n := ex.dag.size - let p := Prep.ofDag ex.dag - let mut width : Array (Option Nat) := Array.replicate n none - for t in [0:n] do - if (← rand 3) == 0 then - let idx := [← rand 8, 8 + (← rand 300), 65530 + (← rand 12), 2^32 + (← rand 3)][← rand 4]! - width := width.set! t (some (shareWidth idx)) - checked := checked + 1 - unless (p.costsAll width).1 == walkCosts ex.dag width && - p.base == walkCosts ex.dag (Array.replicate n none) do - err := some s!"case {i}: available-descendant evaluation differs from the full spine walk" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "telescope evaluation vs full spine walk" <| - test s!"{checked} long-spine DAGs with random dictionaries (widths 1–5): costs equal the O(l) walk over every cut" (err.isNone && checked == 200) ++ - (match err with | some m => test m false | none => .done) - -def deepTests (_ : Unit) : TestSeq := - let d := 10000 - let nested : Ixon.Expr := - (List.range d).foldl (fun acc i => .app (.var (i % 2).toUInt64) acc) (.sort 0) - let telescope : Ixon.Expr := - (List.range d).foldl (fun acc i => .lam (.var (i % 3).toUInt64) acc) (.sort 0) - group "deep inputs" <| - withOk "deep" (optimizeSharing #[nested, telescope]) fun r => - test s!"{d}-deep argument nesting and a {d}-binder telescope optimize under default limits ({r.variableBytes} bytes = unshared {r.unsharedBytes})" - (r.variableBytes == r.unsharedBytes && +def spineWalkTests : Spec := + describe "telescope evaluation vs full spine walk" do + it "200 long-spine DAGs with random dictionaries (widths 1–5): costs equal the O(l) walk over every cut" do + let (checked, err) := runGen 53 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:200] do + if err.isSome then break + let roots ← genSpines + match expandRoots roots with + | .ok ex => + let n := ex.dag.size + let p := Prep.ofDag ex.dag + let mut width : Array (Option Nat) := Array.replicate n none + for t in [0:n] do + if (← rand 3) == 0 then + let idx := [← rand 8, 8 + (← rand 300), 65530 + (← rand 12), 2^32 + (← rand 3)][← rand 4]! + width := width.set! t (some (shareWidth idx)) + checked := checked + 1 + unless (p.costsAll width).1 == walkCosts ex.dag width && + p.base == walkCosts ex.dag (Array.replicate n none) do + err := some s!"case {i}: available-descendant evaluation differs from the full spine walk" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == 200) s!"checked {checked} != 200" + +def deepTests : Spec := + describe "deep inputs" do + it "10000-deep argument nesting and a 10000-binder telescope optimize under default limits" do + let d := 10000 + let nested : Ixon.Expr := + (List.range d).foldl (fun acc i => .app (.var (i % 2).toUInt64) acc) (.sort 0) + let telescope : Ixon.Expr := + (List.range d).foldl (fun acc i => .lam (.var (i % 3).toUInt64) acc) (.sort 0) + withOk "deep" (optimizeSharing #[nested, telescope]) fun r => + expect (r.variableBytes == r.unsharedBytes && r.variableBytes == exprSize nested + exprSize telescope + 1 && r.variableBytes == (serExpr nested).size + (serExpr telescope).size + 1) + s!"variableBytes={r.variableBytes}, unsharedBytes={r.unsharedBytes}" -def dictionaryTestsWith (fixMax fixOffMax genTarget genMaxOrders : Nat) (_ : Unit) : TestSeq := +def dictionaryTestsWith (fixMax fixOffMax genTarget genMaxOrders : Nat) : Spec := let fixtures : List (String × Array Ixon.Expr) := [("T2→T2", #[arr (chain 2) (chain 2)]), ("A→A→B→B", #[tiedMinimaRoot]), ("mixed spines", #[.app (.app (.lam P (arr P P)) (arr P P)) (.app (.var 0) (arr P P))]), ("let/prj", #[.letE false (.value .many) (arr P P) (.prj 0 1 (.app (.var 0) P)) (.app (.var 0) P)])] - let fixtureSeq := fixtures.foldl (init := .done) fun acc (name, roots) => - acc ++ withOk name (expandRoots roots) fun ex => - -- Up to `fixMax` of the ordered dictionaries (strided when there are - -- more), each at indices 0.., and `fixOffMax` of them at every index offset. - let total := (orderedSubsets ex.dag.size (List.range ex.dag.size)).length - let stride := if total > fixMax then 7 else 1 - let (c1, e1) := dictionaryAgreement ex.dag [0] fixMax stride - let (c2, e2) := dictionaryAgreement ex.dag dictOffsets fixOffMax (stride * 3) - let err := e1.or e2 - test s!"{name}: C_M and byte-least materialization = enumeration ({c1 + c2} cases over {total} ordered dictionaries, stride {stride}; {dictOffsets.length} index offsets)" - (err.isNone) ++ - (match err with | some m => test m false | none => .done) - let (genChecked, genErr) := runGen 19 do - let mut checked := 0 - let mut err : Option String := none - let mut cases := 0 - for _ in [0:400] do - if cases ≥ genTarget || err.isSome then break - let roots ← genRoots 3 4 2 - match expandRoots roots with - | .ok ex => - if ex.dag.size ≤ 5 then - cases := cases + 1 - let (c, e) := dictionaryAgreement ex.dag [0, 6, 254] genMaxOrders - checked := checked + c - if let some m := e then err := some s!"{m} roots={reprStr roots}" - | .error _ => pure () - return (checked, err) - group "fixed-dictionary optimizer vs enumeration" <| - fixtureSeq ++ - test s!"generated inputs (N ≤ 5): {genChecked} (dictionary, term) cases agree" genErr.isNone ++ - (match genErr with | some m => test m false | none => .done) - -def dictionaryTests (_ : Unit) : TestSeq := dictionaryTestsWith 2000 300 60 400 () -def dictionaryTestsPR (_ : Unit) : TestSeq := dictionaryTestsWith 120 40 15 80 () + describe "fixed-dictionary optimizer vs enumeration" do + for (name, roots) in fixtures do + it s!"{name}: C_M and byte-least materialization = enumeration" do + withOk name (expandRoots roots) fun ex => do + -- Up to `fixMax` of the ordered dictionaries (strided when there are + -- more), each at indices 0.., and `fixOffMax` of them at every index offset. + let total := (orderedSubsets ex.dag.size (List.range ex.dag.size)).length + let stride := if total > fixMax then 7 else 1 + let (_, e1) := dictionaryAgreement ex.dag [0] fixMax stride + let (_, e2) := dictionaryAgreement ex.dag dictOffsets fixOffMax (stride * 3) + if let some m := e1.or e2 then fail m + it s!"generated inputs (N ≤ 5, up to {genTarget} cases): (dictionary, term) cases agree" do + let (_, genErr) := runGen 19 do + let mut checked := 0 + let mut err : Option String := none + let mut cases := 0 + for _ in [0:400] do + if cases ≥ genTarget || err.isSome then break + let roots ← genRoots 3 4 2 + match expandRoots roots with + | .ok ex => + if ex.dag.size ≤ 5 then + cases := cases + 1 + let (c, e) := dictionaryAgreement ex.dag [0, 6, 254] genMaxOrders + checked := checked + c + if let some m := e then err := some s!"{m} roots={reprStr roots}" + | .error _ => pure () + return (checked, err) + if let some m := genErr then fail m + +def dictionaryTests : Spec := dictionaryTestsWith 2000 300 60 400 +def dictionaryTestsPR : Spec := dictionaryTestsWith 120 40 15 80 /-! ## Full optimizer vs exhaustive oracle (P1/P3) -/ @@ -760,17 +780,19 @@ def oracleAgreement (seed cases maxN : Nat) (product : Bool) : Nat × Nat × Nat err := some s!"case {attempts}: error {reprStr e} roots={reprStr roots}" return (checked, skipped, tables, err) -def oracleTestsWith (partCases prodCases : Nat) (_ : Unit) : TestSeq := - let (n1, s1, t1, e1) := oracleAgreement 23 partCases 6 false - let (n2, s2, t2, e2) := oracleAgreement 29 prodCases 4 true - group "optimizer vs exhaustive oracle (full key)" <| - test s!"per-part oracle: {n1} generated constants (N ≤ 6, all kinds and let modes, {t1} tables) agree on bytes and table IDs ({s1} skipped: oracle budget)" (e1.isNone && n1 == partCases) ++ - (match e1 with | some m => test m false | none => .done) ++ - test s!"full-product oracle: {n2} generated constants (N ≤ 4, {t2} tables) agree ({s2} skipped: oracle budget)" (e2.isNone && n2 == prodCases) ++ - (match e2 with | some m => test m false | none => .done) +def oracleTestsWith (partCases prodCases : Nat) : Spec := + describe "optimizer vs exhaustive oracle (full key)" do + it s!"per-part oracle: {partCases} generated constants (N ≤ 6, all kinds and let modes) agree on bytes and table IDs" do + let (n1, s1, t1, e1) := oracleAgreement 23 partCases 6 false + if let some m := e1 then fail m + expect (n1 == partCases) s!"checked {n1}/{partCases} ({t1} tables, {s1} skipped)" + it s!"full-product oracle: {prodCases} generated constants (N ≤ 4) agree" do + let (n2, s2, t2, e2) := oracleAgreement 29 prodCases 4 true + if let some m := e2 then fail m + expect (n2 == prodCases) s!"checked {n2}/{prodCases} ({t2} tables, {s2} skipped)" -def oracleTests (_ : Unit) : TestSeq := oracleTestsWith 150 40 () -def oracleTestsPR (_ : Unit) : TestSeq := oracleTestsWith 30 10 () +def oracleTests : Spec := oracleTestsWith 150 40 +def oracleTestsPR : Spec := oracleTestsWith 30 10 /-- Unit-width relaxation (§4.1): with no telescope merging and at most 8 positive-weight terms of indegree ≥ 2, the minimum variable length is @@ -794,27 +816,28 @@ def unitWidthLength (roots : Array Ixon.Expr) : Option Nat := Id.run do return some (roots.size + kstar + tag0Size kstar + distinct.foldl (fun acc t => acc + w t) 0) -def unitWidthTestsWith (target minRequired : Nat) (_ : Unit) : TestSeq := - let (checked, err) := runGen 31 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:600] do - if checked ≥ target || err.isSome then break - let roots ← genRoots 6 14 4 (noMerge := true) - let some expected := unitWidthLength roots | continue - match optimizeSharing roots with - | .ok r => - checked := checked + 1 - unless r.variableBytes == expected do - err := some s!"case {i}: exact={r.variableBytes} unit={expected} roots={reprStr roots}" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "unit-width relaxation oracle" <| - test s!"exact length = unit-width optimum on {checked} merge-free generated inputs" (err.isNone && checked ≥ minRequired) ++ - (match err with | some m => test m false | none => .done) +def unitWidthTestsWith (target minRequired : Nat) : Spec := + describe "unit-width relaxation oracle" do + it s!"exact length = unit-width optimum on up to {target} merge-free generated inputs (≥ {minRequired})" do + let (checked, err) := runGen 31 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:600] do + if checked ≥ target || err.isSome then break + let roots ← genRoots 6 14 4 (noMerge := true) + let some expected := unitWidthLength roots | continue + match optimizeSharing roots with + | .ok r => + checked := checked + 1 + unless r.variableBytes == expected do + err := some s!"case {i}: exact={r.variableBytes} unit={expected} roots={reprStr roots}" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (decide (checked ≥ minRequired)) s!"checked {checked} < {minRequired}" -def unitWidthTests (_ : Unit) : TestSeq := unitWidthTestsWith 150 100 () -def unitWidthTestsPR (_ : Unit) : TestSeq := unitWidthTestsWith 50 50 () +def unitWidthTests : Spec := unitWidthTestsWith 150 100 +def unitWidthTestsPR : Spec := unitWidthTestsWith 50 50 /-- Independent atoms: for a fixed stored set the optimal order gives the cheapest slots to the most-used atoms, so a brute force over subsets gives @@ -834,80 +857,87 @@ def atomsBrute (sizes occs : Array Nat) : Nat := Id.run do if mask == 0 || cost < best then best := cost return best -def atomsTests (_ : Unit) : TestSeq := - let (checked, err) := runGen 37 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:12] do - let n := 9 + (← rand 3) - let mut atoms : Array Ixon.Expr := #[] - let mut occs : Array Nat := #[] - for j in [0:n] do - atoms := atoms.push (.ref (j + 2).toUInt64 (Array.replicate (← rand 4) 0)) - occs := occs.push (2 + (← rand 12)) - let roots := (Array.range n).foldl (fun acc j => acc ++ Array.replicate occs[j]! atoms[j]!) #[] - let sizes := atoms.map exprSize - let expected := atomsBrute sizes occs - match optimizeSharing roots with - | .ok r => - checked := checked + 1 - unless r.variableBytes == expected do - err := some s!"case {i}: exact={r.variableBytes} brute={expected} occs={occs} sizes={sizes}" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "multi-width buckets vs brute force" <| - test s!"independent atoms (9–11 atoms, slots cross index 8): {checked} cases equal the brute-force minimum" (err.isNone && checked == 12) ++ - (match err with | some m => test m false | none => .done) +def atomsTests : Spec := + describe "multi-width buckets vs brute force" do + it "independent atoms (9–11 atoms, slots cross index 8): 12 cases equal the brute-force minimum" do + let (checked, err) := runGen 37 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:12] do + let n := 9 + (← rand 3) + let mut atoms : Array Ixon.Expr := #[] + let mut occs : Array Nat := #[] + for j in [0:n] do + atoms := atoms.push (.ref (j + 2).toUInt64 (Array.replicate (← rand 4) 0)) + occs := occs.push (2 + (← rand 12)) + let roots := (Array.range n).foldl (fun acc j => acc ++ Array.replicate occs[j]! atoms[j]!) #[] + let sizes := atoms.map exprSize + let expected := atomsBrute sizes occs + match optimizeSharing roots with + | .ok r => + checked := checked + 1 + unless r.variableBytes == expected do + err := some s!"case {i}: exact={r.variableBytes} brute={expected} occs={occs} sizes={sizes}" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == 12) s!"checked {checked} != 12" /-! ## §2 fixtures -/ def witness2 : Constant := axiomOf (arr (chain 2) (chain 2)) -def witnessTests (_ : Unit) : TestSeq := - -- A valid 17-byte encoding of T2 → T2, two bytes above the minimum. - let altBytes := ByteArray.mk #[0xd2, 0x00, 0x00, 0x91, 0xb1, 0xb1, 0x02, 0x91, - 0x00, 0x00, 0x91, 0x00, 0xb0, 0x00, 0x01, 0x00, 0x00] - let alt := (deConstant altBytes).toOption.getD witness2 - group "fixture T2 → T2 (17 → 15)" <| - test "the 17-byte encoding decodes to T2 → T2" - (hexOf (serConstant alt) == "d2000091b1b1029100009100b000010000" && +def witnessTests : Spec := + describe "fixture T2 → T2 (17 → 15)" do + it "the 17-byte encoding decodes to T2 → T2" do + -- A valid 17-byte encoding of T2 → T2, two bytes above the minimum. + let altBytes := ByteArray.mk #[0xd2, 0x00, 0x00, 0x91, 0xb1, 0xb1, 0x02, 0x91, + 0x00, 0x00, 0x91, 0x00, 0xb0, 0x00, 0x01, 0x00, 0x00] + let alt := (deConstant altBytes).toOption.getD witness2 + expect (hexOf (serConstant alt) == "d2000091b1b1029100009100b000010000" && (expandConstantSharing alt).toOption.map (constantInfoRoots ·.info) == - some (constantInfoRoots witness2.info)) ++ - test "unshared is 16 bytes" (cbytes witness2 == 16) ++ - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots witness2.info)) (fun r => - test "exact table term IDs = [T2] = [2]" (r.tableTerms == #[2])) ++ - withOk "exact" (normalizeConstantSharing witness2) (fun n => - test "exact bytes d2000091b0b0019200000000010000 (15)" - (hexOf (serConstant n) == "d2000091b0b0019200000000010000")) ++ - withOk "exact from the 17-byte encoding" (normalizeConstantSharing alt) (fun n => - test "normalizing the 17-byte encoding gives the same 15 bytes" - (hexOf (serConstant n) == "d2000091b0b0019200000000010000")) ++ - withOk "oracle" (oracleConstant witness2) (fun (oc, o) => - test s!"per-part oracle: 15-byte unique minimum over {o.work.tables} ordered tables" - (hexOf (serConstant oc) == "d2000091b0b0019200000000010000" && - o.work.tables == 65 && o.minima.size == 1)) + some (constantInfoRoots witness2.info)) + itBool "unshared is 16 bytes" (cbytes witness2 == 16) + it "exact table term IDs = [T2] = [2]" do + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots witness2.info)) fun r => + expect (r.tableTerms == #[2]) + it "exact bytes d2000091b0b0019200000000010000 (15)" do + withOk "exact" (normalizeConstantSharing witness2) fun n => + expect (hexOf (serConstant n) == "d2000091b0b0019200000000010000") + it "normalizing the 17-byte encoding gives the same 15 bytes" do + let altBytes := ByteArray.mk #[0xd2, 0x00, 0x00, 0x91, 0xb1, 0xb1, 0x02, 0x91, + 0x00, 0x00, 0x91, 0x00, 0xb0, 0x00, 0x01, 0x00, 0x00] + let alt := (deConstant altBytes).toOption.getD witness2 + withOk "exact from the 17-byte encoding" (normalizeConstantSharing alt) fun n => + expect (hexOf (serConstant n) == "d2000091b0b0019200000000010000") + it "per-part oracle: 15-byte unique minimum over 65 ordered tables" do + withOk "oracle" (oracleConstant witness2) fun (oc, o) => + expect (hexOf (serConstant oc) == "d2000091b0b0019200000000010000" && + o.work.tables == 65 && o.minima.size == 1) /-- Full-product brute-force oracle over all 3,061,082 complete candidates for `witness2` (nightly sweep). -/ -def witnessProductOracleTests (_ : Unit) : TestSeq := - group "fixture T2 → T2 (full-product oracle)" <| - withOk "product oracle" (oracleConstant witness2 {} true) (fun (oc, o) => - test s!"full-product oracle: {o.work.candidates} complete candidates, 15-byte unique minimum" - (hexOf (serConstant oc) == "d2000091b0b0019200000000010000" && - o.work.candidates == 3061082 && o.minima.size == 1)) +def witnessProductOracleTests : Spec := + describe "fixture T2 → T2 (full-product oracle)" do + it "full-product oracle: 3061082 complete candidates, 15-byte unique minimum" do + withOk "product oracle" (oracleConstant witness2 {} true) fun (oc, o) => + expect (hexOf (serConstant oc) == "d2000091b0b0019200000000010000" && + o.work.candidates == 3061082 && o.minima.size == 1) def witness16 : Constant := axiomOf (arr (chain 16) (chain 16)) -def t16Tests (_ : Unit) : TestSeq := - let only16 : Constant := { witness16 with - info := .axio ⟨false, 0, arr (.share 0) (.share 0)⟩, sharing := #[chain 16] } - group "fixture T16 → T16" <| - test "unshared is 46 bytes" (cbytes witness16 == 46) ++ - test "storing only T16 is 30 bytes" (cbytes only16 == 30) ++ - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots witness16.info)) (fun r => - withOk "exact" (normalizeConstantSharing witness16) fun n => - test s!"exact certified minimum = {cbytes n} bytes ≤ 30 (candidates {r.stats.candidates}, states reached {r.stats.statesReached}, expanded {r.stats.statesExpanded}, pruned {r.stats.statesPruned}, transitions {r.stats.transitions})" - (cbytes n ≤ 30 && cbytes n == r.variableBytes + 7)) +def t16Tests : Spec := + describe "fixture T16 → T16" do + itBool "unshared is 46 bytes" (cbytes witness16 == 46) + itBool "storing only T16 is 30 bytes" + (let only16 : Constant := { witness16 with + info := .axio ⟨false, 0, arr (.share 0) (.share 0)⟩, sharing := #[chain 16] } + cbytes only16 == 30) + it "exact certified minimum ≤ 30 bytes" do + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots witness16.info)) fun r => + withOk "exact" (normalizeConstantSharing witness16) fun n => + expect (decide (cbytes n ≤ 30) && cbytes n == r.variableBytes + 7) + s!"cbytes={cbytes n}, variableBytes={r.variableBytes}" /-- The nine-Ref fixture, built as in the production probe: atoms sorted by the blake3 hash of their encoding, each twice, then 98 more uses of the last (hot) atom; one @@ -926,198 +956,212 @@ def nineRef : Constant × Ixon.Expr := univs := #[.zero] } (c, hot) -def nineRefTests (_ : Unit) : TestSeq := - let (c, hot) := nineRef - -- Two tables of the nine atoms: hash order (the hot atom last, in the 2-byte - -- slot 8) and most-used first. - let atoms := (constantInfoRoots c.info).foldl - (fun acc a => if acc.contains a then acc else acc.push a) #[] - let tableWith (table : Array Ixon.Expr) : Constant := - let idxOf (a : Ixon.Expr) : Nat := (table.findIdx? (· == a)).getD 0 - let roots := (constantInfoRoots c.info).map fun a => Ixon.Expr.share (idxOf a).toUInt64 - match withRoots c.info roots with - | .ok info => { c with info, sharing := table } - | .error _ => c - let hashOrder := tableWith atoms - let freqTable := #[hot] ++ (atoms.filter (· != hot)) - group "fixture nine independent Refs (677 → 579)" <| - test "hot atom is Ref(2,[0,0,0])" (hot == .ref 2 #[0, 0, 0]) ++ - test "hash order: 677 bytes, hot atom in slot 8" - (cbytes hashOrder == 677 && atoms.size == 9 && atoms[8]? == some hot) ++ - test "same entries, frequency order: 579 bytes" (cbytes (tableWith freqTable) == 579) ++ - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) (fun r => - withOk "exact" (normalizeConstantSharing c) fun n => - test s!"exact: {cbytes n} bytes, table IDs {r.tableTerms}, hot atom at a width-1 slot" - (cbytes n == 579 && r.tableTerms == #[0, 1, 2, 3, 4, 5, 6, 7, 8] && - ((n.sharing.findIdx? (· == hot)).map fun i => decide (i < 8)) == some true)) +def nineRefTests : Spec := + describe "fixture nine independent Refs (677 → 579)" do + it "hot atom is Ref(2,[0,0,0])" do + let (_, hot) := nineRef + expect (hot == .ref 2 #[0, 0, 0]) + it "hash order: 677 bytes, hot atom in slot 8" do + let (c, hot) := nineRef + let atoms := (constantInfoRoots c.info).foldl + (fun acc a => if acc.contains a then acc else acc.push a) #[] + let tableWith (table : Array Ixon.Expr) : Constant := + let idxOf (a : Ixon.Expr) : Nat := (table.findIdx? (· == a)).getD 0 + let roots := (constantInfoRoots c.info).map fun a => Ixon.Expr.share (idxOf a).toUInt64 + match withRoots c.info roots with + | .ok info => { c with info, sharing := table } + | .error _ => c + let hashOrder := tableWith atoms + expect (cbytes hashOrder == 677 && atoms.size == 9 && atoms[8]? == some hot) + it "same entries, frequency order: 579 bytes" do + let (c, hot) := nineRef + let atoms := (constantInfoRoots c.info).foldl + (fun acc a => if acc.contains a then acc else acc.push a) #[] + let tableWith (table : Array Ixon.Expr) : Constant := + let idxOf (a : Ixon.Expr) : Nat := (table.findIdx? (· == a)).getD 0 + let roots := (constantInfoRoots c.info).map fun a => Ixon.Expr.share (idxOf a).toUInt64 + match withRoots c.info roots with + | .ok info => { c with info, sharing := table } + | .error _ => c + let freqTable := #[hot] ++ (atoms.filter (· != hot)) + expect (cbytes (tableWith freqTable) == 579) + it "exact: 579 bytes, table IDs [0..8], hot atom at a width-1 slot" do + let (c, hot) := nineRef + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) fun r => + withOk "exact" (normalizeConstantSharing c) fun n => + expect (cbytes n == 579 && r.tableTerms == #[0, 1, 2, 3, 4, 5, 6, 7, 8] && + ((n.sharing.findIdx? (· == hot)).map fun i => decide (i < 8)) == some true) /-- Fast PR check for the tied-minima fixture: exact solver picks `[A]`. -/ -def tiedMinimaExactTests (_ : Unit) : TestSeq := - let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] - let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" - group "fixture three 21-byte minima (exact)" <| - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) (fun r => - withOk "exact" (normalizeConstantSharing c) fun n => - test "exact picks the [A] minimum (table IDs [2])" - (hexOf (serConstant n) == onlyA && r.tableTerms == #[2])) +def tiedMinimaExactTests : Spec := + describe "fixture three 21-byte minima (exact)" do + it "exact picks the [A] minimum (table IDs [2])" do + let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] + let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) fun r => + withOk "exact" (normalizeConstantSharing c) fun n => + expect (hexOf (serConstant n) == onlyA && r.tableTerms == #[2]) /-- Full 13,700-table exhaustive oracle check for the tied-minima fixture (nightly sweep). -/ -def tiedMinimaTests (_ : Unit) : TestSeq := - let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] - -- Table [A]: the root is one telescope with binders `Share 0`, `Share 0`, `B`, `P` - -- over `Type`; tables [A,B] and [B,A]: the root is cut at `B`, all `Share`s. - let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" - let first := "d2000093b0b0b1b10291000091000100020001" ++ "0000" - let second := "d2000093b1b1b0b00291000191000000020001" ++ "0000" - group "fixture three 21-byte minima" <| - withOk "oracle" (oracleConstant c) (fun (oc, o) => - test s!"oracle: minimum 21 over {o.work.tables} ordered tables; [A], [A,B] and [B,A] attain it; the least table [A] wins" - (cbytes oc == 21 && o.work.tables == 13700 && o.minima.size == 3 && +def tiedMinimaTests : Spec := + describe "fixture three 21-byte minima" do + it "oracle: minimum 21 over 13700 ordered tables; [A], [A,B] and [B,A] attain it; the least table [A] wins" do + let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] + -- Table [A]: the root is one telescope with binders `Share 0`, `Share 0`, `B`, `P` + -- over `Type`; tables [A,B] and [B,A]: the root is cut at `B`, all `Share`s. + let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" + let first := "d2000093b0b0b1b10291000091000100020001" ++ "0000" + let second := "d2000093b1b1b0b00291000191000000020001" ++ "0000" + withOk "oracle" (oracleConstant c) fun (oc, o) => + expect (cbytes oc == 21 && o.work.tables == 13700 && o.minima.size == 3 && o.minima.any (hexOf · == first) && o.minima.any (hexOf · == second) && - hexOf (serConstant oc) == onlyA && o.table == #[2])) ++ - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) (fun r => - withOk "exact" (normalizeConstantSharing c) fun n => - test "exact picks the [A] minimum (table IDs [2])" - (hexOf (serConstant n) == onlyA && r.tableTerms == #[2])) + hexOf (serConstant oc) == onlyA && o.table == #[2]) + it "exact picks the [A] minimum (table IDs [2])" do + let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] + let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) fun r => + withOk "exact" (normalizeConstantSharing c) fun n => + expect (hexOf (serConstant n) == onlyA && r.tableTerms == #[2]) /-- A parent stored before its separately stored descendant (which the parent's entry therefore inlines): seven hot atoms take slots 0–6, the 50-use parent `P = App(Var 0, D)` takes slot 7 and `D` (3 more uses) slot 8. -/ -def orderingTests (_ : Unit) : TestSeq := - let d : Ixon.Expr := .ref 1 #[0, 0, 0] - let p : Ixon.Expr := .app (.var 0) d - let hots := (Array.range 7).map fun i => Ixon.Expr.ref (i + 2).toUInt64 #[0, 0, 0] - let roots := hots.foldl (fun acc h => acc ++ Array.replicate 100 h) #[] ++ - Array.replicate 50 p ++ Array.replicate 3 d - group "ordering: parent before descendant" <| - withOk "exact" (optimizeSharing roots) fun r => - test s!"variable bytes {r.variableBytes} = 804, table IDs {r.tableTerms} = [2..8, 9 (P), 1 (D)], P's entry inlines D" - (r.variableBytes == 804 && r.tableTerms == #[2, 3, 4, 5, 6, 7, 8, 9, 1] && +def orderingTests : Spec := + describe "ordering: parent before descendant" do + it "variable bytes = 804, table IDs = [2..8, 9 (P), 1 (D)], P's entry inlines D" do + let d : Ixon.Expr := .ref 1 #[0, 0, 0] + let p : Ixon.Expr := .app (.var 0) d + let hots := (Array.range 7).map fun i => Ixon.Expr.ref (i + 2).toUInt64 #[0, 0, 0] + let roots := hots.foldl (fun acc h => acc ++ Array.replicate 100 h) #[] ++ + Array.replicate 50 p ++ Array.replicate 3 d + withOk "exact" (optimizeSharing roots) fun r => + expect (r.variableBytes == 804 && r.tableTerms == #[2, 3, 4, 5, 6, 7, 8, 9, 1] && r.sharing[7]? == some p) /-! ## Properties on generated inputs -/ -def propertyTestsWith (target : Nat) (_ : Unit) : TestSeq := - let (checked, err) := runGen 41 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:target] do - if err.isSome then break - let roots ← genRoots 5 12 4 - let c := wrapRoots roots i - let alt := alternateOf c - match normalizeConstantSharing c, optimizeSharingTable #[] (constantInfoRoots c.info) with - | .ok n, .ok r => - checked := checked + 1 - let idem := (normalizeConstantSharing n).toOption.map serConstant == some (serConstant n) - let fromAlt := (normalizeConstantSharing alt).toOption.map serConstant == some (serConstant n) - let fromExpanded := ((expandConstantSharing n).toOption.bind - fun e => (normalizeConstantSharing e).toOption).map serConstant == some (serConstant n) - let minimum := match checkExactMinimum n with - | .ok .minimum => true - | _ => false - let altCheck := match checkExactMinimum alt with - | .ok .minimum => serConstant alt == serConstant n - | .ok (.notMinimum exp) => exp == serConstant n - | .error _ => false - let f := fixedConstantBytes c - let fixedOk := cbytes n == f + r.variableBytes && cbytes c == f + r.unsharedBytes - let expandsBack := (expandConstantSharing n).toOption.map (fun e => constantInfoRoots e.info) == - some (constantInfoRoots c.info) - unless cbytes n ≤ cbytes c && cbytes n ≤ cbytes alt && idem && fromAlt && - fromExpanded && minimum && altCheck && fixedOk && expandsBack do - err := some s!"case {i}: exact={cbytes n} unshared={cbytes c} uniform-w1={cbytes alt} idem={idem} fromAlt={fromAlt} fromExpanded={fromExpanded} minimum={minimum} altCheck={altCheck} fixed={fixedOk} expands={expandsBack} roots={reprStr roots}" - | .error e, _ | _, .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "properties on generated inputs" <| - test s!"{checked} constants: exact ≤ unshared, exact ≤ uniform-w1, idempotent, normalize(uniform-w1) = normalize(expanded) = exact, check=minimum, decomposition, expansion preserved" (err.isNone && checked == target) ++ - (match err with | some m => test m false | none => .done) - -def propertyTests (_ : Unit) : TestSeq := propertyTestsWith 250 () -def propertyTestsPR (_ : Unit) : TestSeq := propertyTestsWith 60 () +def propertyTestsWith (target : Nat) : Spec := + describe "properties on generated inputs" do + it s!"{target} constants: exact ≤ unshared, exact ≤ uniform-w1, idempotent, normalize(uniform-w1) = normalize(expanded) = exact, check=minimum, decomposition, expansion preserved" do + let (checked, err) := runGen 41 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:target] do + if err.isSome then break + let roots ← genRoots 5 12 4 + let c := wrapRoots roots i + let alt := alternateOf c + match normalizeConstantSharing c, optimizeSharingTable #[] (constantInfoRoots c.info) with + | .ok n, .ok r => + checked := checked + 1 + let idem := (normalizeConstantSharing n).toOption.map serConstant == some (serConstant n) + let fromAlt := (normalizeConstantSharing alt).toOption.map serConstant == some (serConstant n) + let fromExpanded := ((expandConstantSharing n).toOption.bind + fun e => (normalizeConstantSharing e).toOption).map serConstant == some (serConstant n) + let minimum := match checkExactMinimum n with + | .ok .minimum => true + | _ => false + let altCheck := match checkExactMinimum alt with + | .ok .minimum => serConstant alt == serConstant n + | .ok (.notMinimum exp) => exp == serConstant n + | .error _ => false + let f := fixedConstantBytes c + let fixedOk := cbytes n == f + r.variableBytes && cbytes c == f + r.unsharedBytes + let expandsBack := (expandConstantSharing n).toOption.map (fun e => constantInfoRoots e.info) == + some (constantInfoRoots c.info) + unless cbytes n ≤ cbytes c && cbytes n ≤ cbytes alt && idem && fromAlt && + fromExpanded && minimum && altCheck && fixedOk && expandsBack do + err := some s!"case {i}: exact={cbytes n} unshared={cbytes c} uniform-w1={cbytes alt} idem={idem} fromAlt={fromAlt} fromExpanded={fromExpanded} minimum={minimum} altCheck={altCheck} fixed={fixedOk} expands={expandsBack} roots={reprStr roots}" + | .error e, _ | _, .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == target) s!"checked {checked} != {target}" + +def propertyTests : Spec := propertyTestsWith 250 +def propertyTestsPR : Spec := propertyTestsWith 60 /-- LB pruning never changes a result: compare with the search with pruning disabled, on inputs with 9–11 candidates (beyond the oracle's reach; tables can cross the 8-slot width boundary). -/ -def pruningTestsWith (genTarget wideTarget : Nat) (_ : Unit) : TestSeq := - let (checked, wide, err) := runGen 43 do - let mut checked := 0 - let mut wide := 0 - let mut err : Option String := none - for i in [0:4000] do - if checked ≥ genTarget || err.isSome then break - let roots ← genRoots 8 24 6 - let cands := match sharingProfile (wrapRoots roots 0) with - | .ok p => p.candidates - | .error _ => 0 - if cands < 9 || cands > 11 then continue - match optimizeSharing roots, - optimizeSharing roots { prune := false } with - | .ok a, .ok b => - checked := checked + 1 - if a.sharing.size > 8 then wide := wide + 1 - unless a.sharing == b.sharing && a.roots == b.roots && - a.tableTerms == b.tableTerms && a.variableBytes == b.variableBytes do - err := some s!"case {i}: pruned={a.variableBytes} {a.tableTerms} unpruned={b.variableBytes} {b.tableTerms}" - | .error e, _ | _, .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, wide, err) - -- Many profitable atoms plus nested nodes over them: optimal tables - -- usually exceed 8 entries, so widths 1 and 2 compete. - let genWide : RGen (Array Ixon.Expr) := do - let n := 9 + (← rand 3) - let atoms : Array Ixon.Expr := (Array.range n).map fun j => - .ref (j + 2).toUInt64 (Array.replicate (1 + j % 3) 0) - let mut roots : Array Ixon.Expr := #[] - for j in [0:n] do - for _ in [0:2 + (← rand 4)] do roots := roots.push atoms[j]! - for _ in [0:(← rand 3)] do - let a := atoms[← rand n]! - let b := atoms[← rand n]! - let node : Ixon.Expr := if (← rand 2) == 0 then .app a b else arr a b - for _ in [0:2 + (← rand 2)] do roots := roots.push node - return roots - let (wChecked, wWide, wErr) := runGen 47 do - let mut checked := 0 - let mut wide := 0 - let mut err : Option String := none - for i in [0:400] do - if checked ≥ wideTarget || err.isSome then break - let roots ← genWide - let cands := match sharingProfile (wrapRoots roots 0) with - | .ok p => p.candidates - | .error _ => 0 - if cands > 12 then continue - match optimizeSharing roots, - optimizeSharing roots { prune := false } with - | .ok a, .ok b => - checked := checked + 1 - if a.sharing.size > 8 then wide := wide + 1 - unless a.sharing == b.sharing && a.roots == b.roots && - a.tableTerms == b.tableTerms && a.variableBytes == b.variableBytes do - err := some s!"wide case {i}: pruned={a.variableBytes} {a.tableTerms} unpruned={b.variableBytes} {b.tableTerms}" - | .error e, _ | _, .error e => err := some s!"wide case {i}: error {reprStr e}" - return (checked, wide, err) - group "pruning never changes the result" <| - test s!"{checked} inputs with 9–11 candidates ({wide} with more than 8 table entries): pruned search = unpruned search" - (err.isNone && checked == genTarget) ++ - (match err with | some m => test m false | none => .done) ++ - test s!"{wChecked} atom-heavy inputs with ≤ 12 candidates ({wWide} with more than 8 table entries): pruned = unpruned" - (wErr.isNone && wChecked == wideTarget && wWide > 0) ++ - (match wErr with | some m => test m false | none => .done) - -def pruningTests (_ : Unit) : TestSeq := pruningTestsWith 25 15 () -def pruningTestsPR (_ : Unit) : TestSeq := pruningTestsWith 5 5 () - -def profileTests (_ : Unit) : TestSeq := - group "sharing profile" <| - withOk "T2 → T2" (sharingProfile witness2) (fun p => - test "T2→T2: N=4, 3 repeated, 2 candidates (T1,T2), height 3, unshared 9 variable bytes" - (p.distinctSubterms == 4 && p.repeated == 3 && p.candidates == 2 && p.height == 3 && - p.unsharedBytes == 9 && p.inputBytes == 9)) ++ - withOk "T16 → T16" (sharingProfile witness16) (fun p => - test "T16→T16: N=18, 16 candidates, unshared 39 variable bytes" - (p.distinctSubterms == 18 && p.candidates == 16 && p.unsharedBytes == 39)) +def pruningTestsWith (genTarget wideTarget : Nat) : Spec := + describe "pruning never changes the result" do + it s!"{genTarget} inputs with 9–11 candidates: pruned search = unpruned search" do + let (checked, _, err) := runGen 43 do + let mut checked := 0 + let mut wide := 0 + let mut err : Option String := none + for i in [0:4000] do + if checked ≥ genTarget || err.isSome then break + let roots ← genRoots 8 24 6 + let cands := match sharingProfile (wrapRoots roots 0) with + | .ok p => p.candidates + | .error _ => 0 + if cands < 9 || cands > 11 then continue + match optimizeSharing roots, + optimizeSharing roots { prune := false } with + | .ok a, .ok b => + checked := checked + 1 + if a.sharing.size > 8 then wide := wide + 1 + unless a.sharing == b.sharing && a.roots == b.roots && + a.tableTerms == b.tableTerms && a.variableBytes == b.variableBytes do + err := some s!"case {i}: pruned={a.variableBytes} {a.tableTerms} unpruned={b.variableBytes} {b.tableTerms}" + | .error e, _ | _, .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, wide, err) + if let some m := err then fail m + expect (checked == genTarget) s!"checked {checked} != {genTarget}" + it s!"{wideTarget} atom-heavy inputs with ≤ 12 candidates: pruned = unpruned" do + -- Many profitable atoms plus nested nodes over them: optimal tables + -- usually exceed 8 entries, so widths 1 and 2 compete. + let genWide : RGen (Array Ixon.Expr) := do + let n := 9 + (← rand 3) + let atoms : Array Ixon.Expr := (Array.range n).map fun j => + .ref (j + 2).toUInt64 (Array.replicate (1 + j % 3) 0) + let mut roots : Array Ixon.Expr := #[] + for j in [0:n] do + for _ in [0:2 + (← rand 4)] do roots := roots.push atoms[j]! + for _ in [0:(← rand 3)] do + let a := atoms[← rand n]! + let b := atoms[← rand n]! + let node : Ixon.Expr := if (← rand 2) == 0 then .app a b else arr a b + for _ in [0:2 + (← rand 2)] do roots := roots.push node + return roots + let (wChecked, wWide, wErr) := runGen 47 do + let mut checked := 0 + let mut wide := 0 + let mut err : Option String := none + for i in [0:400] do + if checked ≥ wideTarget || err.isSome then break + let roots ← genWide + let cands := match sharingProfile (wrapRoots roots 0) with + | .ok p => p.candidates + | .error _ => 0 + if cands > 12 then continue + match optimizeSharing roots, + optimizeSharing roots { prune := false } with + | .ok a, .ok b => + checked := checked + 1 + if a.sharing.size > 8 then wide := wide + 1 + unless a.sharing == b.sharing && a.roots == b.roots && + a.tableTerms == b.tableTerms && a.variableBytes == b.variableBytes do + err := some s!"wide case {i}: pruned={a.variableBytes} {a.tableTerms} unpruned={b.variableBytes} {b.tableTerms}" + | .error e, _ | _, .error e => err := some s!"wide case {i}: error {reprStr e}" + return (checked, wide, err) + if let some m := wErr then fail m + expect (wChecked == wideTarget && decide (wWide > 0)) s!"wChecked={wChecked}, wWide={wWide}" + +def pruningTests : Spec := pruningTestsWith 25 15 +def pruningTestsPR : Spec := pruningTestsWith 5 5 + +def profileTests : Spec := + describe "sharing profile" do + it "T2→T2: N=4, 3 repeated, 2 candidates (T1,T2), height 3, unshared 9 variable bytes" do + withOk "T2 → T2" (sharingProfile witness2) fun p => + expect (p.distinctSubterms == 4 && p.repeated == 3 && p.candidates == 2 && p.height == 3 && + p.unsharedBytes == 9 && p.inputBytes == 9) + it "T16→T16: N=18, 16 candidates, unshared 39 variable bytes" do + withOk "T16 → T16" (sharingProfile witness16) fun p => + expect (p.distinctSubterms == 18 && p.candidates == 16 && p.unsharedBytes == 39) /-! ## Safety, limits, empty input -/ @@ -1125,53 +1169,41 @@ def staleProjection : Constant := let info : ConstantInfo := .iPrj ⟨0, testRefs[0]!⟩ { info, sharing := #[arr P P, .share 0], refs := testRefs, univs := #[] } -def safetyTests (_ : Unit) : TestSeq := - let roots := constantInfoRoots witness16.info - group "resource limits and edge cases" <| - test "state limit → resourceExhausted, no result" - (isErr (optimizeSharing roots { maxStates := 5 }) (exhausted .states)) ++ - test "transition limit → resourceExhausted" - (isErr (optimizeSharing roots { maxTransitions := 5 }) (exhausted .transitions)) ++ - test "cost-evaluation limit → resourceExhausted" - (isErr (optimizeSharing roots { maxCostEvals := 50 }) (exhausted .costEvals)) ++ - test "output-byte limit → resourceExhausted" - (isErr (optimizeSharing roots { maxOutputBytes := 10 }) (exhausted .outputBytes)) ++ - test "materialization limit → resourceExhausted" - (isErr (optimizeSharing roots { maxMaterialize := 3 }) (exhausted .materialize)) ++ - test "oracle table limit → resourceExhausted" - (isErr (oracleConstant witness2 { maxOracleTables := 10 }) (exhausted .oracleTables)) ++ - test "oracle variant limit → resourceExhausted" - (isErr (oracleConstant witness2 { maxOracleVariants := 100 }) (exhausted .oracleVariants)) ++ - test "larger limits do not change a successful result" - ((optimizeSharing roots { maxStates := 1 <<< 30, maxCostEvals := 1 <<< 40 }).toOption.map (·.sharing) == - (optimizeSharing roots).toOption.map (·.sharing)) ++ - withOk "empty input" (optimizeSharing #[]) (fun r => - test "no roots: empty table, 1 variable byte (the table count)" - (r.sharing.isEmpty && r.roots.isEmpty && r.variableBytes == 1)) ++ - withOk "projection with a stale table" - (normalizeConstantSharing staleProjection) (fun n => - test "a constant without roots drops its (unreachable) table" n.sharing.isEmpty) ++ - test "repeated identical roots can be shared as whole roots" +def safetyTests : Spec := + describe "resource limits and edge cases" do + itBool "state limit → resourceExhausted, no result" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxStates := 5 }) (exhausted .states)) + itBool "transition limit → resourceExhausted" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxTransitions := 5 }) (exhausted .transitions)) + itBool "cost-evaluation limit → resourceExhausted" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxCostEvals := 50 }) (exhausted .costEvals)) + itBool "output-byte limit → resourceExhausted" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxOutputBytes := 10 }) (exhausted .outputBytes)) + itBool "materialization limit → resourceExhausted" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxMaterialize := 3 }) (exhausted .materialize)) + itBool "oracle table limit → resourceExhausted" + (isErr (oracleConstant witness2 { maxOracleTables := 10 }) (exhausted .oracleTables)) + itBool "oracle variant limit → resourceExhausted" + (isErr (oracleConstant witness2 { maxOracleVariants := 100 }) (exhausted .oracleVariants)) + itBool "larger limits do not change a successful result" + (let roots := constantInfoRoots witness16.info + (optimizeSharing roots { maxStates := 1 <<< 30, maxCostEvals := 1 <<< 40 }).toOption.map (·.sharing) == + (optimizeSharing roots).toOption.map (·.sharing)) + it "no roots: empty table, 1 variable byte (the table count)" do + withOk "empty input" (optimizeSharing #[]) fun r => + expect (r.sharing.isEmpty && r.roots.isEmpty && r.variableBytes == 1) + it "a constant without roots drops its (unreachable) table" do + withOk "projection with a stale table" (normalizeConstantSharing staleProjection) fun n => + expect n.sharing.isEmpty + itBool "repeated identical roots can be shared as whole roots" ((optimizeSharing #[chain 5, chain 5, chain 5]).toOption.map (·.sharing.size) == some 1) -/-! ## Randomized codec properties (SlimCheck) -/ - -def slimTests (_ : Unit) : TestSeq := - checkIO "exprSize = serExpr size (SlimCheck)" (∀ e : Ixon.Expr, exprSize e == (serExpr e).size) ++ - checkIO "Constant length decomposition (SlimCheck)" (∀ c : Constant, decompositionHolds c) - -/-! ## Suite -/ +/-! ## Randomized codec properties -/ -/-- Build and run a test group only when the suite executes (never at module -initialization), printing its report and wall time. -/ -def deferred (descr : String) (mk : Unit → TestSeq) : TestSeq := - .individualIO descr none (do - let start ← IO.monoMsNow - let (ok, out) ← (mk ()).runIO 4 - let stop ← IO.monoMsNow - IO.print out - IO.println s!" [{descr}: {stop - start} ms]" - return (ok, 0, 0, if ok then none else some s!"a check in '{descr}' failed; see above")) .done +def slimTests : Spec := + describe "randomized codec properties" do + prop "exprSize = serExpr size" fun (e : Ixon.Expr) => exprSize e == (serExpr e).size + prop "Constant length decomposition" fun (c : Constant) => decompositionHolds c /-! ## Limits: defaults and overrides -/ @@ -1229,76 +1261,79 @@ def limitSpecMismatches : List String := | .error _ => none if got == want then none else some spec -def limitTests (_ : Unit) : TestSeq := - let d : Limits := {} - let resources : List Resource := [.exprVisits, .depth, .nodes, .states, .transitions, - .costEvals, .outputBytes, .materialize, .materializeWork, .knapsackCells] - group "limits" <| - test "the defaults are the safety net" - (d.maxExprVisits == 2 ^ 40 && d.maxDepth == 2 ^ 20 && d.maxNodes == 2 ^ 32 && - d.maxStates == 2 ^ 40 && d.maxTransitions == 2 ^ 40 && d.maxCostEvals == 2 ^ 50 && - d.maxOutputBytes == 2 ^ 40 && d.maxMaterialize == 2 ^ 40 && - d.maxMaterializeWork == 2 ^ 56 && d.maxKnapsackCells == 2 ^ 28) ++ - test "overrides set the named limits, left to right" - (match d.withOverrides " states = 2^10 ,cost_evals=12345, output_bytes=max,, states=2^11" with +def limitTests : Spec := + describe "limits" do + itBool "the defaults are the safety net" + (let d : Limits := {} + d.maxExprVisits == 2 ^ 40 && d.maxDepth == 2 ^ 20 && d.maxNodes == 2 ^ 32 && + d.maxStates == 2 ^ 40 && d.maxTransitions == 2 ^ 40 && d.maxCostEvals == 2 ^ 50 && + d.maxOutputBytes == 2 ^ 40 && d.maxMaterialize == 2 ^ 40 && + d.maxMaterializeWork == 2 ^ 56 && d.maxKnapsackCells == 2 ^ 28) + itBool "overrides set the named limits, left to right" + (let d : Limits := {} + match d.withOverrides " states = 2^10 ,cost_evals=12345, output_bytes=max,, states=2^11" with | .ok l => l.maxStates == 2048 && l.maxCostEvals == 12345 && l.maxOutputBytes == limitMax && l.maxDepth == d.maxDepth - | .error _ => false : Bool) ++ - test "the retired Rust port's keys are unknown keys" - (["height=5", "work=2^3", "layer_states=9", "input_nodes=1", "distinct_nodes=1", - "candidates=1"].all fun s => overrideFails (d.withOverrides s)) ++ - test "unbounded sets every production limit to max; a later item still applies" - (match d.withOverrides "unbounded,states=2" with + | .error _ => false) + itBool "the retired Rust port's keys are unknown keys" + (let d : Limits := {} + ["height=5", "work=2^3", "layer_states=9", "input_nodes=1", "distinct_nodes=1", + "candidates=1"].all fun s => overrideFails (d.withOverrides s)) + itBool "unbounded sets every production limit to max; a later item still applies" + (let d : Limits := {} + match d.withOverrides "unbounded,states=2" with | .ok l => l.maxDepth == limitMax && l.maxMaterializeWork == limitMax && l.maxStates == 2 && l.maxOracleTables == d.maxOracleTables - | .error _ => false : Bool) ++ - test "malformed overrides are errors" - (["bogus=1", "states", "states=2^64", "states=-1", "states=1e3", "=3", - "states=18446744073709551616"].all fun s => overrideFails (d.withOverrides s)) ++ - test s!"the {limitSpecParity.length} grammar specs get the listed verdict" - (limitSpecParity.length == 35 && limitSpecMismatches.isEmpty) ++ - test "every production resource key names a limit" - (resources.all fun r => (d.set? r.key 3).isSome) - -public def suite : List TestSeq := [ - deferred "integer widths" widthTests, - deferred "limits" limitTests, - deferred "exact expression length" exprSizeTests, - deferred "Constant length decomposition" decompositionTests, - deferred "structural IDs" structuralIdTests, - deferred "representation independence" representationTestsPR, - deferred "checked expression cache" cacheTests, - deferred "bounded share expansion" expansionTests, - deferred "root extraction and reassembly" rootApiTests, - deferred "fixed-dictionary optimizer vs enumeration" dictionaryTestsPR, - deferred "telescope evaluation vs full spine walk" spineWalkTests, - deferred "deep inputs" deepTests, - deferred "optimizer vs exhaustive oracle" oracleTestsPR, - deferred "unit-width relaxation oracle" unitWidthTestsPR, - deferred "multi-width buckets vs brute force" atomsTests, - deferred "fixture T2 → T2" witnessTests, - deferred "fixture T16 → T16" t16Tests, - deferred "fixture nine Refs" nineRefTests, - deferred "fixture three 21-byte minima (exact)" tiedMinimaExactTests, - deferred "ordering: parent before descendant" orderingTests, - deferred "properties on generated inputs" propertyTestsPR, - deferred "pruning never changes the result" pruningTestsPR, - deferred "sharing profile" profileTests, - deferred "resource limits and edge cases" safetyTests, - slimTests (), -] + | .error _ => false) + itBool "malformed overrides are errors" + (let d : Limits := {} + ["bogus=1", "states", "states=2^64", "states=-1", "states=1e3", "=3", + "states=18446744073709551616"].all fun s => overrideFails (d.withOverrides s)) + itBool s!"the {limitSpecParity.length} grammar specs get the listed verdict" + (limitSpecParity.length == 35 && limitSpecMismatches.isEmpty) + itBool "every production resource key names a limit" + (let d : Limits := {} + let resources : List Resource := [.exprVisits, .depth, .nodes, .states, .transitions, + .costEvals, .outputBytes, .materialize, .materializeWork, .knapsackCells] + resources.all fun r => (d.set? r.key 3).isSome) + +public def suite : Spec := do + widthTests + limitTests + exprSizeTests + decompositionTests + structuralIdTests + representationTestsPR + cacheTests + expansionTests + rootApiTests + dictionaryTestsPR + spineWalkTests + deepTests + oracleTestsPR + unitWidthTestsPR + atomsTests + witnessTests + t16Tests + nineRefTests + tiedMinimaExactTests + orderingTests + propertyTestsPR + pruningTestsPR + profileTests + safetyTests + slimTests /-- Full exhaustive oracle and large-sweep checks for nightly CI (`exact-sharing-full`). -/ -public def nightlySuite : List TestSeq := [ - deferred "representation independence (full)" representationTests, - deferred "fixed-dictionary optimizer vs enumeration (full)" dictionaryTests, - deferred "optimizer vs exhaustive oracle (full)" oracleTests, - deferred "unit-width relaxation oracle (full)" unitWidthTests, - deferred "fixture T2 → T2 (full-product oracle)" witnessProductOracleTests, - deferred "fixture three 21-byte minima (exhaustive oracle)" tiedMinimaTests, - deferred "properties on generated inputs (full)" propertyTests, - deferred "pruning never changes the result (full)" pruningTests, -] +public def nightlySuite : Spec := do + representationTests + dictionaryTests + oracleTests + unitWidthTests + witnessProductOracleTests + tiedMinimaTests + propertyTests + pruningTests end Tests.SharingExact diff --git a/Tests/Ix/SharingTiered.lean b/Tests/Ix/SharingTiered.lean index 1e7c54d81d..19870c9a81 100644 --- a/Tests/Ix/SharingTiered.lean +++ b/Tests/Ix/SharingTiered.lean @@ -57,25 +57,25 @@ def sameAsCandidates (l : ShareLayout) (c : Constant) : Bool := | .ok r => candidatesOk l c r | .error _ => false -def fixtureTests (_ : Unit) : TestSeq := - let (nine, hot) := nineRef - let w2 := witness2 - let w16 := axiomOf (arr (chain 16) (chain 16)) +def fixtureTests : Spec := let l := ShareLayout.tagN - group "fixtures, TagN layout" ( - withOk "T2" (normalizeConstantSharingTiered l w2) (fun n => - test s!"T2 → T2: {cbytes n} bytes = 15, d2000091b0b0019200000000010000" - (cbytes n == 15 && hexOf (serConstant n) == "d2000091b0b0019200000000010000" && - sameAsCandidates l w2)) ++ - withOk "T16" (normalizeConstantSharingTiered l w16) (fun n => - test s!"T16 → T16: {cbytes n} bytes = 30, the candidates run alone agree" - (cbytes n == 30 && sameAsCandidates l w16)) ++ - withOk "nine" (canonicalSharingTieredTable l #[] (constantInfoRoots nine.info)) (fun r => - withOk "nine" (normalizeConstantSharingTiered l nine) fun n => - test s!"nine Refs: {cbytes n} bytes = 579, the candidates run alone agree; w={r.stats.w} (candidates {r.stats.candidateLengths}); first tier {r.stats.firstTier} holds the hot atom; phase-1 layout {r.stats.phase1LayoutBytes}, final {r.stats.phase3LayoutBytes}" - (cbytes n == 579 && selectionOk r && sameAsCandidates l nine && + describe "fixtures, TagN layout" do + it "T2 → T2: 15 bytes, d2000091b0b0019200000000010000" do + let w2 := witness2 + withOk "T2" (normalizeConstantSharingTiered l w2) fun n => + expect (cbytes n == 15 && hexOf (serConstant n) == "d2000091b0b0019200000000010000" && + sameAsCandidates l w2) + it "T16 → T16: 30 bytes, the candidates run alone agree" do + let w16 := axiomOf (arr (chain 16) (chain 16)) + withOk "T16" (normalizeConstantSharingTiered l w16) fun n => + expect (cbytes n == 30 && sameAsCandidates l w16) + it "nine Refs: 579 bytes, the candidates run alone agree, first tier holds the hot atom" do + let (nine, hot) := nineRef + withOk "nine" (canonicalSharingTieredTable l #[] (constantInfoRoots nine.info)) fun r => + withOk "nine" (normalizeConstantSharingTiered l nine) fun n => + expect (cbytes n == 579 && selectionOk r && sameAsCandidates l nine && r.stats.firstTier.contains 2 && - (n.sharing.findIdx? (· == hot)).map (fun i => decide (i < 8)) == some true))) + (n.sharing.findIdx? (· == hot)).map (fun i => decide (i < 8)) == some true) /-- A heavy parent `P` over two lighter children, next to more than eight ready atoms used three times each. The pinned order fills the first tier @@ -95,43 +95,44 @@ def genHeavyParent : RGen (Array Ixon.Expr) := do roots := roots.push c2 return roots -def allocationTests (_ : Unit) : TestSeq := - let (checked, changed, saved, beatOther, err) := runGen 71 do - let mut checked := 0 - let mut changed := 0 - let mut saved := 0 - let mut beatOther := 0 - let mut err : Option String := none - for i in [0:120] do - if err.isSome then break - let roots ← if i % 2 == 0 then genHeavyParent else genRoots 6 16 5 - let c := wrapRoots roots i - let l := ShareLayout.tagN - match canonicalSharingTieredTable l #[] (constantInfoRoots c.info), - normalizeConstantSharingTiered l c with - | .ok r, .ok n => - checked := checked + 1 - if r.stats.finalRefCost < r.stats.phase1RefCost then changed := changed + 1 - if r.stats.savings > 0 then saved := saved + 1 - let fixedOk := cbytes n == fixedConstantBytes c + r.result.variableBytes - let idem := (normalizeConstantSharingTiered l n).toOption.map serConstant == - some (serConstant n) - -- every candidate run alone has its recorded length, and the result - -- is the candidate at its winning width - let candOk := candidatesOk l c r - if r.stats.candidateLengths.any (·.2 > r.stats.phase3LayoutBytes) then - beatOther := beatOther + 1 - unless r.stats.phase3LayoutBytes ≤ r.stats.phase1LayoutBytes && - r.stats.finalRefCost ≤ r.stats.phase1RefCost && fixedOk && idem && - selectionOk r && candOk && - r.result.modelBytes == r.result.variableBytes do - err := some s!"case {i} {reprStr l}: phase1={r.stats.phase1LayoutBytes} final={r.stats.phase3LayoutBytes} refcost {r.stats.phase1RefCost}->{r.stats.finalRefCost} fixed={fixedOk} idem={idem} selection={selectionOk r} {r.stats.candidateLengths} candidates={candOk}" - | .error e, _ | _, .error e => err := some s!"case {i} {reprStr l}: error {reprStr e}" - return (checked, changed, saved, beatOther, err) - group "slot allocation and re-materialization" <| - test s!"{checked} runs (120 inputs, TagN layout): final ≤ phase 1 in layout bytes and in reference cost; serialized = fixed + variable; wire price = serialized; idempotent; the fewest bytes over w = 1, 2, 3 (lower w at a tie), each candidate as when run alone ({changed} runs where allocation lowered the reference cost, {saved} with positive savings, {beatOther} where another width was longer)" - (err.isNone && checked == 120 && changed > 0) ++ - (match err with | some m => test m false | none => .done) +def allocationTests : Spec := + describe "slot allocation and re-materialization" do + it "120 runs (TagN layout): final ≤ phase 1 in layout bytes and reference cost; serialized = fixed + variable; idempotent; fewest bytes over w = 1, 2, 3" do + let (checked, changed, saved, beatOther, err) := runGen 71 do + let mut checked := 0 + let mut changed := 0 + let mut saved := 0 + let mut beatOther := 0 + let mut err : Option String := none + for i in [0:120] do + if err.isSome then break + let roots ← if i % 2 == 0 then genHeavyParent else genRoots 6 16 5 + let c := wrapRoots roots i + let l := ShareLayout.tagN + match canonicalSharingTieredTable l #[] (constantInfoRoots c.info), + normalizeConstantSharingTiered l c with + | .ok r, .ok n => + checked := checked + 1 + if r.stats.finalRefCost < r.stats.phase1RefCost then changed := changed + 1 + if r.stats.savings > 0 then saved := saved + 1 + let fixedOk := cbytes n == fixedConstantBytes c + r.result.variableBytes + let idem := (normalizeConstantSharingTiered l n).toOption.map serConstant == + some (serConstant n) + -- every candidate run alone has its recorded length, and the result + -- is the candidate at its winning width + let candOk := candidatesOk l c r + if r.stats.candidateLengths.any (·.2 > r.stats.phase3LayoutBytes) then + beatOther := beatOther + 1 + unless r.stats.phase3LayoutBytes ≤ r.stats.phase1LayoutBytes && + r.stats.finalRefCost ≤ r.stats.phase1RefCost && fixedOk && idem && + selectionOk r && candOk && + r.result.modelBytes == r.result.variableBytes do + err := some s!"case {i} {reprStr l}: phase1={r.stats.phase1LayoutBytes} final={r.stats.phase3LayoutBytes} refcost {r.stats.phase1RefCost}->{r.stats.finalRefCost} fixed={fixedOk} idem={idem} selection={selectionOk r} {r.stats.candidateLengths} candidates={candOk}" + | .error e, _ | _, .error e => err := some s!"case {i} {reprStr l}: error {reprStr e}" + return (checked, changed, saved, beatOther, err) + if let some m := err then fail m + expect (checked == 120 && decide (changed > 0)) + s!"checked={checked}, changed={changed}, saved={saved}, beatOther={beatOther}" /-- Brute force over all subsets: dependency-closed, at most `cap` terms, @@ -161,34 +162,34 @@ def bruteTier (n : Nat) (weight : Array Nat) (deps : Array (Array Nat)) (cap : N | some (_, vec) => (items.zipIdx.filter (fun (_, i) => vec[i]!)).map (·.1) |>.qsort (· < ·) | none => #[] -def tierBruteTests (_ : Unit) : TestSeq := - let (checked, err) := runGen 73 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:300] do - if err.isSome then break - let n := 1 + (← rand 12) - let mut weight : Array Nat := #[] - let mut deps : Array (Array Nat) := #[] - for t in [0:n] do - weight := weight.push (1 + (← rand 4)) - let mut ds : Array Nat := #[] - for u in [0:t] do - if (← rand 4) == 0 then ds := ds.push u - deps := deps.push ds - let cap := min 8 (1 + (← rand n)) - match firstTier (Array.range n) (weight[·]!) (fun t => deps[t]!.toList) cap {} with - | .ok (s, _) => - checked := checked + 1 - let expected := bruteTier n weight deps cap - unless s == expected do - err := some s!"case {i}: n={n} cap={cap} weights={weight} deps={deps} search={s} brute={expected}" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "first-tier allocation vs brute force" <| - test s!"{checked} random dependency DAGs (≤ 12 terms, cap ≤ 8, weights 1–4): branch and bound = enumeration, including ties" - (err.isNone && checked == 300) ++ - (match err with | some m => test m false | none => .done) +def tierBruteTests : Spec := + describe "first-tier allocation vs brute force" do + it "300 random dependency DAGs (≤ 12 terms, cap ≤ 8, weights 1–4): branch and bound = enumeration, including ties" do + let (checked, err) := runGen 73 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:300] do + if err.isSome then break + let n := 1 + (← rand 12) + let mut weight : Array Nat := #[] + let mut deps : Array (Array Nat) := #[] + for t in [0:n] do + weight := weight.push (1 + (← rand 4)) + let mut ds : Array Nat := #[] + for u in [0:t] do + if (← rand 4) == 0 then ds := ds.push u + deps := deps.push ds + let cap := min 8 (1 + (← rand n)) + match firstTier (Array.range n) (weight[·]!) (fun t => deps[t]!.toList) cap {} with + | .ok (s, _) => + checked := checked + 1 + let expected := bruteTier n weight deps cap + unless s == expected do + err := some s!"case {i}: n={n} cap={cap} weights={weight} deps={deps} search={s} brute={expected}" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == 300) s!"checked {checked} != 300" /-- Reference Kahn priority order: repeatedly the remaining term whose dependencies in `rest` are all placed, of the largest weight, then the @@ -209,35 +210,35 @@ def kahnRef (weight : Nat → Nat) (deps : Nat → List Nat) (rest : Array Nat) remaining := remaining.erase t return out -def kahnTests (_ : Unit) : TestSeq := - let (checked, err) := runGen 91 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:300] do - if err.isSome then break - let n := 1 + (← rand 30) - let mut weight : Array Nat := #[] - let mut deps : Array (List Nat) := #[] - let mut rest : Array Nat := #[] - for t in [0:n] do - weight := weight.push (1 + (← rand 5)) - let mut ds : List Nat := [] - for u in [0:t] do - if (← rand 5) == 0 then ds := u :: ds - -- occasional repeated references - if (← rand 4) == 0 then if let some d := ds.head? then ds := d :: ds - deps := deps.push ds - if (← rand 4) != 0 then rest := rest.push t - let got := kahnOrder (weight[·]!) (deps[·]!) rest - let want := kahnRef (weight[·]!) (deps[·]!) rest - checked := checked + 1 - unless got == want do - err := some s!"case {i}: weights={weight} deps={deps} rest={rest} kahn={got} reference={want}" - return (checked, err) - group "Kahn priority order" <| - test s!"{checked} random dependency DAGs (≤ 30 terms, weights 1–5, repeated references, dependencies outside the set): kahnOrder = the reference order" - (err.isNone && checked == 300) ++ - (match err with | some m => test m false | none => .done) +def kahnTests : Spec := + describe "Kahn priority order" do + it "300 random dependency DAGs (≤ 30 terms, weights 1–5, repeated references, dependencies outside the set): kahnOrder = the reference order" do + let (checked, err) := runGen 91 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:300] do + if err.isSome then break + let n := 1 + (← rand 30) + let mut weight : Array Nat := #[] + let mut deps : Array (List Nat) := #[] + let mut rest : Array Nat := #[] + for t in [0:n] do + weight := weight.push (1 + (← rand 5)) + let mut ds : List Nat := [] + for u in [0:t] do + if (← rand 5) == 0 then ds := u :: ds + -- occasional repeated references + if (← rand 4) == 0 then if let some d := ds.head? then ds := d :: ds + deps := deps.push ds + if (← rand 4) != 0 then rest := rest.push t + let got := kahnOrder (weight[·]!) (deps[·]!) rest + let want := kahnRef (weight[·]!) (deps[·]!) rest + checked := checked + 1 + unless got == want do + err := some s!"case {i}: weights={weight} deps={deps} rest={rest} kahn={got} reference={want}" + return (checked, err) + if let some m := err then fail m + expect (checked == 300) s!"checked {checked} != 300" /-- An application spine of `1 + apps` nodes over `u = app(var 0, var 1)` (the spine's last term), next to hot references: 100 copies of the spine, 20 @@ -273,24 +274,27 @@ def candidatePaths (roots : Array Ixon.Expr) : let onePass := onePassOrder ex.dag order ex.roots (indexOfPrefix ex.dag.size order order.size) return (w, !onePass, sameMaterialization p order ex.roots ShareLayout.tagN.widthAt) -def fallbackTests (_ : Unit) : TestSeq := - withOk "spine witness" (candidatePaths (spineWitness 1287)) (fun paths => - withOk "spine witness" (canonicalSharingTieredTable .tagN #[] (spineWitness 1287)) fun r => - let perPrefix := (paths.filter (·.2.1)).size - test s!"spine of 1288 nodes: {perPrefix} candidate takes the per-prefix path (expected 1), candidates {r.stats.candidateLengths} (expected #[(1, 7106), (2, 7106), (3, 7123)]), every candidate equal to the specification" - (perPrefix == 1 && paths.all (·.2.2) && - r.stats.candidateLengths == #[(1, 7106), (2, 7106), (3, 7123)])) ++ - withOk "spine control" (candidatePaths (spineWitness 1286)) fun paths => - let perPrefix := (paths.filter (·.2.1)).size - test s!"spine of 1287 nodes: {perPrefix} candidates take the per-prefix path (expected 0), every candidate equal to the specification" - (perPrefix == 0 && paths.all (·.2.2)) - -def layoutTests (_ : Unit) : TestSeq := - test "TagN widths: 1 below 8, 2 below 1032, 3 below 66568, 4 below 16843784, 5 below 4311811080, then 9" - ([7, 8, 1031, 1032, 66567, 66568, 16843783, 16843784, 4311811079, 4311811080].map - ShareLayout.tagN.widthAt == [1, 2, 2, 3, 3, 4, 4, 5, 5, 9] && - tagNRung2End == 1032 && tagNRung3End == 66568 && tagNRung4End == 16843784 && - tagNRung5End == 4311811080) +def fallbackTests : Spec := + describe "phase-3 per-prefix fallback" do + it "spine of 1288 nodes: 1 candidate takes the per-prefix path, every candidate equal to the specification" do + withOk "spine witness" (candidatePaths (spineWitness 1287)) fun paths => + withOk "spine witness" (canonicalSharingTieredTable .tagN #[] (spineWitness 1287)) fun r => + let perPrefix := (paths.filter (·.2.1)).size + expect (perPrefix == 1 && paths.all (·.2.2) && + r.stats.candidateLengths == #[(1, 7106), (2, 7106), (3, 7123)]) + s!"perPrefix={perPrefix}, candidates={r.stats.candidateLengths}" + it "spine of 1287 nodes: 0 candidates take the per-prefix path, every candidate equal to the specification" do + withOk "spine control" (candidatePaths (spineWitness 1286)) fun paths => + let perPrefix := (paths.filter (·.2.1)).size + expect (perPrefix == 0 && paths.all (·.2.2)) s!"perPrefix={perPrefix}" + +def layoutTests : Spec := + describe "tiered layouts" do + itBool "TagN widths: 1 below 8, 2 below 1032, 3 below 66568, 4 below 16843784, 5 below 4311811080, then 9" + ([7, 8, 1031, 1032, 66567, 66568, 16843783, 16843784, 4311811079, 4311811080].map + ShareLayout.tagN.widthAt == [1, 2, 2, 3, 3, 4, 4, 5, 5, 9] && + tagNRung2End == 1032 && tagNRung3End == 66568 && tagNRung4End == 16843784 && + tagNRung5End == 4311811080) /-! ## The production construction at scale -/ @@ -339,31 +343,32 @@ def productionOk (c : Constant) (r : TieredSharingResult) (n : Constant) : Bool r.result.modelBytes == r.result.variableBytes && (normalizeConstantSharingTiered .tagN n).toOption.map serConstant == some (serConstant n) -def scaleTests (_ : Unit) : TestSeq := - let big := wrapRoots (scaleRoots 1040 12) 0 - let spine := wrapRoots (spineRoots 1288) 0 - let d := 10000 - let shared : Ixon.Expr := .ref 5 #[0, 0, 0, 0, 0] - let nested : Ixon.Expr := - (List.range d).foldl (fun acc i => .app (.var (i % 2).toUInt64) acc) shared - let telescope : Ixon.Expr := - (List.range d).foldl (fun acc i => .lam (.var (i % 3).toUInt64) acc) shared - let deep := wrapRoots #[nested, telescope, shared] 0 - group "the production construction at scale" <| - withOk "1040 fillers" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots big.info)) - (fun r => withOk "1040 fillers" (normalizeConstantSharingTiered .tagN big) fun n => - test s!"{r.result.stats.distinctSubterms} terms (parallel widths, ≥ {tieredParMin}), {n.sharing.size} entries (> 1032: 3-byte Shares), the phase-2 guard keeps the phase-1 order (reference cost {r.stats.phase1RefCost}); widths run alone agree, idempotent, serialized = fixed + variable" - (r.result.stats.distinctSubterms ≥ tieredParMin && n.sharing.size > 1032 && +def scaleTests : Spec := + describe "the production construction at scale" do + it s!"1040 fillers (parallel widths, ≥ {tieredParMin}), > 1032 entries (3-byte Shares), phase-2 guard keeps phase-1 order" do + let big := wrapRoots (scaleRoots 1040 12) 0 + withOk "1040 fillers" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots big.info)) fun r => + withOk "1040 fillers" (normalizeConstantSharingTiered .tagN big) fun n => + expect (decide (r.result.stats.distinctSubterms ≥ tieredParMin) && + decide (n.sharing.size > 1032) && r.stats.keptPhase1Order && r.stats.finalRefCost == r.stats.phase1RefCost && - productionOk big r n)) ++ - withOk "spine" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots spine.info)) - (fun r => withOk "spine" (normalizeConstantSharingTiered .tagN spine) fun n => - test s!"a 1288-argument App spine over a stored head: {cbytes n} bytes, {n.sharing.size} entries; widths run alone agree, idempotent, serialized = fixed + variable" - (n.sharing.size ≥ 1 && productionOk spine r n)) ++ - withOk "deep" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots deep.info)) - (fun r => withOk "deep" (normalizeConstantSharingTiered .tagN deep) fun n => - test s!"{d}-deep argument nesting and a {d}-binder telescope over a shared Ref: {cbytes n} bytes, {n.sharing.size} entries; widths run alone agree, idempotent, serialized = fixed + variable" - (n.sharing.size ≥ 1 && productionOk deep r n)) + productionOk big r n) + it "a 1288-argument App spine over a stored head: widths run alone agree, idempotent, serialized = fixed + variable" do + let spine := wrapRoots (spineRoots 1288) 0 + withOk "spine" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots spine.info)) fun r => + withOk "spine" (normalizeConstantSharingTiered .tagN spine) fun n => + expect (decide (n.sharing.size ≥ 1) && productionOk spine r n) + it "10000-deep argument nesting and a 10000-binder telescope over a shared Ref: widths run alone agree, idempotent, serialized = fixed + variable" do + let d := 10000 + let shared : Ixon.Expr := .ref 5 #[0, 0, 0, 0, 0] + let nested : Ixon.Expr := + (List.range d).foldl (fun acc i => .app (.var (i % 2).toUInt64) acc) shared + let telescope : Ixon.Expr := + (List.range d).foldl (fun acc i => .lam (.var (i % 3).toUInt64) acc) shared + let deep := wrapRoots #[nested, telescope, shared] 0 + withOk "deep" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots deep.info)) fun r => + withOk "deep" (normalizeConstantSharingTiered .tagN deep) fun n => + expect (decide (n.sharing.size ≥ 1) && productionOk deep r n) /-! ## The production construction under its limits -/ @@ -382,47 +387,49 @@ def compilerFailsWith (c : Constant) (l : Limits) (key : String) (v : Nat) : Boo (msg.splitOn s!"resource exhausted: {key} (limit {v})").length > 1 | _ => false -def productionLimitTests (_ : Unit) : TestSeq := - let t16c := axiomOf (arr (chain 16) (chain 16)) - let t16 := constantInfoRoots t16c.info +def productionLimitTests : Spec := + let d : Limits := {} + let mkT16 : Unit → Constant := fun () => axiomOf (arr (chain 16) (chain 16)) -- 128 two-use atoms: 128 uncertain components and the table-count bracket -- knapsack (`Tests.SharingUniform.bracketTests`). - let atomRoots : Array Ixon.Expr := (Array.range 128).foldl - (fun acc i => let a : Ixon.Expr := .ref i.toUInt64 #[0]; acc ++ #[a, a]) #[] - let atomsC := wrapRoots atomRoots 0 - let d : Limits := {} - let cases : List (String × Constant × Limits × Resource × Nat) := [ - ("T16", t16c, { d with maxExprVisits := 3 }, .exprVisits, 3), - ("T16", t16c, { d with maxDepth := 2 }, .depth, 2), - ("T16", t16c, { d with maxNodes := 2 }, .nodes, 2), - ("T16", t16c, { d with maxStates := 0 }, .states, 0), - ("128 atoms", atomsC, { d with maxStates := 50 }, .states, 50), - ("128 atoms", atomsC, { d with maxCostEvals := 10 }, .costEvals, 10), - ("T16", t16c, { d with maxOutputBytes := 10 }, .outputBytes, 10), - ("T16", t16c, { d with maxMaterialize := 3 }, .materialize, 3), - ("T16", t16c, { d with maxMaterializeWork := 3 }, .materializeWork, 3), - ("128 atoms", atomsC, { d with maxKnapsackCells := 10 }, .knapsackCells, 10)] - group "the production construction under its limits" <| - cases.foldl (init := .done) (fun acc (name, c, l, r, v) => - acc ++ test s!"{name}: {r.key} = {v} → canonicalSharingTiered fails with resourceExhausted {r.key} {v}; the compiler's builder with resourceLimit naming {r.key}" - (failsWith (constantInfoRoots c.info) l r v && compilerFailsWith c l r.key v)) ++ - test "the transitions limit meters only the width-state oracle: maxTransitions = 0 leaves T16 and the 128 atoms unchanged" - ((canonicalSharingTiered .tagN t16 { d with maxTransitions := 0 }).toOption.map + let mkAtomRoots : Unit → Array Ixon.Expr := fun () => + (Array.range 128).foldl + (fun acc i => let a : Ixon.Expr := .ref i.toUInt64 #[0]; acc ++ #[a, a]) #[] + let mkAtoms : Unit → Constant := fun () => wrapRoots (mkAtomRoots ()) 0 + let cases : List (String × (Unit → Constant) × Limits × Resource × Nat) := [ + ("T16", mkT16, { d with maxExprVisits := 3 }, .exprVisits, 3), + ("T16", mkT16, { d with maxDepth := 2 }, .depth, 2), + ("T16", mkT16, { d with maxNodes := 2 }, .nodes, 2), + ("T16", mkT16, { d with maxStates := 0 }, .states, 0), + ("128 atoms", mkAtoms, { d with maxStates := 50 }, .states, 50), + ("128 atoms", mkAtoms, { d with maxCostEvals := 10 }, .costEvals, 10), + ("T16", mkT16, { d with maxOutputBytes := 10 }, .outputBytes, 10), + ("T16", mkT16, { d with maxMaterialize := 3 }, .materialize, 3), + ("T16", mkT16, { d with maxMaterializeWork := 3 }, .materializeWork, 3), + ("128 atoms", mkAtoms, { d with maxKnapsackCells := 10 }, .knapsackCells, 10)] + describe "the production construction under its limits" do + for (name, mkC, l, r, v) in cases do + it s!"{name}: {r.key} = {v} → canonicalSharingTiered fails with resourceExhausted {r.key} {v}; the compiler's builder with resourceLimit naming {r.key}" do + let c := mkC () + expect (failsWith (constantInfoRoots c.info) l r v && compilerFailsWith c l r.key v) + it "the transitions limit meters only the width-state oracle: maxTransitions = 0 leaves T16 and the 128 atoms unchanged" do + let t16 := constantInfoRoots (mkT16 ()).info + let atomRoots := mkAtomRoots () + expect ((canonicalSharingTiered .tagN t16 { d with maxTransitions := 0 }).toOption.map (·.result.sharing) == (canonicalSharingTiered .tagN t16).toOption.map (·.result.sharing) && (canonicalSharingTiered .tagN atomRoots { d with maxTransitions := 0 }).toOption.map (·.result.variableBytes) == (canonicalSharingTiered .tagN atomRoots).toOption.map (·.result.variableBytes) && (canonicalSharingTiered .tagN t16).toOption.isSome) -public def suite : List TestSeq := [ - deferred "tiered layouts" layoutTests, - deferred "tiered fixtures" fixtureTests, - deferred "tiered allocation" allocationTests, - deferred "first-tier brute force" tierBruteTests, - deferred "Kahn priority order" kahnTests, - deferred "phase-3 per-prefix fallback" fallbackTests, - deferred "tiered at scale" scaleTests, - deferred "tiered limits" productionLimitTests, -] +public def suite : Spec := do + layoutTests + fixtureTests + allocationTests + tierBruteTests + kahnTests + fallbackTests + scaleTests + productionLimitTests end Tests.SharingTiered diff --git a/Tests/Ix/SharingUniform.lean b/Tests/Ix/SharingUniform.lean index 7a022af72d..c712f4ca92 100644 --- a/Tests/Ix/SharingUniform.lean +++ b/Tests/Ix/SharingUniform.lean @@ -118,124 +118,131 @@ def checkUniform (w : Nat) (roots : Array Ixon.Expr) : | .error e, _, _ => .error s!"w={w}: uniform error {reprStr e} roots={reprStr roots}" | _, .error e, _ | _, _, .error e => .error s!"w={w}: reference error {reprStr e} roots={reprStr roots}" -def agreementTestsWith (target : Nat) (_ : Unit) : TestSeq := - let (checked, cs, ce, un, maxComp, withUncertain, err) := runGen 61 do - let mut checked := 0 - let mut cs := 0 - let mut ce := 0 - let mut un := 0 - let mut maxComp := 0 - let mut withUncertain := 0 - let mut err : Option String := none - for i in [0:3000] do - if checked ≥ target || err.isSome then break - let roots ← genUniformRoots - let w := [1, 2, 3, 5][← rand 4]! - -- Keep the reference search small. - let refCands := match sharingProfile (wrapRoots roots 0) with - | .ok p => p.candidates - | .error _ => 100 - if refCands > 11 then continue - match checkUniform w roots with - | .ok (a, b, c, m) => - checked := checked + 1 - cs := cs + a - ce := ce + b - un := un + c - maxComp := max maxComp m - if c > 0 then withUncertain := withUncertain + 1 - | .error m => err := some s!"case {i}: {m}" - return (checked, cs, ce, un, maxComp, withUncertain, err) - group "uniform optimizer vs width-state reference (uniform widths)" <| - test s!"{checked} generated inputs (w ∈ 1,2,3,5; prefixes, 2-byte payloads, parent/child pairs, App chains, general): equal minimum (also = in-degree-≥2 reference); certain-stored ⊆ restricted optimum; certain-excluded in neither optimum; ≤ unshared ({cs} certain-stored, {ce} certain-excluded, {un} uncertain terms; {withUncertain} inputs with uncertain terms; largest component {maxComp})" - (err.isNone && checked == target) ++ - (match err with | some m => test m false | none => .done) - -def agreementTests (_ : Unit) : TestSeq := agreementTestsWith 400 () -def agreementTestsPR (_ : Unit) : TestSeq := agreementTestsWith 60 () - -def witnessTests (_ : Unit) : TestSeq := - let roots := constantInfoRoots witness2.info - let run (w : Nat) := optimizeSharingUniform w roots - group "uniform witness T2 → T2 (ids P=0 T1=1 T2=2 R=3)" <| - withOk "w=1" (run 1) (fun u => - test s!"w=1: T2 has gain 1, certain-stored at threshold 1 (no count bracket within reach), stores only T2, model {u.result.modelBytes} = 8" - (u.certainStored == #[2] && u.stored == #[2] && u.result.modelBytes == 8 && - u.result.variableBytes == 8)) ++ - withOk "w=2" (run 2) (fun u => - test s!"w=2: T2 uncertain, search stores nothing, model {u.result.modelBytes} = 9 (unshared); T1 certain-excluded" - (u.uncertain == #[2] && u.stored.isEmpty && u.result.modelBytes == 9 && - u.certainExcluded.contains 1)) ++ - withOk "w=3" (run 3) (fun u => - test s!"w=3: T1 and T2 certain-excluded, stores nothing, model {u.result.modelBytes} = 9 (unshared)" - (u.certainExcluded.contains 1 && u.certainExcluded.contains 2 && u.stored.isEmpty && - u.result.modelBytes == 9)) ++ - test "w=1,2,3 agree with the reference search" - ([1, 2, 3].all fun w => (checkUniform w roots).toOption.isSome) ++ - test "w=0 is rejected" (isErr (optimizeSharingUniform 0 roots) fun - | .formatBound _ _ => true - | _ => false) - -def t16Tests (_ : Unit) : TestSeq := - let roots := constantInfoRoots (axiomOf (arr (chain 16) (chain 16))).info - group "uniform T16 → T16" <| - withOk "w=1" (optimizeSharingUniform 1 roots) (fun u => - withOk "reference" (optimizeSharingUniformReference 1 roots) fun r => - test s!"w=1: model {u.result.modelBytes} = reference {r.modelBytes}; classes {u.certainStored.size} stored / {u.uncertain.size} uncertain / {u.certainExcluded.size} excluded; {u.statesVisited} states vs reference {r.stats.statesReached}" - (u.result.modelBytes == r.modelBytes && (checkUniform 1 roots).toOption.isSome)) +def agreementTestsWith (target : Nat) : Spec := + describe "uniform optimizer vs width-state reference (uniform widths)" do + it s!"{target} generated inputs (w ∈ 1,2,3,5; prefixes, 2-byte payloads, parent/child pairs, App chains, general)" do + let (checked, cs, ce, un, maxComp, withUncertain, err) := runGen 61 do + let mut checked := 0 + let mut cs := 0 + let mut ce := 0 + let mut un := 0 + let mut maxComp := 0 + let mut withUncertain := 0 + let mut err : Option String := none + for i in [0:3000] do + if checked ≥ target || err.isSome then break + let roots ← genUniformRoots + let w := [1, 2, 3, 5][← rand 4]! + -- Keep the reference search small. + let refCands := match sharingProfile (wrapRoots roots 0) with + | .ok p => p.candidates + | .error _ => 100 + if refCands > 11 then continue + match checkUniform w roots with + | .ok (a, b, c, m) => + checked := checked + 1 + cs := cs + a + ce := ce + b + un := un + c + maxComp := max maxComp m + if c > 0 then withUncertain := withUncertain + 1 + | .error m => err := some s!"case {i}: {m}" + return (checked, cs, ce, un, maxComp, withUncertain, err) + if let some m := err then fail m + expect (checked == target) + s!"checked {checked}/{target} ({cs} certain-stored, {ce} certain-excluded, {un} uncertain, {withUncertain} with uncertain, maxComp={maxComp})" + +def agreementTests : Spec := agreementTestsWith 400 +def agreementTestsPR : Spec := agreementTestsWith 60 + +def witnessTests : Spec := + describe "uniform witness T2 → T2 (ids P=0 T1=1 T2=2 R=3)" do + it "w=1: T2 has gain 1, certain-stored at threshold 1, stores only T2, model = 8" do + let roots := constantInfoRoots witness2.info + withOk "w=1" (optimizeSharingUniform 1 roots) fun u => + expect (u.certainStored == #[2] && u.stored == #[2] && u.result.modelBytes == 8 && + u.result.variableBytes == 8) + it "w=2: T2 uncertain, search stores nothing, model = 9 (unshared); T1 certain-excluded" do + let roots := constantInfoRoots witness2.info + withOk "w=2" (optimizeSharingUniform 2 roots) fun u => + expect (u.uncertain == #[2] && u.stored.isEmpty && u.result.modelBytes == 9 && + u.certainExcluded.contains 1) + it "w=3: T1 and T2 certain-excluded, stores nothing, model = 9 (unshared)" do + let roots := constantInfoRoots witness2.info + withOk "w=3" (optimizeSharingUniform 3 roots) fun u => + expect (u.certainExcluded.contains 1 && u.certainExcluded.contains 2 && u.stored.isEmpty && + u.result.modelBytes == 9) + itBool "w=1,2,3 agree with the reference search" + (let roots := constantInfoRoots witness2.info + [1, 2, 3].all fun w => (checkUniform w roots).toOption.isSome) + itBool "w=0 is rejected" + (let roots := constantInfoRoots witness2.info + isErr (optimizeSharingUniform 0 roots) fun + | .formatBound _ _ => true + | _ => false) + +def t16Tests : Spec := + describe "uniform T16 → T16" do + it "w=1: model = reference" do + let roots := constantInfoRoots (axiomOf (arr (chain 16) (chain 16))).info + withOk "w=1" (optimizeSharingUniform 1 roots) fun u => + withOk "reference" (optimizeSharingUniformReference 1 roots) fun r => + expect (u.result.modelBytes == r.modelBytes && (checkUniform 1 roots).toOption.isSome) + s!"model={u.result.modelBytes}, reference={r.modelBytes}" /-- 128 and 129 independent atoms whose sharing saves exactly one byte each: the table count crosses 128. -/ -def bracketTests (_ : Unit) : TestSeq := +def bracketTests : Spec := let atoms (n : Nat) : Array Ixon.Expr := (Array.range n).map fun i => .ref i.toUInt64 #[0] let rootsOf (n : Nat) := (atoms n).foldl (fun acc a => acc ++ #[a, a]) #[] let sizes (n : Nat) := (atoms n).map exprSize - group "table-count bracket coupling" <| - withOk "128 atoms" (optimizeSharingUniform 1 (rootsOf 128)) (fun u => - test s!"128 atoms: all uncertain; storing 127 ties storing 128 (one count byte); the tie order leaves out the smallest ID; model {u.result.modelBytes} = 642" - (u.uncertain.size == 128 && u.stored.size == 127 && !u.stored.contains 0 && + describe "table-count bracket coupling" do + it "128 atoms: all uncertain; storing 127 ties storing 128 (one count byte); model = 642" do + withOk "128 atoms" (optimizeSharingUniform 1 (rootsOf 128)) fun u => + expect (u.uncertain.size == 128 && u.stored.size == 127 && !u.stored.contains 0 && u.lowerBracket && u.result.modelBytes == 1 + 127 * 5 + 6 && - u.result.modelBytes == 2 + 128 * 5)) ++ - withOk "129 atoms" (optimizeSharingUniform 1 (rootsOf 129)) (fun u => - test s!"129 atoms (the last, Ref(128), is 4 bytes and certain-stored): keeps all 129, model {u.result.modelBytes} = 648" - (u.stored.size == 129 && !u.lowerBracket && u.certainStored == #[128] && - u.result.modelBytes == 2 + 128 * 5 + 6)) ++ - test "atom brute force agrees on 10 atoms with mixed sizes and uses" + u.result.modelBytes == 2 + 128 * 5) + it "129 atoms (the last, Ref(128), is 4 bytes and certain-stored): keeps all 129, model = 648" do + withOk "129 atoms" (optimizeSharingUniform 1 (rootsOf 129)) fun u => + expect (u.stored.size == 129 && !u.lowerBracket && u.certainStored == #[128] && + u.result.modelBytes == 2 + 128 * 5 + 6) + itBool "atom brute force agrees on 10 atoms with mixed sizes and uses" (let as : Array Ixon.Expr := (Array.range 10).map fun i => .ref i.toUInt64 (Array.replicate (i % 3) 0) let occs := (Array.range 10).map fun i => 1 + i % 4 let roots := (Array.range 10).foldl (fun acc i => acc ++ Array.replicate occs[i]! as[i]!) #[] [1, 2, 3].all fun w => (optimizeSharingUniform w roots).toOption.map (·.result.modelBytes) == - some (atomsUniformBrute w (as.map exprSize) occs)) ++ - test "sizes" ((sizes 3).all (· == 3)) - -def propertyTestsWith (target : Nat) (_ : Unit) : TestSeq := - let (checked, err) := runGen 67 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:target] do - if err.isSome then break - let roots ← genRoots 6 16 4 - let c := wrapRoots roots i - let w := [1, 2, 4][← rand 3]! - match normalizeConstantSharingUniform w c with - | .ok n => - checked := checked + 1 - let again := (normalizeConstantSharingUniform w n).toOption.map serConstant - let fresh := match deConstant (serConstant c) with - | .ok c' => (normalizeConstantSharingUniform w c').toOption.map serConstant - | .error _ => none - unless again == some (serConstant n) && fresh == some (serConstant n) do - err := some s!"case {i}: not idempotent or representation dependent" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "uniform properties" <| - test s!"{checked} constants: normalize is idempotent and independent of pointer layout" (err.isNone && checked == target) ++ - (match err with | some m => test m false | none => .done) - -def propertyTests (_ : Unit) : TestSeq := propertyTestsWith 200 () -def propertyTestsPR (_ : Unit) : TestSeq := propertyTestsWith 60 () + some (atomsUniformBrute w (as.map exprSize) occs)) + itBool "sizes" ((sizes 3).all (· == 3)) + +def propertyTestsWith (target : Nat) : Spec := + describe "uniform properties" do + it s!"{target} constants: normalize is idempotent and independent of pointer layout" do + let (checked, err) := runGen 67 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:target] do + if err.isSome then break + let roots ← genRoots 6 16 4 + let c := wrapRoots roots i + let w := [1, 2, 4][← rand 3]! + match normalizeConstantSharingUniform w c with + | .ok n => + checked := checked + 1 + let again := (normalizeConstantSharingUniform w n).toOption.map serConstant + let fresh := match deConstant (serConstant c) with + | .ok c' => (normalizeConstantSharingUniform w c').toOption.map serConstant + | .error _ => none + unless again == some (serConstant n) && fresh == some (serConstant n) do + err := some s!"case {i}: not idempotent or representation dependent" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == target) s!"checked {checked} != {target}" + +def propertyTests : Spec := propertyTestsWith 200 +def propertyTestsPR : Spec := propertyTestsWith 60 /-- `mk a₁ … aₙ`-style prefix chains: `uₖ = uₖ₋₁ aₖ`, each prefix also used once as the head of a longer spine with other arguments (the shape of @@ -324,53 +331,53 @@ uncertain components. The inputs are drawn in order from one seed; both searches run on batches of them in parallel, and the outcomes are read in draw order, so the inputs checked are the first `target` with a component of ≥ 2 uncertain terms, as when the searches ran on one input at a time. -/ -def searchTestsWith (target : Nat) (_ : Unit) : TestSeq := - let inputs := runGen 71 do - let mut out : Array (Array Ixon.Expr × Nat) := #[] - for _ in [0:4000] do - let roots ← genSearchRoots - out := out.push (roots, [1, 2, 3, 5][← rand 4]!) - return out - let (checked, skipped, maxComp, err) := Id.run do - let mut checked := 0 - let mut skipped := 0 - let mut maxComp := 0 - let mut err : Option String := none - for start in [0:inputs.size:64] do - if checked ≥ target || err.isSome then break - let tasks := (inputs.extract start (start + 64)).zipIdx.map fun ((roots, w), k) => - Task.spawn fun _ => searchOutcome (start + k) w roots - for task in tasks do - if checked ≥ target || err.isSome then break - match task.get with - | .small => pure () - | .agree comp => - checked := checked + 1 - maxComp := max maxComp comp - | .skipped => skipped := skipped + 1 - | .failed comp message => - if let some comp := comp then - checked := checked + 1 - maxComp := max maxComp comp - err := some message - return (checked, skipped, maxComp, err) - group "uniform branch and bound vs subset enumeration" <| - test s!"{checked} generated inputs with a component of ≥ 2 uncertain terms (prefix chains, telescopes, App chains, long spines, prefixes, general; w ∈ 1,2,3,5; largest component {maxComp}; {skipped} skipped where the enumeration exceeded 2^16 states): identical retained per-count optima/ties, stored set, model length and bracket choice" - (err.isNone && checked == target) ++ - (match err with | some m => test m false | none => .done) - -def searchTests (_ : Unit) : TestSeq := searchTestsWith 600 () -def searchTestsPR (_ : Unit) : TestSeq := searchTestsWith 60 () +def searchTestsWith (target : Nat) : Spec := + describe "uniform branch and bound vs subset enumeration" do + it s!"{target} generated inputs with a component of ≥ 2 uncertain terms: identical retained per-count optima/ties, stored set, model length and bracket choice" do + let inputs := runGen 71 do + let mut out : Array (Array Ixon.Expr × Nat) := #[] + for _ in [0:4000] do + let roots ← genSearchRoots + out := out.push (roots, [1, 2, 3, 5][← rand 4]!) + return out + let (checked, skipped, maxComp, err) := Id.run do + let mut checked := 0 + let mut skipped := 0 + let mut maxComp := 0 + let mut err : Option String := none + for start in [0:inputs.size:64] do + if checked ≥ target || err.isSome then break + let tasks := (inputs.extract start (start + 64)).zipIdx.map fun ((roots, w), k) => + Task.spawn fun _ => searchOutcome (start + k) w roots + for task in tasks do + if checked ≥ target || err.isSome then break + match task.get with + | .small => pure () + | .agree comp => + checked := checked + 1 + maxComp := max maxComp comp + | .skipped => skipped := skipped + 1 + | .failed comp message => + if let some comp := comp then + checked := checked + 1 + maxComp := max maxComp comp + err := some message + return (checked, skipped, maxComp, err) + if let some m := err then fail m + expect (checked == target) s!"checked {checked}/{target} (largest component {maxComp}, {skipped} skipped)" + +def searchTests : Spec := searchTestsWith 600 +def searchTestsPR : Spec := searchTestsWith 60 /-- Search agreement across the 128-entry table-count bracket: 120 one-byte atoms used twice (uncertain, gain 1) plus an App prefix chain. -/ -def searchBracketTests (_ : Unit) : TestSeq := - let atoms : Array Ixon.Expr := (Array.range 120).map fun i => .ref i.toUInt64 #[0] - let chain := runGen 5 genPrefixChain - let roots := atoms.foldl (fun acc a => acc ++ #[a, a]) #[] ++ chain - group "uniform branch and bound across a count bracket" <| - test "w=1,2,3: the branch and bound and the subset enumeration store the same set" - ([1, 2, 3].all fun w => +def searchBracketTests : Spec := + describe "uniform branch and bound across a count bracket" do + it "w=1,2,3: the branch and bound and the subset enumeration store the same set" do + let atoms : Array Ixon.Expr := (Array.range 120).map fun i => .ref i.toUInt64 #[0] + let chain := runGen 5 genPrefixChain + let roots := atoms.foldl (fun acc a => acc ++ #[a, a]) #[] ++ chain + expect ([1, 2, 3].all fun w => match optimizeSharingUniform w roots, optimizeSharingUniform w roots { uniformSubsetSearch := true } with | .ok u, .ok r => u.stored == r.stored && u.result.modelBytes == r.result.modelBytes && @@ -412,33 +419,31 @@ def symmDiffMinIn (a b : Array Nat) : Bool := | some m => b.contains m | none => false -def tieOrderTests (_ : Unit) : TestSeq := - group "uniform tie order" <| - test "setPrec agrees with the imperative loop on all arrays of length ≤ 3 over 0..3" - (smallArrays.all fun a => smallArrays.all fun b => setPrec a b == setPrecLoop a b) ++ - test "on sets, setPrec a b iff the least element of the symmetric difference is in b" - (smallSets.all fun a => smallSets.all fun b => setPrec a b == symmDiffMinIn a b) ++ - test "setPrec is a strict total order on the subsets of 0..4" +def tieOrderTests : Spec := + describe "uniform tie order" do + itBool "setPrec agrees with the imperative loop on all arrays of length ≤ 3 over 0..3" + (smallArrays.all fun a => smallArrays.all fun b => setPrec a b == setPrecLoop a b) + itBool "on sets, setPrec a b iff the least element of the symmetric difference is in b" + (smallSets.all fun a => smallSets.all fun b => setPrec a b == symmDiffMinIn a b) + itBool "setPrec is a strict total order on the subsets of 0..4" (smallSets.all fun a => !setPrec a a && smallSets.all fun b => (a == b || setPrec a b != setPrec b a) && smallSets.all fun c => !(setPrec a b && setPrec b c) || setPrec a c) -public def suite : List TestSeq := [ - deferred "uniform tie order" tieOrderTests, - deferred "uniform witness" witnessTests, - deferred "uniform vs reference" agreementTestsPR, - deferred "uniform T16" t16Tests, - deferred "uniform table-count brackets" bracketTests, - deferred "uniform properties" propertyTestsPR, - deferred "uniform search vs enumeration" searchTestsPR, - deferred "uniform search across a bracket" searchBracketTests, -] +public def suite : Spec := do + tieOrderTests + witnessTests + agreementTestsPR + t16Tests + bracketTests + propertyTestsPR + searchTestsPR + searchBracketTests /-- Full randomized sweeps for nightly CI (`exact-sharing-full`). -/ -public def nightlySuite : List TestSeq := [ - deferred "uniform vs reference (full)" agreementTests, - deferred "uniform properties (full)" propertyTests, - deferred "uniform search vs enumeration (full)" searchTests, -] +public def nightlySuite : Spec := do + agreementTests + propertyTests + searchTests end Tests.SharingUniform diff --git a/Tests/Ix/SourceContract.lean b/Tests/Ix/SourceContract.lean index 2de2fbc839..9b3a9b7148 100644 --- a/Tests/Ix/SourceContract.lean +++ b/Tests/Ix/SourceContract.lean @@ -15,9 +15,6 @@ namespace Tests.Ix.SourceContract open Lean LSpec open Ix.Compile -private def test (description : String) (condition : Bool) : TestSeq := - LSpec.test description (condition = true) - private def natType : Expr := .const `Nat [] private def definition (name : Name) (type value : Expr) : ConstantInfo := @@ -49,34 +46,34 @@ private def resolvedModes (actual : Except SourceContractError ResolvedSourceCon | .error _ => #[] | .ok contract => contract.binders.map fun binder => (binder.site, binder.mode, binder.result) -def telescopeTests : TestSeq := - test "identity resolves once/unique type and once body at independent sites" +public def telescopeTests : LSpec.Spec := do + itBool "identity resolves once/unique type and once body at independent sites" (resolvedModes (resolveTelescope (identity) #[{ binder := .position 0, mode := .once, result := some .unique }]) == - #[(⟨.type, []⟩, .once, some .unique), (⟨.body, []⟩, .once, none)]) ++ - test "all seven binder modes are accepted without inferring resource validity" + #[(⟨.type, []⟩, .once, some .unique), (⟨.body, []⟩, .once, none)]) + itBool "all seven binder modes are accepted without inferring resource validity" ([Ixon.BinderMode.many, .borrowed, .unique, .uniqueBorrowed, .once, .onceBorrowed, .erased].all fun mode => - (resolveTelescope (identity) #[{ binder := .position 0, mode, result := some .shared }]).isOk) ++ - test "result mode shorthand affects only the selected curried arrow" + (resolveTelescope (identity) #[{ binder := .position 0, mode, result := some .shared }]).isOk) + itBool "result mode shorthand affects only the selected curried arrow" (resolvedModes (resolveTelescope curried #[{ binder := .name `y, mode := .once, result := some .unique }]) == #[(⟨.type, [.binderBody]⟩, .once, some .unique), - (⟨.body, [.binderBody]⟩, .once, none)]) ++ - test "implicit argument retains its position and does not imply erasure" + (⟨.body, [.binderBody]⟩, .once, none)]) + itBool "implicit argument retains its position and does not imply erasure" (match resolveTelescope curried #[{ binder := .position 0, mode := .many }] with | .ok result => result.binders.all fun binder => binder.binderInfo == .implicit && binder.mode == .many - | .error _ => false) ++ - test "out-of-range elaborated positions are rejected" + | .error _ => false) + itBool "out-of-range elaborated positions are rejected" (expectError (resolveTelescope curried #[{ binder := .position 2, mode := .once }]) - (.argumentOutOfRange `curried 2)) ++ - test "missing binder names are rejected" + (.argumentOutOfRange `curried 2)) + itBool "missing binder names are rejected" (expectError (resolveTelescope curried #[{ binder := .name `missing, mode := .once }]) - (.unknownBinder `curried `missing)) ++ - test "name and position annotations cannot silently overwrite the same site" + (.unknownBinder `curried `missing)) + itBool "name and position annotations cannot silently overwrite the same site" (expectError (resolveTelescope curried #[{ binder := .name `y, mode := .once }, { binder := .position 1, mode := .borrowed }]) (.duplicateSite `curried ⟨.type, [.binderBody]⟩)) -def occurrenceTests : TestSeq := Id.run do +public def occurrenceTests : LSpec.Spec := do let lam := Expr.lam `shadow natType (.bvar 0) .default let nested := definition `nested (.forallE `x natType natType .default) (.lam `x natType (.app lam (.app lam (.bvar 0))) .default) @@ -91,28 +88,28 @@ def occurrenceTests : TestSeq := Id.run do let wrapped := definition `wrapped (.mdata {} (.forallE `x natType natType .default)) (.mdata {} (.lam `x natType (.bvar 0) .default)) - return test "equal nested lambdas can carry different occurrence contracts" - (resolvedModes (distinct.resolve nested) == #[(left, .once, none), (right, .borrowed, none)]) ++ - test "annotation order has a canonical resolved order" - (resolvedModes (({ distinct with binders := distinct.binders.reverse }).resolve nested) == - resolvedModes (distinct.resolve nested)) ++ - test "shadowed declaration binders require an explicit position" - (expectError (resolveTelescope shadowed #[{ binder := .name `x, mode := .once }]) - (.ambiguousBinder `shadowed `x)) ++ - test "position disambiguates shadowed declaration binders" - ((resolveTelescope shadowed #[{ binder := .position 1, mode := .once }]).isOk) ++ - test "metadata wrappers appear in resolved telescope paths" - (resolvedModes (resolveTelescope wrapped #[{ binder := .position 0, mode := .once, result := some .unique }]) == - #[(⟨.type, [.metadata]⟩, .once, some .unique), - (⟨.body, [.metadata]⟩, .once, none)]) ++ - test "invalid structural edges fail before canonicalization" - (expectError (({ source := identity, binders := #[{ site := ⟨.body, [.appArg]⟩, mode := .once }] } : SourceContract).resolve identity) - (.invalidSite `identity ⟨.body, [.appArg]⟩)) ++ - test "an expression occurrence must actually be a binder" - (expectError (({ source := identity, binders := #[{ site := ⟨.body, [.binderBody]⟩, mode := .once }] } : SourceContract).resolve identity) - (.expectedBinder `identity ⟨.body, [.binderBody]⟩)) + itBool "equal nested lambdas can carry different occurrence contracts" + (resolvedModes (distinct.resolve nested) == #[(left, .once, none), (right, .borrowed, none)]) + itBool "annotation order has a canonical resolved order" + (resolvedModes (({ distinct with binders := distinct.binders.reverse }).resolve nested) == + resolvedModes (distinct.resolve nested)) + itBool "shadowed declaration binders require an explicit position" + (expectError (resolveTelescope shadowed #[{ binder := .name `x, mode := .once }]) + (.ambiguousBinder `shadowed `x)) + itBool "position disambiguates shadowed declaration binders" + ((resolveTelescope shadowed #[{ binder := .position 1, mode := .once }]).isOk) + itBool "metadata wrappers appear in resolved telescope paths" + (resolvedModes (resolveTelescope wrapped #[{ binder := .position 0, mode := .once, result := some .unique }]) == + #[(⟨.type, [.metadata]⟩, .once, some .unique), + (⟨.body, [.metadata]⟩, .once, none)]) + itBool "invalid structural edges fail before canonicalization" + (expectError (({ source := identity, binders := #[{ site := ⟨.body, [.appArg]⟩, mode := .once }] } : SourceContract).resolve identity) + (.invalidSite `identity ⟨.body, [.appArg]⟩)) + itBool "an expression occurrence must actually be a binder" + (expectError (({ source := identity, binders := #[{ site := ⟨.body, [.binderBody]⟩, mode := .once }] } : SourceContract).resolve identity) + (.expectedBinder `identity ⟨.body, [.binderBody]⟩)) -def rejectionTests : TestSeq := Id.run do +public def rejectionTests : LSpec.Spec := do let bodySite : BinderSite := ⟨.body, []⟩ let typeSite : BinderSite := ⟨.type, []⟩ let contract : SourceContract := { @@ -125,23 +122,23 @@ def rejectionTests : TestSeq := Id.run do let changedMetadata := definition `identity (.forallE `x natType natType .default) (.mdata {} (.lam `x natType (.bvar 0) .default)) let alias := definition `alias (.forallE `x natType natType .default) (.const `identity []) - return test "type/body mode disagreement is rejected" - (expectError (({ source := identity, binders := #[{ site := typeSite, mode := .once }] } : SourceContract).resolve identity) - (.inconsistentTelescope `identity 0 .once .many)) ++ - test "a lambda has no independent result-mode field" - (expectError (({ source := identity, binders := #[{ site := bodySite, mode := .many, result := some .shared }] } : SourceContract).resolve identity) - (.resultOnNonArrow `identity bodySite)) ++ - test "source binder spelling is part of the occurrence fingerprint" - (expectError (contract.resolve renamed) (.staleSource `identity)) ++ - test "source BinderInfo drift invalidates a previously resolved contract" - (expectError (contract.resolve changedInfo) (.staleSource `identity)) ++ - test "source metadata shape drift invalidates structural paths" - (expectError (contract.resolve changedMetadata) (.staleSource `identity)) ++ - test "unsupported body telescope normalization gets a diagnostic" - (expectError (resolveTelescope alias #[{ binder := .position 0, mode := .once }]) - (.missingBodyBinder `alias 0)) + itBool "type/body mode disagreement is rejected" + (expectError (({ source := identity, binders := #[{ site := typeSite, mode := .once }] } : SourceContract).resolve identity) + (.inconsistentTelescope `identity 0 .once .many)) + itBool "a lambda has no independent result-mode field" + (expectError (({ source := identity, binders := #[{ site := bodySite, mode := .many, result := some .shared }] } : SourceContract).resolve identity) + (.resultOnNonArrow `identity bodySite)) + itBool "source binder spelling is part of the occurrence fingerprint" + (expectError (contract.resolve renamed) (.staleSource `identity)) + itBool "source BinderInfo drift invalidates a previously resolved contract" + (expectError (contract.resolve changedInfo) (.staleSource `identity)) + itBool "source metadata shape drift invalidates structural paths" + (expectError (contract.resolve changedMetadata) (.staleSource `identity)) + itBool "unsupported body telescope normalization gets a diagnostic" + (expectError (resolveTelescope alias #[{ binder := .position 0, mode := .once }]) + (.missingBodyBinder `alias 0)) -def inputTests : TestSeq := Id.run do +public def inputTests : LSpec.Spec := do let source := identity let constants := [(source.name, source)] let first : SourceContract := { @@ -155,42 +152,42 @@ def inputTests : TestSeq := Id.run do { constants := constants ++ [(second.name, second)], contracts := #[first, secondContract] } let hinted : CompileInput := { constants, contracts := #[], measureHints := #[⟨source, .name `x, some 1⟩] } - return test "plain input preserves selected source and has no semantic contracts" - (match (CompileInput.plain constants).resolve with - | .ok result => result.constants == constants && result.contracts.isEmpty - | .error _ => false) ++ - test "equal declaration bodies retain their distinct semantic contracts" - (match sameBody.resolve with - | .ok result => result.contracts.size == 2 && - result.contracts[0]!.modeAt ⟨.body, []⟩ == .once && - result.contracts[1]!.modeAt ⟨.body, []⟩ == .borrowed - | .error _ => false) ++ - test "duplicate selected declarations are rejected" - (expectError ((CompileInput.plain (constants ++ constants)).resolve) - (.duplicateDeclaration `identity)) ++ - test "selected names must match their declaration" - (expectError ((CompileInput.plain [(`wrong, source)]).resolve) - (.declarationNameMismatch `wrong `identity)) ++ - test "a dangling registry entry cannot be silently dropped" - (expectError (({ constants := [], contracts := #[first] } : CompileInput).resolve) - (.missingDeclaration `identity)) ++ - test "duplicate declaration contracts cannot overwrite each other" - (expectError (({ constants, contracts := #[first, first] } : CompileInput).resolve) - (.duplicateContract `identity)) ++ - test "measure hints resolve to positions without changing source or modes" - (match hinted.resolve with - | .ok result => result.constants == constants && result.contracts.isEmpty && - result.measureHints.size == 1 && result.measureHints[0]!.argument == 0 && - result.measureHints[0]!.site == ⟨.type, []⟩ - | .error _ => false) ++ - test "zero-step proposals receive a diagnostic" - (expectError (({ hinted with measureHints := #[⟨source, .position 0, some 0⟩] }).resolve) - (.zeroFixedStep `identity)) ++ - test "multiple measure proposals for one declaration are rejected" - (expectError (({ hinted with measureHints := hinted.measureHints ++ hinted.measureHints }).resolve) - (.duplicateMeasure `identity)) + itBool "plain input preserves selected source and has no semantic contracts" + (match (CompileInput.plain constants).resolve with + | .ok result => result.constants == constants && result.contracts.isEmpty + | .error _ => false) + itBool "equal declaration bodies retain their distinct semantic contracts" + (match sameBody.resolve with + | .ok result => result.contracts.size == 2 && + result.contracts[0]!.modeAt ⟨.body, []⟩ == .once && + result.contracts[1]!.modeAt ⟨.body, []⟩ == .borrowed + | .error _ => false) + itBool "duplicate selected declarations are rejected" + (expectError ((CompileInput.plain (constants ++ constants)).resolve) + (.duplicateDeclaration `identity)) + itBool "selected names must match their declaration" + (expectError ((CompileInput.plain [(`wrong, source)]).resolve) + (.declarationNameMismatch `wrong `identity)) + itBool "a dangling registry entry cannot be silently dropped" + (expectError (({ constants := [], contracts := #[first] } : CompileInput).resolve) + (.missingDeclaration `identity)) + itBool "duplicate declaration contracts cannot overwrite each other" + (expectError (({ constants, contracts := #[first, first] } : CompileInput).resolve) + (.duplicateContract `identity)) + itBool "measure hints resolve to positions without changing source or modes" + (match hinted.resolve with + | .ok result => result.constants == constants && result.contracts.isEmpty && + result.measureHints.size == 1 && result.measureHints[0]!.argument == 0 && + result.measureHints[0]!.site == ⟨.type, []⟩ + | .error _ => false) + itBool "zero-step proposals receive a diagnostic" + (expectError (({ hinted with measureHints := #[⟨source, .position 0, some 0⟩] }).resolve) + (.zeroFixedStep `identity)) + itBool "multiple measure proposals for one declaration are rejected" + (expectError (({ hinted with measureHints := hinted.measureHints ++ hinted.measureHints }).resolve) + (.duplicateMeasure `identity)) -def modeBijectionTests : TestSeq := Id.run do +public def modeBijectionTests : LSpec.Spec := do let source := identity let typeSite : BinderSite := ⟨.type, []⟩ let bodySite : BinderSite := ⟨.body, []⟩ @@ -217,46 +214,46 @@ def modeBijectionTests : TestSeq := Id.run do source := ctor binders := #[{ site := ⟨.type, []⟩, mode := .erased }] fieldModes := #[{ fieldIndex := 0, mode := .shared }] } - return test "unique input is independent of the arrow result" - (match resolveTelescope source #[unique] with - | .ok result => result.modeAt typeSite == .unique && result.modeAt bodySite == .unique && - result.resultAt typeSite == .shared - | .error _ => false) ++ - test "all 28 AllMode combinations preserve input, result, and matching lambda fields" - (binderModes.all fun mode => resultModes.all fun output => - match resolveTelescope source #[{ binder := .position 0, mode, result := some output }] with - | .ok c => c.modeAt typeSite == mode && c.modeAt bodySite == mode && - c.resultAt typeSite == output - | .error _ => false) ++ - test "type and body must agree on unique mode" - (expectError (ownershipMismatch.resolve source) - (.inconsistentTelescope `identity 0 .unique .many)) ++ - test "type and body must agree on borrowed mode" - (expectError (localityMismatch.resolve source) - (.inconsistentTelescope `identity 0 .borrowed .many)) ++ - test "borrow let retains its explicit borrow flag and borrowed mode" - (match borrow.resolve binding with - | .ok c => c.binders[0]!.kind == .letE && c.binders[0]!.isBorrow && - c.binders[0]!.mode == .borrowed && c.binders[0]!.result.isNone - | .error _ => false) ++ - test "a shared borrow cannot manufacture unique ownership" - (expectError (({ borrow with binders := borrow.binders.map fun (b : BinderContract) => { b with mode := .uniqueBorrowed } }).resolve binding) - (.invalidBorrowView `binding bodySite)) ++ - test "a borrow flag cannot annotate a function binder" - (expectError (resolveTelescope source #[{ unique with mode := .borrowed, isBorrow := true }]) - (.borrowOnNonLet `identity typeSite)) ++ - test "constructor fieldModes and erased field resolve cleanly and reject @erased + @shared conflict" - (match ctorShared.resolve ctor with - | .ok r => r.fieldModeAt 0 == .shared && r.fieldModeAt 1 == .inherited && - r.modeAt ⟨.type, [.binderBody]⟩ == .erased - | .error _ => false) ++ - test "constructor rejects field that is both @erased and @shared" - (expectError (ctorConflict.resolve ctor) (.erasedSharedField `MyBox.mk 0)) ++ - test "fieldMode on non-constructor is rejected" - (expectError (({ source, fieldModes := #[{ fieldIndex := 0, mode := .shared }] } : SourceContract).resolve source) - (.fieldModeOnNonCtor `identity)) + itBool "unique input is independent of the arrow result" + (match resolveTelescope source #[unique] with + | .ok result => result.modeAt typeSite == .unique && result.modeAt bodySite == .unique && + result.resultAt typeSite == .shared + | .error _ => false) + itBool "all 28 AllMode combinations preserve input, result, and matching lambda fields" + (binderModes.all fun mode => resultModes.all fun output => + match resolveTelescope source #[{ binder := .position 0, mode, result := some output }] with + | .ok c => c.modeAt typeSite == mode && c.modeAt bodySite == mode && + c.resultAt typeSite == output + | .error _ => false) + itBool "type and body must agree on unique mode" + (expectError (ownershipMismatch.resolve source) + (.inconsistentTelescope `identity 0 .unique .many)) + itBool "type and body must agree on borrowed mode" + (expectError (localityMismatch.resolve source) + (.inconsistentTelescope `identity 0 .borrowed .many)) + itBool "borrow let retains its explicit borrow flag and borrowed mode" + (match borrow.resolve binding with + | .ok c => c.binders[0]!.kind == .letE && c.binders[0]!.isBorrow && + c.binders[0]!.mode == .borrowed && c.binders[0]!.result.isNone + | .error _ => false) + itBool "a shared borrow cannot manufacture unique ownership" + (expectError (({ borrow with binders := borrow.binders.map fun (b : BinderContract) => { b with mode := .uniqueBorrowed } }).resolve binding) + (.invalidBorrowView `binding bodySite)) + itBool "a borrow flag cannot annotate a function binder" + (expectError (resolveTelescope source #[{ unique with mode := .borrowed, isBorrow := true }]) + (.borrowOnNonLet `identity typeSite)) + itBool "constructor fieldModes and erased field resolve cleanly and reject @erased + @shared conflict" + (match ctorShared.resolve ctor with + | .ok r => r.fieldModeAt 0 == .shared && r.fieldModeAt 1 == .inherited && + r.modeAt ⟨.type, [.binderBody]⟩ == .erased + | .error _ => false) + itBool "constructor rejects field that is both @erased and @shared" + (expectError (ctorConflict.resolve ctor) (.erasedSharedField `MyBox.mk 0)) + itBool "fieldMode on non-constructor is rejected" + (expectError (({ source, fieldModes := #[{ fieldIndex := 0, mode := .shared }] } : SourceContract).resolve source) + (.fieldModeOnNonCtor `identity)) -def markerTests : TestSeq := Id.run do +public def markerTests : LSpec.Spec := do let annotation : BinderAnnotation := { origin := 0, binder := `x, mode := .uniqueBorrowed } let data := annotation.toMetadata @@ -273,126 +270,127 @@ def markerTests : TestSeq := Id.run do rules := [⟨`constructor, 0, .mdata missingVersion natType⟩] k := false, isUnsafe := false } let shared := (List.range 28).foldl (fun expr _ => Expr.app expr expr) natType - return test "source annotation metadata roundtrips v5 BinderMode, ResultMode, borrow flag, and origin" - (match BinderAnnotation.ofMetadata? data with + itBool "source annotation metadata roundtrips v5 BinderMode, ResultMode, borrow flag, and origin" + (match BinderAnnotation.ofMetadata? data with + | .ok decoded => decoded == some annotation + | .error _ => false) + itBool "adding source markers preserves Lean's singleton native borrow wrapper" + (match annotation.attach borrowed with + | .ok type => Lean.isMarkedBorrowed type && + match binderAnnotation? type with | .ok decoded => decoded == some annotation - | .error _ => false) ++ - test "adding source markers preserves Lean's singleton native borrow wrapper" - (match annotation.attach borrowed with - | .ok type => Lean.isMarkedBorrowed type && - match binderAnnotation? type with - | .ok decoded => decoded == some annotation - | .error _ => false - | .error _ => false) ++ - test "strict source metadata rejects unknown keys, duplicates, old versions, and overflowing codes" - ([data.setNat `ix.source.binder.future 0, duplicate, missingVersion, - data.setNat sourceAnnotationKey 3, data.setNat `ix.source.binder.mode 7, - data.setNat `ix.source.binder.mode 256, data.setNat `ix.source.binder.borrow 2].all fun malformed => - !(BinderAnnotation.ofMetadata? malformed).isOk) ++ - test "malformed reserved metadata is still detected by the preflight" - (exprHasSourceAnnotations (.mdata missingVersion natType)) ++ - test "source markers in raw recursor rules are detected and explicitly unsupported" - (sourceHasAnnotations recursor && - expectError (SourceContract.fromAnnotations recursor) (.annotatedRecursorRule recursor.name)) ++ - test "annotation scan handles heavily shared ordinary source and nearby markers" - (!exprHasSourceAnnotations shared && - exprHasSourceAnnotations (.app shared (.mdata data natType))) ++ - test "source markers require explicit matching records and cannot be overridden" - (expectError input.resolve (.missingContract marked.name) && - match SourceContract.fromAnnotations marked with - | .ok contract => - let changed : SourceContract := { contract with - binders := contract.binders.map fun binder => { binder with mode := .many } } - contract.binders.size == 2 && (contract.resolve marked).isOk && - !(changed.resolve marked).isOk - | .error _ => false) + | .error _ => false + | .error _ => false) + itBool "strict source metadata rejects unknown keys, duplicates, old versions, and overflowing codes" + ([data.setNat `ix.source.binder.future 0, duplicate, missingVersion, + data.setNat sourceAnnotationKey 3, data.setNat `ix.source.binder.mode 7, + data.setNat `ix.source.binder.mode 256, data.setNat `ix.source.binder.borrow 2].all fun malformed => + !(BinderAnnotation.ofMetadata? malformed).isOk) + itBool "malformed reserved metadata is still detected by the preflight" + (exprHasSourceAnnotations (.mdata missingVersion natType)) + itBool "source markers in raw recursor rules are detected and explicitly unsupported" + (sourceHasAnnotations recursor && + expectError (SourceContract.fromAnnotations recursor) (.annotatedRecursorRule recursor.name)) + itBool "annotation scan handles heavily shared ordinary source and nearby markers" + (!exprHasSourceAnnotations shared && + exprHasSourceAnnotations (.app shared (.mdata data natType))) + itBool "source markers require explicit matching records and cannot be overridden" + (expectError input.resolve (.missingContract marked.name) && + match SourceContract.fromAnnotations marked with + | .ok contract => + let changed : SourceContract := { contract with + binders := contract.binders.map fun binder => { binder with mode := .many } } + contract.binders.size == 2 && (contract.resolve marked).isOk && + !(changed.resolve marked).isOk + | .error _ => false) -def arityProducerTests : TestSeq := Id.run do +public def arityProducerTests : LSpec.Spec := do let canonical := fun source => (Id.run ((_root_.Ix.CanonM.canonConst source).run {})).1 let frame := fun (kind : _root_.Ix.SemanticContract.Kind) (e : _root_.Ix.Expr) => match e with | .mdata data _ _ => data.size == 3 && ((_root_.Ix.SemanticContract.read data).toOption).any (·.kind == kind) | _ => false let readable := fun e => (_root_.Ix.LeanIngress.ingressExpr (fun _ => 0) e).isOk - let once := resolveTelescope identity #[{ binder := .position 0, mode := .once, result := some .unique }] - let pair := once.toOption.bind (fun c => c.decorate.toOption) - let pairOK := pair.any fun out => match canonical out with - | .defnInfo v => frame .all v.cnst.type && frame .lam v.value && readable v.cnst.type && readable v.value - | _ => false - let binding := definition `arityLet natType (.letE `view natType (.lit (.natVal 0)) (.bvar 0) false) - let borrow : SourceContract := { - source := binding - binders := #[{ site := ⟨.body, []⟩, mode := .borrowed, isBorrow := true }] } - let letOK := ((borrow.resolve binding).toOption.bind (fun c => c.decorate.toOption)).any fun out => - match canonical out with | .defnInfo v => frame .letE v.value && readable v.value | _ => false - -- DefAsserts decoration & extraction - let assertsContract : SourceContract := { - source := identity - defAsserts := { alloc := .noAlloc, boundedStack := true } } - let assertsOK := ((assertsContract.resolve identity).toOption.bind (fun c => c.decorate.toOption)).any fun out => - match canonical out with - | .defnInfo v => - frame .defAsserts v.cnst.type && readable v.cnst.type && - _root_.Ix.SemanticContract.defAsserts .defn v.cnst.type == { alloc := .noAlloc, boundedStack := true } && - _root_.Ix.SemanticContract.defAsserts .thm v.cnst.type == {} - | _ => false - -- Constructor FieldMode decoration & extraction - let ctor : ConstantInfo := .ctorInfo { - name := `ArityBox.mk, levelParams := [] - type := .forallE `a natType (.forallE `b natType (.const `ArityBox []) .default) .default - induct := `ArityBox, cidx := 0, numParams := 0, numFields := 2, isUnsafe := false } - let ctorContract : SourceContract := { - source := ctor - fieldModes := #[{ fieldIndex := 1, mode := .shared }] } - let ctorOK := ((ctorContract.resolve ctor).toOption.bind (fun c => c.decorate.toOption)).any fun out => - match canonical out with - | .ctorInfo v => - readable v.cnst.type && - (_root_.Ix.SemanticContract.ctorFieldModes v.numParams v.numFields.toUInt64 v.cnst.type).toArray == - #[.inherited, .shared] - | _ => false - let thmId : ConstantInfo := .thmInfo { - name := `arityThmId, levelParams := [] - type := .forallE `p (.sort .zero) (.bvar 0) .default - value := .lam `p (.sort .zero) (.bvar 0) .default - all := [`arityThmId] } - let thmStripped := ((resolveTelescope thmId #[{ binder := .position 0, mode := .erased }]).toOption.bind - (fun c => c.decorate.toOption)).any fun out => - !exprHasSemanticContracts out.type && match out with - | .thmInfo v => !exprHasSemanticContracts v.value - | _ => false - let theoremSource : ConstantInfo := .thmInfo { - name := `arityTheorem, levelParams := [], type := .const `True [], value := .const `True.intro [], all := [`arityTheorem] } - let opaqueSource : ConstantInfo := .opaqueInfo { - name := `arityOpaque, levelParams := [], type := natType, value := .lit (.natVal 0), isUnsafe := false, all := [`arityOpaque] } - let axiomSource : ConstantInfo := .axiomInfo { - name := `arityAxiom, levelParams := [], type := natType, isUnsafe := false } - let kinds := [(theoremSource, 0), (opaqueSource, 1), (axiomSource, 2)].all fun (source, expected) => - ((resolveTelescope source #[]).toOption.bind (fun c => c.decorate.toOption)).any fun out => - out.name == source.name && match canonical out, expected with - | .thmInfo v, 0 => readable v.cnst.type && readable v.value - | .opaqueInfo v, 1 => readable v.cnst.type && readable v.value - | .axiomInfo v, 2 => readable v.cnst.type && (sourceBody? out).isNone - | _, _ => false - let body := (sourceBody? identity).getD natType - let plain := ({} : MData).setNat `native.hint 7 - let marker := ({ origin := 0, binder := `x, mode := .once } : BinderAnnotation).toMetadata - let semantic : _root_.Ix.SemanticContract.Contract := .lam .once - let metadata := (resolveTelescope identity #[]).toOption.any fun c => - let kept := (decorateExpr c .body [] (.mdata plain body)).toOption - let stripped := (decorateExpr c .body [] (.mdata marker body)).toOption - (match kept with | some (.mdata data inner) => data.entries == plain.entries && inner == body | _ => false) && - (match stripped with | some (.lam ..) => stripped == some body | _ => false) && - (match decorateExpr c .body [] (semantic.attach body) with - | .error "source transport: reserved semantic metadata in unprocessed source" => true | _ => false) - return test "actual decorator and CanonM keep distinct type/value semantic frames and ingress accepts valid modes" - (pairOK && thmStripped) ++ - test "actual borrow-let decoration has a three-field semantic frame accepted by the ingress" letOK ++ - test "DefAsserts and constructor FieldMode decoration roundtrip cleanly through CanonM and ingress" - (assertsOK && ctorOK) ++ - test "actual theorem/opaque/axiom outputs preserve kind and optional-value boundaries" kinds ++ - test "decorator preserves plain metadata, removes source markers and refuses original semantic frames" metadata + it "actual decorator and CanonM keep distinct type/value semantic frames and ingress accepts valid modes" do + let once := resolveTelescope identity #[{ binder := .position 0, mode := .once, result := some .unique }] + let pair := once.toOption.bind (fun c => c.decorate.toOption) + let pairOK := pair.any fun out => match canonical out with + | .defnInfo v => frame .all v.cnst.type && frame .lam v.value && readable v.cnst.type && readable v.value + | _ => false + let thmId : ConstantInfo := .thmInfo { + name := `arityThmId, levelParams := [] + type := .forallE `p (.sort .zero) (.bvar 0) .default + value := .lam `p (.sort .zero) (.bvar 0) .default + all := [`arityThmId] } + let thmStripped := ((resolveTelescope thmId #[{ binder := .position 0, mode := .erased }]).toOption.bind + (fun c => c.decorate.toOption)).any fun out => + !exprHasSemanticContracts out.type && match out with + | .thmInfo v => !exprHasSemanticContracts v.value + | _ => false + expect (pairOK && thmStripped) + it "actual borrow-let decoration has a three-field semantic frame accepted by the ingress" do + let binding := definition `arityLet natType (.letE `view natType (.lit (.natVal 0)) (.bvar 0) false) + let borrow : SourceContract := { + source := binding + binders := #[{ site := ⟨.body, []⟩, mode := .borrowed, isBorrow := true }] } + let letOK := ((borrow.resolve binding).toOption.bind (fun c => c.decorate.toOption)).any fun out => + match canonical out with | .defnInfo v => frame .letE v.value && readable v.value | _ => false + expect letOK + it "DefAsserts and constructor FieldMode decoration roundtrip cleanly through CanonM and ingress" do + let assertsContract : SourceContract := { + source := identity + defAsserts := { alloc := .noAlloc, boundedStack := true } } + let assertsOK := ((assertsContract.resolve identity).toOption.bind (fun c => c.decorate.toOption)).any fun out => + match canonical out with + | .defnInfo v => + frame .defAsserts v.cnst.type && readable v.cnst.type && + _root_.Ix.SemanticContract.defAsserts .defn v.cnst.type == { alloc := .noAlloc, boundedStack := true } && + _root_.Ix.SemanticContract.defAsserts .thm v.cnst.type == {} + | _ => false + let ctor : ConstantInfo := .ctorInfo { + name := `ArityBox.mk, levelParams := [] + type := .forallE `a natType (.forallE `b natType (.const `ArityBox []) .default) .default + induct := `ArityBox, cidx := 0, numParams := 0, numFields := 2, isUnsafe := false } + let ctorContract : SourceContract := { + source := ctor + fieldModes := #[{ fieldIndex := 1, mode := .shared }] } + let ctorOK := ((ctorContract.resolve ctor).toOption.bind (fun c => c.decorate.toOption)).any fun out => + match canonical out with + | .ctorInfo v => + readable v.cnst.type && + (_root_.Ix.SemanticContract.ctorFieldModes v.numParams v.numFields.toUInt64 v.cnst.type).toArray == + #[.inherited, .shared] + | _ => false + expect (assertsOK && ctorOK) + it "actual theorem/opaque/axiom outputs preserve kind and optional-value boundaries" do + let theoremSource : ConstantInfo := .thmInfo { + name := `arityTheorem, levelParams := [], type := .const `True [], value := .const `True.intro [], all := [`arityTheorem] } + let opaqueSource : ConstantInfo := .opaqueInfo { + name := `arityOpaque, levelParams := [], type := natType, value := .lit (.natVal 0), isUnsafe := false, all := [`arityOpaque] } + let axiomSource : ConstantInfo := .axiomInfo { + name := `arityAxiom, levelParams := [], type := natType, isUnsafe := false } + let kinds := [(theoremSource, 0), (opaqueSource, 1), (axiomSource, 2)].all fun (source, expected) => + ((resolveTelescope source #[]).toOption.bind (fun c => c.decorate.toOption)).any fun out => + out.name == source.name && match canonical out, expected with + | .thmInfo v, 0 => readable v.cnst.type && readable v.value + | .opaqueInfo v, 1 => readable v.cnst.type && readable v.value + | .axiomInfo v, 2 => readable v.cnst.type && (sourceBody? out).isNone + | _, _ => false + expect kinds + it "decorator preserves plain metadata, removes source markers and refuses original semantic frames" do + let body := (sourceBody? identity).getD natType + let plain := ({} : MData).setNat `native.hint 7 + let marker := ({ origin := 0, binder := `x, mode := .once } : BinderAnnotation).toMetadata + let semantic : _root_.Ix.SemanticContract.Contract := .lam .once + let metadata := (resolveTelescope identity #[]).toOption.any fun c => + let kept := (decorateExpr c .body [] (.mdata plain body)).toOption + let stripped := (decorateExpr c .body [] (.mdata marker body)).toOption + (match kept with | some (.mdata data inner) => data.entries == plain.entries && inner == body | _ => false) && + (match stripped with | some (.lam ..) => stripped == some body | _ => false) && + (match decorateExpr c .body [] (semantic.attach body) with + | .error "source transport: reserved semantic metadata in unprocessed source" => true | _ => false) + expect metadata -def inspectionTests : TestSeq := Id.run do +public def inspectionTests : LSpec.Spec := do let digest := fun (n : UInt8) => Address.mk (ByteArray.mk (Array.replicate 32 n)) let scalar := _root_.Ix.Expr.lit (.natVal 0) (digest 3) let lam := _root_.Ix.Expr.lam _root_.Ix.Name.mkAnon scalar @@ -414,44 +412,51 @@ def inspectionTests : TestSeq := Id.run do ("aliased metadata-key hash", data.set! 2 (unknown, .ofNat 1), "unknown or duplicate semantic contract field")] let inspect := _root_.Ix.SemanticContract.inspect let eq := _root_.Ix.Compile.ExactKey.exprEq - let mut tests := TestSeq.done for (label, md, message) in cases do - let bad := frame md - let refused := [bad, .app bad good (digest 1), .app good bad (digest 1)].all fun e => - match inspect e with | .error actual => actual == message | _ => false - tests := tests ++ test s!"exact inspection rejects {label} despite equal digests in either visitation order" - (bad.getHash == good.getHash && !eq bad good && refused) + itBool s!"exact inspection rejects {label} despite equal digests in either visitation order" + (let bad := frame md + let refused := [bad, .app bad good (digest 1), .app good bad (digest 1)].all fun e => + match inspect e with | .error actual => actual == message | _ => false + bad.getHash == good.getHash && !eq bad good && refused) let twin := _root_.Ix.Expr.mdata contract.ixMetadata (.lam _root_.Ix.Name.mkAnon scalar (.bvar 0 (digest 4)) .default (digest 2)) (digest 0) let plain := _root_.Ix.Expr.mdata #[(_root_.Ix.Name.fromLeanName `native.hint, .ofNat 7)] lam (digest 0) - return tests ++ test "exact inspection accepts plain, equal and shared valid nodes" + itBool "exact inspection accepts plain, equal and shared valid nodes" ((inspect scalar).toOption == some false && (inspect plain).toOption == some false && eq good twin && (inspect (.app good good (digest 1))).toOption == some true && (inspect (.app good twin (digest 1))).toOption == some true) -def presenceMemoTests : TestSeq := Id.run do +public def presenceMemoTests : LSpec.Spec := do let plain := Expr.lit (.natVal 0) let binder := Expr.lam `x natType (.bvar 0) .default let contract : _root_.Ix.SemanticContract.Contract := .lam .once let marked := contract.attach binder let hinted := Expr.mdata (({} : MData).setNat `native.hint 7) binder let bucket := fun (_ : Expr) => (0 : USize) - let mut memo : SemanticPresence.Memo := {} - let mut valid := true - for e in [plain, marked, hinted, plain, marked, marked] do - let (result, after) := Id.run ((SemanticPresence.go bucket e).run memo) - valid := valid && result.1 == SemanticPresence.spec e - memo := after - let seeded : SemanticPresence.Memo := ({} : SemanticPresence.Memo).insert 0 - ⟨plain, SemanticPresence.spec plain, rfl⟩ - return test "presence memo preserves real results through constant-bucket collisions, overwrites and warm hits" valid ++ - test "presence memo confirms retained source and computes both positive and negative answers" - ((SemanticPresence.probe seeded 0 marked).isNone && - SemanticPresence.runWith bucket marked && !SemanticPresence.runWith bucket hinted) + it "presence memo preserves real results through constant-bucket collisions, overwrites and warm hits" do + let mut memo : SemanticPresence.Memo := {} + let mut valid := true + for e in [plain, marked, hinted, plain, marked, marked] do + let (result, after) := Id.run ((SemanticPresence.go bucket e).run memo) + valid := valid && result.1 == SemanticPresence.spec e + memo := after + expect valid + itBool "presence memo confirms retained source and computes both positive and negative answers" + (let seeded : SemanticPresence.Memo := ({} : SemanticPresence.Memo).insert 0 + ⟨plain, SemanticPresence.spec plain, rfl⟩ + (SemanticPresence.probe seeded 0 marked).isNone && + SemanticPresence.runWith bucket marked && !SemanticPresence.runWith bucket hinted) -def suite : List TestSeq := - [telescopeTests, occurrenceTests, rejectionTests, inputTests, modeBijectionTests, markerTests, - arityProducerTests, inspectionTests, presenceMemoTests] +public def suite : LSpec.Spec := do + telescopeTests + occurrenceTests + rejectionTests + inputTests + modeBijectionTests + markerTests + arityProducerTests + inspectionTests + presenceMemoTests end Tests.Ix.SourceContract diff --git a/Tests/Ix/SourceContract/Driver.lean b/Tests/Ix/SourceContract/Driver.lean index 7bca53d07a..6ca8a4751a 100644 --- a/Tests/Ix/SourceContract/Driver.lean +++ b/Tests/Ix/SourceContract/Driver.lean @@ -30,20 +30,21 @@ private def markedSource : ConstantInfo := .axiomInfo { private def constants (source : ConstantInfo) := [(source.name, source)] -private def ioTest (description : String) (check : IO Bool) : TestSeq := - .individualIO description none (do return (← check, 0, 0, none)) .done +private def ioTest (description : String) (check : IO Bool) : Spec := + it description do + expect (← check) /-- An IO test that reports what the compile said when mode checking did not refuse an annotated constant with no run body. -/ private def refusalTest (description : String) (result : IO (Except String Ix.CompileM.CertifiedOut)) : - TestSeq := - .individualIO description none (do + Spec := + it description do match ← result with - | .ok _ => return (false, 0, 0, some "compiled") + | .ok _ => fail "compiled" | .error message => let ok := (message.splitOn "not in the extern set").length > 1 || (message.splitOn "annotated source is refused").length > 1 - return (ok, 0, 0, if ok then none else some message)) .done + expect ok message private def compileConsts (consts : List (Lean.Name × ConstantInfo)) : IO (Except String Ix.CompileM.CertifiedOut) := do @@ -91,8 +92,8 @@ private def placement : IO Bool := do unless ok do throw (IO.userError s!"semantic placement: {label}") return true -def suite : List TestSeq := [ - ioTest "prepared semantic lambda: source presence, binder inspection and malformed-frame refusal" placement, +public def suite : LSpec.Spec := do + ioTest "prepared semantic lambda: source presence, binder inspection and malformed-frame refusal" placement ioTest "ordinary source preflight preserves declarations and validates names" do let env ← Lean.mkEmptyEnvironment let sources := constants plainSource @@ -100,7 +101,7 @@ def suite : List TestSeq := [ if (prepare sources).toOption != some sources then return false if (prepare (sources ++ sources)).toOption.isSome then return false if (prepare [(`wrongName, plainSource)]).toOption.isSome then return false - return true, + return true ioTest "ordinary source preflight cannot bypass reserved semantic metadata" do let env ← Lean.mkEmptyEnvironment let source : ConstantInfo := .axiomInfo { @@ -111,7 +112,7 @@ def suite : List TestSeq := [ if (prepare (constants source)).toOption.isSome then return false let .ok marked := prepare (constants markedSource) | return false if marked == constants markedSource then return false - return true, + return true ioTest "parallel source preflight checks every batch and its final remainder" do let sources := (List.range 2049).map fun i => let name := Lean.Name.num plainSource.name i @@ -128,28 +129,28 @@ def suite : List TestSeq := [ isUnsafe := false } (name, source) if (checkOrdinaryConstants marked (fun _ => false)).toOption != some false then return false - return true, + return true refusalTest "Lean constant-list driver refuses an annotated axiom" - (compileConsts (constants markedSource)), + (compileConsts (constants markedSource)) ioTest "explicit Lean input rejects a missing annotation registry" do match ← compileInput (.plain (constants markedSource)) with | .error message => return (message.splitOn "missingContract").length > 1 - | .ok _ => return false, + | .ok _ => return false refusalTest "explicit Lean input refuses an annotated axiom" (do let .ok contract := SourceContract.ofTelescope plainSource #[ { binder := .position 0, mode := .once }] | return .error "the telescope contract does not resolve" - compileInput { constants := constants plainSource, contracts := #[contract] }), + compileInput { constants := constants plainSource, contracts := #[contract] }) ioTest "measure-only input preserves ordinary production bytes" do let input := CompileInput.plain (constants plainSource) let .ok plain ← compileInput input | return false let hinted := { input with measureHints := #[⟨plainSource, .position 0, some 1⟩] } let .ok measured ← compileInput hinted | return false - return (Ixon.serEnv plain.env).toOption == (Ixon.serEnv measured.env).toOption, + return (Ixon.serEnv plain.env).toOption == (Ixon.serEnv measured.env).toOption ioTest "prepared-source preflight rejects unresolved source binder contracts" do match checkPreparedSource (constants markedSource) with | .error message => return (message.splitOn "unresolved source binder contracts").length > 1 - | .ok _ => return false, + | .ok _ => return false ioTest "explicit Lean input compiles and mode-checks a valid annotated definition with DefAsserts" do let tyA : ConstantInfo := .axiomInfo { name := `SourceContractDriver.TyA, levelParams := [], type := .sort (.succ .zero), isUnsafe := false } @@ -169,7 +170,6 @@ def suite : List TestSeq := [ | .defn d => d.asserts == { alloc := .noAlloc, boundedStack := true } | _ => false return out.annotated && assertsOk && _root_.Ix.Compile.BinderData.hasModes c -] end Tests.Ix.SourceContract.Driver diff --git a/Tests/Ix/TruthMines.lean b/Tests/Ix/TruthMines.lean index f210d1656a..7be0a6262f 100644 --- a/Tests/Ix/TruthMines.lean +++ b/Tests/Ix/TruthMines.lean @@ -65,12 +65,11 @@ private def memberLabels (ixc : String) : IO (Except String (List String)) := do through the core: member set complete, roots well-formed, verify green over a non-empty union. -/ private def driverBuild (mini : Bool) (ixc : System.FilePath) - (expectMembers : Nat) : IO (Bool × Nat × Nat × Option String) := do + (expectMembers : Nat) : AssertM Unit := do unless (← ixExe.pathExists) do - return (false, 0, 0, some s!"{ixExe} missing — run `lake build ix` first") + fail s!"{ixExe} missing — run `lake build ix` first" unless (← driverExe.pathExists) do - return (false, 0, 0, - some s!"{driverExe} missing — run `lake build truthmines` first") + fail s!"{driverExe} missing — run `lake build truthmines` first" let exe ← IO.FS.realPath driverExe let mut args := #["build", "--out", ixc.toString] if mini then @@ -78,38 +77,30 @@ private def driverBuild (mini : Bool) (ixc : System.FilePath) let child ← IO.Process.spawn { cmd := exe.toString, args } let exit ← child.wait if exit != 0 then - return (false, 0, 0, some s!"truthmines build failed ({exit})") + fail s!"truthmines build failed ({exit})" unless (← (ixc / "manifest").pathExists) do - return (false, 0, 0, some s!"driver exited 0 but {ixc} has no manifest") - let labels ← match ← memberLabels ixc.toString with - | .ok ls => pure ls - | .error e => return (false, 0, 0, some s!"manifest: {e}") + fail s!"driver exited 0 but {ixc} has no manifest" + let labels ← expectOk ((← memberLabels ixc.toString).mapError (s!"manifest: {·}")) unless labels.length == expectMembers do - return (false, labels.length, expectMembers, - some s!"manifest carries {labels.length} members, the spec has \ -{expectMembers}") + fail s!"manifest carries {labels.length} members, the spec has {expectMembers}" -- Independent re-verify through the core (the driver already -- verified; this pins the suite's own read of the artifact). let verifyContent ← Ix.Cli.CatalogCmd.rsCatalogVerifyFFI ixc.toString false let union : Except String Nat := do let json ← Lean.Json.parse verifyContent (← json.getObjVal? "unionConsts").getNat? - match union with - | .ok n => - if n == 0 then - return (false, 0, 0, some "catalog verify reports an empty union") - return (true, labels.length, n, none) - | .error e => return (false, 0, 0, some s!"verify: {e}") + let n ← expectOk (union.mapError (s!"verify: {·}")) + if n == 0 then + fail "catalog verify reports an empty union" /-- Drive `truthmines check [--mini]`: the per-piece `ix check-lean --anon` sweep over the tier's `.ixc` — the fat-profile checking rung lives in the driver (bounded pool, output captured per piece, tails + solo repro surfaced on rejection); the suite is exit-code gated. -/ -private def driverCheck (mini : Bool) : IO (Bool × Nat × Nat × Option String) := do +private def driverCheck (mini : Bool) : AssertM Unit := do unless (← driverExe.pathExists) do - return (false, 0, 0, - some s!"{driverExe} missing — run `lake build truthmines` first") + fail s!"{driverExe} missing — run `lake build truthmines` first" let exe ← IO.FS.realPath driverExe let mut args := #["check"] if mini then @@ -117,24 +108,20 @@ private def driverCheck (mini : Bool) : IO (Bool × Nat × Nat × Option String) let child ← IO.Process.spawn { cmd := exe.toString, args } let exit ← child.wait if exit != 0 then - return (false, 0, 0, some s!"truthmines check failed ({exit})") - return (true, 0, 0, none) - -def buildSuite : List TestSeq := [ - .individualIO - "truthmines: full corpus pieces + self-contained .ixc via the driver" - none (driverBuild false "truthmines.ixc" catalogSpec.libs.size) .done ] - -def checkSuite : List TestSeq := [ - .individualIO "truthmines: per-piece kernel check sweep (fat rung 1)" - none (driverCheck false) .done ] - -def miniSuite : List TestSeq := [ - .individualIO - "truthmines-mini: fixtures + spine + Mathlib + FLT → .ixc directory" - none (driverBuild true "truthmines-mini.ixc" - catalogMiniSpec.libs.size) .done, - .individualIO "truthmines-mini: per-piece kernel check sweep" - none (driverCheck true) .done ] + fail s!"truthmines check failed ({exit})" + +def buildSuite : LSpec.Spec := do + it "truthmines: full corpus pieces + self-contained .ixc via the driver" + (driverBuild false "truthmines.ixc" catalogSpec.libs.size) + +def checkSuite : LSpec.Spec := do + it "truthmines: per-piece kernel check sweep (fat rung 1)" + (driverCheck false) + +def miniSuite : LSpec.Spec := do + it "truthmines-mini: fixtures + spine + Mathlib + FLT → .ixc directory" + (driverBuild true "truthmines-mini.ixc" catalogMiniSpec.libs.size) + it "truthmines-mini: per-piece kernel check sweep" + (driverCheck true) end Tests.Ix.TruthMines diff --git a/Tests/Ix/TruthMinesRecords.lean b/Tests/Ix/TruthMinesRecords.lean index 9e6e137930..2554f9dd97 100644 --- a/Tests/Ix/TruthMinesRecords.lean +++ b/Tests/Ix/TruthMinesRecords.lean @@ -30,32 +30,24 @@ open TruthMinesSpec namespace Tests.Ix.TruthMinesRecords -private def check (ok : Bool) (message : String) : - Bool × Nat × Nat × Option String := - (ok, 0, 0, if ok then none else some message) - -private def validationTest : IO (Bool × Nat × Nat × Option String) := do +private def validationTest : AssertM Unit := do let errors := catalogValidationErrors - return check errors.isEmpty + expect errors.isEmpty s!"catalog validation errors:\n{String.intercalate "\n" errors.toList}" -private def toolchainTest : IO (Bool × Nat × Nat × Option String) := do +private def toolchainTest : AssertM Unit := do let repo := (← IO.FS.readFile "lean-toolchain").trimAscii.toString let workspace := (← IO.FS.readFile workspaceToolchainPath).trimAscii.toString let compileWorkspace := (← IO.FS.readFile compileWorkspaceToolchainPath).trimAscii.toString - if repo != expectedToolchain then - return check false - s!"repo lean-toolchain `{repo}` != derived `{expectedToolchain}`" - if workspace != expectedToolchain then - return check false - s!"workspace lean-toolchain `{workspace}` != derived `{expectedToolchain}`" - if compileWorkspace != expectedToolchain then - return check false - s!"compile workspace lean-toolchain `{compileWorkspace}` != derived `{expectedToolchain}`" - return check true "" - -private def projectionTest : IO (Bool × Nat × Nat × Option String) := do + expect (repo == expectedToolchain) + s!"repo lean-toolchain `{repo}` != derived `{expectedToolchain}`" + expect (workspace == expectedToolchain) + s!"workspace lean-toolchain `{workspace}` != derived `{expectedToolchain}`" + expect (compileWorkspace == expectedToolchain) + s!"compile workspace lean-toolchain `{compileWorkspace}` != derived `{expectedToolchain}`" + +private def projectionTest : AssertM Unit := do let mut expected := [ (workspaceLakefilePath, renderWorkspaceLakefile), (workspaceToolchainPath, renderWorkspaceToolchain), @@ -68,10 +60,9 @@ private def projectionTest : IO (Bool × Nat × Nat × Option String) := do (compileMemberModulePath lib.qualifier, renderCompileMemberModule lib)] for (path, content) in expected do unless (← path.pathExists) do - return check false s!"{path} missing — run `lake exe truthmines gen`" + fail s!"{path} missing — run `lake exe truthmines gen`" unless (← IO.FS.readFile path) == content do - return check false s!"{path} is stale — run `lake exe truthmines gen`" - return check true "" + fail s!"{path} is stale — run `lake exe truthmines gen`" /-- Lake stores non-identifier package names guillemet-quoted in the lockfile (`«lean-grpc»`); the records carry them bare. -/ @@ -119,13 +110,11 @@ private def manifestErrors (content : String) : Except String (Array String) := s!"lockfile places `{fixture}` at `{lockDir}`, expected `{dir}`" return errors -private def manifestTest : IO (Bool × Nat × Nat × Option String) := do +private def manifestTest : AssertM Unit := do let content ← IO.FS.readFile workspaceManifestPath - match manifestErrors content with - | .error error => return check false s!"lockfile walk failed: {error}" - | .ok errors => - return check errors.isEmpty - s!"lockfile/record drift:\n{String.intercalate "\n" errors.toList}" + let errors ← expectOk ((manifestErrors content).mapError (s!"lockfile walk failed: {·}")) + expect errors.isEmpty + s!"lockfile/record drift:\n{String.intercalate "\n" errors.toList}" /-- The independent fidelity workspace shares the canonical package store and adds exactly one authored source pin: the aggregate Palomar.ix library. -/ @@ -162,52 +151,42 @@ private def compileManifestErrors (content : String) : Except String (Array Stri errors := errors.push "compile lockfile is missing canonical TruthMines path" return errors -private def compileManifestTest : IO (Bool × Nat × Nat × Option String) := do +private def compileManifestTest : AssertM Unit := do let content ← IO.FS.readFile compileWorkspaceManifestPath - match compileManifestErrors content with - | .error error => return check false s!"compile lockfile walk failed: {error}" - | .ok errors => - return check errors.isEmpty - s!"compile lockfile drift:\n{String.intercalate "\n" errors.toList}" + let errors ← expectOk ((compileManifestErrors content).mapError (s!"compile lockfile walk failed: {·}")) + expect errors.isEmpty + s!"compile lockfile drift:\n{String.intercalate "\n" errors.toList}" /-- The positional member vector is what `ix catalog` receives: one `Qualifier=Root[,Root…]` entry per member, parseable by the same splitting the CLI does (`=` once, roots comma-joined, no whitespace or empty components anywhere). -/ -private def specArgvTest : IO (Bool × Nat × Nat × Option String) := do +private def specArgvTest : AssertM Unit := do for (label, spec) in [("full", catalogSpec), ("mini", catalogMiniSpec)] do let rendered := commandArguments spec if rendered.size != spec.libs.size then - return check false - s!"{label}: {rendered.size} argv entries for {spec.libs.size} members" + fail s!"{label}: {rendered.size} argv entries for {spec.libs.size} members" for (entry, lib) in rendered.zip spec.libs do let parts := entry.splitOn "=" match parts with | [qualifier, roots] => if qualifier.isEmpty || qualifier != lib.qualifier.toString (escape := false) then - return check false s!"{label}: qualifier drift in `{entry}`" + fail s!"{label}: qualifier drift in `{entry}`" let rootParts := roots.splitOn "," if rootParts.length != lib.roots.size || rootParts.any (·.isEmpty) then - return check false s!"{label}: root list drift in `{entry}`" + fail s!"{label}: root list drift in `{entry}`" if entry.any (fun c => c == ' ' || c == '\n') then - return check false s!"{label}: whitespace in argv entry `{entry}`" + fail s!"{label}: whitespace in argv entry `{entry}`" | _ => - return check false s!"{label}: entry `{entry}` is not `Qualifier=Roots`" - return check true "" - -def suite : List TestSeq := [ - .individualIO "truthmines records: catalog validation clean" - none validationTest .done, - .individualIO "truthmines records: one toolchain by construction" - none toolchainTest .done, - .individualIO "truthmines records: workspace projections byte-identical" - none projectionTest .done, - .individualIO "truthmines records: lockfile pins match the records" - none manifestTest .done, - .individualIO "truthmines records: compile workspace pins are coherent" - none compileManifestTest .done, - .individualIO "truthmines records: positional spec argv is well-formed" - none specArgvTest .done ] + fail s!"{label}: entry `{entry}` is not `Qualifier=Roots`" + +def suite : LSpec.Spec := do + it "truthmines records: catalog validation clean" validationTest + it "truthmines records: one toolchain by construction" toolchainTest + it "truthmines records: workspace projections byte-identical" projectionTest + it "truthmines records: lockfile pins match the records" manifestTest + it "truthmines records: compile workspace pins are coherent" compileManifestTest + it "truthmines records: positional spec argv is well-formed" specArgvTest end Tests.Ix.TruthMinesRecords diff --git a/Tests/Main.lean b/Tests/Main.lean index 32192029bf..dddb0ad6cc 100644 --- a/Tests/Main.lean +++ b/Tests/Main.lean @@ -115,8 +115,7 @@ def registry : List Entry := [ .suite "import-ixe" .primary Tests.Ix.ImportIxe.suite, .suite "lean-export" .primary Tests.Ix.LeanExport.suite, .suite "truthmines-spec" .primary Tests.Ix.TruthMinesRecords.suite, - -- `concurrently`: the long role and admission checks run at once - .suiteIO "ixon" .primary (concurrently (Tests.Ixon.suite ++ Tests.Ix.IxonUniverse.suite)), + .suite "ixon" .primary (do Tests.Ixon.suite; Tests.Ix.IxonUniverse.suite), .suiteIO "ixon-reject-parity" .primary Tests.Ix.IxonRejectParity.suite, .suiteIO "ixon-rust-parity" .primary Tests.Ix.IxonRustParity.suite, .suite "role-equations" .primary Tests.Ix.RoleEquations.suite, @@ -125,9 +124,9 @@ def registry : List Entry := [ .suite "merkle" .primary Tests.Merkle.suite, .suite "assumption-tree" .primary Tests.AssumptionTree.suite, .suite "commit" .primary Tests.Commit.suite, - .suiteIO "exact-sharing" .primary (concurrently (Tests.SharingExact.suite ++ Tests.SharingUniform.suite ++ Tests.SharingTiered.suite)), + .suite "exact-sharing" .primary (do Tests.SharingExact.suite; Tests.SharingUniform.suite; Tests.SharingTiered.suite), .suite "sharing-components" .primary Tests.SharingComponents.suite, - .suite "source-contract" .primary (Tests.Ix.SourceContract.suite ++ Tests.Ix.SourceContract.Driver.suite), + .suite "source-contract" .primary (do Tests.Ix.SourceContract.suite; Tests.Ix.SourceContract.Driver.suite), .suite "aiur-statistics" .primary Tests.Ix.AiurStatistics.suite, .suite "bench-measures" .primary Tests.Ix.BenchMeasures.suite, -- the compile's named refusal of ungrounded input (the IO pipeline and the pure compile) @@ -181,7 +180,7 @@ def registry : List Entry := [ .suite "primitive-address-parity" .primary Tests.Ix.Kernel.BuildPrimitives.paritySuite, .suite "decompile-unit" .primary Tests.Decompile.unitSuite, -- getFileEnv body-inclusion regression guard (IO: loads a fixture file) - .suiteIO "getfileenv-body" .primary (do return [← Tests.Ix.EnvBody.suite]), + .suiteIO "getfileenv-body" .primary Tests.Ix.EnvBody.suite, -- Reductions no kernel may make beyond Lean's (class methods reduced -- without their instance, `numBits ≡ 64`, the `Fin.val` commute): every -- probe's closure through IxCK. @@ -273,8 +272,8 @@ def registry : List Entry := [ .runner "admission-hash-diff-initstd" (.ci .nightly) Tests.Ix.Kernel.AdmissionHashDiff.runInitStd, -- Full brute-force exact-sharing oracle (`witness2` 3M-candidate sweep, -- 13.7k tied-minima tables, and 400/600-input uniform search sweeps). - .suiteIO "exact-sharing-full" (.ci .nightly) - (concurrently (Tests.SharingExact.nightlySuite ++ Tests.SharingUniform.nightlySuite)) + .suite "exact-sharing-full" (.ci .nightly) + (do Tests.SharingExact.nightlySuite; Tests.SharingUniform.nightlySuite) ] /-- The host entries that must stay registered once, in their tier diff --git a/Tests/ProofHelpers.lean b/Tests/ProofHelpers.lean index 50b167125d..b7424e82ea 100644 --- a/Tests/ProofHelpers.lean +++ b/Tests/ProofHelpers.lean @@ -7,16 +7,21 @@ namespace Tests.ProofHelpers open LSpec /-- A passing test iff `e` is `.ok`; on `.error` the message is surfaced. -/ -def expectOk [ToString ε] (descr : String) (e : Except ε α) : TestSeq := - match e with - | .ok _ => test descr true - | .error msg => test s!"{descr} — unexpected error: {msg}" false +def checkOk [ToString ε] (descr : String) (e : Except ε α) : Spec := + it descr do + let _ ← LSpec.expectOk e /-- A passing test iff the verifier rejected the input. -/ -def expectErr (descr : String) (e : Except ε α) : TestSeq := - match e with - | .error _ => test descr true - | .ok _ => test s!"{descr} — expected a rejection but it was accepted" false +def checkErr [Repr α] (descr : String) (e : Except ε α) : Spec := + it descr do + let _ ← LSpec.expectErr e + +/-- A passing test iff `e` is `.error` (no `Repr` needed on `α`). -/ +def checkErrAny (descr : String) (e : Except ε α) : Spec := + it descr do + match e with + | .error _ => pure () + | .ok _ => fail s!"{descr} — expected a rejection but it was accepted" /-- Inner-proof commitment/FRI parameters. -/ def recCommitParams : Aiur.CommitmentParameters := diff --git a/Tests/Registry.lean b/Tests/Registry.lean index c3ac6f0ec1..28619b45ef 100644 --- a/Tests/Registry.lean +++ b/Tests/Registry.lean @@ -109,10 +109,10 @@ def Tier.parse? (s : String) : Option (Tier → Bool) := /-- What an entry runs. -/ inductive Body where - /-- LSpec suites (values; built when their module initializes, as before). -/ - | suite (tests : List LSpec.TestSeq) - /-- LSpec suites built by an IO action when the entry is selected. -/ - | suiteIO (tests : IO (List LSpec.TestSeq)) + /-- LSpec v3 specification (deferred; zero work at module initialization). -/ + | suite (spec : LSpec.Spec) + /-- LSpec v3 specification built by an IO action when the entry is selected. -/ + | suiteIO (spec : IO LSpec.Spec) /-- A runner; its result is the exit code. -/ | runner (run : IO UInt32) /-- A runner that takes the test binary's Lean environment. -/ @@ -123,36 +123,16 @@ structure Entry where tier : Tier body : Body -/-- Smart constructors, so that a registration reads `.suite "name" tier tests`. -/ -def Entry.suite (name : String) (tier : Tier) (tests : List LSpec.TestSeq) : Entry := - ⟨name, tier, .suite tests⟩ -def Entry.suiteIO (name : String) (tier : Tier) (tests : IO (List LSpec.TestSeq)) : Entry := - ⟨name, tier, .suiteIO tests⟩ +/-- Smart constructors, so that a registration reads `.suite "name" tier spec`. -/ +def Entry.suite (name : String) (tier : Tier) (spec : LSpec.Spec) : Entry := + ⟨name, tier, .suite spec⟩ +def Entry.suiteIO (name : String) (tier : Tier) (spec : IO LSpec.Spec) : Entry := + ⟨name, tier, .suiteIO spec⟩ def Entry.runner (name : String) (tier : Tier) (run : IO UInt32) : Entry := ⟨name, tier, .runner run⟩ def Entry.env (name : String) (tier : Tier) (run : Lean.Environment → IO UInt32) : Entry := ⟨name, tier, .env run⟩ -/-- `tests` with every `individualIO` check started now, each on a thread of -its own with its output captured; each check of the result waits for its -thread and then prints that output, so results and output keep their order. -For a suite of independent long checks, the suite takes as long as its -longest check rather than their sum. -/ -def startChecks : LSpec.TestSeq → IO LSpec.TestSeq - | .individualIO descr shown check next => do - let task ← IO.asTask (IO.FS.withIsolatedStreams check) .dedicated - return .individualIO descr shown (do - let (output, result) ← IO.ofExcept (← IO.wait task) - IO.print output - return result) (← startChecks next) - | .individual descr p shown inst next => return .individual descr p shown inst (← startChecks next) - | .group descr tests next => return .group descr (← startChecks tests) (← startChecks next) - | .done => return .done - -/-- `suites`, their checks started at once (`startChecks`). -/ -def concurrently (suites : List LSpec.TestSeq) : IO (List LSpec.TestSeq) := - suites.mapM startChecks - /-- A workflow line without its YAML comment: from the first `#` at the line's start or after a space or a tab. A `#` inside a quoted string after a space is cut too, which can only hide a mention, never invent one. -/ @@ -306,6 +286,7 @@ structure Options where exclude : List String := [] list : Bool := false listGate : Option (Tier → Bool) := none + threads : Nat := 1 def parseArgs : List String → Options → Except String Options | [], o => .ok o @@ -318,10 +299,24 @@ def parseArgs : List String → Options → Except String Options | "--list" :: rest, o => parseArgs rest { o with list := true } | "--ignored" :: rest, o => parseArgs rest { o with ignored := true } | "--include-ignored" :: rest, o => parseArgs rest { o with includeIgnored := true } + | "-j" :: val :: rest, o | "--threads" :: val :: rest, o => + match val.toNat? with + | some n => if n == 0 then .error "--threads must be at least 1" else parseArgs rest { o with threads := n } + | none => .error s!"expected natural number for --threads, got '{val}'" | a :: rest, o => if a.startsWith "--exclude=" then let xs := ((a.drop "--exclude=".length).toString.splitOn ",").filter (!·.isEmpty) parseArgs rest { o with exclude := o.exclude ++ xs } + else if a.startsWith "--threads=" then + let val := (a.drop "--threads=".length).toString + match val.toNat? with + | some n => if n == 0 then .error "--threads must be at least 1" else parseArgs rest { o with threads := n } + | none => .error s!"expected natural number for --threads, got '{val}'" + else if a.startsWith "-j" && a.length > 2 then + let val := (a.drop 2).toString + match val.toNat? with + | some n => if n == 0 then .error "-j must be at least 1" else parseArgs rest { o with threads := n } + | none => .error s!"expected natural number for -j, got '{val}'" else if a.startsWith "-" then .error s!"unknown option '{a}'" else parseArgs rest { o with names := o.names ++ [a] } @@ -345,13 +340,43 @@ def select (entries : List Entry) (o : Options) : Except String (List Entry) := if out.isEmpty then throw "nothing selected" return out -def runEntry (getEnv : IO Lean.Environment) (e : Entry) : IO UInt32 := do +def runEntry (getEnv : IO Lean.Environment) (threads : Nat) (e : Entry) : IO UInt32 := do match e.body with - | .suite tests => LSpec.lspecIO (.ofList [(e.name, tests)]) [] - | .suiteIO tests => LSpec.lspecIO (.ofList [(e.name, ← tests)]) [] + | .suite spec => + let tree ← spec.toTestTree e.name + LSpec.defaultMainTree tree [] { threads } + | .suiteIO mkSpec => + let spec ← mkSpec + let tree ← spec.toTestTree e.name + LSpec.defaultMainTree tree [] { threads } | .runner run => run | .env run => run (← getEnv) +/-- Convert an `Entry` into a `TestTree` so all selected entries can share a + single bounded LSpec v3 `WorkerPool` when `threads > 1`. -/ +private def entryToTestTree (getEnv : IO Lean.Environment) (e : Entry) : IO LSpec.TestTree := do + match e.body with + | .suite spec => spec.toTestTree e.name + | .suiteIO mkSpec => + let spec ← mkSpec + spec.toTestTree e.name + | .runner run => + return .leaf e.name #[] fun _ => do + let code ← run + if code == 0 then return .pass + else return .fail s!"exited with code {code}" + | .env run => + return .leaf e.name #[] fun _ => do + let env ← getEnv + let code ← run env + if code == 0 then return .pass + else return .fail s!"exited with code {code}" + +/-- Total duration across all leaves of a `ReportTree`. -/ +private partial def reportTreeDuration : LSpec.ReportTree → Nat + | .leaf r => r.durationMs + | .group _ cs => cs.foldl (fun acc c => acc + reportTreeDuration c) 0 + /-- Internal dispatch shared by `run`, `runScoped`, and `runManual`. -/ private def runEntries (entries : List Entry) (loadEnv : IO Lean.Environment) (args : List String) : IO UInt32 := do @@ -371,17 +396,46 @@ private def runEntries (entries : List Entry) (loadEnv : IO Lean.Environment) -- Non-primary entries ran after the dispatcher's `get_env!`, which also -- set the Lean search path; keep the search path without the import. if selected.any (!isPrimary ·) then initLeanSearchPath - let envRef ← IO.mkRef (none : Option Lean.Environment) - let getEnv : IO Lean.Environment := do - if let some env ← envRef.get then return env - let env ← loadEnv - envRef.set (some env) - return env + let envMutex ← Std.Mutex.new (none : Option Lean.Environment) + let getEnv : IO Lean.Environment := + envMutex.atomically do + if let some env ← get then return env + let env ← loadEnv + set (some env) + return env + if o.threads > 1 && selected.length > 1 then + -- Run ALL selected entries inside one shared bounded LSpec v3 WorkerPool! + let mut children := Array.mkEmpty selected.length + for e in selected do + children := children.push (← entryToTestTree getEnv e) + let combined : LSpec.TestTree := .group "" children + let (report, summary) ← LSpec.runTree combined { threads := o.threads } + let useColor := (← IO.getEnv "NO_COLOR").isNone + let entryReports := match report with + | .group _ cs => cs + | other => #[other] + let mut failed : Array String := #[] + for h : i in [:selected.length] do + let e := selected[i] + let rep := entryReports.getD i (.group e.name #[]) + let s := rep.summarize + let ms := reportTreeDuration rep + if s.allPassed then + IO.println s!"[ixtests] {e.name}: ok {ms} ms ({s.passed} tests)" + else + let rendered := LSpec.Processors.formatReport rep useColor false + unless rendered.isEmpty do IO.eprintln rendered + IO.println s!"[ixtests] {e.name}: FAILED ({s.failed} failed) {ms} ms" + failed := failed.push e.name + IO.println s!"[ixtests] {selected.length - failed.size} of {selected.length} passed\ + {if failed.isEmpty then "" else s!"; failed: {", ".intercalate failed.toList}"} \ + ({summary.totalDurationMs} ms wall, threads={o.threads})" + return if failed.isEmpty then 0 else 1 let mut first : UInt32 := 0 let mut failed : Array String := #[] for e in selected do let start ← IO.monoMsNow - let code ← try runEntry getEnv e catch ex => do + let code ← try runEntry getEnv o.threads e catch ex => do IO.eprintln s!"[ixtests] {e.name}: uncaught exception: {ex}" pure 1 let ms := (← IO.monoMsNow) - start diff --git a/Tests/SourceContractMain.lean b/Tests/SourceContractMain.lean index 8c786eba11..2b9627f9dc 100644 --- a/Tests/SourceContractMain.lean +++ b/Tests/SourceContractMain.lean @@ -4,5 +4,6 @@ import Tests.Ix.SourceContract.SyntaxCheck import Tests.Ix.SourceContract.Driver def main (args : List String) : IO UInt32 := - LSpec.lspecIO (.ofList [("source-contract", - Tests.Ix.SourceContract.suite ++ Tests.Ix.SourceContract.Driver.suite)]) args + LSpec.lspecMain (LSpec.describe "source-contract" do + Tests.Ix.SourceContract.suite + Tests.Ix.SourceContract.Driver.suite) args diff --git a/lake-manifest.json b/lake-manifest.json index e1b2d0cf75..b8cdeb2b44 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -42,10 +42,10 @@ "type": "git", "subDir": null, "scope": "", - "rev": "d8eb3e0d9a8e33fc116e6700df0418a1d8114508", + "rev": "b12338b60c87cc2d2dfeeeaa16d859100ec038c8", "name": "LSpec", "manifestFile": "lake-manifest.json", - "inputRev": "d8eb3e0d9a8e33fc116e6700df0418a1d8114508", + "inputRev": "b12338b60c87cc2d2dfeeeaa16d859100ec038c8", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/argumentcomputer/CertiFRI", @@ -89,16 +89,6 @@ "inherited": false, "dir": "Aiur", "configFile": "lakefile.lean"}, - {"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": true, - "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4", "type": "git", "subDir": null, @@ -109,6 +99,16 @@ "inputRev": "v4.34.1", "inherited": true, "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/LeanSearchClient", "type": "git", "subDir": null, diff --git a/lakefile.lean b/lakefile.lean index 25d129ba9c..6ac6dbd81f 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -22,7 +22,7 @@ require «certifri-proofs» from git "https://github.com/argumentcomputer/CertiFRI" @ "2baa40411f32521987069a8526ac3db50c7a5154" / "Proofs" require LSpec from git - "https://github.com/argumentcomputer/LSpec" @ "d8eb3e0d9a8e33fc116e6700df0418a1d8114508" + "https://github.com/argumentcomputer/LSpec" @ "b12338b60c87cc2d2dfeeeaa16d859100ec038c8" /- The pinned package supplies the pure Lean hash and host C/Rust accelerators. -/ @@ -397,7 +397,8 @@ lean_exe «gen-paper-fixtures» where section Tests -lean_lib Tests +lean_lib Tests where + moreLeanArgs := #["-Dcompiler.extract_closed=false"] /-- The certified entry's host cases (`Tests.Ix.Kernel.EntryCaseDefs`), built as a library of their own so that suites can import them at run time (some host cases