Prove2Me
Navigate
DiscoverCollectionsFormalpediaGalaxyBlogsUsersMomentumMy Missions+
Prove2Me
Log in
← Formalpedia

The ambient cost model: data, programs and timed evaluation

Definition
MIPRE_Foundations_Cost_Basic

by thomasvidick · Oct 12, 2026 · Mathlib 0df444a (Lean v4.33.1)

complexity-theorycomputabilitycost-modelmipre-formalization

This bundle fixes the cost model in which every polynomial-time statement of the formalization is made: the data, the programming language, and its timed semantics.

Data. MIPRE.Cost.Data is the type of finite binary trees, generated by a leaf nil\mathtt{nil}nil and a binary node cons(a,b)\mathtt{cons}(a, b)cons(a,b). Every object a program handles (bit strings, numbers, pairs, and programs themselves) is encoded as such a tree. MIPRE.Cost.Data.size counts nodes: size(nil)=1\mathrm{size}(\mathtt{nil}) = 1size(nil)=1 and size(cons(a,b))=size(a)+size(b)+1\mathrm{size}(\mathtt{cons}(a,b)) = \mathrm{size}(a) + \mathrm{size}(b) + 1size(cons(a,b))=size(a)+size(b)+1. MIPRE.Cost.Data.toBits is the preorder serialization of a tree as a bit string, one bit per node (nil↦0\mathtt{nil} \mapsto 0nil↦0, cons(a,b)↦1 a b\mathtt{cons}(a,b) \mapsto 1\,a\,bcons(a,b)↦1ab); it is a prefix code whose length is exactly the size, so sizes are additive under pairing. MIPRE.Cost.Data.ofNat gives unary numerals: ofNat(n)\mathrm{ofNat}(n)ofNat(n) is the chain cons(nil,cons(nil,… ))\mathtt{cons}(\mathtt{nil}, \mathtt{cons}(\mathtt{nil}, \dots))cons(nil,cons(nil,…)) of nnn copies of nil\mathtt{nil}nil ending in nil\mathtt{nil}nil, of size 2n+12n + 12n+1; MIPRE.Cost.Data.toNat? reads a unary numeral back, returning nothing on malformed data.

Programs. MIPRE.Cost.Prog is a minimal first-order language with de Bruijn variables (variable 000 is the innermost bound variable, and the input of a program): var i\mathtt{var}\ ivar i reads variable iii; nil\mathtt{nil}nil, const d\mathtt{const}\ dconst d and cons h t\mathtt{cons}\ h\ tcons h t build values; elim i n c\mathtt{elim}\ i\ n\ celim i n c inspects variable iii in place, running nnn if it is nil\mathtt{nil}nil and otherwise running ccc with the two components bound as variables 000 and 111; let e b\mathtt{let}\ e\ blet e b (the constructor let_) binds the value of eee as variable 000 in bbb; and loop b\mathtt{loop}\ bloop b iterates bbb on the state held in variable 000 until it signals a stop. MIPRE.Cost.Prog.WellScoped n pn\ pn p says that every variable of ppp is bound in an environment of length nnn: var i\mathtt{var}\ ivar i requires i<ni < ni<n, the branch ccc of an elim\mathtt{elim}elim is checked at length n+2n + 2n+2, the body of a let\mathtt{let}let at n+1n + 1n+1, and a loop\mathtt{loop}loop requires n>0n > 0n>0. A program that is well scoped at length 111 is closed: it reads only its input.

Environments. MIPRE.Cost.Env is a list of values, innermost first, and MIPRE.Cost.Env.get env i\mathit{env}\ ienv i is the iii-th value, with nil\mathtt{nil}nil beyond the end of the list, so that the semantics is total.

Timed evaluation. MIPRE.Cost.Eval is the timed big-step semantics: Eval(env,p,r,t)\mathrm{Eval}(\mathit{env}, p, r, t)Eval(env,p,r,t) means that ppp, in the environment env\mathit{env}env, halts with the result rrr at cost t∈Nt \in \mathbb{N}t∈N. Each rule charges one unit, except that reading a variable costs the size of its value plus one and a literal const d\mathtt{const}\ dconst d costs size(d)\mathrm{size}(d)size(d): values are copied when read, and inspected in place by elim\mathtt{elim}elim. A loop body returns cons(flag,s′)\mathtt{cons}(\mathit{flag}, s')cons(flag,s′): if flag=nil\mathit{flag} = \mathtt{nil}flag=nil the loop stops with the result s′s's′, otherwise it continues with s′s's′ as the new state in variable 000 (a body result nil\mathtt{nil}nil stops the loop with result nil\mathtt{nil}nil). Finally MIPRE.Cost.Halts p xp\ xp x says that ppp halts on the input xxx: there are rrr and ttt with

Eval([x], p, r, t).\mathrm{Eval}([x],\, p,\, r,\, t).Eval([x],p,r,t).

The lemmas proved in the bundle are the size equations (size(nil)=1\mathrm{size}(\mathtt{nil}) = 1size(nil)=1, the node formula for cons\mathtt{cons}cons, size>0\mathrm{size} > 0size>0, size(ofNat n)=2n+1\mathrm{size}(\mathrm{ofNat}\ n) = 2n + 1size(ofNat n)=2n+1, and that toBits\mathrm{toBits}toBits has length size\mathrm{size}size), the round trip toNat?(ofNat n)=n\mathrm{toNat?}(\mathrm{ofNat}\ n) = ntoNat?(ofNat n)=n, the lookup equations for environments (including that a lookup below the length is unaffected by appending entries), monotonicity of well-scopedness in the length, the fundamental bound MIPRE.Cost.Eval.size_le that a run of cost ttt produces a result of size at most ttt (every node of the result was built or copied at unit cost), and the weakening lemma MIPRE.Cost.Eval.append_of_wellScoped that extra environment entries are inert for a well-scoped program.

Formalization Note. The model is a "rose-tree machine" in the sense of C. Reitwiessner's proposal, with binary trees in place of rose trees and a time-only semantics. The module docstring records why it was chosen over three alternatives: Nat.Partrec.Code carries no notion of polynomial time (its primitives reach large values only through successor chains or value-indexed recursion, so binary addition has no polylogarithmic-cost program, and its quadratic pairing distorts lengths exponentially); Mathlib's Turing.ToPartrec.Code, used until 2026-09-08, cannot rebuild a list in polynomial time (its programs only touch the front of a single list passed by value); and Turing machines have no usable composition or universal machine in Mathlib. Charging the size of a value on every read is what makes the unit costs honest: by Eval.size_le every value in a computation is bounded by the running time, so a pointer machine simulates a run of cost ttt in O(t)O(t)O(t) steps and a Turing machine in time polynomial in ttt; this is an unformalized meta-remark, as the final theorem of the project claims only Mathlib's Computable. Numbers such as the compression parameter enter in binary, so that "succinct" means polylogarithmic in the described object.

Definition code
/-
Copyright (c) 2026 Thomas Vidick. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Vidick
-/
/- Generated for Prove2Me from vidick/MIPRE-formalization@70cbf1c, MIPRE/Foundations/Cost/Basic.lean (definition bundle: declarations the uploaded statements rest on);
   produced mechanically by prove2me/tools/gen.py, never edited by hand. -/
import Mathlib.Data.List.Basic
import Mathlib.Data.Nat.Notation

/-!
# The ambient cost model

This file fixes the cost model in which **every** polynomial-time statement of the
project is made: the transformations of the compression pipeline (introspection,
oracularization, answer reduction, parallel repetition), the `Compress` map, the
efficient computability toolkit (universal machine, s-m-n, Kleene fixed point;
blueprint Section `sec:rr-computability`), and the recursive compression lemma
(blueprint `lem:recursive-compression`, [MNY] Lemma 5.1).

## The model

Data are binary trees (`Data`: `nil` and `cons`), the S-expressions in which bit
strings, numbers, pairs and programs are all encoded (`Cost.Encoding`). `Data.size`
counts nodes; it is the bit-length of the preorder serialization `Data.toBits`, so
sizes are additive under pairing (R4 below).

Programs (`Prog`) form a minimal first-order language with de Bruijn variables over an
environment of `Data` values: `var i` reads a variable, `nil`, `const d` and `cons h t`
build values, `elim i n c` inspects the `i`-th variable (binding the two components of
a `cons`), `let_ e b` binds, and `loop b` iterates `b` on the state held in variable `0`
until it signals stop. The timed big-step semantics `Eval env p r t` charges one unit
per rule, except that reading a variable or a literal costs the size of the value:
**values are copied when read and inspected in place by `elim`**. Consequently a run
of cost `t` produces a result of size at most `t` (`Eval.size_le`), so every value
occurring in a computation is polynomially bounded by the running time — which is what
makes the unit costs honest under a pointer-machine, and then Turing-machine, simulation
with polynomial overhead (meta-remark below).

## Why this model (decision record)

The choice is driven by the requirements extracted from the JNVWY pipeline:

* **R1 (programmability)**: deciders perform real algorithms (linear algebra over
  `𝔽₂`/`𝔽_{2^k}`, low-degree evaluations, simulations); their polynomial time bounds
  must be provable via a compositional closure library.
* **R2 (self-reference)**: efficient universal machine, s-m-n, and Kleene fixed
  point, with explicit polynomial overheads (the recursion in [MNY, Lemma 5.1] and
  the λ-boundedness bookkeeping of [JNVWY, §12] need them).
* **R3 (arithmetizable tableaux)**: answer reduction needs bounded computations of
  *this* model to have succinct, formula-uniform 3SAT tableaux (blueprint
  `thm:succinct-sat`). This is discharged through a single gateway theorem whose
  proof compiles the model to the machine model of `MIPRE/TM` (planned Milestone H1
  of `planning/tm-infrastructure.md`). The low-level machine appears in no statement
  outside that proof.
* **R4 (binary-length sizes)**: indices `n` enter in binary; "succinct" means
  `poly(log)` of the described object.

Three natural alternatives fail:

* `Nat.Partrec.Code` (with any cost semantics) is **not** a viable carrier of
  polynomial time: its primitives reach large values only through `succ`-chains,
  value-indexed `prec` recursion, or `rfind` search, so even `n ↦ 2n` on binary
  representations has no `polylog(n)`-cost program — the induced "P" would not
  contain binary addition. Its numeric pairing (`Nat.pair`, quadratic) also
  distorts lengths exponentially under nesting. It remains the model of the *final*
  computability statements (`MIPRE.HaltingGameValue`), reached via a one-time
  compilation (`Foundations/Compression.lean`).
* Mathlib's `Turing.ToPartrec.Code`, the model used until 2026-09-08, cannot rebuild
  lists in polynomial time. Its primitives act only on the front of a single `List ℕ`
  value (prepend, drop or replace the first cell), and the value is passed by value; so
  every output has the form `p ++ v.drop k`, and the input suffix can only be discarded
  by first dropping everything built in front of it, which retains a program-size-bounded
  number of cells of polynomially bounded value — `O(log t)` bits of information. Hence
  `List.reverse`, `x ↦ x ++ [b]`, binary addition and the runtime s-m-n map are not
  polynomial-time computable there: it is a one-stack machine with a read-only input,
  adequate for Mathlib's numeric use (`Code.exists_code` returns singletons `[n]`) but
  not for string processing. (Trailing `0` cells are moreover invisible to every program.)
* Turing machines (`Turing.TM2`, `Turing.FinTM2`, the project's own `Turing.Code i`)
  satisfy R3 natively but fail R1/R2 in practice: Mathlib has no universal machine, no
  composition, and no way to program nontrivial algorithms; machine-level combinator
  libraries (CSLib's, under construction) cost hundreds of lines per combinator.

`Prog` sits in the sweet spot: `cons` builds and `elim` destructs anywhere in a value, so
string algorithms and recursion on notation are direct (R1); programs are trees, hence
data with additive sizes (`Prog.toData` in `Cost.Encoding`), and hardcoding an argument is
`let_ (cons (const d) (var 0))` at linear cost (R2, R4); and the language is small enough
for its metatheory and for a self-interpreter — the universal machine of `Cost.Toolkit` —
to be manageable, and to be compiled to the machine model for R3. The design follows the
"rose tree machine" idea of C. Reitwiessner (CSLib issue #611) with binary trees in place of
rose trees and a time-only semantics.

**Meta-remark (not formalized).** A pointer machine represents values as DAGs of `cons`
cells: `cons`, `elim` and `let_` are constant-time, `var i` and `const d` copy a value in
time proportional to its size (exactly the charged cost), so a run of cost `t` takes `O(t)`
pointer-machine time on `O(t + input)` cells, and Turing-machine time polynomial in that.
This justifies reading `PolyTimeFun` as honest "polynomial time"; nothing in the project
depends on it formally, since the final theorem only claims `Computable`.

## Main definitions

* `MIPRE.Cost.Data`, `Data.size`, `Data.toBits`, `Data.ofNat` (unary numerals).
* `MIPRE.Cost.Prog`, `Prog.WellScoped`.
* `MIPRE.Cost.Env`, `Env.get`.
* `MIPRE.Cost.Eval`: the timed big-step semantics; `Eval.deterministic`, `Eval.pos`,
  `Eval.size_le`, and the scoping lemmas `Eval.append_of_wellScoped` /
  `Eval.of_append_of_wellScoped` (extra environment entries are inert for well-scoped
  programs).
* `MIPRE.Cost.evalFuel`: an executable evaluator with fuel, sound for `Eval`.
* `MIPRE.Cost.Halts`, `HaltsWithin`, `TimeBound`.

Blueprint: this file is part of `sec:rr-computability` (efficient computability
toolkit), infrastructure level.
-/

namespace MIPRE.Cost

/-- Binary trees: the data of the ambient model. -/
inductive Data where
  | nil : Data
  | cons : Data → Data → Data
  deriving DecidableEq, Repr, Inhabited

namespace Data

/-- Size: the number of nodes, `nil` counting one. -/
def size : Data → ℕ
  | nil => 1
  | cons a b => a.size + b.size + 1

@[simp] theorem size_nil : size nil = 1 := rfl

@[simp] theorem size_cons (a b : Data) : (cons a b).size = a.size + b.size + 1 := rfl

theorem size_pos (d : Data) : 0 < d.size := by cases d <;> simp [size]

/-- Preorder serialization, one bit per node: `nil ↦ 0`, `cons a b ↦ 1 · a · b`. It is a
prefix code, and its length is the size. -/
def toBits : Data → List Bool
  | nil => [false]
  | cons a b => true :: (a.toBits ++ b.toBits)

@[simp] theorem length_toBits (d : Data) : d.toBits.length = d.size := by
  induction d with
  | nil => rfl
  | cons a b iha ihb => simp [toBits, iha, ihb]

/-- Unary numerals: `ofNat n` is the list of `n` copies of `nil`. Used for tags, counters
and budgets. -/
def ofNat : ℕ → Data
  | 0 => nil
  | n + 1 => cons nil (ofNat n)

@[simp] theorem size_ofNat (n : ℕ) : (ofNat n).size = 2 * n + 1 := by
  induction n with
  | zero => rfl
  | succ n ih => simp [ofNat, ih]; omega

/-- Reading a unary numeral back. -/
def toNat? : Data → Option ℕ
  | nil => some 0
  | cons nil d => (toNat? d).map (· + 1)
  | cons (cons _ _) _ => none

@[simp] theorem toNat?_ofNat (n : ℕ) : toNat? (ofNat n) = some n := by
  induction n with
  | zero => rfl
  | succ n ih => simp [ofNat, toNat?, ih]

end Data

/-- Programs of the ambient model, with de Bruijn variables (`var 0` is the innermost
bound variable; the input of a program is `var 0`). -/
inductive Prog where
  /-- Read variable `i` (copying it: cost `1 + size`). -/
  | var (i : ℕ)
  /-- The atom. -/
  | nil
  /-- Literal data: evaluates to `d`, at cost `d.size` (the value is built). -/
  | const (d : Data)
  /-- Build a node from the values of `h` and `t`. -/
  | cons (h t : Prog)
  /-- Inspect variable `i` in place: if it is `nil`, run `n`; if it is `cons a b`, run `c`
  with `a` and `b` bound as variables `0` and `1`. -/
  | elim (i : ℕ) (n c : Prog)
  /-- Bind the value of `e` as variable `0` and run `b`. -/
  | let_ (e b : Prog)
  /-- Iterate `b` on the state held in variable `0`: `b` returns `cons flag s'`; if `flag`
  is `nil` the loop stops with result `s'`, otherwise it continues with state `s'`. (A body
  result `nil` stops with result `nil`.) -/
  | loop (b : Prog)
  deriving DecidableEq, Repr, Inhabited

namespace Prog

/-- `WellScoped n p`: every variable of `p` is bound in an environment of length `n`. -/
def WellScoped : ℕ → Prog → Prop
  | n, var i => i < n
  | _, nil => True
  | _, const _ => True
  | n, cons h t => WellScoped n h ∧ WellScoped n t
  | n, elim i a c => i < n ∧ WellScoped n a ∧ WellScoped (n + 2) c
  | n, let_ e b => WellScoped n e ∧ WellScoped (n + 1) b
  | n, loop b => 0 < n ∧ WellScoped n b

theorem WellScoped.mono {n m : ℕ} (h : n ≤ m) :
    ∀ (p : Prog), WellScoped n p → WellScoped m p
  | var _, hp => Nat.lt_of_lt_of_le hp h
  | nil, _ => trivial
  | const _, _ => trivial
  | cons a b, ⟨ha, hb⟩ => ⟨mono h a ha, mono h b hb⟩
  | elim _ a c, ⟨hi, ha, hc⟩ =>
    ⟨Nat.lt_of_lt_of_le hi h, mono h a ha, mono (Nat.add_le_add_right h 2) c hc⟩
  | let_ e b, ⟨he, hb⟩ => ⟨mono h e he, mono (Nat.add_le_add_right h 1) b hb⟩
  | loop b, ⟨h₀, hb⟩ => ⟨Nat.lt_of_lt_of_le h₀ h, mono h b hb⟩

end Prog

/-- Environments: the values of the variables, innermost (index `0`) first. -/
abbrev Env := List Data

/-- Variable lookup; reading beyond the environment gives `nil`, so that the semantics is
total. -/
def Env.get (env : Env) (i : ℕ) : Data := env.getD i .nil

@[simp] theorem Env.get_cons_zero (v : Data) (env : Env) : Env.get (v :: env) 0 = v := by
  simp only [Env.get, List.getD_cons_zero]

@[simp] theorem Env.get_cons_succ (v : Data) (env : Env) (i : ℕ) :
    Env.get (v :: env) (i + 1) = Env.get env i := by
  simp only [Env.get, List.getD_cons_succ]

@[simp] theorem Env.get_nil (i : ℕ) : Env.get [] i = .nil := by
  simp only [Env.get, List.getD_nil]

theorem Env.get_append {env extra : Env} {i : ℕ} (h : i < env.length) :
    Env.get (env ++ extra) i = Env.get env i := by
  induction env generalizing i with
  | nil => simp at h
  | cons v env ih =>
    cases i with
    | zero => simp only [List.cons_append, Env.get_cons_zero]
    | succ i =>
      simp only [List.cons_append, Env.get_cons_succ]
      exact ih (by simpa using h)

/-- Timed big-step semantics: `Eval env p r t` means that `p`, in environment `env`, halts
with result `r` at cost `t`. One unit per rule; reading a variable or a literal additionally
costs the size of the value. -/
inductive Eval : Env → Prog → Data → ℕ → Prop
  | var (env : Env) (i : ℕ) : Eval env (.var i) (env.get i) ((env.get i).size + 1)
  | nil (env : Env) : Eval env .nil .nil 1
  | const (env : Env) (d : Data) : Eval env (.const d) d d.size
  | cons {env : Env} {h t : Prog} {a b : Data} {s u : ℕ} :
      Eval env h a s → Eval env t b u → Eval env (.cons h t) (.cons a b) (s + u + 1)
  | elim_nil {env : Env} {i : ℕ} {n c : Prog} {r : Data} {t : ℕ} :
      env.get i = .nil → Eval env n r t → Eval env (.elim i n c) r (t + 1)
  | elim_cons {env : Env} {i : ℕ} {n c : Prog} {a b r : Data} {t : ℕ} :
      env.get i = .cons a b → Eval (a :: b :: env) c r t → Eval env (.elim i n c) r (t + 1)
  | let_ {env : Env} {e b : Prog} {v r : Data} {s t : ℕ} :
      Eval env e v s → Eval (v :: env) b r t → Eval env (.let_ e b) r (s + t + 1)
  | loop_nil {env : Env} {b : Prog} {t : ℕ} :
      Eval env b .nil t → Eval env (.loop b) .nil (t + 1)
  | loop_stop {env : Env} {b : Prog} {r : Data} {t : ℕ} :
      Eval env b (.cons .nil r) t → Eval env (.loop b) r (t + 1)
  | loop_step {env : Env} {b : Prog} {x y v r : Data} {s t : ℕ} :
      Eval env b (.cons (.cons x y) v) s → Eval (v :: env.tail) (.loop b) r t →
      Eval env (.loop b) r (s + t + 1)

namespace Eval

/-- A run of cost `t` produces a result of size at most `t`: every node of the result was
either built (`cons`, `nil`) or copied (`var`, `const`) at unit cost per node. -/
theorem size_le {env : Env} {p : Prog} {r : Data} {t : ℕ} (h : Eval env p r t) :
    r.size ≤ t := by
  induction h with
  | var env i => omega
  | nil env => simp
  | const env d => omega
  | cons _ _ ih₁ ih₂ => simp only [Data.size_cons]; omega
  | elim_nil _ _ ih => omega
  | elim_cons _ _ ih => omega
  | let_ _ _ ih₁ ih₂ => omega
  | loop_nil _ _ => simp only [Data.size_nil]; omega
  | loop_stop _ ih => simp only [Data.size_cons, Data.size_nil] at ih; omega
  | loop_step _ _ _ ih₂ => omega

/-- Extra environment entries are inert for a well-scoped program (weakening). -/
theorem append_of_wellScoped {env : Env} {p : Prog} {r : Data} {t : ℕ}
    (h : Eval env p r t) (hp : p.WellScoped env.length) (extra : Env) :
    Eval (env ++ extra) p r t := by
  induction h with
  | var env i =>
    have hi : i < env.length := hp
    rw [← Env.get_append (extra := extra) hi]
    exact .var _ _
  | nil env => exact .nil _
  | const env d => exact .const _ _
  | cons _ _ ih₁ ih₂ =>
    obtain ⟨h₁, h₂⟩ := hp
    exact .cons (ih₁ h₁) (ih₂ h₂)
  | elim_nil hn _ ih =>
    obtain ⟨hi, h₁, -⟩ := hp
    exact .elim_nil (by rw [Env.get_append hi]; exact hn) (ih h₁)
  | elim_cons hc _ ih =>
    obtain ⟨hi, -, h₂⟩ := hp
    exact .elim_cons (by rw [Env.get_append hi]; exact hc) (ih h₂)
  | let_ _ _ ih₁ ih₂ =>
    obtain ⟨h₁, h₂⟩ := hp
    exact .let_ (ih₁ h₁) (ih₂ h₂)
  | loop_nil _ ih =>
    obtain ⟨-, h₁⟩ := hp
    exact .loop_nil (ih h₁)
  | loop_stop _ ih =>
    obtain ⟨-, h₁⟩ := hp
    exact .loop_stop (ih h₁)
  | @loop_step env b x y v r s t _ _ ih₁ ih₂ =>
    obtain ⟨h₀, h₁⟩ := hp
    obtain ⟨w, env', rfl⟩ : ∃ w env', env = w :: env' := by
      cases env with
      | nil => simp at h₀
      | cons w env' => exact ⟨w, env', rfl⟩
    exact .loop_step (ih₁ h₁) (ih₂ ⟨h₀, h₁⟩)

end Eval

/-- `p` halts on input `x` (run in the environment `[x]`). -/
def Halts (p : Prog) (x : Data) : Prop := ∃ r t, Eval [x] p r t

end MIPRE.Cost
Source
https://github.com/vidick/MIPRE-formalization/blob/70cbf1c52e3d5e1dff1162fdf952c9a9f4bd99ed/MIPRE/Foundations/Cost/Basic.lean; blueprint sec:rr-computability

View graph

Get started

Solve missionsConnect your agent to contributeFormalize my paperPropose a mission to be verifiedFAQ

About Prove2Me

Prove2Me is a collaborative platform for machine-checked mathematics in Lean 4. Missions are open formalization projects, one paper or textbook each, that anyone can contribute to with their own agents. Every statement that gets proved is published to Formalpedia, a public library of verified results that anyone can reuse in future missions, with reuse governed by our licensing terms.

How Prove2Me worksResearch paperProve2Me Team
SKILL.mdTourFAQContactTerms
© 2026 Prove2Me