Suppose a single order asks for 3 keyboards and 3 cables. If keyboards are plentiful but only 2 cables remain, rejecting the order must leave all 3 keyboards available for someone else to reserve. If a system mutated stock in place after each line item succeeded, rejecting the second item would mean putting back the keyboards reserved for the first.
In this tutorial, we evaluate a batch of reservation requests sequentially and emit the updated inventory only when every item in the batch succeeds. Even when a batch succeeds, there are numbers to verify: we will prove theorems showing that reserving keyboards never touches cable stock and that multiple requests for the same SKU deduct the exact combined total.
1. Separating Inventory Logic from the Executable
We build the project with Lake from Part 7. Create a new working directory containing four files: lean-toolchain, lakefile.toml, StockDemo.lean, and Main.lean. Append the StockDemo.lean code blocks from Sections 2 through 4 into a single StockDemo.lean file in the order they appear.
lean-toolchain
leanprover/lean4:v4.36.0lakefile.toml
name = "stock_demo"
version = "0.1.0"
defaultTargets = ["stock_demo"]
[[lean_lib]]
name = "StockDemo"
[[lean_exe]]
name = "stock_demo"
root = "Main"We keep all inventory calculations and proofs inside StockDemo and push terminal parsing and printing into Main.lean in Section 5. Because the core rules are pure, verifying them needs neither a terminal nor an external database.1
2. Moving One SKU’s Available Stock into Reserved Stock
Given a product identifier Sku, looking up its stock returns a pair of natural numbers (Nat): available quantity and reserved quantity. Here Inventory is simply a function that maps each Sku to that pair, and put constructs a new function rather than mutating existing state in place, returning the updated pair only when queried for the target SKU.
SKU stands for stock keeping unit, an identifier used to distinguish products in inventory. Here a Sku is either a keyboard or a cable, and a Slot holds both counts for that product. abbrev Inventory := Sku → Slot gives this function type a shorter name. That's why a lookup looks like a call: stock r.sku.
If is the available quantity, is the already-reserved quantity, and is the newly requested quantity, we can form only when . Because natural-number subtraction in Lean clamps at 0 even when stock is insufficient, checking before subtracting is essential to prevent an out-of-stock request from silently succeeding.2
Below is the beginning of StockDemo.lean. We derive DecidableEq so Lean can test whether two SKUs are equal, and on failure we return structured data recording which SKU failed and how many units were available at that moment.
import Std loads the standard library shipped with Lean. In Except Rejection Inventory, Except is a type with two possible cases: .ok carries the updated stock, and .error carries a Rejection explaining why the operation failed. In the next section, Except Rejection Unit leaves the inventory in the other component of the result and uses .ok () to report success without an additional value.
import Std
inductive Sku where
| keyboard
| cable
deriving DecidableEq, Repr
structure Slot where
available : Nat
reserved : Nat
deriving Repr
abbrev Inventory := Sku → Slot
structure Request where
sku : Sku
units : Nat
inductive Rejection where
| zeroUnits (sku : Sku)
| shortage (sku : Sku) (requested available : Nat)
deriving Repr
def put (stock : Inventory) (key : Sku) (next : Slot) : Inventory :=
fun sku => if sku = key then next else stock sku
def reserveOne (stock : Inventory) (r : Request) : Except Rejection Inventory :=
if r.units = 0 then
.error (.zeroUnits r.sku)
else
let slot := stock r.sku
if r.units ≤ slot.available then
.ok (put stock r.sku {
available := slot.available - r.units
reserved := slot.reserved + r.units
})
else
.error (.shortage r.sku r.units slot.available)3. Returning the Original Inventory When the Batch Fails
Each time a step succeeds, reserveAll threads the updated inventory into the next request. If an order asks for 4 keyboards followed by 2 keyboards, the second request is checked against the remaining 1 unit rather than the initial 5. As soon as any step fails, reserveAll returns that rejection reason immediately, and any intermediate inventory computed along the way is discarded by submit.
The batch entry point submit returns both the resulting inventory state and the success/error outcome together. Writing for the starting inventory and for the request list gives our rollback contract on failure:
Instead of issuing compensating undo commands to a mutable store, submit computes the candidate state purely and selects it only if the entire list succeeds. Append the code below to StockDemo.lean.3
def reserveAll (stock : Inventory) : List Request → Except Rejection Inventory
| [] => .ok stock
| r :: rest =>
match reserveOne stock r with
| .error reason => .error reason
| .ok next => reserveAll next rest
def submit (before : Inventory) (requests : List Request) :
Inventory × Except Rejection Unit :=
match reserveAll before requests with
| .ok after => (after, .ok ())
| .error reason => (before, .error reason)4. Auditing Successful Reservations per SKU
If we only checked that ‘available + reserved stays constant,’ a dummy function that never moved a single unit from available to reserved would also pass! That is why Moved separately tallies the total demand requested for a specific SKU across the request list .
In the formula below, the sigma symbol means “sum in order from the first request () through the -th request,” and the bold numeral (an indicator function) acts as a switch that equals when the -th request targets SKU and for any other SKU. Scanning down the order, we add the requested units whenever the SKU matches and skip non-matching lines via .
Take the first sample order from Section 5, keyboard:3 cable:2 keyboard:2: the first and third requests ask for keyboards (3 and 2 units), while the second asks for cables (0 toward the keyboard total), giving .
Let be the starting available and reserved quantities for SKU , and be the quantities after completion. Every successful batch must satisfy both equations below for every SKU :
The proof code below introduces four tactics that appear constantly in real-world verification. First, by_cases cond splits a proof into two branches, one where the condition holds and one where it does not, while cases h unpacks an equality hypothesis such as Except.ok before = Except.ok after to conclude that the values before and after inside the boxes are identical.
Next, obtain ⟨a1, r1⟩ := ... destructures a conjunction (‘and’, ∧) into two separate equality hypotheses a1 (available stock) and r1 (reserved stock) in one shot, and omega is an arithmetic decision procedure that automatically solves linear equations and inequalities over natural numbers and integers like a system of school algebra equations.
In reserveAll_moved, we write induction requests generalizing before because after the first request succeeds, the starting inventory changes from before to an intermediate inventory mid, so our induction hypothesis must hold for *any* starting inventory before we can instantiate it at mid.
When you see at h, the tactic is working on hypothesis h. In the zero-quantity branch, reserveOne returns .error, so simplifying the hypothesis that it succeeded exposes a contradiction. simp only [...] limits this step to the rules in the brackets.
In the success branch, have next : ... := by names a smaller proof: the rest of the order also succeeds. simpa [reserveAll, step] using h simplifies both the original success hypothesis h and the new goal with the same rules so that h supplies the evidence for next. We then pass that evidence to the induction hypothesis ih.
def unitsFor (sku : Sku) (r : Request) : Nat :=
if sku = r.sku then r.units else 0
def demand (sku : Sku) : List Request → Nat
| [] => 0
| r :: rest => unitsFor sku r + demand sku rest
def Moved (before after : Inventory) (requests : List Request) : Prop :=
∀ sku : Sku,
(after sku).available + demand sku requests = (before sku).available ∧
(after sku).reserved = (before sku).reserved + demand sku requests
theorem reserveOne_moved {before after : Inventory} {r : Request}
(h : reserveOne before r = .ok after) : Moved before after [r] := by
by_cases zero : r.units = 0
· simp [reserveOne, zero] at h
· by_cases fits : r.units ≤ (before r.sku).available
· simp only [reserveOne, ite_eq_right zero, ite_eq_left fits] at h
cases h
intro sku
by_cases same : sku = r.sku
· subst sku
simp [put, demand, unitsFor, Nat.sub_add_cancel fits]
· simp [put, demand, unitsFor, same]
· simp [reserveOne, zero, fits] at h
theorem reserveAll_moved {before after : Inventory} {requests : List Request}
(h : reserveAll before requests = .ok after) : Moved before after requests := by
induction requests generalizing before with
| nil =>
change Except.ok before = Except.ok after at h
cases h
intro sku
simp [demand]
| cons r rest ih =>
cases step : reserveOne before r with
| error reason => simp [reserveAll, step] at h
| ok mid =>
have next : reserveAll mid rest = .ok after := by
simpa [reserveAll, step] using h
intro sku
obtain ⟨a1, r1⟩ := reserveOne_moved step sku
obtain ⟨a2, r2⟩ := ih next sku
simp [demand] at a1 r1 ⊢
exact ⟨by omega, by omega⟩
theorem reserveAll_conserves {before after : Inventory} {requests : List Request}
(h : reserveAll before requests = .ok after) (sku : Sku) :
(after sku).available + (after sku).reserved =
(before sku).available + (before sku).reserved := by
obtain ⟨available, reserved⟩ := reserveAll_moved h sku
omegaCombining from the first equation with from the second cancels on both sides and immediately yields (total stock conservation before and after), which is exactly what reserveAll_conserves proves.
On top of that, we also prove the completeness direction: whenever every request asks for a positive quantity () and the total demand per SKU does not exceed the initial available stock (), there necessarily exists a resulting inventory for which the batch succeeds (, where the backward-E symbol reads “there exists at least one value satisfying the condition”).
Without this theorem, a broken implementation that unconditionally rejected every order with .error would vacuously pass the first two theorems!4
Processing the first request deducts its requested units from that SKU’s available stock. Because those same units are no longer part of the remaining demand either, the updated inventory still has enough available stock for the rest of the order. In the proof below, restEnough establishes that inequality and omega discharges the arithmetic. Append these final completeness and rollback theorems to StockDemo.lean.
∀ r ∈ requests says the claim holds for each request r in the list. have fits names a proof that the first request fits in the stock, while let mid names the actual inventory value after that request. The proof for the tail uses mid as its starting inventory.
theorem reserveAll_succeeds {before : Inventory} {requests : List Request}
(positive : ∀ r ∈ requests, r.units ≠ 0)
(enough : ∀ sku, demand sku requests ≤ (before sku).available) :
∃ after, reserveAll before requests = .ok after := by
induction requests generalizing before with
| nil => exact ⟨before, rfl⟩
| cons r rest ih =>
have nonzero : r.units ≠ 0 := positive r (by simp)
have fits : r.units ≤ (before r.sku).available := by
have total := enough r.sku
simp [demand, unitsFor] at total
omega
let mid := put before r.sku {
available := (before r.sku).available - r.units
reserved := (before r.sku).reserved + r.units
}
have step : reserveOne before r = .ok mid := by
simp [reserveOne, nonzero, fits, mid]
have restPositive : ∀ q ∈ rest, q.units ≠ 0 := by
intro q inRest
exact positive q (List.mem_cons_of_mem r inRest)
have restEnough : ∀ sku, demand sku rest ≤ (mid sku).available := by
intro sku
have total := enough sku
have moved := (reserveOne_moved step sku).1
simp [demand] at total moved
omega
obtain ⟨after, done⟩ := ih restPositive restEnough
exact ⟨after, by simp [reserveAll, step, done]⟩
theorem submit_rollback {before : Inventory} {requests : List Request}
{reason : Rejection} (h : reserveAll before requests = .error reason) :
submit before requests = (before, .error reason) := by
simp [submit, h]5. Observing Mid-Batch Rejection in the Executable
Main.lean accepts command-line arguments formatted as keyboard:3 with a colon separating the SKU name and quantity. It first parses the strings into a list of requests, exiting with an input error if a quantity is not a natural number or a SKU name is unknown, while a well-formed cable:0 argument is rejected by our core domain rules, cleanly separating parse failures from business-rule rejections. Save the code below as Main.lean.5
args.mapM parseRequest reads the arguments in order, applying parseRequest to each string. It collects the requests in .ok if all the parses succeed, or stops at the first .error. Only the completed list goes to submit, so you can follow parsing and stock calculation separately.
import StockDemo
def skuName : Sku → String
| .keyboard => "keyboard"
| .cable => "cable"
def parseSku : String → Option Sku
| "keyboard" => some .keyboard
| "cable" => some .cable
| _ => none
def parseRequest (arg : String) : Except String Request :=
match arg.splitOn ":" with
| [name, amount] =>
match parseSku name, amount.toNat? with
| none, _ => .error s!"unknown SKU: {name}"
| some _, none => .error s!"expected a natural number: {amount}"
| some sku, some units => .ok { sku, units }
| _ => .error s!"expected sku:units: {arg}"
def initial : Inventory
| .keyboard => { available := 5, reserved := 1 }
| .cable => { available := 2, reserved := 1 }
def showStock (stock : Inventory) : IO Unit := do
for sku in [Sku.keyboard, Sku.cable] do
let slot := stock sku
IO.println s!"{skuName sku}: available={slot.available}, reserved={slot.reserved}"
def showReason : Rejection → String
| .zeroUnits sku => s!"{skuName sku}: quantity must be positive"
| .shortage sku requested available =>
s!"{skuName sku}: wanted {requested}, available {available}"
def main (args : List String) : IO UInt32 := do
if args.isEmpty then
IO.eprintln "usage: stock_demo sku:units ..."
return 2
match args.mapM parseRequest with
| .error message =>
IO.eprintln message
return 2
| .ok requests =>
let (stock, result) := submit initial requests
match result with
| .ok () =>
IO.println "committed"
showStock stock
return 0
| .error reason =>
IO.println s!"rejected: {showReason reason}"
showStock stock
return 1Build the project in your working folder and run a batch that reserves the exact remaining stock:
lake build
lake exe stock_demo keyboard:3 cable:2 keyboard:2Output:
committed
keyboard: available=0, reserved=6
cable: available=0, reserved=3Next, request 3 keyboards followed by more cables than are available:
lake exe stock_demo keyboard:3 cable:3Output:
rejected: cable: wanted 3, available 2
keyboard: available=5, reserved=1
cable: available=2, reserved=1To check the exit code, run echo $? in Bash or read $LASTEXITCODE in PowerShell right after the command. A committed batch returns 0, a rejected reservation returns 1, and missing or invalid input returns 2.
Compare the numbers in both outputs against the initial stock (keyboards: 5 available, 1 reserved; cables: 2 available, 1 reserved). In the first run, keyboard:3 cable:2 keyboard:2 requests 3 + 2 = 5 keyboards across two arguments and 2 cables, bringing available stock to 5 - 5 = 0 and 2 - 2 = 0 while adding the requested quantities to the existing 1 reserved unit to print 1 + 5 = 6 and 1 + 2 = 3 under committed (exit code 0).
In the second run, keyboard:3 cable:3, the first request keyboard:3 fits within the 5 available keyboards on its own, but the second request cable:3 exceeds the 2 available cables; the program prints rejected: cable: wanted 3, available 2 (exit code 1) and cleanly discards the earlier 3-keyboard deduction so keyboard stock remains available=5, reserved=1!
To test cumulative deductions on the same SKU, run lake exe stock_demo keyboard:4 keyboard:2: after deducting 4 keyboards on the first item, only 1 available unit remains in the intermediate state, so the second item is rejected with wanted 2, available 1 and the final output preserves the pre-order stock of 5 keyboards.
Footnotes
- Lean Language Reference 4.36.0. Lake: Configuration File Format · Lake: Building and Running. Explains configuring library and executable targets with
lean_libandlean_exe. ↩ - Lean Language Reference 4.36.0. Natural Numbers: Arithmetic (`Nat.sub`) · Varieties of Monads: Exception Monads. Explains truncation at 0 in
Nat.suband theokanderrorconstructors ofExcept. ↩ - Lean Language Reference 4.36.0. Recursive Definitions: Structural Recursion. Explains why recursing on the tail of the request list is accepted as terminating. ↩
- Lean Language Reference 4.36.0. Tactic Reference: Eliminating Inductive Types · Tactic Reference: Decision Procedures. Covers generalizing variables in induction hypotheses with
generalizingand solving linear natural-number arithmetic withomega. ↩ - Lean Language Reference 4.36.0. Linked Lists: Iteration · IO. Shows left-to-right monadic traversal with
List.mapMand printing results at theIOboundary. ↩