3.4. Why we trust the kernel#
The kernel accepts a proof when every node of the tree is a correct application of one of the five rules. But why should it follow from this that the theorem is true? And does the Python program do exactly what we wrote down on paper? In this section we answer both questions: first with a careful proof, then with tests. The care pays off — the proof points to two holes in the first version of the kernel. At the end we compare checking a proof with searching for one.
3.4.1. The soundness theorem#
For a proof to be a proof and not a sketch, we need precise definitions. Each of them corresponds to a piece of code we already know.
3.4.1.1. Terms, substitutions and algebras#
A signature \(\Sigma\) is a finite set of symbols, each with a fixed number of arguments \(\operatorname{ar}(f)\). In our case \(+\) and \(\cdot\) take two arguments, \(n\) one, and \(0\) and \(1\) none: constants are symbols without arguments. Variables are identifiers outside the signature; we denote their set by \(V\).
Terms are defined inductively: every variable is a term, and if \(\operatorname{ar}(f) = k\) and \(t_1, \dots, t_k\) are terms, then \(f(t_1, \dots, t_k)\) is a term (for \(k = 0\) this is just the constant \(f\)). We denote the set of terms by \(T\). In the code this definition is checked by the methods
termandis_var.A substitution is a function \(\sigma\colon V \to T\) with \(\sigma(x) \neq x\) for only finitely many variables (in the code: a dictionary). The term \(t\sigma\) is defined recursively: \(x\sigma = \sigma(x)\) and \(f(t_1, \dots, t_k)\sigma = f(t_1\sigma, \dots, t_k\sigma)\) — this is the function
subst. A substitution changes only variables: a constant is a symbol without arguments, so \(0\sigma = 0\). We write \(C[z := a]\) for \(C\sigma\) where the substitution changes only the variable \(z\), into \(a\).An algebra \(A\) is a non-empty set \(|A|\) with a function \(f^A\colon |A|^{\operatorname{ar}(f)} \to |A|\) for every symbol \(f\) (for a constant, a distinguished element). A valuation is any function \(v\colon V \to |A|\). The value of a term is computed recursively: \([\![x]\!]_v = v(x)\) and \([\![f(t_1, \dots, t_k)]\!]_v = f^A([\![t_1]\!]_v, \dots, [\![t_k]\!]_v)\).
An equation \(l = r\) holds in the algebra \(A\) if \([\![l]\!]_v = [\![r]\!]_v\) for every valuation \(v\). For a set \(H\) of names of facts, \(\operatorname{Mod}(H)\) denotes the class of algebras in which the equations of all facts in \(H\) hold. Boolean algebras are \(\operatorname{Mod}(\{\mathrm{H1}, \dots, \mathrm{H8}\})\).
3.4.1.2. What exactly the kernel computes#
An environment \(\Gamma\) assigns to the name of a fact a triple \((\bar x;\, l;\, r)\): a list of variables
\(\bar x = (x_1, \dots, x_k)\) and the two sides of an equation. With every fact \(G\) the kernel also stores the
set \(\mathrm{ax}(G)\) (the dictionary assumptions). The method conclusion computes a partial function
\(\mathrm{concl}_\Gamma\) that assigns a pair of terms to a proof tree. Here is its complete definition, one clause
per rule. When the condition in the second column fails, \(\mathrm{concl}_\Gamma(d)\) is undefined and the kernel
raises ProofError.
node \(d\) |
condition checked by the kernel |
\(\mathrm{concl}_\Gamma(d)\) |
|---|---|---|
|
\(t \in T\) |
\((t,\ t)\) |
|
\(\mathrm{concl}_\Gamma(p) = (a, b)\) is defined |
\((b,\ a)\) |
|
\(\mathrm{concl}_\Gamma(p) = (a, b)\), \(\mathrm{concl}_\Gamma(q) = (b', c)\), \(b'\) is the same term as \(b\) |
\((a,\ c)\) |
|
\(z \in V\), \(C \in T\), \(\mathrm{concl}_\Gamma(p) = (a, b)\) |
\((C[z := a],\ C[z := b])\) |
|
\(\Gamma(G) = (x_1 \dots x_k;\, l;\, r)\), \(m = k\), all \(t_i \in T\) |
\((l\sigma,\ r\sigma)\) for \(\sigma = \{x_i \mapsto t_i\}\) |
Only two methods change the environment. Both add the fact with the method _add, which checks that the
name is new, that \(l, r \in T\), that \(x_1, \dots, x_k \in V\), and that every variable of \(l\) and \(r\) is on the
list \(\bar x\).
axiom(G, x̄, l, r)adds the fact without a proof and sets \(\mathrm{ax}(G) = \{G\}\).theorem(G, x̄, l, r, d)adds the fact only if \(\mathrm{concl}_\Gamma(d) = (l, r)\), and sets \(\mathrm{ax}(G) = \mathrm{ax}(d)\). Here \(\mathrm{ax}(d)\) is the union of the sets \(\mathrm{ax}(F)\) over all facts \(F\) in theInstnodes of the tree \(d\) (the functionused_facts).
3.4.1.3. Three lemmas#
Lemma 1 (substitution)
For every term \(t\), substitution \(\sigma\), algebra \(A\) and valuation \(v\)
Proof. Induction on the structure of the term \(t\). If \(t\) is a variable \(x\), then \([\![x\sigma]\!]_v = [\![\sigma(x)]\!]_v = v^\sigma(x) = [\![x]\!]_{v^\sigma}\). If \(t = f(t_1, \dots, t_k)\), also for a constant (\(k = 0\)), then by the definition of substitution, the definition of value and the induction hypothesis for \(t_1, \dots, t_k\)
The proof uses the fact that \(\sigma\) changes only variables. If a “substitution” could also change
constants — like the dictionary {"0": "y"} passed to the function subst — the lemma would be false:
for \(t = 0\) the left-hand side is \(v(y)\) and the right-hand side is \(0^A\).
Lemma 2 (context)
If \([\![a]\!]_v = [\![b]\!]_v\), then \([\![C[z := a]]\!]_v = [\![C[z := b]]\!]_v\) for every term \(C\) and every variable \(z\).
Proof. Let \(\sigma_a\) and \(\sigma_b\) change only the variable \(z\), into \(a\) and into \(b\) respectively. By Lemma 1 both sides are values of the same term \(C\) under the valuations \(v^{\sigma_a}\) and \(v^{\sigma_b}\). These valuations are equal: at the point \(z\) they give \([\![a]\!]_v = [\![b]\!]_v\), and at every other point \(x\) the value \(v(x)\). Under equal valuations a term has equal values. \(\square\)
Lemma 3 (instances)
If the equation \(l = r\) holds in the algebra \(A\), then for every substitution \(\sigma\) the equation \(l\sigma = r\sigma\) holds in it as well.
Proof. For any valuation \(v\), Lemma 1 gives \([\![l\sigma]\!]_v = [\![l]\!]_{v^\sigma} = [\![r]\!]_{v^\sigma} = [\![r\sigma]\!]_v\). The middle equality holds because \(l = r\) holds under every valuation, in particular under \(v^\sigma\). \(\square\)
3.4.1.4. The theorem and its proof#
We call an environment \(\Gamma\) sound if each of its facts \(G = (\bar x;\, l;\, r)\) satisfies three conditions: (i) \(x_1, \dots, x_k \in V\); (ii) \(l, r \in T\); (iii) the equation \(l = r\) holds in every algebra in \(\operatorname{Mod}(\mathrm{ax}(G))\).
Theorem (soundness of the kernel)
Let the environment \(\Gamma\) be sound. If \(\mathrm{concl}_\Gamma(d) = (s, t)\), then \(s\) and \(t\) are terms and the equation \(s = t\) holds in every algebra in \(\operatorname{Mod}(\mathrm{ax}(d))\).
Proof. Induction on the structure of the tree \(d\). Fix an algebra \(A \in \operatorname{Mod}(\mathrm{ax}(d))\) and a valuation \(v\); we have to show that \(s, t \in T\) and \([\![s]\!]_v = [\![t]\!]_v\). Every fact used in a subtree is used in \(d\), so \(\mathrm{ax}\) of the subtree is a subset of \(\mathrm{ax}(d)\), and \(A\) also belongs to the class \(\operatorname{Mod}\) of the subtree. We can therefore apply the induction hypothesis to subtrees with the same algebra \(A\) and the same \(v\). We consider five cases, one per row of the table.
Refl(t). The kernel checked that \(t \in T\), and \([\![t]\!]_v = [\![t]\!]_v\).Symm(p). Then \(\mathrm{concl}_\Gamma(p) = (a, b)\) and \((s, t) = (b, a)\). By the induction hypothesis \(a, b \in T\) and \([\![a]\!]_v = [\![b]\!]_v\), so \([\![b]\!]_v = [\![a]\!]_v\).Trans(p, q). Then \(\mathrm{concl}_\Gamma(p) = (a, b)\), \(\mathrm{concl}_\Gamma(q) = (b', c)\) and \((s, t) = (a, c)\). By the induction hypothesis \([\![a]\!]_v = [\![b]\!]_v\) and \([\![b']\!]_v = [\![c]\!]_v\). The kernel checked that \(b'\) is the same term as \(b\), so \([\![b]\!]_v = [\![b']\!]_v\), and the chain of equalities gives \([\![a]\!]_v = [\![c]\!]_v\). Without the comparison of the middles nothing would follow from \(a = b\) and \(b' = c\).CongrArg(z, C, p). The kernel checked that \(z \in V\) and \(C \in T\), and \(\mathrm{concl}_\Gamma(p) = (a, b)\). By the induction hypothesis \(a, b \in T\) and \([\![a]\!]_v = [\![b]\!]_v\). Putting a term in place of a variable in a term gives a term, and Lemma 2 gives \([\![C[z := a]]\!]_v = [\![C[z := b]]\!]_v\).Inst(G, (t₁, …, tₖ)). Then \(\Gamma(G) = (\bar x;\, l;\, r)\) and \((s, t) = (l\sigma, r\sigma)\), where \(\sigma(x_i) = t_i\). By condition (i) all \(x_i\) are variables, so \(\sigma\) is a substitution in the sense of the definition. The fact \(G\) is used in \(d\), so \(\mathrm{ax}(G) \subseteq \mathrm{ax}(d)\) and \(A \in \operatorname{Mod}(\mathrm{ax}(G))\); by condition (iii) the equation \(l = r\) holds in \(A\). Lemma 3 gives \([\![l\sigma]\!]_v = [\![r\sigma]\!]_v\), and \(l\sigma, r\sigma \in T\), because \(l, r \in T\) (condition (ii)) and the kernel checked that \(t_i \in T\). \(\square\)
The theorem speaks about a single tree. It remains to show that the kernel’s environment is always sound.
Corollary (environment invariant)
Every environment obtained from the empty environment by calls to the methods axiom and theorem is
sound. In particular, every theorem accepted in the environment theory() holds in every Boolean algebra, and
even in every algebra in which the axioms on its list assumptions hold.
Proof. Induction on the number of calls. The empty environment is sound. Let \(\Gamma\) be sound and let the
next call add a fact \(G = (\bar x;\, l;\, r)\). The method _add checks conditions (i) and (ii), and the
old facts do not change, because the name \(G\) must be new. Condition (iii) remains. If \(G\) is an axiom, then
\(\mathrm{ax}(G) = \{G\}\), and \(\operatorname{Mod}(\{G\})\) consists by definition of the algebras in which
\(l = r\) holds. If \(G\) is a theorem with proof \(d\), then the kernel checked that \(\mathrm{concl}_\Gamma(d) = (l, r)\)
and set \(\mathrm{ax}(G) = \mathrm{ax}(d)\); the soundness theorem, applied to the sound environment \(\Gamma\),
gives (iii). The last sentence of the corollary: in the environment theory() every \(\mathrm{ax}(G)\) consists
of axioms among H1–H8, so every Boolean algebra belongs to \(\operatorname{Mod}(\mathrm{ax}(G))\). \(\square\)
The corollary says more than “everything the kernel accepts is true in Boolean algebras”. The list
assumptions — our counterpart of the command #print axioms — is reliable: a theorem holds in every
structure in which the axioms on this list hold, even if the others do not. Let us check this on an example.
On the set \(\{0, 1\}\) let \(x + y\) be disjunction, \(n(x)\) negation, and \(x \cdot y = 1\) exactly when \(x = y\)
(equivalence instead of conjunction):
from itertools import product
from boolean import theory_with_theorems
j, proofs = theory_with_theorems()
STRANGE = {"+": lambda a, b: a | b, # disjunction
"*": lambda a, b: int(a == b), # equivalence instead of conjunction
"n": lambda a: 1 - a, # negation
"0": 0, "1": 1}
def value_s(t, v):
"""The value of the term t in STRANGE under the valuation v."""
if isinstance(t, str):
return STRANGE[t] if t in STRANGE else v[t]
return STRANGE[t[0]](*(value_s(u, v) for u in t[1:]))
def holds_s(name):
"""Does the equation of the fact hold in STRANGE under every valuation?"""
variables, l, r = j.facts[name]
for w in product((0, 1), repeat=len(variables)):
v = dict(zip(variables, w))
if value_s(l, v) != value_s(r, v):
return False
return True
for name in j.facts:
status = "holds" if holds_s(name) else "does NOT hold"
print(f"{name:13} {status:13} assumptions: {' '.join(sorted(j.assumptions[name]))}")
H1 holds assumptions: H1
H2 holds assumptions: H2
H3 holds assumptions: H3
H4 does NOT hold assumptions: H4
H5 holds assumptions: H5
H6 holds assumptions: H6
H7 holds assumptions: H7
H8 holds assumptions: H8
add_idem holds assumptions: H3 H5 H6 H7 H8
mul_idem does NOT hold assumptions: H4 H5 H6 H7 H8
add_one holds assumptions: H2 H3 H6 H7
mul_zero does NOT hold assumptions: H1 H4 H5 H8
absorb does NOT hold assumptions: H1 H2 H3 H4 H6 H7
compl_compl holds assumptions: H1 H2 H4 H6 H7 H8
In this algebra all axioms hold except H4. The theorems whose assumption lists do not contain H4 —
add_idem and add_one — hold, just as the corollary promises. Theorems whose proofs use H4 need not
hold: \(x \cdot x = x\) fails already for \(x = 0\), because \(0 \cdot 0 = 1\). The involution holds, although its
proof uses H4 — the corollary promises nothing in this direction.
3.4.1.5. From the algorithm to the program#
The theorem is about the function \(\mathrm{concl}_\Gamma\) from the table. The method conclusion computes exactly
this function under three assumptions about the world in which it runs:
Python and the computer work according to their specifications. Every kernel assumes the same, including Lean’s kernel, which is written in C++.
Only the methods
axiomandtheoremchange the environment. Python does not forbid writingj.facts["falsehood"] = …. In Robin Milner’s LCF system this was guarded by the type system of the ML language: a theorem was a value of an abstract type that only the kernel could create. In Lean only the kernel extends the environment.A term is a plain string or a plain tuple, and
==means “the same term”. The code itself guards this: the methodstermandis_varchecktype(t) is strandtype(t) is tuple.
The proof also shows which checks in the code are indispensable. These are: the comparison of the middles in
Trans (case 3), condition (i) in the method _add (case 5), a new name when adding a fact (old facts do
not change), and the comparison of the conclusion with the announced equation in the method theorem.
The other checks tidy up the input, and the soundness proof would survive without them, albeit with other
lemmas: the number of arguments in Inst (exercise 2), the condition \(z \in V\) in CongrArg (exercise 3),
the well-formedness of terms, and the declaration of all variables of the equation.
3.4.1.6. Two holes the proof exposed#
The first version of the kernel, published together with this lecture, did not check two things that the
proof above needs: the method _add did not check condition (i), and the method term accepted objects of
arbitrary subclasses of the type str. Both holes came to light only when the proof was written out case by
case. Let us recreate the old version as a subclass of the class Kernel and see what it let through:
from kernel import Kernel, ProofError, Refl, Trans, Inst, term_vars
from syntax import equation, show_equation
class OldKernel(Kernel):
"""Two methods of the kernel in the first version (before the fix)."""
def term(self, t): # isinstance, not type(t) is
if isinstance(t, str):
if self.signature.get(t) == 0 or (
t.isidentifier() and t not in self.signature):
return t
elif (isinstance(t, tuple) and t
and self.signature.get(t[0]) == len(t) - 1):
for a in t[1:]:
self.term(a)
return t
raise ProofError(f"not a term: {t!r}")
def _add(self, name, variables, l, r, assumptions): # no condition (i)
if name in self.facts:
raise ProofError(f"name already taken: {name}")
self.term(l), self.term(r)
if not term_vars(l) | term_vars(r) <= set(variables):
raise ProofError(f"{name}: undeclared variable")
self.facts[name] = (tuple(variables), l, r)
self.assumptions[name] = frozenset(assumptions)
def clone(cls):
"""A kernel of the given class with the axioms and theorems of j."""
k = cls(j.signature)
k.facts, k.assumptions = dict(j.facts), dict(j.assumptions)
return k
# hole 1: the constant 0 declared as a variable of the theorem x * 0 = 0
for cls in (OldKernel, Kernel):
k = clone(cls)
try:
k.theorem("bad", ["x", "0"], *equation("x * 0 = 0"),
proofs["mul_zero"])
result = show_equation(k.conclusion(Inst("bad", ("x", "y"))))
print(f"{cls.__name__:11} accepts; Inst('bad', ('x', 'y')) gives {result}")
except ProofError as error:
print(f"{cls.__name__:11} rejects: {error}")
OldKernel accepts; Inst('bad', ('x', 'y')) gives x * y = y
Kernel rejects: bad: ('x', '0') are not all variables
class Joker(str):
"""A string that claims to be equal to everything."""
def __eq__(self, other):
return True
def __ne__(self, other):
return False
__hash__ = str.__hash__
# hole 2: “x = x” and “0 = 0” glued by the rule Trans into “x = 0”
fake = Trans(Refl(Joker("x")), Refl("0"))
for cls in (OldKernel, Kernel):
k = clone(cls)
try:
k.theorem("bad2", ["x"], "x", "0", fake)
print(f"{cls.__name__:11} accepts the theorem x = 0")
except ProofError as error:
print(f"{cls.__name__:11} rejects: {error}")
OldKernel accepts the theorem x = 0
Kernel rejects: not a term: 'x'
The first hole is a genuine logical error. The constant \(0\) declared as a variable of a theorem becomes
a “variable” in the rule Inst, and the true equation \(x \cdot 0 = 0\) turns into the false \(x \cdot y = y\)
(in the algebra \(\{0, 1\}\) it fails for \(x = 0\), \(y = 1\)). In the proof of the theorem this corresponds to
case 5: the dictionary \(\{x \mapsto x,\ 0 \mapsto y\}\) is not a substitution, so Lemma 3 may not be used. The
second hole is an abuse of the programming language: a subclass of str with a lying == fools the
comparison of the middles, that is, case 3. The fix is two conditions in the code: _add now checks that
the list \(\bar x\) consists of variables, and term and is_var accept only plain strings and tuples. The
kernel’s tests (the directory kernel/tests) check both examples.
It is the same with real kernels: to trust a kernel, it is not enough that it “looks right”. Soundness proofs, independent implementations and tests help — and each of these methods catches different errors.
3.4.1.7. The soundness proof checked by Lean#
Is the proof of the soundness theorem itself flawless? The best thing is to hand it over to… a kernel. In the
file KernelSoundness.lean
we rewrote the kernel in Lean 4 (without Mathlib): terms, substitution, the value of a term in an algebra, the
five rules and the function check, the counterpart of the method conclusion. The two main theorems read:
theorem soundness {α : Type} (A : Algebra α) (Γ : Env) (hΓ : Model A Γ)
(d : Proof) {l r : Term} (h : check Γ d = some (l, r)) : Holds A l r
theorem invariant {α : Type} (A : Algebra α) {Ax : Fact → Prop} {Γ₀ Γ : Env}
(hAx : ∀ f, Ax f → Holds A f.lhs f.rhs) (h₀ : Model A Γ₀)
(h : Reachable Ax Γ₀ Γ) : Model A Γ
Here Holds A l r means “\(l = r\) holds in the algebra \(A\)”, Model A Γ — “every fact of the environment
\(\Gamma\) holds in \(A\)”, and Reachable Ax Γ₀ Γ — “the environment \(\Gamma\) arises from \(\Gamma_0\) by adding
axioms satisfying Ax and theorems accepted by check”. A third theorem, relative_soundness, is the
version with the assumption list: it suffices that the facts the proof really uses hold in \(A\). Lean 4.33.1
checked the whole file, and the command #print axioms answers:
'soundness' does not depend on any axioms
'relative_soundness' does not depend on any axioms
'invariant' does not depend on any axioms
In Lean both holes from the previous subsection are impossible by construction. A variable and a constant are
different constructors of the type Term (var "x" and app "0" []), and the comparison of the middles in the
rule Trans yields not just “yes” or “no” but a proof that the terms are equal or a proof that they differ.
The file also shows the kernel at work: #eval check H add_idem prints some (x + x, x), the same
conclusion that the method conclusion computes.
3.4.2. Checking in models#
The soundness theorem is about the function \(\mathrm{concl}_\Gamma\), and the program computes it under assumptions that we cannot prove without a formal semantics of Python. What we can do is test the program. First, a function that searches for a valuation refuting an equation in the algebra of subsets of a \(k\)-element set (we encode subsets as bit masks, as in the first section):
from itertools import product
from kernel import Kernel, ProofError, Refl, Symm, Trans, CongrArg, Inst
from kernel import term_vars
from syntax import term, equation, show, show_equation, size
def value(t, v, k):
"""The value of t in the algebra of subsets of a k-element set."""
full = 2**k - 1
if isinstance(t, str):
return {"0": 0, "1": full}.get(t, v.get(t))
a = [value(u, v, k) for u in t[1:]]
if t[0] == "+":
return a[0] | a[1]
if t[0] == "*":
return a[0] & a[1]
return full & ~a[0]
def counterexample(l, r, k):
"""A valuation under which l = r fails, or None."""
xs = sorted(term_vars(l) | term_vars(r))
for values in product(range(2**k), repeat=len(xs)):
v = dict(zip(xs, values))
if value(l, v, k) != value(r, v, k):
return v
return None
The first test: all facts of the environment, including the six theorems, are true in the algebras of subsets of a \(1\)-, \(2\)-, and \(3\)-element set.
from boolean import theory_with_theorems
j, proofs = theory_with_theorems()
for k in (1, 2, 3):
bad = [name for name, (_, l, r) in j.facts.items()
if counterexample(l, r, k)]
print(f"k = {k}: {len(j.facts)} facts, false: {len(bad)}")
k = 1: 14 facts, false: 0
k = 2: 14 facts, false: 0
k = 3: 14 facts, false: 0
The second test is more interesting. We draw random trees built from the five rules — with random terms,
facts, and contexts — and give them to the kernel. Most random trees are not correct proofs, so the
generator sometimes “helps”: in the rule Trans it chooses the second subtree so that the middle terms
match. Every equation that the kernel accepts must be true in the model.
import random
TERMS = [term(s) for s in ["x", "y", "0", "1", "n(x)", "x + y",
"x * n(y)", "n(x + 1)"]]
CONTEXTS = [("+", "z", "x"), ("n", "z"), ("*", ("n", "z"), "z"),
("+", "y", "1")]
def valid(kernel, d):
try:
kernel.conclusion(d)
return True
except ProofError:
return False
def random_proof(kernel, rng, depth):
"""A random tree of the five rules: often, but not always, valid."""
if depth == 0 or rng.random() < 0.3:
if rng.random() < 0.2:
return Refl(rng.choice(TERMS))
name = rng.choice(list(kernel.facts))
k = len(kernel.facts[name][0])
return Inst(name, tuple(rng.choice(TERMS) for _ in range(k)))
p = random_proof(kernel, rng, depth - 1)
roll = rng.random()
if roll < 0.3:
return Symm(p)
if roll < 0.6:
return CongrArg("z", rng.choice(CONTEXTS), p)
q = random_proof(kernel, rng, depth - 1)
if rng.random() < 0.7 and valid(kernel, p): # match the middles
_, b = kernel.conclusion(p)
q = Trans(Refl(b), q) if rng.random() < 0.5 else Refl(b)
return Trans(p, q)
def random_test(checker, trials=5000, seed=2026):
"""Numbers of accepted and rejected trees, and accepted false equations."""
rng = random.Random(seed)
accepted, rejected, falsehoods = 0, 0, []
for _ in range(trials):
d = random_proof(j, rng, 4)
try:
l, r = checker.conclusion(d)
except ProofError:
rejected += 1
continue
accepted += 1
v = counterexample(l, r, 2)
if v is not None:
falsehoods.append((l, r, v))
return accepted, rejected, falsehoods
accepted, rejected, falsehoods = random_test(j)
print(f"accepted: {accepted}, rejected: {rejected}, "
f"accepted false: {len(falsehoods)}")
accepted: 3241, rejected: 1759, accepted false: 0
None of the accepted equations is false. Can such a test detect anything at all? Let us try it on a kernel
with a deliberately introduced bug: in the rule Trans we forget to compare the middle terms.
class BrokenKernel(Kernel):
"""A kernel with a bug: Trans does not compare the middles."""
def conclusion(self, d):
if isinstance(d, Trans):
a, _ = self.conclusion(d.p)
_, c = self.conclusion(d.q)
return a, c
return super().conclusion(d)
broken = BrokenKernel(j.signature)
broken.facts, broken.assumptions = dict(j.facts), dict(j.assumptions)
accepted_b, rejected_b, falsehoods_b = random_test(broken)
print(f"accepted: {accepted_b}, rejected: {rejected_b}, "
f"accepted false: {len(falsehoods_b)}")
l, r, v = falsehoods_b[0]
print("for example:", show(l), "=", show(r), "under", v)
accepted: 5000, rejected: 0, accepted false: 1219
for example: (x + y) * 1 = x * y + x * y under {'x': 0, 'y': 1}
The test immediately found false “theorems”. Tests do not prove that a program is correct, but they are good at catching implementation bugs — including ones that are not visible when reading the code. It is best to have both: a proof for the algorithm and tests for the program.
3.4.3. What the kernel does not guarantee#
The soundness theorem says: if the kernel has accepted a proof, then the theorem follows from the axioms. That is a great deal, but it is not everything. There are three things that no kernel will check, and each of them can be seen in the story of the proof of the Riemann hypothesis.
Whether the statement means what we think. The kernel checks a proof of the statement it was given. If the parser misreads the text or a definition is wrong, the kernel will check a different statement from the one we have in mind. That is why the five final theorems of the proof of the Riemann hypothesis were compared, with the program Comparator, against the file
Challenge.lean, in which the statements were written down independently of the proof; the first of them has the typeRiemannHypothesisfrom Mathlib (summary of the checks).Whether the axioms are true. The kernel checks logical consequence, not the axioms — we saw this with the axiom
miraclein the second section. That is why the list of axioms is checked: for the proof of the Riemann hypothesis,#print axiomslists only the three standard axioms of Lean,propext,Classical.choice, andQuot.sound.Whether the kernel program, the compiler, and the computer work correctly. There are two remedies for this. The first is a kernel small enough to be read and checked by hand (the de Bruijn criterion). The second is several independent kernels: the proof of the Riemann hypothesis was accepted both by Lean’s kernel and by NanoDA, written separately in Rust, and several people repeated the check on their own computers. For a false proof to get through, all these programs would have to make the same mistake.
Nor does the kernel tell us why the theorem is true. No program can replace that: understanding a proof and reviewing it are still work for people.
3.4.4. Searching versus checking#
The kernel checks the proof it is given; it does not have to find it. Searching is much harder. The file
tactics.py contains a small solver: it searches breadth-first through all terms reachable from both
sides of the equation by single rewrites with the axioms H1–H8 (in both directions), until the two sides
meet. To make the search terminate, it discards terms larger than a given size (the number of nodes of the
term tree). The proof it finds is an ordinary tree of rules, so it is checked by the kernel:
from boolean import theory
from tactics import search
H = [f"H{i}" for i in range(1, 9)]
j0 = theory()
d, examined = search(j0, "x + x = x", H, max_size=8)
print("terms examined:", examined)
print("proof nodes:", size(d))
print("the kernel accepts:", show_equation(j0.conclusion(d)))
terms examined: 135
proof nodes: 17
the kernel accepts: x + x = x
For \(x + x = x\) it was easy. Let us try the involution law \(n(n(x)) = x\), which we proved in the previous section with a chain of nine equalities:
d, examined = search(j0, "n(n(x)) = x", H, max_size=10)
print("proof found:", d is not None, "| terms examined:", examined)
proof found: False | terms examined: 35890
The solver examined all terms with at most ten nodes that can be reached from either side, and found no proof. The reason becomes clear when we measure the terms in our chain:
from tactics import subterms
chain = ["n(n(x))", "n(n(x)) * 1", "n(n(x)) * (x + n(x))",
"n(n(x)) * x + n(n(x)) * n(x)", "n(n(x)) * x + 0",
"n(n(x)) * x + x * n(x)", "x * n(n(x)) + x * n(x)",
"x * (n(n(x)) + n(x))", "x * 1", "x"]
for text in chain:
print(f"{len(list(subterms(term(text)))):3} {text}")
3 n(n(x))
5 n(n(x)) * 1
8 n(n(x)) * (x + n(x))
12 n(n(x)) * x + n(n(x)) * n(x)
7 n(n(x)) * x + 0
10 n(n(x)) * x + x * n(x)
10 x * n(n(x)) + x * n(x)
8 x * (n(n(x)) + n(x))
3 x * 1
1 x
Our proof passes through a term with twelve nodes. With the bound \(10\) the solver therefore could not hit
upon this proof, and with larger bounds the number of terms to examine grows explosively: with the bound \(12\)
the solver finds a proof only after examining 296,766 terms. (For this one has to raise the argument
limit, which by default stops the search after 200,000 terms. A hidden cell checks this result when the
book is built; the computation takes quite long, so we do not show it here.) A person who knows that one has to
“multiply by \(1 = x + n(x)\)” needs nine steps. Searching requires an idea or enormous computing power;
checking requires only a walk through the tree.
3.4.5. The Robbins problem#
The most famous example of this division of roles comes from Boolean algebras themselves. In 1933 Huntington showed that Boolean algebras can be described by three equations for the operations \(+\) and \(n\): commutativity \(x + y = y + x\), associativity \((x + y) + z = x + (y + z)\), and the Huntington equation
Soon afterwards Herbert Robbins asked whether the Huntington equation can be replaced by the simpler Robbins equation
that is, whether every Robbins algebra (commutative and associative \(+\) together with the Robbins equation) is a Boolean algebra. The other direction is easy: both equations hold in every Boolean algebra. Let us check them at least in the algebras of subsets:
for name, text in [
("Huntington", "n(n(x) + y) + n(n(x) + n(y)) = x"),
("Robbins", "n(n(x + y) + n(x + n(y))) = x")]:
l, r = equation(text)
result = [counterexample(l, r, k) is None for k in (1, 2, 3)]
print(f"{name:10} true for k = 1, 2, 3: {result}")
Huntington true for k = 1, 2, 3: [True, True, True]
Robbins true for k = 1, 2, 3: [True, True, True]
The hard part was the converse implication. Robbins’s question remained open for more than sixty years. It was settled by the program EQP, an automated theorem prover from Argonne National Laboratory written by William McCune (description of the solution):
on October 10, 1996, EQP found a proof that every Robbins algebra satisfies the so-called second Winker condition: there exist \(C\) and \(D\) such that \(n(C + D) = n(C)\); by an earlier lemma of Winker, it follows that every Robbins algebra is a Boolean algebra;
the successful search took about 8 days on an RS/6000 processor and used about 30 MB of memory;
EQP could not output the proof as an object that can be checked independently. Its proof therefore served as a hint for another of McCune’s programs, Otter, which built a proof of the same theorem in the form of a proof object, and this object was checked by a separate checking program;
the result was published in the article W. McCune, Solution of the Robbins Problem, Journal of Automated Reasoning 19(3), 263–276 (1997).
Later the proof was formalized in the proof assistant Isabelle: M. Wampler-Doty, A Complete Proof of the Robbins Conjecture, Archive of Formal Proofs (2010), based on a version of the proof prepared by A. Mann (2003).
This is the same pattern as in our small example and in the proof of the Riemann hypothesis. The proof is produced with the help of a large, clever program that we do not have to trust: EQP searched for eight days, and the proof of the Riemann hypothesis was written with the help of the Claude system. It is checked by a small program that we trust because it can be read and because independent programs arrived at the same result.
3.4.6. Further#
Our kernel is deliberately minimal. The topics announced on the slides marked 🤿 — the Robbins problem in detail, bound variables and de Bruijn indices, completeness and truth tables, associativity from Huntington’s axioms, and real kernels — are discussed in the deep-dive section.
3.4.7. Summary#
The soundness theorem: in a sound environment every conclusion of the kernel holds in every algebra in which the axioms on the proof’s assumption list hold. The proof is an induction on the tree, one case per rule, based on the substitution lemma; the environment invariant is proved by induction on the successive calls to
axiomandtheorem.The list
assumptions(like#print axioms) is reliable: in an algebra in which only H4 fails, every theorem whose assumption list does not contain H4 holds.A careful proof exposed two holes in the first version of the kernel: a constant declared as a variable, and a subclass of
strwith a lying==. Two additional conditions in the code removed both.The proof is about the algorithm; we check the program with tests. Random trees and models quickly detect a bug, e.g., a missing comparison of the middle terms in the rule
Trans.The kernel does not check whether a statement means what we think, whether the axioms are true, or whether it works correctly itself. What helps: an independent formulation of the statements, the list of axioms, small kernels, and several independent kernels.
Searching for a proof is hard; checking it is easy. The Robbins problem was solved in 1996 by the program EQP, and its proof was checked independently; the roles were divided in the same way in the proof of the Riemann hypothesis.
3.4.8. Exercises#
★ Deduce from the soundness theorem that the kernel will not accept any proof of the equation \(x \cdot y = x + y\). Which valuation in the algebra \(\{0, 1\}\) shows this?
★★ Remove the check of the number of arguments from the rule
Inst(in a subclass of the classKernel). Can such a kernel accept a false equation? Justify your answer by going through the proof of the soundness theorem once more. Then check it by an experiment: the random proof generator from this section always passes the right number of arguments, so change it to sometimes pass one argument too few or too many.★★ Remove the condition \(z \in V\) from the rule
CongrArg, so that a constant, e.g. \(0\), can also serve as the “hole”. Prove that the kernel remains sound: state and prove a counterpart of Lemma 2 for replacing all occurrences of a constant. Why does the same idea fail for the ruleInst?★★ Write a program that finds all algebras on the set \(\{0, 1\}\) (arbitrary tables of the operations \(+\), \(\cdot\), \(n\) and arbitrary values of the constants) in which the axioms H3, H5, H6, H7 and H8 hold. Check the theorem
add_idemin each of them and compare the result with its assumption list.★★ Run the solver on the equations \(x \cdot x = x\), \(x + 1 = 1\), and \(x + x \cdot y = x\) with an increasing size bound
max_sizeand record the numbers of examined terms. What is the smallest bound at which the solver finds a proof of \(x + 1 = 1\)? Compare the length of the proof found with the proof from the fileboolean.py.★★ Add the theorem
add_oneto the list of facts that the solver uses, and repeat exercise 5 for \(x + x \cdot y = x\). How does a library of theorems change the search?★★★ Prove in our kernel the uniqueness of the complement in a version “for concrete terms”: if for terms \(a\), \(b\) you have proofs of \(a + b = 1\) and \(a \cdot b = 0\), build a proof of \(b = n(a)\). Write a function that takes these two proofs and returns a proof of \(b = n(a)\). Why can this not be stated as a single theorem in our logic?