kernel design
The kernel is the trusted computing base of QED: the only code that must be correct for a theorem to be believed. This page explains the logic it implements, why its interface makes every other package untrusted, and how the soundness argument of the formal specification maps onto the code in src/kernel.
Design goal
A theorem prover is only as trustworthy as the code that can create theorems. QED follows the LCF approach of Milner’s Edinburgh LCF and its descendants HOL Light and HOL4:11 R. Milner, “LCF: A way of doing proofs with a machine”, 1979; J. Harrison, “HOL Light: An overview”, TPHOLs 2009. QED follows HOL Light’s choice of primitive rules most closely. theorems are values of an abstract type whose only constructors are the inference rules of the logic. Parsers, tactics, proof search and the command-line tool may contain any number of bugs, but a bug there can only make a proof fail, never make a false statement a theorem.
The kernel therefore has three goals:
- implement higher-order logic (HOL) with a small, fixed set of rules that can be read and checked by hand;
- make the theorem type impossible to forge from outside the package;
- grow the theory only through extensions that are provably conservative, and record each one for audit.
Mathematical background
Types
Types are generated by type variables and type constructors with fixed arities:
The constructors bool (arity 0), fun (arity 2, written ) and ind (arity 0) are built in. A type substitution maps type variables to types and acts homomorphically. A type is an instance of a schema , written , when for some ; ty_is_instance_of decides this by first-order matching.
Terms
Terms are those of the simply typed λ-calculus over a signature of constants:
A variable is a pair of a name and a type. A constant occurrence is legal when is declared with schema and . The typing judgement is the usual one:
Typing is syntax-directed and every well-typed term has exactly one type, so type_of is a total function into HolType?: it makes one pass over the term and, at each application, compares the argument type with the domain of the function type, so its cost is the size of the term times the size of the largest type compared.
The only logical constants of the core are equality and choice:
Every other connective is a definition in terms of these two, made by the logic package through the DefOK gate; the logic design gives the definitions. Keeping connectives out of the kernel keeps the kernel small: it knows nothing about or .
α-equivalence and De Bruijn terms
Two terms are α-equivalent when they differ only in the names of bound variables: . The rules of HOL must not depend on bound names, so the kernel works on a nameless representation. A De Bruijn term replaces each bound occurrence by the number of binders between it and its binder:22 N. G. de Bruijn, “Lambda calculus notation with nameless dummies”, Indagationes Mathematicae 34, 1972.
The conversion (to_db_term) satisfies , so α-equivalence becomes structural equality (db_term_eq). Constants carry one more field than in HOL Light, their identity stamp (see “Every rule is checked against a state” below), and db_term_eq compares it too: an occurrence built with mk_const (stamp , unresolved) and one built with ks_mk_const (the resolved identity) are different De Bruijn terms. db_term_logical_eq ignores the stamp. QED’s De Bruijn terms are typed: bound occurrences and binders keep their types. Two consequences follow. Abstractions over different types never collapse, since for . And a term such as , whose inner variable has the name of the binder but another type, has no conversion at all: to_db_term returns None and every rule reports BoundaryFailure. HOL Light reads the inner x as a separate free variable; QED rejects the term, so that a binder name always refers to one variable.
Substitution and β-reduction
Write for the shift that adds to every index in , and for the replacement of index by , shifting as it passes under binders:
Shifts and replacement act homomorphically on applications and leave free variables and constants alone. β-contraction of is then
Why this cannot capture: inside , index refers to the binder being removed and indices to binders outside it. Shifting up by one before inserting it makes every free index of skip the binder that is about to disappear, and the replacement shifts again under each inner binder, so an index of always counts the binders that actually surround it. After replacement no occurrence of index remains, because each one was replaced, so the final shift down by one is defined and turns the indices that pointed past the removed binder back into their original values. The named counterpart is the capture-avoiding substitution ; the specification states this correspondence as the lemma “Well-Scoped Beta Contraction Safety”. The kernel computes every index with overflow checks and reports CapacityExceeded instead of wrapping.
Substitution for free variables (db_subst_free_parallel, used by INST) is simpler: a free variable is a name, never an index, and the inserted term is shifted by the current binder depth, which is a no-op for a term with no loose indices. Capture is impossible by construction, which is why INST needs no renaming step.
Sequents and theorems
A theorem is a sequent : a finite set of propositions (terms of type bool) and a proposition . The kernel stores and as De Bruijn terms and deduplicates hypotheses with db_term_logical_eq, so is a set of α-equivalence classes: inserting a hypothesis that is α-equivalent to one already present does nothing (db_hyps_union), and DEDUCT_ANTISYM_RULE removes every entry α-equivalent to the given term (db_hyps_remove). The comparison ignores constant identity stamps: every checked rule has already shown its premises admissible in one state, where a constant name denotes one identity, so an unstamped occurrence (stamp , from mk_const) and a stamped one (from ks_mk_const) of the same constant are the same proposition and are not kept twice.
The intended meaning is the standard semantics of HOL: types denote non-empty sets, denotes , denotes the full set of functions, denotes identity and denotes a choice function. A sequent is valid when every model and every valuation of the free variables that make all of true also make true.
Design decisions
The theorem type is abstract
Problem. If code outside the kernel could construct a Thm, any bug or shortcut in that code could produce a false theorem.
Options. An LCF-style abstract type; proof terms checked by a separate checker (the approach of Coq and Lean); or a trusted record with a “verified” flag.
Choice. Thm is declared type Thm in the interface: its fields are private and it has no public constructor. The only functions that return a Thm are the eleven rule functions (refl_checked to inst_checked, plus add_assum_checked), the gates ks_define_const_thm and ks_specify_const, the stored-theorem readers ks_definition_theorem, ks_typedef_contract and ks_ind_infinity_axiom, and thm_bind_const_ids, which returns its argument with its constant identities resolved again in the given state and checked (see “Every rule is checked against a state” below). MoonBit enforces this at compile time.
Why. With an abstract type the trusted base is exactly this package. Proof terms would add a second trusted component, the checker, and a large proof object per theorem; QED’s specification makes the LCF discipline normative (obligation “Interface safety”) and checks it by inspecting the interface file.
HOL Light’s primitive rules
Problem. Choose the rules that generate all theorems.
Choice. The ten rules of HOL Light, the smallest standard basis for HOL with equality as the only primitive connective:
Matching of premises (the middle term of TRANS, the antecedent of EQ_MP) is up to α-equivalence and ignores constant identities (db_term_logical_eq), because both theorems have already been checked against the current state.
One deviation: QED’s BETA accepts any redex , whereas HOL Light’s primitive BETA only accepts and derives the general form with INST. The general form is a derived rule in HOL Light, so this adds no theorems; it saves the kernel a renaming step and is exactly the rule stated in the specification.
Why HOL and not dependent types. HOL has a simple, well-understood set-theoretic semantics, a kernel of a few hundred lines in HOL Light, and decades of experience showing that the ten rules suffice for mathematics when combined with definitions. The kernel stays small enough for its soundness argument to be read in full, which is the point of a kernel-first design.
Weakening is provided natively
add_assum_checked implements weakening: for a proposition , gives . The classical HOL basis has ten rules; weakening is derivable from that basis and therefore adds no theorems. QED exposes it as a native checked rule, and the Typed HOL calculus represents it explicitly and proves its semantic preservation. Both and have type (every conclusion does, and the rule checks ), so the two rules below apply:
The hypothesis set of line 4 is : the part is contained in , and . The derivation works whether or not or , and it only uses set operations on hypotheses, so it gives the same hypothesis set as the native rule whatever equality the kernel uses to compare hypotheses. Every premise and result is checked against the same state, as in the native rule. The native rule is a shortcut used by replay in the logic package to make hypothesis sets match exactly.
A named boundary over a De Bruijn core
Problem. Users and the frontend think in named terms; the rules must be name-independent.
Options. Named terms with explicit renaming (HOL Light); locally nameless terms; De Bruijn terms everywhere.
Choice. The interface takes and returns named Term values; every rule converts its inputs with to_db_term, works on DbTerm, and converts back with from_db_term only when a caller asks for hypotheses or a conclusion. A failed conversion is the error BoundaryFailure, not a derivation.
Why. α-equivalence becomes equality, substitution needs no fresh names, and hypothesis sets are sets of α-classes for free. The cost is that terms read back from a theorem carry generated binder names (_b0, _b1, …), so callers compare with term_alpha_eq. The specification proves the commutation square that justifies the boundary: lowering, running the De Bruijn rule and lifting gives a result α-equivalent to running the named rule.
Every rule is checked against a state
Problem. Constants are declared in scopes and can be shadowed. A theorem about the constant c proved in one scope must not be reused after an inner scope declares a different c.
Choice. Every rule takes the KernelState and runs ensure_thm_admissible on its premises and on its result. A theorem records the identity (ConstId) of each constant it mentions. It is admissible in a state when each recorded identity is the one the state resolves the name to, each constant occurrence is an instance of the declared schema, each type uses only admitted constructors, and a definition theorem still agrees with its definition.
Why. Name lookup changes as scopes are pushed and popped, but a recorded identity does not. Freezing identities makes resolution stable under scope mutation (the specification’s “Resolution Freeze” theorem), and the check turns a stale theorem into an InvalidInstantiation failure instead of a silent change of meaning. The tutorial shows a theorem that is rejected inside a shadowing scope and accepted again after the scope is popped.
The provenance check is a second, state-level guard. When a theorem is first
admitted, the kernel records the current declaration lineage. A theorem remains
admissible only when that lineage is a prefix of the receiving state’s lineage.
Linear descendants, including a theorem carried through a temporary pushed and
popped scope, therefore retain the theorem; an independently forked state with
a divergent lineage is rejected even when its independently allocated ConstId
values happen to collide. Two branches that perform the same lineage events have
the same lineage and may exchange the resulting theorem.
A lineage is a persistent chain of events. Every event node is interned by its parent and the event text, so two branches that perform the same events from the same parent share the node and lineage equality is node identity. Each node keeps a skew-binary jump pointer, so asking whether a theorem’s lineage is an ancestor of the state’s lineage costs in the length of the history. Appending an event and recording the lineage in a theorem are . The intern table is private to the kernel and holds one small node per distinct event.
One exception: thm_bind_const_ids. An occurrence built with mk_const has stamp , and the identity the theorem records for it is taken from the state when the theorem is built. For a theorem that has not yet been admitted, thm_bind_const_ids(state, th) resolves every unstamped occurrence again in state and records the new identity. Applied after a scope has shadowed a constant c, it can turn such a raw theorem about the outer c into a theorem about the inner one. This is sound, because only constants without a definition can be shadowed: ks_add_const and both definition gates refuse names that are already definition, representation or abstraction heads, so a shadowed constant is uninterpreted, and a theorem about an uninterpreted constant stays valid when another constant of the same type takes its place, just as INST may replace a free variable. An admitted theorem already carries declaration lineage, so thm_bind_const_ids rejects remaining unstamped occurrences and cannot bypass the provenance check. Code that relies on frozen identities should build constants with ks_mk_const, whose occurrences carry their identity and cannot be rebound.
Extensions go through gates
The theory grows in three ways, each guarded by a gate that checks side conditions and appends an ExtensionCert.
DefOK, constant definition. ks_define_const(c, \tau, t) adds a constant and the theorem . Each side condition rules out a known way to break conservativity:
| Condition | Error | Counterexample it prevents |
|---|---|---|
| is closed | DefinitionNotClosed | would give , then INST gives and so for all . |
| No occurrence in denotes itself: a name that does not denote a declared constant would denote the new constant | DefinitionIsCyclic | would give , a contradiction. |
GhostTypeVariable | with is true when has one element and false at ; INST_TYPE gives both instances of the definition, with the same left-hand side , so . | |
| has never been defined | DefinitionAlreadyExists | Two definitions of one name would give and , so . |
The counterexamples in the second and last rows are stated, as in the specification, for constants identified by name. The code identifies constants by ConstId: the new constant always receives a fresh identity, so an occurrence in of a name that already denotes a declared constant is an older constant (for example one of an outer scope that the new constant will shadow), and a definition cannot depend on itself through identities, whatever the earlier definitions mention. The only way can mention the constant being defined is an occurrence of the name that does not denote a declared constant yet, because after the definition that name would denote the new constant; ks_define_const refuses that with DefinitionIsCyclic. This is the freshness condition of the Lean DefinitionGate (the defined identifier does not occur in the right-hand side). In particular ks_define_const accepts c := d in an inner scope when an earlier definition of d mentions an outer, undefined constant named c. A second definition of one name is still refused (DefinitionAlreadyExists, which is by name over the whole theory history), and a theorem is never rebound from one constant to another of the same name (see thm_bind_const_ids).
Under these conditions a definition is conservative. Every instance of the new constant is for some type substitution , and replacing it by maps each proof in the extended theory to a proof in the old theory: the definition theorem and its type instances become instances of REFL, every other rule step maps to the same step, and a theorem that does not mention is mapped to itself. The ghost-variable condition is what makes the replacement a function of the instance alone. The specification proves this as “Definition-level conservativity”.
TypeDefOK, type definition. ks_register_type_definition admits a type in bijection with , given a hypothesis-free theorem for a closed term . It declares the representation , named by the caller, and the abstraction , named Abs_ followed by , and returns three contract theorems, with and free variables:
The first says that is injective, the second that its image lies inside , and the third that every element of is in the image. HOL Light characterises a type bijection by the first theorem and the equivalence . The third theorem is the left-to-right direction of that equivalence, and the right-to-left direction follows from the second theorem instantiated at and rewritten with the hypothesis .
The witness matters because the second contract theorem holds for a free variable . If were empty, for example , it would read : HOL types denote non-empty sets, so no model can interpret a type in bijection with an empty set, and the logic, in which every type is inhabited, proves the contradiction. The gate also requires the predicate’s type variables to be among the parameters , for the same reason that DefOK forbids ghost type variables.
SpecOK, constant specification. ks_specify_const introduces a constant with the property , given a hypothesis-free theorem for a closed term . The specification asks for instead; a concrete witness is a stronger premise, since it implies the existential. The gate defines through DefOK, which records a DefOK certificate, then builds itself and records a SpecOK certificate.
The theorem is not derived by kernel rules. It is an instance of the choice axiom
at , rewritten with the definition , and the kernel has no rule or theorem for the choice axiom: the specification takes the axiom schema as part of its trusted baseline. The theorem is valid because denotes a choice function in every model: makes non-empty, so , and denotes . For the same reason the extension is conservative over the old theory together with the choice axiom: in a derivation, each use of can be replaced by the choice instance at and the definition, and then unfolded as for DefOK. The conservativity of DefOK alone does not cover this step, because does not follow from without the axiom. The specification proves the combined statement as “Conservativity of Specification Extension”.
Infinity anchor. HOL needs an infinite type for arithmetic, and the specification assumes that ind is one. ks_register_ind_infinity_axiom stores a theorem as the anchor of that assumption, but it accepts any hypothesis-free admissible theorem whose statement mentions ind, even for , and it does not check that the theorem says ind is infinite. Since the kernel has no axiom of infinity, no theorem it can produce says so. The anchor therefore adds no theorem and no risk to consistency; it only marks, for audit, the model-class restriction of the specification. Arithmetic over ind is not available.
Results, not exceptions
Every kernel function returns Result or Option; none aborts on bad input. A rule that cannot apply says why, with a constructor of LogicError or SigError, and the caller decides what to do. This is what makes the frontend fail closed: the tactics and prover packages turn these values into structured diagnostics, and no path turns a failed rule into a theorem.
Correctness and invariants
Why soundness reduces to the kernel
Call a theorem value sound when its sequent is valid in every model of the current theory. The argument has three steps.
1. Every rule preserves validity. For each primitive rule, valid premises give a valid conclusion. Two cases show the pattern.
ABS. Let be a model and a valuation that satisfies . Since , every valuation also satisfies , so by validity of the premise for every . Hence
by function extensionality in the standard model. Without the side condition the step “every satisfies ” fails: from one could derive , which is false whenever holds and the type of has a second element.
DEDUCT_ANTISYM_RULE. Let satisfy . If , then satisfies (the only hypothesis that may have been removed from is ), so . Symmetrically implies . Two booleans that imply each other are equal, so .
The remaining rules follow the same way: REFL and TRANS from reflexivity and transitivity of identity, MK_COMB from congruence of application, BETA from the substitution lemma , EQ_MP from the meaning of on booleans, ASSUME trivially, INST from the substitution lemma for free variables (a valid sequent holds under every valuation, in particular under ), and INST_TYPE because a valid sequent holds under every interpretation of its type variables by non-empty sets, and every type the state admits denotes one. The specification proves each case (“Rule-level preservation”).
2. Every extension preserves consistency. Every model of the old theory in which is a choice function extends to such a model of the new one: interpret a defined constant by its right-hand side, a new type by the non-empty subset its witness exhibits, with the inclusion and any retraction onto it, and a specified constant by the chosen element . The theorems the gates return are valid in the extended model, as argued above, so no false sentence in the old language becomes provable.
3. Interface safety. Because Thm is abstract, every Thm that exists at run time is the root of a finite derivation tree whose nodes are rule applications and gate outputs. add_assum_checked is a derived rule, as shown above; the readers ks_definition_theorem, ks_typedef_contract and ks_ind_infinity_axiom return gate outputs stored in the state; and thm_bind_const_ids changes only constant identities, in the way shown to be sound above. Induction on the depth of the tree, using steps 1 and 2, shows that every Thm is sound.
Step 3 is a property of the code, not of the logic, and it is why nothing outside src/kernel needs to be trusted: the logic, tactics and prover packages can only call the functions in the kernel API, so whatever they compute, any Thm they return has a derivation. The specification states the six obligations and their dependencies; the conformance pack in formal_verification/ checks the paper side in Lean.
Invariants maintained by the code
- A
Thmstores its hypotheses as a list without duplicates underdb_term_logical_eq(α-equivalence, constant stamps ignored) and its conclusion as a De Bruijn term; every rule result passesensure_thm_admissiblein the state it was built in. KernelStateis persistent. A gate returns a new state; the base state stays valid, soks_conservative_replay_ok(base, extended, th)can re-checkthagainst both.- Constant identities are allocated from a counter in the theory state and never reused, even after a scope is popped. (The
sig_*functions on a bareGlobalSignumber new constants after the largest identity still visible, so they can reuse one after a pop; they never touch theorems.) - Definition heads, type-definition heads and the infinity anchor are recorded in the theory history, which
ks_pop_scopedoes not touch: a name, once defined, cannot be defined again.
Complexity
Write for the size of the terms involved, for their binder depth, for the number of hypotheses, for the number of constant occurrences in a theorem and for the number of declarations in the signature. The costs are polynomial in these sizes:
- Lowering a named input with
to_db_termsearches the binder environment at each variable and copies it at each abstraction, . Reading a term back withfrom_db_term, asthm_conclandthm_hypsdo, also searches the names already in use, with the number of free names. - The rule cores walk their terms once. BETA and INST shift the inserted term at every occurrence they replace, so their cost is the size of the result, at most for an inserted term of size .
- Hypothesis union and removal compare hypotheses pairwise, .
ensure_thm_admissibleruns on every premise and on every result. It collects constant names with linear membership tests, , and looks each occurrence up in the scoped signature and matches it against the schema, plus the size of the types.
Proof sizes in the shipped subset are small; the kernel favours checks that are easy to audit over asymptotic speed.
Alternatives rejected
- Named terms with renaming, as in HOL Light. Every rule would need a correct renaming function, which is a classic source of kernel bugs. The De Bruijn core avoids renaming entirely.
- Connectives as kernel primitives. Adding , or as primitive constants with their own rules would enlarge the kernel and its soundness proof. They are definitions over instead.
- Exceptions for rule failure. HOL Light raises
Failure. Results make every failure visible in the type and keep the frontend from accidentally catching and ignoring one. - Unchecked rules with a separate validation pass. Checking admissibility only at the end would let an inadmissible intermediate theorem feed later steps. Every rule checks its inputs and output instead.
- Arbitrary axioms. There is no function that turns a term into a theorem. The only non-derived theorems are definitions, type-definition contracts and the property of a specified constant, all produced by gates with side conditions that keep the extension conservative.
Boundaries
- The kernel does not parse text, elaborate names or run tactics; those are the elab, parser and tactics packages, and none of them is trusted.
- It implements no connective other than equality and choice, and no quantifier syntax; the logic package defines the rest.
- It does not store proved theorems by name. Theorem names are a frontend concern.
- It has no metavariables and no incomplete theorems: a
holein a proof script never reaches the kernel. - It does not prove its own soundness. The argument above and in the specification is a paper proof;
formal_verification/aligns the specification with Lean, not the MoonBit source. - It does not provide the choice axiom as a theorem.
@is declared and used bySpecOK, but no public function returns .