Skip to content

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:

  1. 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.
  2. 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:

Program anatomy Five building blocks and two independent proofs
Layer -1 · Core
1 · Pure foundation Total · No ambient I/O

Pure data, functions, and laws

structure · inductive · def · law
2 · Effect signature Dependent ability

Command vocabulary (C and R)

cmd : C -> R cmd : Type
3 · Caller tree

Prog C R A

Finite free-monad decision tree of .step requests and reply callbacks ending at .done.

4 · Protocol rulebook Model state S

Contract C R S

  • pre(s, c) Legal to issue?
  • next(s, c, r) Next model state
  • post(s, c, r) Reply promise
5 · Concrete engine Private memory M

Impl C R M

Stateful effect handler computing (reply, nextMemory), or Prog.interp lowering to host I/O.

Proof A · Caller side: Safe K Q p s0 Obeys pre, hits Q
Proof B · Engine side: Implements K h Inv Honors post & Inv
5b · Host lowering (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 as Nat, UInt64, Bool, String, ByteArray, List, or Option.
  • 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 (Option or Except).
  • 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:

Pure definitions and laws (Pythonic view)
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) == amount

Inside 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:

A two-command vocabulary (Lean syntax)
-- 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 Nat can issue zero external commands; it is guaranteed pure.
  • Prog KvCmd kvReply Nat can 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:

  1. done(value): Stop immediately and return value : A without issuing any more commands.
  2. step(cmd, nextFn): Issue one command cmd : C, pause for the reply r : R cmd, and pass r into the callback nextFn(r), which returns the rest of the Prog.

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:

Decision tree · Prog getOrInit(key, defaultVal) : Prog KvCmd kvReply Nat
Free monad · Finite paths
Step 1 · Yield command KvCmd.get
.step (.get key) (fun reply => ...)

Pauses for reply : Option Nat from the handler.

Branch A · Key found .done leaf
.done existing

Stops immediately and returns existing : Nat without issuing a write.

Branch B · Key missing (Step 2) KvCmd.put
.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:

Constructing getOrInit as a Prog tree
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 defaultVal

Two practical questions naturally come up when programmers first see Prog:

  • How do you sequence several programs without deep nesting? Prog is a finite free monad, and Core provides Prog.bind p f (“run p until it reaches .done a, then continue with f a”), the same monadic sequencing operation that backs do-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 N requests 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.

Reading the fields of a contract K
K.pre(s, c)
K.next(s, c, reply)
K.post(s, c, reply)

Lean

Lean syntax
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 → Prop

Explanation

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 command c legal to send in model state s? (For example, close requires isOpen = true so double-closing is forbidden.)
  • next(s, c, r) (state transition): Given prior model state s, command c, and reply r, what is the new model state?
  • post(s, c, r) (engine’s promise): What property does the engine promise about reply r? (For example, get k promises r = 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₂:

Effect handler · Prog.interp Translating one application command down to 4 KiB disk sectors
C1 -> C2 -> Tag 0x03
Application vocabulary · C1 KvCmd
.step (.put "user:7" 42) ...

High-level caller asks to store one key-value entry.

Sub-step 1 · BlockCmd 4 KiB read
readBlock 0

Reads the active epoch superblock and sector bitmap.

Sub-step 2 · BlockCmd CoW write
writeBlock 9 frame

Writes updated tree into a free shadow sector.

Sub-step 3 · BlockCmd Barrier
flush

Persists sectors before flipping the alternating superblock.

Host capability boundary (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):

TagFamilyOperationsHost boundary role
0x01tcpconnect, accept, send, recv, closeRaw TCP byte streams
0x02udpsendTo, recvFromBounded UDP datagrams
0x03blockinfo, readBlock, writeBlock, flushFixed 4096-byte disk sectors and barriers
0x04randombytesCryptographic randomness from the OS
0x05clockutcMs, monoNsUTC wall-clock and monotonic timestamps
0x06secretgetRole-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 Open or Close command in your protocol vocabulary translates via interp into TcpCmd.connect and TcpCmd.close binary 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 or Core.

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:

  1. 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.

  2. 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.

  3. 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:

  1. Against any lawful future host (safe_runs): Even before picking a concrete engine, safe_runs guarantees that for every execution trace whose environment honors K.post, a Safe program reaches Q.
  2. Against a proved Impl (sound): Once you pair Proof A (Safe) and Proof B (Implements) with compatible starting states (Inv s₀ m₀), sound guarantees in one line that run h p m₀ returns a final value and state satisfying Q while 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

Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility