Part I · Executable Specifications Ch 01 · 25 min · ProveIt/Ch01.lean

Silent Truncation Bug

Why natural-number subtraction breaks an AI-written rate limiter—and how Lean's kernel catches what 10,000 unit tests miss.

5-Line Production Bug · AI Rate-Limiter Quota Check
def remainingQuota (limit used : Nat) : Nat := limit - used
def allowRequest (limit used cost : Nat) : Bool :=
  remainingQuota limit (used + cost) > 0
-- Suppose limit = 10, used = 12, cost = 1.
-- Now a refund subtracts 5 from (limit - used): (10 - 12) + 5 = ??
Socratic Gate · Commit to a Prediction Unanswered · Locks on commit

In Lean 4, `limit` and `used` have type `Nat` (natural numbers ≥ 0). What does `(10 : Nat) - 12 + 5` evaluate to?

Why Tests Miss Truncation—and Equations Catch It

Ask an AI coding assistant for a token-bucket rate limiter and a test suite, and both files will look clean. The tests pass limit = 100, used = 40 and limit = 100, used = 100. Because the same model wrote both implementation and tests, neither asks what happens after an administrative quota reduction lowers limit below used.

In Lean 4, every function must return a valid value of its return type for every possible input—a design guarantee we call a total function (earned here because there are no exceptions, null pointers, or undefined traps to hide behind). Making Nat - Nat : Nat total forces 0 - 1 = 0, known as saturating subtraction.

Instead of hoping callers remember used ≤ limit, we have two honest engineering options: use signed integers (Int), or return Option Nat (some remaining vs none) so failure is explicit in the return type and prove conservation across all valid withdrawals.

Your First Two Proof Tools: `rfl` and `omega`

When both sides of an equation compute to the exact same value—such as #guard (10 : Nat) - 12 = 0 or withdraw 10 4 = some 6—Lean closes the proof by computation (rfl, short for reflexivity).

When your claim universally quantifies over every limit used : Nat—infinitely many inputs—computation on concrete constants is no longer enough. Lean's linear integer/natural solver omega checks whether the arithmetic equation holds across all non-negative integers, and immediately flags missing bounds like used ≤ limit.

⊢ ProveIt/Ch01.lean · Guarded Quota Conservation
Step 1 / 1
Lean Infoview Open Goal
Hands-On Exercise (ProveIt/Ch01.lean):

In `ProveIt/Ch01.lean`, replace the buggy `Nat` rate-limiter helper with an `Option`-returning function and prove both non-underflow and quota conservation.

Finished the Socratic gate, Infoview trace, and playground run?
Record completion in local browser storage to track your 20-unit progress.