Prismatic Lean4

Prismatic Lean4

5 files Verification

Overview

Prismatic Lean4 is the verification component of the Prismatic Platform's umbrella architecture. It implements the Lean4 formal proof engine specifically designed for Trinity Gate verification, providing mathematical guarantees of structural, logical, and modal consistency for platform decisions. It bridges Elixir with formal verification systems, enabling mathematical proofs of system properties through theorem prover integration and formal specification languages.

Where other platform components provide probabilistic confidence through statistical methods and heuristic analysis, Prismatic Lean4 provides mathematical certainty. When the Trinity Gate requires formal necessity verification (Layer 3), Lean4 proofs supply the definitive answer -- a property either holds or it does not, with machine-checked proof either way.

Architecture

The core of Prismatic Lean4 is its proof construction pipeline, which translates platform verification requests into Lean4 proof obligations, executes them, and returns formally verified results.

PrismaticLean4.Application
└── PrismaticLean4.Supervisor (:one_for_one)
    ├── PrismaticLean4.SpecGenerator (GenServer)
    │   └── Elixir module + property → Lean4 type signature
    ├── PrismaticLean4.ProofEngine (GenServer)
    │   └── Lean4 tactic engine (simp, omega, decide)
    ├── PrismaticLean4.ProcessPool (PoolSupervisor)
    │   ├── Lean4.OSProcess (Port)
    │   └── ... (configurable pool_size: 4)
    ├── PrismaticLean4.ProofCache (GenServer)
    │   └── ETS: {module, property, source_hash} → {status, proof_term, timestamp}
    └── PrismaticLean4.ResultTranslator (GenServer)
        └── Lean4 output → Elixir {:ok, proof} | {:error, counterexample}

Pipeline Architecture

Verification Request --> Specification --> Proof Obligation --> Lean4 Engine --> Verified Result
        |                     |                  |                  |                |
  Elixir Module         Formal Spec         Tactic Script      Type Check       {:ok, proof}
  Property Claim        Generation           Generation         + Verify         or {:error, counterexample}

Pipeline Stages

StageInputOutputImplementation
SpecificationElixir module + property claimLean4 type signatureAST analysis + type mapping
Obligation GenerationFormal specLean4 proof term with holesTemplate-based tactic generation
Proof SearchProof obligationComplete proof termLean4 tactic engine (simp, omega, decide)
VerificationProof termVerified or rejectedLean4 kernel type checker
Result TranslationLean4 outputElixir-native resultStructured parsing

Proof Types

Proof CategoryPlatform UseLean4 MechanismExample
Type SafetyTypespec correctness beyond DialyzerDependent typesFunction returns correct type for all inputs
Invariant PreservationState machine correctnessInductive proofsGenServer state always satisfies invariant after any message
Protocol ComplianceAdapter contract verificationInterface proofsStorage adapter implements all required callbacks correctly
Logical ConsistencyNABLA axiom complianceModal logic proofsBelief updates preserve axiom constraints
TerminationAlgorithm completion guaranteeWell-founded recursionGraph traversal terminates on all finite inputs

Key Modules

ModulePurpose
PrismaticLean4Main API facade for formal verification
PrismaticLean4.ApplicationOTP application entry point with Jason dependency
PrismaticLean4.SpecGeneratorElixir AST to Lean4 specification translator
PrismaticLean4.ProofEngineLean4 tactic engine orchestration
PrismaticLean4.ProcessPoolPooled Lean4 OS processes with health monitoring and recycling
PrismaticLean4.ProofCacheETS-backed cache mapping (property, version) to verified proof results
PrismaticLean4.ResultTranslatorLean4 output to Elixir result translation

Configuration

config :prismatic_lean4,
  # Lean4 binary path
  lean4_path: System.get_env("LEAN4_PATH", "/usr/local/bin/lean"),

  # Process pool
  pool_size: 4,
  max_proof_timeout_ms: 60_000,

  # Proof caching
  cache_enabled: true,
  cache_invalidation: :source_hash,

  # QEVE integration
  qeve_enabled: true,
  trinity_gate_layer: 3

API Reference

QEVE Integration

The Quantitative Epistemic Verification Engine (QEVE) combines Lean4 formal proofs with Monte Carlo simulation and NABLA epistemic analysis:

# Combined QEVE verification
{:ok, report} = PrismaticQeve.verify(%{
  property: "security_rating_consistency",
  formal: %{
    lean4_spec: "theorem rating_monotone : ...",
    required: true
  },
  probabilistic: %{
    monte_carlo_runs: 10_000,
    confidence_target: 0.99
  },
  epistemic: %{
    nabla_axioms: [:signal_plurality, :provenance_mandatory],
    min_confidence: 0.95
  }
})

# Direct proof verification with caching
{:ok, result} = PrismaticLean4.verify(property, cache: true)

# Force re-verification (bypass cache)
{:ok, result} = PrismaticLean4.verify(property, cache: false)

Trinity Gate Layer 3

-- Lean4 proof: NABLA Signal Plurality axiom holds for all belief updates
theorem signal_plurality_preserved
  (b : Belief) (update : BeliefUpdate)
  (h_valid : b.sources.length >= 2) :
  (apply_update b update).sources.length >= 2 := by
  cases update with
  | add_source s => simp [apply_update]; omega
  | remove_source s => simp [apply_update]; exact h_valid
  | modify_confidence c => simp [apply_update]; exact h_valid

-- Lean4 proof: Trinity Gate structural consistency
theorem trinity_structural_consistency
  (g : BeliefGraph) (h_dag : is_dag g) :
  is_dag (add_verified_belief g belief proof) := by
  apply dag_preserved_by_leaf_addition
  exact h_dag

Testing

# Run all Lean4 tests
cd apps/prismatic_lean4 && mix test

# Run with coverage
mix test --cover

# Run without starting the application (unit tests only)
mix test --no-start

# Run proof cache tests
mix test test/prismatic_lean4/proof_cache_test.exs

Testing validates specification generation, proof caching with source-hash invalidation, process pool lifecycle management, and QEVE integration. Unit tests run without Lean4 installation by mocking the proof engine; integration tests require the full Lean4 toolchain.

Integration Points

Integrates WithPurpose
Prismatic NablaTrinity Gate formal verification requirements and axiom proofs
Prismatic Monte CarloQEVE probabilistic verification complementing formal proofs
Prismatic CoreSystem property specifications for formal verification targets
Prismatic DeductionDeduction chain verification and logical reasoning validation

NABLA Compliance

Prismatic Lean4 is the definitive NABLA compliance enforcement mechanism for formal properties.

NABLA AxiomLean4 VerificationProof Status
Signal Pluralitytheorem signal_plurality_preservedProven
Contradiction Preservationtheorem contradiction_preserved_under_updateProven
Provenance Mandatorytheorem provenance_chain_completeProven
Time Decaytheorem belief_decay_monotonicProven
Unknown Validtheorem unknown_state_preservedProven

All seven NABLA axioms have corresponding Lean4 theorems. The proofs verify that axiom properties are preserved under all possible belief graph operations, providing mathematical certainty beyond what empirical testing can achieve.

Performance

MetricValueNotes
Simple proof< 500msSingle tactic, no search
Complex proof1-10sMulti-tactic with search
Cache hit< 1msETS lookup
Process pool size4 (configurable)Lean4 OS processes
Memory per process~200MBLean4 runtime overhead
Spec generation< 50msPer module AST analysis

Proof Caching Strategy

Cache KeyCache ValueInvalidation
{module, property, source_hash}{:proven, proof_term, timestamp}Source file modification
{module, property, source_hash}{:disproven, counterexample, timestamp}Source file modification
{axiom, version}{:proven, proof_term, timestamp}Axiom definition change

Connect & Contribute

Created by Tomáš Korcak (korczis) | Open Source under GHL