Program core
The module Core, in namespace Lema. Programs, contracts, traces and implementations, the two tiers of replacement, refinement, contract status, how programs run and related work.
The program core is the module Core, in the namespace Lema. It defines
programs as typed descriptions of effects, contracts over their commands
and implementations of those commands, and it proves the theorems that
connect them. Many modules receive its objects by identity, among them
Fueled, Handles, Protected, Replace, Channels, Sessions,
Actor and CallGraph, and capability modules such as Capability,
Lift and BlockStore. The command families, such as Cap.TaskCmd,
Cap.ActorCmd and Cap.SessionCmd, combined by Cap.Plus, are command
types for its programs. An application’s root has the type
Nat → ByteArray → Prog C R ByteArray.
The module is written in restricted Lean, the language of its data types,
definitions and proofs. Contracts and laws are also read and written in the
contract syntax, the language of .lema files. The statement page of
Core shows each theorem as a law in that syntax’s Lean form, and each
definition by its type. It shows a text only when that text re-derives the
accepted object.
Programs, contracts and implementations
- Prog C R A
- A program over commands C, where command c has replies of type R c. It either returns a value of type A (ret) or issues a command and continues with a function of the reply (call).
- Contract C R S
- A protocol over states S. Its field pre says when a command may run, next says how a reply moves the state, and post says what the reply promises.
- Impl C R M
- An implementation: one step function from a machine state and a command to a reply and the next machine state. It is a total mathematical model, not a claim about blocking operating-system input and output.
- Safe K Q p s
- Protocol typing. From state s, the next command p issues is permitted by pre, and after every reply that keeps the promise the rest of p is safe from the next state. When p returns a value, Q holds of the state and the value.
- Implements K h Inv
- From a contract state and a machine state related by the invariant Inv, for every command pre permits, the reply of h keeps post, and Inv holds again at the next states.
- run h p m
- Runs p on h from machine state m. It returns the result and the final machine state.
- trace h p m
- The list of command and reply pairs of that run.
- after K s t
- The contract state reached from s by applying next along the trace t.
- interp module p
- Replaces each command d of a high-level program p by the low-level program module d, whose result is the reply.
- link h dev
- Builds an Impl of an upper command set from a lower Impl h and handlers dev, stepping each upper command by run h (dev d) m.
- Runs p τ a
- Inductive relation saying p can produce trace τ and result a on some sequence of replies, with no Impl assumed.
Allowed K s t says a trace is one the contract allows: each command
permitted, each reply promised. Promised K s t asks only the reply half:
whenever a command in t meets Contract.pre at the current state, its
reply meets Contract.post. unpromised builds a contract whose post
is always true, so it promises nothing about replies.
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.
The handles example
HandleOp has two commands, open and close h. The contract handles
keeps, for each number, whether that handle is open. open is always
permitted and promises a handle that is not open. close h needs h open.
The implementation counter answers open with its counter and increments
it. counter_implements proves Implements handles counter Unused, where
Unused says every handle from the counter onwards is closed.
twoHandles opens two handles and closes both. twoHandles_safe proves it
safe on handles, and twoHandles_runs applies sound to its run on the
counter. Without the promise the same program is not safe
(twoHandles_unsafe_unpromised): the second open could return the first
handle.
Programs are a lawful monad
bind sequences two programs. Three theorems are the monad laws:
ret_bind (bind (Prog.ret a) f = f a), bind_ret
(bind p Prog.ret = p) and bind_assoc (binding is associative).
instMonadProg makes Prog C R a monad, so programs can be written in
do notation, and instLawfulMonadProg proves it lawful from the three
laws. leakyClient_do shows one program both ways. run_bind,
trace_bind, safe_bind and interp_bind split a run, its trace, Safe
and interp over bind; safe_ret and safe_call unfold Safe, and
safe_mono weakens its postcondition.
Two tiers of replacement
Conformance. safe_runs states what Safe buys on any trace (Runs p τ a)
without an Impl or an invariant: if Safe K Q p s and Promised K s τ
hold, then τ is Allowed K s τ and Q (after K s τ) a holds. run_runs
connects any model run h p m back to Runs p (trace h p m) (run h p m).1,
and sound is the model-level first tier: if Implements K h Inv, a
program is Safe K Q p s, and Inv s m holds, then the run’s trace is
Allowed from s, Inv holds after the run, and Q holds of the final
contract state and the result. So every implementation that keeps the
promises, started where its invariant holds, keeps the safe client’s
guarantee. It does not say two implementations give the client the same
result.
Replacement. Simulates K first second Rel says that from states
related by Rel, for every command pre permits, both implementations
give the same reply, the reply keeps post, and the next states are
related again. replacement is the second tier: given
Simulates K first second Rel and a client that is Safe K Q p s, from
states related by Rel the two runs have equal results and equal traces,
and Rel holds after them. Simulates names no start states, so
Replaces s0 m0 n0 K first second Rel adds them: Rel s0 m0 n0 and
Simulates. replaces_runs gives a safe client the
same result from both implementations, from those start states.
replaces_conforms shows a replacement claim carries conformance: the new
implementation implements the contract, with an invariant that holds at
its start state.
Why the first tier does not give the second. leakyClient opens a
handle, closes it, and returns whether the handle was 0.
leakyClient_safe proves it safe on handles. leakyClient_leaks proves
that the counter’s invariant holds on the empty state from 0 and from 1,
so both runs keep every promise of handles, yet the client gets true
from the counter started at 0 and false from the counter started at 1.
So handles_not_replaceable proves there is no relation Rel that holds
of the empty state, 0 and 1 and makes Simulates handles counter counter Rel
true. The promise of open leaves the reply open, since any handle that is
not open keeps it, so handles is not deterministic.
Deterministic contracts get both tiers. Deterministic K says that
under pre at most one reply keeps post. On such a contract,
implements_simulates turns two conformance proofs, Implements for each
implementation, into Simulates, with the relation “both invariants
hold”. implements_replaces adds each invariant at its start state and
gives Replaces from those states. No pairwise simulation proof is needed:
MapDet proves Std.Map.contract deterministic (Std.MapDet.contract_deterministic)
and derives Std.MapDet.replaces_list, which MapTree applies in one step
to prove its binary search tree replaces the sorted association list
(Std.MapTree.tree_replaces_list).
Refinement
Same signature. Refines new old Rel relates two contracts over the
same commands and replies. Rel is total: every old state has a related
new state, so an empty relation cannot make two contracts refine. From
related states, every command the old contract permits the new one
permits, every reply the new one promises the old one promised, and the
next states are related. refines_implements proves that an
implementation of the new contract implements the old one.
refines_refl and refines_trans make refinement reflexive and
transitive. refines_safe carries a client that is safe on the old
contract to the new one, with its postcondition read through Rel
(Transported), and refines_covers pairs that transport with totality so
every safe client of the old contract, from every old state, has a related
new state from which it is safe. refines_runs adds an implementation of the new contract
and its invariant at the start state, and gives the client an allowed
trace and the transported postcondition on the run. Refinement does not
give Simulates.
Across signatures. safe_interp links a high-level contract to a
low-level one over other commands, through a relation between their
states. Its premise is that, from related states, for each high-level
command the high-level contract permits, the low-level program the module
gives for it is safe on the low-level contract: its result is a reply the
high-level contract promises, and the states it ends in are related. Then
every program that is safe on the high-level contract becomes, through
interp, a program that is safe on the low-level contract from related
states, with the postcondition carried through the relation. link,
run_link and link_implements compose the implementation side under the
same handler premise: running interp dev p on a lower implementation h
equals running p on link h dev (run_link), and a conforming lower
implementation h lifts to a conforming upper implementation link h dev
(link_implements).
What the vacuity guards cover
Safe is relative to the promise. false_post_safe proves that a
contract whose promise no reply keeps makes every permitted call safe,
whatever the postcondition. false_post_unimplementable proves that no
implementation of such a contract has its invariant at a start state where
a command is permitted. So Safe says something about runs only through
safe_runs, sound and replacement, whose premises make replies keep the
promise. Simulates alone is vacuous with a relation that never holds:
Protected.plain_offset_bare proves one.
A protected reference’s gates read claims through templates the store pins
by identity. A conformance gate needs Implements K impl Inv and Inv at
the deployed start states. The gates refuse a bare Simulates claim, a
Replaces claim from other start states, a converse refinement, a client
guarantee weaker than the transported one and a contract whose promise no
reply keeps. A gate over parameters also refuses a claim with an added
hypothesis or for one fixed instance. Protected holds the checked
examples, such as Protected.never_unimplementable. The refusals
themselves are store code, and they are tested.
A contract selection under decision 0051 has none of these gate checks.
checked means an accepted theorem states the selection’s target exactly.
A selection of Implements K impl Inv whose invariant holds nowhere can
read checked, with a theorem such as Protected.never_implements, yet
it says nothing about a run. Only a gate asks for Inv at the deployed
start states.
A target stated under an assumption that nothing proves is checked only
under that assumption. The store counts the closed premises of a target’s
leading binders as its hypotheses. Such a selection reads
checked under n hypotheses, the summary counts it as conditional, and
a policy’s require.contracts rule accepts it only with
hypotheses: true. The count is not complete: a premise headed by another
of Lean’s constants, wrapped in a type, or past the leading binders is not
counted, and that selection reads plain checked.
Contract status
Contracts are selected and tracked by contract records, outside identity (decision 0051). A selection’s target is the contract applied to exact arguments, and Lean checks that the target is a well-typed closed proposition. Its status is one of three:
checked: an accepted theorem whose statement is the target, every hypothesis and quantifier included.open: no witness of the whole target and no waiver yet. Laws proved one by one are reported asn/m laws proved, and the record staysopen.waived: closed with a reason, by an actor the project’s policy lists. A waiver closes the workflow obligation and is never evidence. A policy rule never counts it.
Records are immutable: a law’s witness, a whole target’s witness and a
waiver each add a record, and status is read over all of a selection’s
records. An open selection does not stop a build. lema build --contracts
names selections about code the build deploys, never a waiver, and a
release of the build carries them. A policy’s require.contracts rule is
what asks for a witness: a reference’s move, or a release under that
reference, needs the selections the rule counts to be checked. A
revision obligation that names a selection is discharged only by a witness
of its target.
Running programs
Fueled is a model of bounded work. A Prog can hide any amount of
computation in a continuation, so counting its commands bounds nothing. A
Fueled.FProg is first-order data over a vocabulary (Fueled.Vocab)
whose steps, tests and commands each cost units of fuel. Fueled.toProg
gives the Core program it denotes, so Core’s theorems apply to it.
Fueled.runF runs it with N units per slice, refilled at each
scheduling point. Fueled.runF_enough proves that with gap v p ≤ N the
runner is never cut off and computes the Core run. Fueled.slices_le_gap
bounds the work between scheduling points, and Fueled.commands_le
bounds the commands. That each vocabulary member runs within its declared
cost, and how units become time, are not proved.
Applications do not run as Fueled.FProg. They run on the store-native
VM: lema build compiles an accepted root to LemaIR, and the VM runs it
with no Lean or C compiler. The artifact binds its limits, which a run
cannot override: steps and allocation (one allowance shared by every
task), big-integer width, call depth and a deadline. A run past its step
limit fails with vm_steps_limit. The static passes a build can request
are guarantee profiles, each recorded in a receipt: NoCopySliceCall,
NoBigIntPrimitives, NoBoxOrCtorInCycles, FlatMessage,
ExclusiveActorLoop, ConstantTime and SecretFlow, one profile per
role (SecretFlow.SigV4, for example). They are versioned static checks
of the compiled program, not Lean proofs, and an analysis without a
verdict refuses.
The evidence for this path is split. Admission is checked: the Lean kernel
accepts every object of the closure. The IR semantics’ vectors are
checked: each vector’s outcome under the semantics is a kernel-checked
theorem. The lowering, the VM and its limits, the receipts and the VM’s
agreement with the semantics are tested. The worker binary, rustc, the
operating system and the network are assumed.
How objects are cited
Every object has an ID: the SHA-256 of its canonical encoding under a
versioned hash domain, 64 lowercase hex digits. Stored forms keep the bare
hex. Under Identity Genesis (decision 0060), a full ID is printed with its
rules version, in the form lema4:<hex>.
Related work
Core combines known constructions from dependent type theory, program logics for free monads, and content-addressed codebases:
- Command–response trees. Peter Hancock and Anton Setzer, “Interactive Programs in Dependent Type Theory” (Computer Science Logic, CSL 2000, LNCS 1862, pp. 317–331, Springer, 2000), parameterise interactive programs over a world of commands and command-indexed responses
(C, R), represent strategies as command–response trees, and translate high-level worlds over lower-level ones.Prog,bindandinterpare the well-founded, inductive form of that container tree (Prog.retandProg.call); Hancock and Setzer also formulate potentially infinite reactive loops (whileandrepeat) up to bisimulation, whereasProghas only well-founded trees andFueled.FProgbounds loops explicitly by fuel. - Interaction trees. Li-yao Xia, Yannick Zakowski, Paul He, Chung-Kil Hur, Gregory Malecha, Benjamin C. Pierce and Steve Zdancewic, “Interaction Trees: Representing Recursive and Impure Programs in Coq” (Proceedings of the ACM on Programming Languages 4, POPL, Article 51, 2020; Coq has since been renamed Rocq), define coinductive trees of uninterpreted events with a silent step, general recursion combinators, monadic event handlers, and equational reasoning up to weak bisimulation, executed via extraction to OCaml.
Progshares the uninterpreted-event tree and monadicinterp, while remaining inductive without a silent step (as Xia and others note in §9, Lean has no coinductive types), reasoning against stateful protocol contracts (ContractandSafe) rather than weak bisimulation, and compiling accepted roots to LemaIR for the store-native VM rather than extracting to a host language. - Interface contracts over free monads. Thomas Letan and Yann Régis-Gianas, “FreeSpec: Specifying, Verifying and Executing Impure Computations in Coq” (Proceedings of the 9th ACM SIGPLAN International Conference on Certified Programs and Proofs, CPP ‘20, pp. 32–46, ACM, 2020; building on Letan, Régis-Gianas, Pierre Chifflier and Guillaume Hiet, FM 2018), model well-founded impure computations over an interface family and specify components by a three-part contract over a witness state: witness update, caller obligation and callee obligation.
Contract(next,pre,postover a ghost state) is the same three-part protocol specification. FreeSpec splits caller compliance from an existential respectful-run predicate for outcomes, composes interfaces via typeclasses, and models handlers coinductively;Corefolds caller obligations, reply promises and final postconditions into one weakest-precondition predicate (Safe), models handlers as total step functions (Impl), and separates promise-preserving conformance (Implementsandsound) from reply-preserving simulation (Simulates,replacementandReplaces) and interface change (Refines). - Weakest preconditions over free monads. Wouter Swierstra and Tim Baanen, “A Predicate Transformer Semantics for Effects (Functional Pearl)” (Proceedings of the ACM on Programming Languages 3, ICFP, Article 103, 2019), take the Hancock–Setzer free monad in Agda, fold monotone predicate transformers over it to compute weakest preconditions across Kleisli composition, and use the induced refinement preorder for stepwise program calculation.
Safe,safe_monoandsafe_bindare that weakest-precondition fold specialised to protocol contracts over a ghost state; Swierstra and Baanen instead choose a predicate transformer per effect (partiality, state, angelic or demonic nondeterminism, step-bounded recursion) and mix specification holes into leaves for calculation rather than pairing one protocolSafewith state-machineImplconformance. - Content-addressed definitions. Paul Chiusano, Rúnar Bjarnason and contributors, Unison (“The big idea”), identify definitions by cryptographic hashes of syntax trees with variable names erased and dependencies cited by hash, treating human-readable names as mutable pointers in a codebase database. Lema shares content-addressed definitions and mutable human-readable names, but hashes kernel-checked Lean terms and statements (with explicitness of binders in identity and inductive families tied to recorded project seeds), tracks kernel axiom footprints per receipt, and gates how published names move.
What Lema adds is the connection between those program-logic statements and a content-addressed store. The store recognises Implements, Safe, Simulates, Replaces, Refines and Transported by their pinned statement and template identities rather than by module path or name. Moving a published name on a gated reference requires an accepted theorem of the gate’s exact claim: simulation for replace, or refinement and transported safety for refine. Release policies read contract selections that record which obligations are checked (and under how many hypotheses), open or waived.
Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility