Relating Programs through Abstraction and Parametricity for Good

Relating Programs
through Abstraction
and Parametricity
for Good

Part 1: relating programs, why?

Relating Programs why?
through Abstraction
and Parametricity
for Good

A toy problem

inductive Expr where | lit : Nat → Expr | add : Expr → Expr → Expr def Expr.eval : Expr → Nat | .lit n => n | .add x y => x.eval + y.eval def addC (p q : Nat × Nat) : Nat × Nat := (p.1 + q.1, p.2 + q.2 + 1) def deep : Expr := .add (.lit 1) (.lit 2) def shallow : Nat := Nat.add 1 2 def counted : Nat × Nat := addC (1, 0) (2, 0)
  • Programs: same structure, different operations

  • Goal: relate them, e.g.

    • deep.eval = shallow

    • counted.1 = shallow (drop the counter)

Less toy problems

  • Is a fast implementation faithful to its model?

  • Does erasing ghost code preserve the behavior?

  • Do properties proved for a syntactic representation carry over to its concrete interpretation?

Data refinement

  • Is a fast implementation faithful to its model?

abbrev LogicalStore := String → Nat abbrev Journal := List (String × Nat)abbrev Source := StateM LogicalStore abbrev Target := StateM Journal
  • The programs may differ only in the state they manipulate

Ghost erasure

  • Does erasing ghost code preserve the behavior?

  • Relate a program in StateT σ m and another in m:

    • StateT σ m: ghost state handled as real state

    • m: every operation on ghost state becomes pure ()

Symbolic vs. executable

  • Do properties proved for a syntactic representation carry over to its concrete interpretation?

inductive Choice : Type → Type where | pick (τ : Type) : Choice τ/-- Executions keep the balance in the state of an arbitrary base monad. -/ abbrev Exec (n : Type → Type v) := StateT Nat n /-- Verification adds uninterpreted choices on top of the balance. -/ abbrev Symbolic (n : Type → Type v) := FreerT Choice (Exec n)
  • Relate a Symbolic program to its Exec version, with every Choice resolved ("extraction")

How to relate them?

  • Directly, following the shared structure

    • One side is deep: induction on it

    • Both are shallow: unfold them, then tactics

  • What if we abstract first?

    • Factor out the shared structure, with the operations as parameters

    • Both programs are instantiations of it

    • A general engine could traverse the structure; we only relate the operations

Part 2: through abstraction

Relating Programs
through Abstraction (e.g., tagless-final style)
and Parametricity
for Good

Observation

  • Turn the building blocks into type classes

    • how parts combine (e.g. add) and the leaves (e.g. lit)

  • The shared structure: one program, written against the classes

  • Each concrete program: that program at a set of instances of the classes

Goal: relate two instantiations of the same program

One way: tagless-final style

class Arith (A : Type) where lit : Nat → A add : A → A → A def expression [Arith A] : A := Arith.add (Arith.lit 1) (Arith.lit 2) instance : Arith Expr := ⟨.lit, .add⟩ instance : Arith Nat := ⟨id, Nat.add⟩ instance : Arith (Nat × Nat) := ⟨fun n => (n, 0), addC⟩ example : expression = deep := rfl example : expression = shallow := rfl example : expression = counted := rfl
  • deep, shallow, counted: expression at three instances

The monadic case

def withdraw [Monad m] [MonadReaderOf Nat m] [MonadStateOf Nat m] [MonadExceptOf String m] (amount : Nat) : m Unit := do let fee ← read modify (· - fee) if (← get) < amount then throw "insufficient funds" modify (· - amount)
  • Composition: pure, bind; effects: capability operations

    • E.g., MonadStateOf provides get, set and modifyGet

Goal: R (p (m := M)) (p (m := M')) for a tagless-final program p

Part 3: and parametricity

Relating Programs
through Abstraction
and Parametricity with Tapas
for Good

Intuition

  • Suppose R relates pure and bind:

    • R (pure a) (pure a)

    • R x y, ∀ a, R (f a) (g a) ⇒ R (x >>= f) (y >>= g)

  • If p is only built with pure and bind, then by recursively applying the two rules, we have R (p (m := M)) (p (m := M'))

Beyond pure and bind

  • The two rules are read off the class Monad

  • Other classes come with their own, e.g. MonadStateOf:

    • R get get

    • ∀ s, R (set s) (set s)

  • A program that also uses get and set relies on these rules too

Relating programs of a type

abbrev Tp := {m : Type → Type u} → [Monad m] → [MonadStateOf Nat m] → m Unit def Tp.Rel (p q : Tp.{u}) : Prop := ∀ {m m' : Type → Type u} (R : ∀ ⦃α⦄, m α → m' α → Prop), ∀ [Monad m] [Monad m'], /- `pure` and `bind` are related by R for the two instances -/ ∀ [MonadStateOf Nat m] [MonadStateOf Nat m'], /- state operations are related by R for the two instances -/ R (p (m := m)) (q (m := m'))
  • Premises: R relates the monad operations and the state operations

  • Conclusion: R relates the two instances

Parametricity

  • Tp.Rel p p: same program, different interpretations

  • To prove R (p (m := M)) (p (m := M')):

    1. Prove parametricity of p: Tp.Rel p p

    2. Prove the operations of M and M' preserve R

Reynolds 1983; Wadler 1989; Voigtländer 2009

What Tapas does

  1. Infer the tagless-final form: infer_effects

  2. Generate the relations: derive_effect_rel, derive_type_rel

  3. Prove parametricity: derive_parametric

    • One program at a time; Lean's kernel checks each proof

1. Abstraction, automated

infer_effects def withdraw (amount : Nat) : m Unit := do let fee ← read modify (· - fee) if (← get) < amount then throw "insufficient funds" modify (· - amount) example : @withdraw = @ByHand.withdraw := rfl
  • Elaborate against an unknown m; stuck instance problems become parameters

  • A trick from Veil; also for recursive and mutual definitions

2. Relations of classes

variable (R : ∀ ⦃α⦄, m α → m' α → Prop) [Monad.Rel R] -- pure : α → m α example : ∀ {α} (a : α), R (pure a) (pure a) := Monad.Rel.pure -- bind : m α → (α → m β) → m β example : ∀ {α β} (x : m α) (x' : m' α), R x x' → ∀ (f : α → m β) (f' : α → m' β), (∀ a, R (f a) (f' a)) → R (x >>= f) (x' >>= f') := Monad.Rel.bind
  • Pre-generated for Lean's classes; else derive_effect_rel C

2. Relations of types

abbrev Tp := {m : Type → Type u} → [Monad m] → [MonadStateOf Nat m] → m Unit derive_type_rel Tp (repr := m) #print Tp.Rel
def WithTapas.Tp.Rel.{u, u_target} : Tp → Tp → Prop := fun left right => ∀ {m : Type → Type u} {m' : Type → Type u_target} (R : ⦃a : Type⦄ → m a → m' a → Prop) [inst : Monad m] [inst' : Monad m'], Monad.Rel R → ∀ [inst_1 : MonadStateOf Nat m] [inst'_1 : MonadStateOf Nat m'], MonadStateOf.Rel R → R left right

3. Parametricity

def tick [Monad m] [MonadStateOf Nat m] : m Unit := modify (· + 1) derive_parametric tick example : Tp.Rel @tick @tick := tick.parametric

Back to the examples

Data refinement: the relation

abbrev LogicalStore := String → Nat abbrev Journal := List (String × Nat)abbrev Source := StateM LogicalStore abbrev Target := StateM Journal/-- Most recent writes shadow older ones; absent keys contain zero. -/ @[expose] def decode : Journal → LogicalStore | [] => fun _ => 0 | (key, value) :: rest => fun query => if query = key then value else decode rest query/-- Preserve returned values and logical final stores for every represented initial store. The target's journal layout and shadowed entries are intentionally unobservable. -/ @[expose] def R : ComputationRelation Source Target := fun {_} source target => ∀ journal, source (decode journal) = ((target journal).1, decode (target journal).2)
  • R: from every journal, same result and same logical store

Data refinement: the interface

class Store (m : Type → Type v) where fetch : String → m Nat store : String → Nat → m Unit /-- Run a computation, retaining its return value but restoring the initial store. -/ sandbox : {α : Type} → m α → m α derive_effect_rel Store
  • sandbox is higher-order: its argument is a computation
    (transfer passes it a whole do block)

  • Store.Rel R asks for it:
    R x y → R (sandbox x) (sandbox y)

Ghost erasure: the setup

class MonadGhostOf (I : Type u) (m : Type u → Type v) where ghost : I → m PUnit.{u + 1} class GhostUpdateStep (I σ : Type u) where step : I → σ → σ/-- Keep the ghost state in the state monad. -/ instance stateGhost [inst : GhostUpdateStep I σ] : MonadGhostOf I (StateT σ m) where ghost i := fun s => pure (⟨⟩, inst.step i s) instance (priority := low) erasedGhost : MonadGhostOf I m where ghost _ := pure ⟨⟩

Ghost erasure: the relation

/-- The instrumented run returns the same value, from every initial ghost state. -/ @[expose] def Erase (σ : Type u) (m : Type u → Type v) [Monad m] : ComputationRelation (StateT σ m) m := fun {_} withGhost noGhost => ∀ s, Prod.fst <$> withGhost s = noGhost
  • R (Erase): from every ghost state, same result once it is dropped

Symbolic vs. executable: the relation

/-- Executions keep the balance in the state of an arbitrary base monad. -/ abbrev Exec (n : Type → Type v) := StateT Nat n /-- Verification adds uninterpreted choices on top of the balance. -/ abbrev Symbolic (n : Type → Type v) := FreerT Choice (Exec n)-- Parametricity relates the two instantiations along any relation that their operations -- preserve. The relation chosen here is the conclusion wanted. /-- The execution establishes every postcondition that the symbolic computation establishes. -/ def Refines : ComputationRelation (Symbolic n) (Exec n) := fun {α} x y => ∀ (Q : α → Nat → Pred) (E : EPred), wp x Q E ⊑ wp y Q E
  • R (Refines): postconditions verified under demonic choice carry over to executions whose choices preserve R

  • Symbolic proof + Refines ⇒ executable proof

Loops: partial_fixpoint

  • Loops, partial_fixpoint: least fixpoints on each side

  • Divergence is the least element of each side's monad

  • Extra premise: AdmissibleRel R, closed under chain suprema

theorem drain_certificate (l : List Nat) : Erase Nat Option (drain (m := CountedOpt) l) (drain (m := PlainOpt) l) := drain.parametric l _ Erase.monadRel Erase.ghostRel (fun {_} => Erase.admissible)
  • No interaction trees, no coinduction

Part 4: for good

Relating Programs
through Abstraction
and Parametricity
for Good compared to …

Abstracting into data

-- Reified requests and their continuations. No Functor instance for E is needed. inductive Freer (E : Type u → Type v) (α : Type u) : Type (max (u + 1) v) where | pure : α → Freer E α | impure {β : Type u} : E β → (β → Freer E α) → Freer E α@[expose] def fold {m : Type u → Type w} [Monad m] (h : (β : Type u) → E β → m β) (t : Freer E α) : m α := match t with | .pure a => Pure.pure a | .impure op k => h _ op >>= fun x => fold h (k x)
  • A program as data: a request tree (or an interaction tree)

  • An interpretation: fold the tree with a handler h

Two routes, one skeleton

  • Each operation (or handler) preserves the relation: proved once

  • Function (tagless-final): prove parametricity for each program

  • Data (tree): one induction relates the folds of every tree

  • With only first-order operations, the two abstractions are interconvertible

Function ⇄ data

abbrev Final (E : Type u → Type v) (α : Type u) := {m : Type u → Type w} → [Monad m] → [MonadLiftT E m] → m α @[expose] def toFinal {E : Type u → Type v} {α : Type u} (t : Freer E α) : Final.{u, v, w} E α := fun {m} _ _ => Freer.fold (m := m) (fun _ => monadLift) t-- Reification needs an output universe large enough to instantiate m := Freer E. @[expose] def toFreer {E : Type u → Type v} {α : Type u} (p : Final.{u, v, max (u + 1) v} E α) : Freer E α := p (m := Freer E)
  • toFinal: fold the tree; toFreer: instantiate m := Freer E

MonadLiftT E ≅ a first-order class

-- One capability adapter. Keep modifyGet as an independent operation, since -- MonadStateOf does not require its implementation to be derived from get/set. inductive StateOp (σ : Type u) : Type u → Type (u + 1) where | get : StateOp σ σ | set : σ → StateOp σ PUnit | modifyGet {α : Type u} : (σ → α × σ) → StateOp σ α-- Keep the adapters as definitions: registering both directions as global instances -- would make instance search follow a cycle between the two capabilities. /-- Use a request interpreter as a state capability. -/ @[instance_reducible] def stateOfLift (lift : MonadLiftT (StateOp σ) m) : MonadStateOf σ m where get := lift.monadLift .get set s := lift.monadLift (.set s) modifyGet f := lift.monadLift (.modifyGet f) /-- Interpret state requests using a state capability. -/ @[instance_reducible] def liftOfState (state : MonadStateOf σ m) : MonadLiftT (StateOp σ) m where monadLift op := match op with | .get => state.get | .set s => state.set s | .modifyGet f => state.modifyGet f
  • Round trips need no monad laws; the relations correspond too

Interconversion

theorem toFreer_toFinal {E : Type u → Type v} {α : Type u} (t : Freer E α) : toFreer (toFinal t) = t := Freer.fold_self t/-- Reifying a self-related final program preserves its interpretation in any lawful monad. -/ theorem toFinal_toFreer {E : Type u → Type v} {α : Type u} (p : Final.{u, v, max (u + 1) v} E α) (hp : Final.Rel @p @p) {m : Type u → Type (max (u + 1) v)} [Monad m] [LawfulMonad m] [MonadLiftT E m] : toFinal (toFreer @p) (m := m) = p (m := m) := toFinal_toFreer_rel @p @p hp
  • Tree → function → tree: identity, by induction on the tree

  • Function → tree → function: identity, given p's parametricity

"Why not freer?" You can: the two carry the same information.
What differs is what each makes cheap.

Instantiation is reduction; fold is a theorem

Route

Concrete program

Equals the original by

After compilation

Function

an instance of the abstract program

unfolding (rfl), no monad laws

an ordinary program, can be specialized

Data

a folded tree

a theorem to prove

the intermediate tree remains today

today: a limitation of Lean / Tapas today, not of the abstraction itself

Eliminating fold

Proving, compiling, generating VCs:
each pushes fold in until it is gone.

  • Straight-line code: reduction does it (partial evaluation)

  • A branch on a runtime value c: definitional reduction is infeasible

    • fold h (if c then t else e): fold needs a constructor

    • … = if c then fold h t else fold h e: a theorem, by cases on c

Instantiation: nothing to push; both branches are already in M'.

Below: why this might be useful

Run time: the tree stays

  • Same body p, same handler, same monad Exec:

    • direct: p (m := Exec)

    • via the tree: Freer.fold handle (p (m := Freer Op))

  • Via the tree: 3.4–6.6× slower on six workloads
    (1.9–3.5× on a five-layer stack)

  • Optimized IR: Lean's compiler does not eliminate fold;
    the tree route still builds nodes and folds them today

Proof time: VCs by reduction

abbrev Spec (σ α : Type) := (α → σ → Prop) → σ → Prop def Sound : ⦃α : Type⦄ → StateM σ α → Spec σ α → Prop := fun {_} x w => ∀ post s, w post s → post (x.run s).1 (x.run s).2 def step {m : Type → Type} [Monad m] [MonadStateOf Nat m] (v : Nat) : m Unit := do let s ← get; set (s + v) let s ← get; set (s - v) derive_parametric step example : step (m := Spec Nat) v post s = post () (s + v - v) := rfl example : Sound (step (m := StateM Nat) v) (step (m := Spec Nat) v) := step.parametric Sound Sound.monad Sound.state v
  • WP by reduction (rfl), soundness by parametricity

    • "Lazy proof" once more?

Proof time: if and match

def clamp {m : Type → Type} [Monad m] [MonadStateOf Nat m] (k : Nat) : m Unit := do let s ← get if s < k then set k theorem clamp_wp : clamp (m := Spec Nat) k post s = (if s < k then fun post _ => post () k else fun post s => post () s) post s := rfl example : clamp (m := Spec Nat) k (fun _ s' => k ≤ s') s := by rw [clamp_wp]; split <;> (dsimp only; omega)
  • The branches reduce to WPs; post s stays outside the if

  • A case split finishes it (as in vcgen); grind does it

Proof time: stand-ins for procedures

def double {m : Type → Type} [Monad m] [MonadStateOf Nat m] (k : Nat) : m Nat := do let n ← get; set (n + k); pure (2 * k) def doubleSpec (k : Nat) : Spec Nat Nat := fun post s => ∀ r, k ≤ r → post r (s + k) class Double (m : Type → Type) where double : Nat → m Nat instance : Double (StateM Nat) := ⟨fun k => double k⟩ instance : Double (Spec Nat) := ⟨doubleSpec⟩ def caller {m : Type → Type} [Monad m] [MonadStateOf Nat m] [Double m] : m Nat := do let r ← Double.double 3 let s ← get pure (s + r) derive_parametric caller example : caller (m := Spec Nat) post s = ∀ r, 3 ≤ r → post (s + 3 + r) (s + 3) := rfl example : Sound (caller (m := StateM Nat)) (caller (m := Spec Nat)) := caller.parametric Sound Sound.monad Sound.state Sound.double
  • The caller's WP shows the spec, not the body

  • Proved once per procedure: the spec is sound for the body

Proof time: against vcgen

Case

vcgen

Reduction

AddSubCancel

1.67 s

0.60 s

MatchSplit

10.3 s

0.15 s

ReaderState

0.58 s

0.55 s

PurePrecond

0.90 s

43.3 s

GetThrowSet (VCs only)

3.69 s

0.15 s

  • PurePrecond: vcgen discharges each precondition as it goes;
    reduction leaves one big VC, slow for grind

Cases from Lean's vcgen benchmark suite; Lean 4.35; complete proofs unless noted.
zqy1018.top/blog/tapas-for-vcgen

Back to the start: relating directly

  • Relating directly: the rules for bind and each operation

  • That redoes the parametricity proof for this one pair of instances

  • Abstracting first buys:

    • one derivation, reused for every relation and every pair of instances

    • automatic alignment of the two sides' structures

Back to the start: deep vs. shallow

  • Abstracting into data: a request tree, the program's deep embedding

  • Abstracting into a function: tagless final, a parameterized shallow embedding

  • The opening's deep.eval = shallow is exactly "fold = original program"

example : expression (A := Expr) = deep := rfl example : expression (A := Nat) = shallow := rfl example : (expression (A := Expr)).eval = expression (A := Nat) := expression.parametric (fun (d : Expr) s => d.eval = s) evalRel