Anatomy of a Lema program
A plain-English tour of the five building blocks and two proofs inside a Lema program, from pure data and command vocabularies to Prog decision trees, Contracts, Impls, and host capabilities.
In imperative languages like Python, Go, or TypeScript, any function can mix calculation with ambient side effects: reading the clock, opening a network socket, mutating a global cache, or raising an exception. That makes code quick to sketch, and very hard to verify mathematically. If calling calculate_discount(order) might touch disk or fail on a timeout, you cannot prove an algebraic equation about calculate_discount on its own.
Purely functional and effect-tracked languages have separated pure calculation from external effects for decades: Haskell isolates effects behind monads such as IO, while Unison and Koka track interactions through typed algebraic effects (abilities) and handlers.
Lema sits directly in that purely functional, algebraic-effects tradition, adapted for formal verification:
- Total pure functions (as in dependently typed languages like Lean, Idris, and Rocq): pure functions always finish, handle every input case, never fail with untracked exceptions, and never touch the outside world.
- Algebraic effect trees (
Prog) governed by protocol contracts (Contract): external interaction (storage, sockets, clocks, actors, or concurrency) is written as an explicit free-monad decision tree of commands and replies (closely related to finite Interaction Trees) and checked against a state-machine rulebook (Contract).
Because an effectful program is an ordinary data structure describing what commands it issues and how it handles every reply, Lema can prove behavioral laws about stateful, networked systems using ordinary logic (Where the ideas come from).
High-level picture: five building blocks and two proofs
Before looking at each piece individually, see how a complete Lema program fits together end to end:
Pure data, functions, and laws
structure · inductive · def · law Command vocabulary (C and R)
cmd : C -> R cmd : Type Prog C R A
Finite free-monad decision tree of .step requests and reply callbacks ending at .done.
Contract C R S
pre(s, c)Legal to issue?next(s, c, r)Next model statepost(s, c, r)Reply promise
Impl C R M
Stateful effect handler computing (reply, nextMemory), or Prog.interp lowering to host I/O.
Safe K Q p s0
Obeys pre, hits Q
Implements K h Inv
Honors post & Inv
Prog.interp + sound): translates commands down to tcp, udp, block, random, clock, secret Ring.call · Flat binary frames Caller proof Safe and engine proof Implements meet only at the shared Contract, so either side can change without re-proving the other.
Every interactive subsystem is built from those five building blocks plus two independent proofs:
- 1. Pure data, functions, and laws
- Ordinary records, enums, and total functions (parseHeader, computeFee) that do deterministic work in memory and can be backed by pure mathematical laws.
- 2. Command vocabulary (C and R)
- A menu of requests C (such as Get key or Put key val) paired with a reply-type lookup R telling the typechecker what type of answer comes back for each request.
- 3. Caller program (Prog C R A)
- A finite decision tree that uses pure functions to decide which command from C to issue next, receives the reply, and finishes with a final value of type A.
- 4. Protocol rulebook (Contract C R S)
- The specification sitting between caller and engine. Using a conceptual model state S, it defines when a call is legal (pre), how the model state updates (next), and what the reply promises (post).
- 5. Concrete engine (Impl C R M) or interpreter (interp)
- Code that fulfills commands in C, either directly in memory (an Impl with private state M, great for tests and in-memory state machines) or by translating each command into lower-level commands via interp down to the host OS.
- 6. Two independent proofs (Safe and Implements)
- Caller proof Safe checks the Prog against the Contract without looking inside the engine. Engine proof Implements checks the Impl (or interpreter) against the Contract without knowing which callers exist.
1. Pure data, functions, and laws
Most of any real application (parsing requests, validating business rules, formatting responses, computing cryptographic digests) does not need to talk to the outside world at all. In Lema, this foundation is built out of three pieces:
- Data types: Records (
structure, like a Python@dataclass) and tagged unions (inductive, like a TypeScript discriminated union) holding immutable values such asNat,UInt64,Bool,String,ByteArray,List, orOption. - Pure functions (
def): Deterministic functions from inputs to outputs. Every pure function in Lema is total: it handles every case of its input, cannot loop forever, cannot read global state, and cannot throw an untracked runtime exception. When an operation can fail (such as parsing malformed JSON), that possibility appears explicitly in its return type (OptionorExcept). - Pure laws (
law/theorem): Universal guarantees proved once across all valid inputs rather than a handful of sample test cases.
In Pythonic Lema syntax, pure definitions and laws read like typed functions with explicit requires and ensures clauses:
def clampFee(amount: Nat, cap: Nat) -> Nat:
if amount <= cap then amount else cap
law clampFee_at_most_cap(amount: Nat, cap: Nat):
clampFee(amount, cap) <= cap
law clampFee_preserves_small(amount: Nat, cap: Nat):
requires amount <= cap
ensures clampFee(amount, cap) == amountInside a Prog step, all branching, parsing, and formatting is done by pure functions like clampFee, and their proved laws plug straight into your caller and engine proofs.
2. Command vocabulary (C and R)
Before writing an interactive program, you list which commands it is allowed to ask for (C) and what type of reply comes back for each command (R). In effect-system terminology, (C, R) is a dependent algebraic effect signature (playing the same role as an ability interface in Unison or an effect signature in Koka, generalized so the reply type can depend on the command value).
Suppose a service needs a tiny key-value store with String keys and Nat values:
-- 1. The commands a caller can issue:
inductive KvCmd where
| get (key : String)
| put (key : String) (val : Nat)
-- 2. The reply type returned for each specific command:
def kvReply : KvCmd → Type
| .get _ => Option Nat -- get returns either `some n` or `none`
| .put _ _ => Unit -- put returns an empty acknowledgment `()`Notice what kvReply gives us: the return type depends on the exact command value. Issuing .get "visits" hands your next step an Option Nat; issuing .put "visits" 1 hands your next step a Unit. An engine cannot accidentally answer a get with (), and a caller cannot misread a put reply as a number, because those mismatched combinations do not typecheck.
Because C is an explicit type parameter on your program, capability security is visible in the type signature:
Prog Empty emptyReply Natcan issue zero external commands; it is guaranteed pure.Prog KvCmd kvReply Natcan only read and write keys; it has no way to express opening a TCP socket or reading a secret.
3. Programs as decision trees (Prog)
Once a vocabulary (C, R) is chosen, an interactive caller program has type Prog C R A (“a program using command set C with reply types R that finishes with a value of type A”).
Every Prog is built from just two shapes:
done(value): Stop immediately and returnvalue : Awithout issuing any more commands.step(cmd, nextFn): Issue one commandcmd : C, pause for the replyr : R cmd, and passrinto the callbacknextFn(r), which returns the rest of theProg.
Consider a tiny helper getOrInit(key, defaultVal) that looks up key; if found, it returns the existing number, and if missing (none), it writes defaultVal and returns defaultVal:
.step (.get key) (fun reply => ...)
Pauses for reply : Option Nat from the handler.
.done existing Stops immediately and returns existing : Nat without issuing a write.
.step (.put key defaultVal) (fun () => ...)
Writes defaultVal, receives reply = () : Unit, then finishes:
.done defaultVal
returns defaultVal : Nat
Every external request is a .step node whose continuation branches on the typed reply until reaching a .done return leaf.
In Lean syntax, that tree is constructed directly from .step and .done:
def getOrInit (key : String) (defaultVal : Nat) : Prog KvCmd kvReply Nat :=
.step (.get key) fun reply =>
match reply with
| some existing =>
.done existing
| none =>
.step (.put key defaultVal) fun () =>
.done defaultValTwo practical questions naturally come up when programmers first see Prog:
- How do you sequence several programs without deep nesting?
Progis a finite free monad, andCoreprovidesProg.bind p f(“runpuntil it reaches.done a, then continue withf a”), the same monadic sequencing operation that backsdo-notation in Haskell and Lean. - How do servers and retry loops work if every tree path is finite? Every recursive function in Lema takes an explicit fuel or structural bound (such as handling up to
Nrequests in an epoch, or an outer supervisor loop invoking one proved epoch step at a time). No single step can silently hang forever (Fueled).
4. Contracts and implementations (Contract and Impl)
A Prog tree on its own is inert data. To reason about it and run it, Lema separates the specification of the world (Contract) from the implementation of the world (Impl).
Contract C R S: the protocol rulebook
A Contract specifies how commands behave in terms of an idealized conceptual model state S (for example, modeling a complex disk-backed B-tree as a mathematical lookup function String → Option Nat, or modeling a file handle as a Bool tracking whether the handle is open). It has three fields:
Pythonic
For an existing contract K, these expressions read its command condition, next state and reply condition. The record also contains a state transition function, so its declaration uses Lean rather than a proposition-only contract block.
K.pre(s, c)
K.next(s, c, reply)
K.post(s, c, reply)Lean
structure Contract (C : Type) (R : C → Type) (S : Type) where
pre : S → C → Prop
next : (s : S) → (c : C) → R c → S
post : S → (c : C) → R c → PropExplanation
A protocol contract describes which commands are permitted, which replies are promised, and how the protocol state changes after a reply.
pre checks whether command c is permitted in state s. next computes the next state from s, c and its reply. post states what that reply must satisfy. The reply’s type R c depends on the command.
The record defines the rules. Separate safety and implementation proofs establish that a program and its implementation follow those rules.
pre(s, c)(caller’s responsibility): Is commandclegal to send in model states? (For example,closerequiresisOpen = trueso double-closing is forbidden.)next(s, c, r)(state transition): Given prior model states, commandc, and replyr, what is the new model state?post(s, c, r)(engine’s promise): What property does the engine promise about replyr? (For example,get kpromisesr = s k.)
Impl C R M: a concrete state machine
An Impl is an in-memory effect handler with private internal memory M (such as an array buffer, ring index, or hash table). For each command c in memory state m : M, Impl.step m c deterministically computes (reply, nextMemory).
Keeping the contract’s conceptual state S separate from the engine’s private memory M is what makes modular verification practical: callers write simple proofs against clean mathematical state S, while an engine author is free to pack bits, maintain caches, or reorganize M inside Impl.
5. Interpreting layers (interp) down to the host
An in-memory Impl is great for state machines and deterministic unit tests, yet a production database or HTTPS service has to talk to real disks and network sockets rather than living purely in RAM.
Lema bridges high-level application commands down to the operating system using Prog.interp: a layer-to-layer effect handler (playing the same role as handling a Unison ability or Koka effect in terms of lower-level effects) that replaces every high-level command in C₁ with a sub-program of lower-level commands in C₂:
.step (.put "user:7" 42) ...
High-level caller asks to store one key-value entry.
readBlock 0 Reads the active epoch superblock and sector bitmap.
writeBlock 9 frame Writes updated tree into a free shadow sector.
flush Persists sectors before flipping the alternating superblock.
Ring.call): self-contained LC\x02 binary frames
Tag 0x03 block -> OS sector I/O & fsync Prog.interp expands each high-level command into a proved lower-level sub-program before crossing Ring.call as flat binary frames.
For standard machines (Linux and macOS), that translation chain bottoms out at six primitive host capability families (Capabilities and the host boundary):
| Tag | Family | Operations | Host boundary role |
|---|---|---|---|
0x01 | tcp | connect, accept, send, recv, close | Raw TCP byte streams |
0x02 | udp | sendTo, recvFrom | Bounded UDP datagrams |
0x03 | block | info, readBlock, writeBlock, flush | Fixed 4096-byte disk sectors and barriers |
0x04 | random | bytes | Cryptographic randomness from the OS |
0x05 | clock | utcMs, monoNs | UTC wall-clock and monotonic timestamps |
0x06 | secret | get | Role-gated secret lookups inside verified sub-runs |
Notice why the core language (Prog, Contract, interp) does not hardcode those six tags into the compiler:
- Standard hosts: A high-level
OpenorClosecommand in your protocol vocabulary translates viainterpintoTcpCmd.connectandTcpCmd.closebinary frames executed across the host’s synchronous request/reply boundary (Ring.call). - New hardware targets: Because
(C, R)is an ordinary type parameter, targeting GPUs, DMA accelerators, embedded microcontrollers, or non-Von-Neumann dataflow hardware means defining a new capability vocabulary and host runner without changing a single rule in the Lean kernel orCore.
6. Checking callers and engines (Safe and Implements)
How do we know a caller and an engine actually obey their shared Contract? Lema checks each side independently:
-
Proof A · Caller side
Safe K Q p s₀
Walks every branch of caller program p starting at model state s₀. Proves every step satisfies K.pre, and assuming any reply obeying K.post, reaches final postcondition Q.
-
Proof B · Engine side
Implements K h Inv
Links model state S to private memory M via invariant Inv s m. Proves that whenever K.pre holds, engine h returns a reply obeying K.post and preserves Inv at K.next.
-
Master theorem · Combined run
sound (Core)
Plugging any Safe caller into any Implements engine (or safe_interp translator) guarantees the run finishes with Q(result, finalState) without ever re-walking the tree.
Two composition theorems do the heavy lifting here:
- Against any lawful future host (
safe_runs): Even before picking a concrete engine,safe_runsguarantees that for every execution trace whose environment honorsK.post, aSafeprogram reachesQ. - Against a proved
Impl(sound): Once you pair Proof A (Safe) and Proof B (Implements) with compatible starting states (Inv s₀ m₀),soundguarantees in one line thatrun h p m₀returns a final value and state satisfyingQwhile preserving the engine’s private memory invariant.
Better yet, both Safe and Implements live purely in Lean’s logical Prop universe. Once the store verifies them during admission, the compiler erases every proof term completely (Arg::Erased), leaving only compact, direct bytecode for the Lema VM (The compiler and VM).
Where to go next
- Read Types and invariants (
#3) to see how pure types carry preconditions and erase proofs at zero runtime cost. - Read Contracts, selections and proofs (
#4) to see how day-to-day proof-optional development (open,checked,waived) works in a project. - Jump ahead to Evolving programs, handles and concurrency (
#6) to see howProgscales to upgrades (Replaces,Refines,link), linear handles, and concurrent actors.
Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility