Contracts, selections and proofs
How Pythonic and Lean views present the same stored logic, how proof-optional contract selections let you ship code on day one, and how theorems compose across modules.
If formal verification required proving every single theorem before running "hello world", nobody would ship software with it. Early in a feature, you are still discovering the right data structures and API boundaries; locking everything down with proofs too early would mean throwing work away whenever requirements shift.
Lema is built around interface-first, proof-optional development. You can sketch data types and implementations, compile and run your application on the Lema VM immediately, and layer mathematical contracts onto critical components as your design stabilizes.
Two views over one stored specification
Every contract and function in Lema lives in the store as canonical typed objects, and can be read in two complementary syntaxes:
- Pythonic Lema syntax renders only the clean specification (
def,contract,law,requires,ensures,forall,select), omitting proof tactics so a human engineer can review what is promised in seconds. - Lean syntax exposes the full implementation and proof terms (
theorem ... := ...) that an AI coding agent writes and the Lean 4.34.1 kernel checks.
Toggle between the Pythonic, Lean, and Explanation tabs below to compare the same specification and selection:
Pythonic
def advance(n: Nat) -> Nat:
n + 1
def Advances(f: Nat -> Nat) -> Prop:
forall n: Nat :: f(n) > n
select Advances(advance)Lean
These declarations express the same implementation and promise. Selection is a Lema codebase operation; the final comment names its target, without supplying a proof.
def advance (n : Nat) : Nat := n + 1
def Advances (f : Nat → Nat) : Prop :=
∀ n : Nat, f n > n
-- Selected proposition: Advances advanceExplanation
For every nonnegative integer n, the selected function must return a number greater than n. The implementation advance adds one.
Advances describes the promise independently of the implementation. Selecting Advances(advance) records an open obligation about that exact function. It becomes checked only when a matching proof is accepted.
The promise requires an increase, but does not require an increase of exactly one. A function that adds two would satisfy it too.
Because both views are rendered directly from the store’s canonical AST (Code stored by identity), the Pythonic view and the Lean view can never drift out of sync like comments or separate interface files do.
Separating operational interfaces from behavioral contracts
Suppose you are building an escrow service that loads and saves user accounts. If you bundled proof fields directly into your storage record type on day one, you could not instantiate an in-memory mock or disk engine until every proof was finished.
Instead, Lema separates operational interfaces (data records holding functions) from behavioral contracts (contract blocks stating the laws those functions must obey):
Pythonic
You can publish this contract structure and select it for an implementation on day one without proving the laws first. Your implementation compiles and runs on the VM while the selection is tracked as open.
contract LawfulEscrowStorage(ops: EscrowStorage):
law load_after_save(db: StoreHandle, u: Nat, acc: Account):
ops.load_account(ops.save_account(db, u, acc), u) == acc
law load_other_unchanged(db: StoreHandle, u1: Nat, u2: Nat, acc: Account):
requires u1 != u2
ensures ops.load_account(ops.save_account(db, u1, acc), u2) == ops.load_account(db, u2)
select LawfulEscrowStorage(MemoryStorage)Lean
structure LawfulEscrowStorage (ops : EscrowStorage) : Prop where
load_after_save : ∀ (db : StoreHandle) (u : Nat) (acc : Account),
ops.load_account (ops.save_account db u acc) u = acc
load_other_unchanged : ∀ (db : StoreHandle) (u1 u2 : Nat) (acc : Account),
u1 ≠ u2 →
ops.load_account (ops.save_account db u1 acc) u2 = ops.load_account db u2
-- Selected contract record: LawfulEscrowStorage MemoryStorageExplanation
A key-value or account store needs two complementary laws: reading back the key you just saved returns the new account (load_after_save), and saving one user’s account never clobbers another user’s account (load_other_unchanged).
Separating the operational interface (EscrowStorage) from the proposition-valued contract (LawfulEscrowStorage) lets you write, build, and run MemoryStorage immediately, while recording LawfulEscrowStorage(MemoryStorage) as an open contract selection in the store.
Later, an AI coding agent can prove each law in a separate module. Proving one law records partial progress (1/2 laws proved, status still open); proving the whole contract marks the selection checked and unlocks generic conservation theorems.
Selecting a contract (select LawfulEscrowStorage(MemoryStorage)) creates an explicit, trackable obligation in the store that moves through three clear states (Checked, tested and assumed):
| Selection status | What it means | Can the application build and run? |
|---|---|---|
open | The contract target is typechecked and pinned to MemoryStorage, with zero or some laws proved so far (for example, 1/2 laws proved). | Yes. lema test and lema run work normally during development. |
checked | An accepted theorem proves every law in the contract for that exact MemoryStorage implementation. | Yes, and protected branch policies can require checked before merge or release. |
waived | An authorized project actor recorded an explicit reason to defer proof on a revision. Never displayed as checked. | Yes, with the waiver permanently visible in lema diff and audit pages. |
Notice one subtle safeguard: when an agent submits a theorem to mark LawfulEscrowStorage(MemoryStorage) as checked, the store checks both that the theorem proves the exact contract statement and that it cites the exact MemoryStorage implementation ID in your project, preventing an agent from accidentally proving the contract about a toy stub with the same name.
Writing tight contracts and composing proofs
What separates a weak contract from a strong one, and how do proofs scale across larger modules?
Closing loopholes with complementary laws
Consider a sorting function sortBy(le, l). If your contract only stated “the output list is in sorted order” (sortBy_sorted), a buggy implementation that threw away its input and returned the empty list [] would pass, because an empty list is trivially sorted.
Pairing sortBy_sorted with a second law, sortBy_perm (“the output is an exact permutation of the input”), closes that loophole completely:
Pythonic
Both views below are rendered from the same accepted statement objects in the store. A sorting contract needs both laws: returning an empty list would be in order, so the second law requires every original element and its count to survive.
law sortBy_sorted(le: alpha -> alpha -> Bool, l: List(alpha)):
requires forall a: alpha, b: alpha, c: alpha :: (le(a, b) == true and le(b, c) == true) -> le(a, c) == true
requires forall a: alpha, b: alpha :: le(a, b) == true or le(b, a) == true
ensures Pairwise(fn(a: alpha, b: alpha) -> le(a, b) == true, sortBy(le, l))
law sortBy_perm(le: alpha -> alpha -> Bool, l: List(alpha)):
Perm(sortBy(le, l), l)Lean
theorem sortBy_sorted {α : Type} (le : α → α → Bool)
(trans : ∀ a b c, le a b = true → le b c = true → le a c = true)
(total : ∀ a b, le a b = true ∨ le b a = true) :
∀ l : List α, (sortBy le l).Pairwise (fun a b => le a b = true)
theorem sortBy_perm {α : Type} (le : α → α → Bool) :
∀ l : List α, (sortBy le l).Perm lExplanation
The first law (sortBy_sorted) promises that for any comparison function le that is transitive and total, every item in sortBy(le, l) is ordered before or equal to the items that follow it.
The second law (sortBy_perm) closes the loophole where a buggy implementation simply drops elements or returns an empty list: it promises that the output list is an exact permutation of the input list, preserving every element and its multiplicity.
Because both laws live in the content-addressed store as accepted statement objects, callers such as canonical HTTP header sorting depend only on these statement hashes, never on the internal sorting implementation or proof steps.
Sample input
[4, 1, 3, 1]Output
[1, 1, 3, 4]A unit test checks this single list. Together, sortBy_sorted and sortBy_perm hold across every list of every length: the output is ordered and preserves every element and duplicate count.
Proofs compose like function calls
In a test-only codebase, unit-testing sortBy does not prove anything mathematically about higher-level HTTP signing code that calls sortBy. In Lema, theorems call earlier theorems just like functions call helper functions.
For example, when canonical URL query encoding formats key-value pairs (queryPairs) by calling sortBy with lexicographical byte comparison pairLe, proving that queryPairs always emits sorted parameters takes a single line:
theorem queryPairs_sorted (qs : List (List UInt8 × List UInt8)) :
(queryPairs qs).Pairwise (fun p q => pairLe p q = true) :=
sortBy_sorted pairLe pairLe_trans pairLe_total _Look at what queryPairs_sorted depends on: only the statement of sortBy_sorted, plus proofs that pairLe is transitive and total. It never unfolds how sortBy works internally (insertBy vs. merge sort) and never inspects how sortBy_sorted was proved. Next, Code stored by identity shows how the store makes that decoupling mechanical.
Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility