About this notebook

Companion to Lecture 10: Verifying systems. Every cell below was executed against the course’s pinned Lean 4 + Mathlib (see lean/lean-toolchain); each Lean result is exactly what Lean printed. Download the notebook (.ipynb)

Lecture 10 proves facts about fixed-width words with bv_decide and proves a safety property of a small protocol with an inductive invariant. This notebook runs both and compares them with what a Python test can tell you. You will:

  1. compute with 8-bit and 64-bit words and see them overflow;
  2. prove two bit tricks for all words and audit what the proofs trust;
  3. give bv_decide a false identity and check its counterexample;
  4. test the same identities by brute force in Python, and see what a test with the wrong model of the machine “proves”;
  5. explore the mutex protocol of the lecture in Python, then prove its invariant in Lean.
import leanmagic
 
leanmagic.setup("import Std.Tactic.BVDecide")
Lean 4.35.0 ready; header `import Std.Tactic.BVDecide` elaborated.

bv_decide ships with Lean, in the Std library, so the header needs no Mathlib.

1. Words of fixed width

BitVec w holds w bits, and its arithmetic wraps around modulo . The literal 255#8 is 255 as an 8-bit word. Without Mathlib, Lean prints words in hexadecimal.

#eval 255#8 + 1#8
#eval (0b10110100#8).toNat
#eval 0b10110100#8 &&& (0b10110100#8 - 1)
#eval 0b10110100#8 &&& -0b10110100#8

✓ Lean accepted this

0x00#8
180
0xb0#8
0x04#8

The first line overflows to zero. 0b10110100 is 180, and the next two lines are the bit tricks of the lecture: x &&& (x - 1) clears the lowest set bit (0xb0 is 1011 0000), and x &&& -x keeps only that bit (0x04 is 0000 0100).

2. Proofs for every 64-bit word

theorem clear_lowest (x : BitVec 64) : x &&& (x - 1) = x - (x &&& -x) := by
  bv_decide
 
theorem and_plus_or (x y : BitVec 64) : (x &&& y) + (x ||| y) = x + y := by
  bv_decide
 
#print axioms clear_lowest

✓ Lean accepted this

'clear_lowest' depends on axioms: [propext, Classical.choice, Quot.sound, clear_lowest._native.bv_decide.ax_1]

The second theorem holds because, bit by bit, and and or together contain each 1 of x and y exactly once. The audit shows three standard axioms and one more, named after the theorem. That extra axiom records that the certificate checker, run as compiled code, accepted the SAT solver’s certificate: the trust in Lean’s compiler that the lecture describes.

3. A false identity

The average of two words, computed the obvious way, against the exact average computed in one more bit:

This cell is meant to fail:

theorem avg_naive (x y : BitVec 8) :
    (x + y) >>> 1 = ((x.setWidth 9 + y.setWidth 9) >>> 1).setWidth 8 := by
  bv_decide

✗ rejected, as intended

error, line 3The prover found a counterexample, consider the following assignment:
x = 255#8
y = 255#8

bv_decide reports an assignment for x and y that breaks the claim. Do not take it on trust; evaluate both sides at those values:

#eval (255#8 + 255#8) >>> 1
#eval ((255#8).setWidth 9 + (255#8).setWidth 9) >>> 1

✓ Lean accepted this

0x7f#8
0x0ff#9

The left side is 0x7f (127): the sum 510 wrapped to 254 before the shift. The right side, in 9 bits, is 255. The repair from the lecture needs lo ≤ hi:

theorem mid_ok (lo hi : BitVec 64) (h : lo ≤ hi) :
    lo + ((hi - lo) >>> 1) =
      ((lo.setWidth 65 + hi.setWidth 65) >>> 1).setWidth 64 := by
  bv_decide

✓ Lean accepted this (no messages)

4. The same questions, by brute force

An 8-bit identity in one variable has 256 cases and one in two variables has 65,536, so a Python loop can try them all. Python integers never overflow, so the test must model the machine by masking every result to 8 bits.

MASK = 0xFF
 
 
def clear_lowest_8(x):
    return (x & ((x - 1) & MASK)) == ((x - (x & (-x & MASK))) & MASK)
 
 
def avg_naive_8(x, y):
    return (((x + y) & MASK) >> 1) == ((x + y) >> 1)
 
 
print("clear_lowest, 8 bits:",
      sum(not clear_lowest_8(x) for x in range(256)), "failures of 256")
fails = [(x, y) for x in range(256) for y in range(256) if not avg_naive_8(x, y)]
print("naive average, 8 bits:", len(fails), "failures of 65536; first:", fails[0])
clear_lowest, 8 bits: 0 failures of 256
naive average, 8 bits: 32640 failures of 65536; first: (1, 255)

The loop agrees with Lean at 8 bits. Where does the naive average fail? Plot every failing pair.

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
 
grid = [[0 if avg_naive_8(x, y) else 1 for x in range(256)] for y in range(256)]
fig, ax = plt.subplots(figsize=(4.6, 4.2))
ax.imshow(grid, origin="lower", cmap=ListedColormap(["#2c7d54", "#b5523b"]),
          extent=(0, 256, 0, 256))
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("naive average: correct (green), wrong (red)", fontsize=10)
ax.text(80, 80, "x + y < 256", color="white", ha="center", va="center", fontsize=11)
ax.text(176, 176, "x + y ≥ 256", color="white", ha="center", va="center", fontsize=11)
ax.set_xticks([0, 64, 128, 192, 256])
ax.set_yticks([0, 64, 128, 192, 256])
plt.tight_layout()
plt.show()
Pairs of 8-bit words where the naive average (x + y) >>> 1 is wrong: exactly the pairs whose sum is at least 256, so the true sum does not fit in 8 bits.

Pairs of 8-bit words where the naive average (x + y) >>> 1 is wrong: exactly the pairs whose sum is at least 256, so the true sum does not fit in 8 bits.

The wrong pairs are exactly those with : the triangle above the diagonal . Now drop the mask, as a hasty test might:

def avg_naive_unmasked(x, y):
    return ((x + y) >> 1) == ((x + y) >> 1)
 
 
print("naive average, no mask:",
      sum(not avg_naive_unmasked(x, y) for x in range(256) for y in range(256)),
      "failures of 65536")
naive average, no mask: 0 failures of 65536

Zero failures, and the test is worthless: without the mask, both sides compute the same Python expression. A test is only as good as its model of the machine. In Lean the model is BitVec 8, defined once in the library, and bv_decide reasons about that definition.

What each method establishes:

                     what it covers                    what you trust
  Python, 8 bits     all 2^8 or 2^16 cases             your Python model of the machine
  Python, 64 bits    not feasible: 2^64 or 2^128       (nothing finishes)
  bv_decide, 64 bits every value of BitVec 64          Lean's kernel, Lean's compiler
                                                       (one auxiliary axiom per proof)

At cases per second, cases take about 585 years:

print(f"2^64 / 1e9 per second = {2**64 / 1e9 / (3600 * 24 * 365):.0f} years")
2^64 / 1e9 per second = 585 years

5. A protocol and its invariant

The mutex of the lecture has two processes, each idle, wait or crit, and a lock bit: states. A state is a tuple (a, b, lock). Python can list every state reachable from the start by breadth-first search. This is what a model checker does, and it works because the state space is finite.

from collections import deque
 
PCS = ("idle", "wait", "crit")
 
 
def steps(state):
    a, b, lock = state
    out = []
    if a == "idle":
        out.append(("wait", b, lock))
    if a == "wait" and not lock:
        out.append(("crit", b, True))
    if a == "crit":
        out.append(("idle", b, False))
    if b == "idle":
        out.append((a, "wait", lock))
    if b == "wait" and not lock:
        out.append((a, "crit", True))
    if b == "crit":
        out.append((a, "idle", False))
    return out
 
 
def safe(s):
    return not (s[0] == "crit" and s[1] == "crit")
 
 
def inv(s):
    a, b, lock = s
    return safe(s) and (a != "crit" or lock) and (b != "crit" or lock)
 
 
start = ("idle", "idle", False)
reachable, todo = {start}, deque([start])
while todo:
    for t in steps(todo.popleft()):
        if t not in reachable:
            reachable.add(t)
            todo.append(t)
 
states = [(a, b, l) for a in PCS for b in PCS for l in (False, True)]
print("all states:      ", len(states))
print("safe states:     ", sum(safe(s) for s in states))
print("invariant states:", sum(inv(s) for s in states))
print("reachable states:", len(reachable))
print("every reachable state satisfies the invariant:",
      all(inv(s) for s in reachable))
all states:       18
safe states:      16
invariant states: 12
reachable states: 8
every reachable state satisfies the invariant: True

The three sets are nested: reachable inside invariant inside safe.

  ┌─ all states (18) ────────────────────────────────────────┐
  │  ┌─ safe (16) ────────────────────────────────────────┐  │
  │  │  ┌─ invariant (12) ─────────────────────────────┐  │  │
  │  │  │  ┌─ reachable (8) ───────────────────────┐   │  │  │
  │  │  │  │  start = (idle, idle, False)  ...     │   │  │  │
  │  │  │  └───────────────────────────────────────┘   │  │  │
  │  │  └──────────────────────────────────────────────┘  │  │
  │  │   e.g. (crit, wait, False): safe, not invariant    │  │
  │  └────────────────────────────────────────────────────┘  │
  │   (crit, crit, _): unsafe                                │
  └──────────────────────────────────────────────────────────┘

“Inductive” means no step leaves the set. Check it for both predicates over all 18 states, reachable or not:

def escapes(pred):
    return [(s, t) for s in states if pred(s) for t in steps(s) if not pred(t)]
 
 
print("steps that leave the invariant:", escapes(inv))
print("steps that leave Safe:", escapes(safe))
steps that leave the invariant: []
steps that leave Safe: [(('wait', 'crit', False), ('crit', 'crit', True)), (('crit', 'wait', False), ('crit', 'crit', True))]

The invariant is closed under steps; Safe is not, and the escaping steps start in the unreachable states such as (crit, wait, False) that the lecture showed. Python can do this because there are 18 states. The Lean proof below does not enumerate states: cases splits on the six actions, and in each the other process’s state stays a variable. That is why the same proof style scales to systems with unbounded state.

inductive PC where
  | idle | wait | crit
  deriving DecidableEq, Repr
 
structure MState where
  a : PC
  b : PC
  lock : Bool
  deriving DecidableEq, Repr
 
inductive Step : MState → MState → Prop
  | requestA (b : PC) (l : Bool) : Step ⟨.idle, b, l⟩ ⟨.wait, b, l⟩
  | enterA (b : PC) : Step ⟨.wait, b, false⟩ ⟨.crit, b, true⟩
  | leaveA (b : PC) (l : Bool) : Step ⟨.crit, b, l⟩ ⟨.idle, b, false⟩
  | requestB (a : PC) (l : Bool) : Step ⟨a, .idle, l⟩ ⟨a, .wait, l⟩
  | enterB (a : PC) : Step ⟨a, .wait, false⟩ ⟨a, .crit, true⟩
  | leaveB (a : PC) (l : Bool) : Step ⟨a, .crit, l⟩ ⟨a, .idle, false⟩
 
def start : MState := ⟨.idle, .idle, false⟩
 
inductive Reachable : MState → Prop
  | start : Reachable start
  | step {s t : MState} : Reachable s → Step s t → Reachable t
 
def Safe (s : MState) : Prop := ¬ (s.a = .crit ∧ s.b = .crit)
 
def MutexInv (s : MState) : Prop :=
  Safe s ∧ (s.a = .crit → s.lock = true) ∧ (s.b = .crit → s.lock = true)
 
theorem inv_step {s t : MState} (h : MutexInv s) (hs : Step s t) :
    MutexInv t := by
  cases hs <;> simp_all [MutexInv, Safe]
 
theorem mutual_exclusion {s : MState} (h : Reachable s) : Safe s := by
  have hinv : MutexInv s := by
    induction h with
    | start => simp [MutexInv, Safe, start]
    | step _ hst ih => exact inv_step ih hst
  exact hinv.1
 
#print axioms mutual_exclusion

✓ Lean accepted this

'mutual_exclusion' depends on axioms: [propext]

Now watch the induction fail with the weaker predicate. The step case needs Safe to be preserved by every step, and simp_all is left with the case it cannot close:

This cell is meant to fail:

theorem safe_step {s t : MState} (h : Safe s) (hs : Step s t) : Safe t := by
  cases hs <;> simp_all [Safe]

✗ rejected, as intended

error, line 1unsolved goals
case enterA
b✝ : PC
⊢ ¬b✝ = PC.crit
 
case enterB
a✝ : PC
⊢ ¬a✝ = PC.crit

The unsolved goals are the two enter actions: entering is unsafe when the other process is already in its critical section, and Safe alone does not say that the lock is then taken. These are the escaping steps that Python listed above.

Try this

  • Prove that x &&& -x has at most one bit set: clearing its lowest set bit gives 0.
  • Change steps in Python so that a process enters without checking the lock. How many states become reachable, and which unsafe one is reached first?
  • Prove x * 2 = x <<< 1 for BitVec 64 with bv_decide. Then ask it whether x * 2 / 2 = x, and explain the counterexample.
  • Add a third process to the Python model. Count the states, then write the Lean invariant for three processes.