Skip to content

From design to code

A trading desk holds 80 shares of a stock and may never hold more than 100. Its check looks obviously right:

if (position + quantity <= limit) {
position += quantity;
}

Two orders to buy 15 arrive at the same moment, A and B:

  1. A checks: 80 + 15 = 95, within 100. Approved.
  2. B checks: the position is still 80, so 95 again. Approved.
  3. A executes: the desk holds 95.
  4. B executes: the desk holds 110.

The sum was right both times. What broke is that two orders ran the check before either executed. Example tests rarely find this: it needs two orders, in one order, at one moment, and a test tries the cases its author thought of.

This guide builds the desk four times over, one tool per question:

Question Tool
Can any order of events break the design? TLA+, and its model checker, TLC
Is the calculation right for every number? Lean
Does the Java do what the design and the calculation say? proptastic
Would the tests notice if the Java were wrong? mutastic

TLC checked six designs with two orders of 15, a start of 80 and a limit of 100. Each is a section below.

Design The limit A worker crashes mid-order What TLC can’t weigh
Check then execute broken: 80 → 95 → 110 (11 states) not checked it’s wrong
A lock holds (9 states) every other order waits for ever (13 states) orders wait their turn
Reserve first holds (9 states) the 15 stay reserved for ever (13 states)
Reserve, with leases holds the lease runs out, the 15 return (24 states) how long a lease is
A single writer holds (11 states) not modelled one writer’s speed
Optimistic retries holds harmless: nothing is held (19 states) retries under load

A state is one snapshot of the desk; the counts are how many TLC visited. Reserve with leases is the design the rest of the guide builds.

TLA+ describes a system as a state, the values of some variables, and the steps that change it. That description is a spec. TLC, TLA+‘s model checker, starts from the first state, takes every step that can be taken, in every order, and checks every state it reaches. When something the spec says must hold doesn’t, TLC prints a trace: the states, one step at a time, that get there. You write the spec before the code, so a design that can’t work is found before it’s built.

TLA+ reads like mathematics. The few symbols this guide uses:

TLA+ Read it as
x' = x + 1 the value of x after the step is x + 1
/\ and \/ and, or; a column of them is a list
UNCHANGED x x stays the same in this step
[status EXCEPT ![o] = "done"] status, with o’s entry now "done"
\E o \in Orders : … for some order o, …
\A o \in Orders : … for every order o, …
<>P eventually, P is true
[]P P is true from then on, always

Every design shares one module, Desk.tla: the orders, the numbers, and what must hold.

Desk.tla
\* The desk starts at Start, every order new.
DeskInit == /\ position = Start
/\ status = [o \in Orders |-> "new"]
\* An order fits beside what's held, p, if p + Quantity stays in the limit.
Fits(p) == p + Quantity <= Limit
\* The position never passes the limit.
Within == position <= Limit
\* In the end, every order is done or rejected.
EventuallyDecided ==
<>(\A o \in Orders : status[o] \in {"done", "rejected"})
\* In the end, every order is settled; a crashed one counts.
EventuallySettled ==
<>(\A o \in Orders :
status[o] \in {"done", "rejected", "crashed", "expired"})

In words: the desk starts at 80 with every order new. An order fits if what’s held plus 15 is at most 100. Within must be true in every state TLC reaches: it’s an invariant. The last two are promises about the end of every run: each order is decided, or, when workers can crash, settled.

Each design is a module that extends Desk, and a config says what to check it with:

designs/check-then-execute.cfg
CONSTANTS
Orders = {A, B}
Quantity = 15
Start = 80
Limit = 100
Crashes = FALSE
SPECIFICATION FairSpec
INVARIANT Within
PROPERTY EventuallyDecided

FairSpec adds one assumption: a step that can be taken is, in the end, taken. Without it, a desk could simply stop, and nothing promised “eventually” could ever hold.

The obvious design: check an order against the position, execute it later.

CheckThenExecute.tla
Check(o) ==
/\ status[o] = "new"
/\ status' = [status EXCEPT ![o] =
IF Fits(position) THEN "approved" ELSE "rejected"]
/\ UNCHANGED position
Execute(o) ==
/\ status[o] = "approved"
/\ position' = position + Quantity
/\ status' = [status EXCEPT ![o] = "done"]
Next == \E o \in Orders : Check(o) \/ Execute(o)

In words: a new order is checked against the position as it is now, and becomes approved if it fits, rejected if not; the position doesn’t move. An approved order executes: 15 is added, and it’s done. Next says each step is one order doing one of those two things.

Before reading on: will TLC find a way past the limit?

Yes. Nothing stops both orders being checked before either executes.

TLC’s verdict, and the run it found. TLC prints only the variables each step changes, then the last state in full:

Error: Invariant Within is violated.
Error: The behavior up to this point is:
State 1: <Initial predicate>
/\ position = 80
/\ status = (A :> "new" @@ B :> "new")
State 2: <Check line 12, col 3 to line 15, col 23 of module CheckThenExecute>
/\ status = (A :> "approved" @@ B :> "new")
State 3: <Check line 12, col 3 to line 15, col 23 of module CheckThenExecute>
/\ status = (A :> "approved" @@ B :> "approved")
State 4: <Execute line 18, col 3 to line 20, col 44 of module CheckThenExecute>
/\ position = 95
/\ status = (A :> "done" @@ B :> "approved")
State 5: <Execute line 18, col 3 to line 20, col 44 of module CheckThenExecute>
/\ position = 110
/\ status = (A :> "done" @@ B :> "done")
12 states generated, 11 distinct states found, 2 states left on queue.

That is the story from the top of the page, found by TLC without being told it.

Take a lock before checking, and let it go after executing: one order at a time.

Lock.tla
Acquire(o) ==
/\ status[o] = "new"
/\ lock = "free"
/\ lock' = o
/\ status' = [status EXCEPT ![o] = "locked"]
/\ UNCHANGED position
Decide(o) ==
/\ status[o] = "locked"
/\ IF Fits(position)
THEN /\ position' = position + Quantity
/\ status' = [status EXCEPT ![o] = "done"]
ELSE /\ status' = [status EXCEPT ![o] = "rejected"]
/\ UNCHANGED position
/\ lock' = "free"
Crash(o) ==
/\ Crashes
/\ status[o] = "locked"
/\ status' = [status EXCEPT ![o] = "crashed"]
/\ UNCHANGED <<position, lock>>
Next == \E o \in Orders : Acquire(o) \/ Decide(o) \/ Crash(o)

In words: a new order takes the lock if it’s free. Holding the lock, it executes if it fits and is rejected if not, and lets the lock go either way.

Crash is different: no code runs it. A spec has to say what the world can do to the system as well as what the system does, and a worker dying mid-order is one of those things. So Crash is a step the world takes: the worker holding the lock stops, and never lets it go. It happens only when the config sets Crashes.

Here is a run TLC found of the lock at work, A then B:

The limit holds, and every order is decided (lock in the verdicts above). But let a worker crash:

Will every order still be settled in the end?

No. A crashed worker never lets the lock go, so the other order waits for ever.

Error: Temporal properties were violated.
Error: The following behavior constitutes a counter-example:
State 1: <Initial predicate>
/\ position = 80
/\ lock = "free"
/\ status = (A :> "new" @@ B :> "new")
State 2: <Acquire line 14, col 3 to line 18, col 23 of module Lock>
/\ lock = A
/\ status = (A :> "locked" @@ B :> "new")
State 3: <Crash line 30, col 3 to line 33, col 33 of module Lock>
/\ status = (A :> "crashed" @@ B :> "new")
State 4: Stuttering
13 states generated, 13 distinct states found, 0 states left on queue.

Stuttering is TLC’s word for a state from which nothing more happens: A is new for ever.

Decide and reserve in one step: an order that fits takes its 15 from the room left at once, so the next order sees it.

Reserve.tla
Reserve(o) ==
/\ status[o] = "new"
/\ IF Fits(position + reserved)
THEN /\ reserved' = reserved + Quantity
/\ status' = [status EXCEPT ![o] = "approved"]
ELSE /\ status' = [status EXCEPT ![o] = "rejected"]
/\ UNCHANGED reserved
/\ UNCHANGED position
Execute(o) ==
/\ status[o] = "approved"
/\ position' = position + Quantity
/\ reserved' = reserved - Quantity
/\ status' = [status EXCEPT ![o] = "done"]

In words: a new order fits if the position and everything already reserved leave room for 15; then its 15 are reserved and it’s approved, or else it’s rejected. An approved order executes: its reservation becomes position. Two orders can’t both pass the check at 80, because the first one’s 15 are counted before the second checks.

The limit holds (reserve above). A crash and a lease:

Reserve.tla
\* Crash and Expire aren't code the desk runs: they're what the world
\* does to it. A worker can die holding a reservation, and time passes.
Crash(o) ==
/\ Crashes
/\ status[o] = "approved"
/\ status' = [status EXCEPT ![o] = "crashed"]
/\ UNCHANGED <<position, reserved>>
Expire(o) ==
/\ Leases
/\ status[o] = "crashed"
/\ reserved' = reserved - Quantity
/\ status' = [status EXCEPT ![o] = "expired"]
/\ UNCHANGED position

In words: an approved order’s worker can die, holding its reservation. With Leases, time passes and a dead worker’s reservation runs out: its 15 return and the order is expired. Neither is something the desk does; the spec says the world can do them, and the design must survive it. What reserving must keep true:

Reserve.tla
\* What's reserved is what approved orders still hold.
NoLostCapacity ==
reserved = Quantity * Cardinality({o \in Orders : status[o] = "approved"})
\* In the end, nothing stays reserved for an order that won't execute.
EventuallyReleased == <>[]NoLostCapacity
\* With leases, a crashed order holds its share until the lease runs out.
Accounted ==
LET holding == {o \in Orders : status[o] \in {"approved", "crashed"}}
IN reserved = Quantity * Cardinality(holding)

Without leases, a crash leaves the 15 reserved for ever:

Error: Temporal properties were violated.
Error: The following behavior constitutes a counter-example:
State 1: <Initial predicate>
/\ position = 80
/\ reserved = 0
/\ status = (A :> "new" @@ B :> "new")
State 2: <Reserve line 19, col 3 to line 25, col 23 of module Reserve>
/\ reserved = 15
/\ status = (A :> "approved" @@ B :> "new")
State 3: <Crash line 38, col 3 to line 41, col 37 of module Reserve>
/\ status = (A :> "crashed" @@ B :> "new")
State 4: <Reserve line 19, col 3 to line 25, col 23 of module Reserve>
/\ status = (A :> "crashed" @@ B :> "rejected")
State 5: Stuttering
17 states generated, 13 distinct states found, 0 states left on queue.

The desk sits at 80 with 15 reserved for an order that will never execute, and turns away every order that needs that room.

The same design with Leases on. Every property holds, crashes included (reserve-leases above). Here is TLC’s run of a lease at work:

Every order goes into a queue, and one writer takes them in turn.

SingleWriter.tla
Submit(o) ==
/\ status[o] = "new"
/\ queue' = Append(queue, o)
/\ status' = [status EXCEPT ![o] = "queued"]
/\ UNCHANGED position
Write ==
/\ queue # <<>>
/\ LET o == Head(queue) IN
IF Fits(position)
THEN /\ position' = position + Quantity
/\ status' = [status EXCEPT ![o] = "done"]
ELSE /\ status' = [status EXCEPT ![o] = "rejected"]
/\ UNCHANGED position
/\ queue' = Tail(queue)
Next == (\E o \in Orders : Submit(o)) \/ Write

In words: a new order joins the queue. The writer takes the order at the head, executes it if it fits and rejects it if not. Only the writer touches the position, so there’s no race.

The limit holds. This spec doesn’t model the writer crashing: when the one writer stops, every order stops.

Read a version with the position, check against it, and commit only if nothing moved since; if it did, read again.

Optimistic.tla
Read(o) ==
/\ status[o] \in {"new", "retrying"}
/\ seen' = [seen EXCEPT ![o] = version]
/\ status' = [status EXCEPT ![o] =
IF Fits(position) THEN "approved" ELSE "rejected"]
/\ UNCHANGED <<position, version>>
Commit(o) ==
/\ status[o] = "approved"
/\ IF seen[o] = version
THEN /\ position' = position + Quantity
/\ version' = version + 1
/\ status' = [status EXCEPT ![o] = "done"]
ELSE /\ status' = [status EXCEPT ![o] = "retrying"]
/\ UNCHANGED <<position, version>>
/\ UNCHANGED seen
Crash(o) ==
/\ Crashes
/\ status[o] = "approved"
/\ status' = [status EXCEPT ![o] = "crashed"]
/\ UNCHANGED <<position, version, seen>>
Next == \E o \in Orders : Read(o) \/ Commit(o) \/ Crash(o)

In words: reading records the version an order saw and checks it against the position then. A commit goes through only if the version hasn’t moved; otherwise the order retries from the read.

The limit holds, and a crash is harmless, since a reading order holds nothing.

Four designs keep the limit. Reserve with leases also survives a crash, and decides each order as it arrives without waiting on another’s lock. A single writer and optimistic retries are safe too; what they cost, one writer’s speed and retries under load, isn’t in this spec, and is a judgement TLC can’t make for you. TLC checked two orders and these numbers. That found every bug above, but says nothing of other numbers. That’s the next step’s job.

The chosen design keeps the limit as long as one decision is right: whether an order fits beside the position and what’s reserved. TLC tried it with a handful of numbers. Lean is a programming language whose compiler checks proofs. A theorem states something about a function for every input, and its proof is checked as it compiles: a wrong one is a build that fails. Lake is Lean’s build tool, and lake build checks every proof in a project.

The decision, as Lean sees it:

Trading.lean
/-- An order of `quantity` fits when what's held, plus it, stays within
`limit`. -/
def canExecute (held quantity limit : Nat) : Bool :=
held + quantity ≤ limit
/-- What a reservation does: approved, with what's reserved after it,
or rejected. -/
inductive Outcome where
| approved (reserved : Nat)
| rejected
deriving Repr, DecidableEq
/-- The desk's decision for one order: does it fit beside the position
and every reservation? -/
def reserve (position reserved quantity limit : Nat) : Outcome :=
if canExecute (position + reserved) quantity limit then
.approved (reserved + quantity)
else .rejected

The design relies on one theorem: an approved order keeps the position and the reservations within the limit, for every number. Its proof, one step at a time. Each show states what’s left to prove at that point, and Lean checks it is:

Trading.lean
/-- An approved order keeps the position and the reservations within the
limit. Each `show` states the goal at that point, and Lean checks it. -/
theorem reserve_keeps_within (position reserved quantity limit after : Nat)
(approved : reserve position reserved quantity limit = .approved after) :
position + after ≤ limit := by
unfold reserve canExecute at approved
split at approved
· -- the order fit: `approved` says `after` is the new reservations
rename_i fits
show position + after ≤ limit
cases approved
show position + (reserved + quantity) ≤ limit
simp at fits
omega
· -- the order didn't fit: `.rejected = .approved after` is impossible
cases approved

unfold replaces reserve and canExecute by what they mean, and split takes the if apart: either the order fit, or it didn’t. In the first case, cases puts the new reservations, reserved + quantity, in place of after, and omega, Lean’s arithmetic solver, finishes it from the fact that the order fit. In the second, approved claims a rejection is an approval, which can’t be, and cases says so.

The next theorem rules out a desk that keeps the limit by refusing everything. grind, a solver in core Lean, finds the proof itself:

Trading.lean
/-- A rejected order is one that wouldn't fit: the desk refuses only what
would breach. -/
theorem reserve_rejects_only_breaches (position reserved quantity limit : Nat)
(rejected : reserve position reserved quantity limit = .rejected) :
limit < position + reserved + quantity := by
grind [reserve, canExecute]

Two more say the position itself is computed right: keeping it as trades arrive gives what adding them all up gives, and the order trades arrive in doesn’t change it.

Trading.lean
/-- The position after `trades`, recalculated in full: the start plus
their sum. -/
def fullPosition (start : Nat) (trades : List Nat) : Nat :=
start + trades.sum
/-- The position after `trades`, kept as the desk keeps it: each trade
added as it comes. -/
def incrementalPosition (start : Nat) (trades : List Nat) : Nat :=
trades.foldl (· + ·) start
/-- Keeping the position as trades come gives what a full recalculation
gives. -/
theorem incremental_is_full (start : Nat) (trades : List Nat) :
incrementalPosition start trades = fullPosition start trades := by
induction trades generalizing start <;>
simp_all [incrementalPosition, fullPosition] <;> omega
/-- The position doesn't depend on the order trades arrive in: core Lean
knows a permutation keeps a sum (`List.Perm.sum_nat`). -/
theorem order_independent (start : Nat) {trades other : List Nat}
(same : trades.Perm other) :
fullPosition start trades = fullPosition start other := by
simp [fullPosition, same.sum_nat]

All of this is core Lean, with no library to download. Mathlib is the step up for proofs about real mathematics; a desk’s arithmetic doesn’t need it.

Here is the desk in Java, the design TLC chose. canExecute is the calculation Lean proved. A reservation is a lease, timed by a clock the desk is given (java.time.InstantSource): an order not executed before its lease runs out stops counting against the limit, and is expired.

ReservationDesk.java
/**
* Whether an order of {@code amount} fits beside {@code held}, within
* the limit.
*/
public boolean canExecute(long held, long amount) {
return held + amount <= limit;
}
/** What an order is checked beside: the position and every reservation. */
protected long held() {
return position + reserved();
}
/**
* Decides a new order and, if it fits, reserves its quantity for one
* lease: one step, so no order slips by.
*/
public synchronized void reserve(String order) {
if (status(order) == Status.NEW) {
var fits = canExecute(held(), quantity);
if (fits) {
leases.put(order, clock.instant().plus(LEASE));
}
statuses.put(order, fits ? Status.APPROVED : Status.REJECTED);
}
}
/** Executes an approved order: its reservation becomes position. */
public synchronized void execute(String order) {
if (status(order) == Status.APPROVED) {
position += quantity;
leases.remove(order);
statuses.put(order, Status.DONE);
}
}
/** What's reserved: the quantity of every lease still running. */
public synchronized long reserved() {
var running = leases.keySet().stream().filter(order -> !ranOut(order));
return quantity * running.count();
}
/** An approved order whose lease ran out is expired: it can't execute. */
public synchronized Status status(String order) {
var status = statuses.getOrDefault(order, Status.NEW);
return status == Status.APPROVED && ranOut(order) ? Status.EXPIRED : status;
}
private boolean ranOut(String order) {
var ends = leases.get(order);
return ends != null && !clock.instant().isBefore(ends);
}

There’s no crash method, and no expire. A worker that dies doesn’t tell anyone: it just never calls execute again. And a lease runs out because time passes, not because something calls a method. The spec’s Crash and Expire are the world’s steps; all the code has for them is the lease.

The spec and the proofs don’t make this code right: they’re about the design and the calculation, and the Java was written by hand. Two properties tie it to them.

A stateful test draws runs of steps on orders A, B and C. .follows(spec(…)) checks, after every step, that the step was one the spec allows from the state before it. Two of the spec’s steps are the world’s, so the test needs a world to take them: TradingFloor holds the desk, the workers that have died, and a clock that moves only when the test moves it.

.follows matches a step to the spec by its name: the step crash is checked as Crash. So the steps are the spec’s actions, written down once as an interface marked @StepBuilder. proptastic’s annotation processor writes two classes from it as the test code compiles: ReserveSteps, the steps, and ReserveStep, one step, for a pin (Steps from an interface sets it up). A step can’t then be named for an action the interface doesn’t have, and a pin that names one doesn’t compile:

Reserve.java
/**
* Spec Reserve's actions, as the test takes them: each method is one,
* named for it, on an order.
*/
@StepBuilder
interface Reserve {
void reserve(String order);
void execute(String order);
void crash(String order);
void expire(String order);
}

The floor takes each action, on the desk or on the world around it:

TradingFloor.java
/** A worker places an order: the desk reserves it, or rejects it. */
@Override
public void reserve(String order) {
placed.add(order);
desk.reserve(order);
}
/** The worker executes its order. */
@Override
public void execute(String order) {
if (!abandoned.contains(order)) {
desk.execute(order);
}
}
/**
* The worker holding an approved order dies: nothing calls the desk
* for that order again.
*/
@Override
public void crash(String order) {
if (desk.status(order) == Status.APPROVED) {
abandoned.add(order);
}
}
/** Time passes until a dead worker's lease has run out. */
@Override
public void expire(String order) {
if (abandoned.contains(order) && desk.status(order) == Status.APPROVED) {
clock.advance(ReservationDesk.LEASE);
}
}
/**
* Whether time can pass: only while no live worker holds a lease.
* A live worker executes in time, as the spec assumes, and one clock
* moving on would expire its lease too.
*/
boolean noLiveLease() {
return placed.stream().noneMatch(order -> status(order).equals("approved"));
}

Each step the test draws is something the world does:

Step What happens Spec action
reserve a worker places an order: desk.reserve(o) Reserve(o)
execute the worker executes it: desk.execute(o) Execute(o)
crash the worker dies: nothing calls the desk for o again Crash(o)
expire time passes, until a dead worker’s lease has run out, once no live worker holds one Expire(o)

Time passes on one clock, so moving it on expires every lease, a live worker’s too, where the spec’s Expire(o) expires one. The spec assumes a live worker executes in time, so the floor lets time pass only once none holds a lease: .when(TradingFloor::noLiveLease) on expire. The constants here allow one approved order at a time, so the graph can’t show the difference; following the spec by TLC traces at larger ones found it.

The desk can’t tell an order whose worker died from one still being worked on: both are approved, both hold 15. The floor can, so it calls the first crashed, as the spec does. The test reads the graph of every state TLC reached for Reserve.tla with leases and three orders:

private static final List<String> ORDERS = List.of("A", "B", "C");
/**
* Spec Reserve, as TLC checked it with three orders: the floor's state
* named as the spec names it.
*/
static Spec<TradingFloor> reserveSpec() {
return spec(
"Reserve",
floor ->
Map.of(
"position", floor.desk().position(),
"reserved", floor.desk().reserved(),
"status", statuses(floor)),
floor -> true);
}
/** Each order's status, as the spec spells it: {@code A :> "crashed"}. */
static Map<String, String> statuses(TradingFloor floor) {
var statuses = new LinkedHashMap<String, String>();
for (var order : ORDERS) {
statuses.put(order, floor.status(order));
}
return statuses;
}
/** What the world does to a desk: the spec's actions, on any order. */
static ReserveSteps<TradingFloor> theDesk(Desks desks) {
var orders = elements(ORDERS);
return ReserveSteps.steps(() -> new TradingFloor(desks))
.reserve(orders)
.execute(orders)
.crash(orders)
.expire(orders)
.when(TradingFloor::noLiveLease);
}
@Test
void theDeskFollowsTheSpec() {
var steps = theDesk(clock -> new ReservationDesk(80, 15, 100, clock));
forAll(steps).seed(0x5eed).follows(reserveSpec());
}

It passes, and says what it covered:

Terminal window
followed spec Reserve 1 on 100 runs (TLC: 154 states, 57 of 204 edges reached) · actions Reserve 118 · Execute 17 · Crash 20 · Expire 10 · left the model 0%
how sure: 0 of 100 runs failed, so under 3% of runs drawn this way fail it (95% confidence)
why: https://docs.proptastic.io/concepts/how-sure-is-a-pass/

To check a step, proptastic needs to know which step each edge of TLC’s graph is, and for which order. A spec doesn’t say: TLC labels an edge only with the action’s name, and every spec allows a step that changes nothing, so a desk whose execute silently did nothing would pass. So the build checks the spec through a module proptastic writes, which extends Reserve.tla and adds a history variable, last: each step records itself, as in (Reserve(o) /\ last' = <<"Reserve", o>>). It only records the past, so the design is unchanged, and Reserve.tla stays as it was designed. “Why the spec needs last” says more.

A desk whose check forgets what’s already reserved is check then execute again:

/**
* Check then execute: the check forgets what's reserved, so two orders
* can pass it at once.
*/
final class RaceDesk extends ReservationDesk {
RaceDesk(long start, long quantity, long limit, InstantSource clock) {
super(start, quantity, limit, clock);
}
@Override
protected long held() {
return position();
}
}
@Test
@Tag("failing")
void aCheckThenExecuteDeskDoesnt() {
var steps = theDesk(clock -> new RaceDesk(80, 15, 100, clock));
forAll(steps).follows(reserveSpec());
}
Terminal window
does not follow spec Reserve 1 (TLA+)
step 2 is not one spec Reserve allows: reserve("B")
allowed position = 80, reserved = 15, status = {A=approved, B=rejected, C=new}
did position = 80, reserved = 30, status = {A=approved, B=approved, C=new}
differs reserved 15 → 30 · status[B] rejected → approved
keeps invariants Within, Accounted
aCheckThenExecuteDeskDoesnt failed after 3 tries (seed 0x5eed)
shrunk steps:
1. reserve("A")
2. reserve("B") ← position 80, reserved 30, {A=APPROVED, B=APPROVED}
pin it:
.example(reserve("A"), reserve("B"))
// import static spec.ReserveStep.*
rerun:
PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'DeskFollowsTheSpecTest.aCheckThenExecuteDeskDoesnt'

The spec says B is rejected with 15 already reserved; the desk approved it. proptastic shrank the run to the two steps that show it.

The Lean model also runs as a program, a model proptastic asks for every try’s answer. It names the cases it tells apart, its outcomes, and the theorems it proved, and hands them to Proptastic.serve, a small Lean library beside it that speaks the protocol:

Main.lean
/-- The cases the model tells apart, and what each means. -/
def outcomes : List Proptastic.Outcome :=
[⟨"fits", "the order fits, with room to spare"⟩,
⟨"fills", "the order exactly fills the limit"⟩,
⟨"breach", "the order would take what's held past the limit"⟩]
/-- The theorems about `reserve`: a name that isn't a theorem here doesn't
compile. -/
def proved : List Lean.Name :=
[``reserve_keeps_within, ``reserve_rejects_only_breaches]
/-- One reservation in, the model's case and answer out. -/
def answer (values : Array Json) : Except String Proptastic.Answer := do
let order := values.getD 0 Json.null
let position ← order.getObjValAs? Nat "position"
let reserved ← order.getObjValAs? Nat "reserved"
let quantity ← order.getObjValAs? Nat "quantity"
let limit ← order.getObjValAs? Nat "limit"
let outcome := match reserve position reserved quantity limit with
| .approved _ =>
if position + reserved + quantity = limit then "fills" else "fits"
| .rejected => "breach"
return ⟨outcome, Json.bool (outcome != "breach")⟩
def main : IO Unit :=
Proptastic.serve "Trading.reserve" outcomes proved answer

The property draws a reservation and asks both the model and the desk whether it’s approved:

/**
* An order of {@code quantity} at a desk holding {@code position} and
* {@code reserved}.
*/
record Reservation(long position, long reserved, long quantity, long limit) {
/** What the order is checked beside: the position and every reservation. */
long held() {
return position + reserved;
}
}
/**
* The Lean model of the desk's decision, the program
* {@code lake build} built in models/lean.
*/
static Model trading() {
return lean("Trading");
}
/**
* Reservations whose limit is drawn beside what they'd hold, so an
* order that exactly fills it comes up often: drawn apart, four numbers
* seldom meet there.
*/
static Domain<Reservation> reservations() {
return domain(
longs().atLeast(0).atMost(200),
longs().atLeast(0).atMost(100),
longs().atLeast(1).atMost(100),
longs().atLeast(-3).atMost(3),
(position, reserved, quantity, slack) -> {
var limit = Math.max(0, position + reserved + quantity + slack);
return new Reservation(position, reserved, quantity, limit);
});
}
@Test
void theDeskFollowsTheModel() {
forAll(reservations()).follows(trading(), approvedBy(ReservationDesk::new));
}
/**
* The code's answer for an order: whether a desk, the design's or one
* with a bug, approves it.
*/
static Property1.Answer<Reservation> approvedBy(Desks desks) {
return order -> {
var desk = desks.open(order.position(), order.quantity(), order.limit());
return desk.canExecute(order.held(), order.quantity());
};
}
/** How a test opens a desk: its constructor. */
@FunctionalInterface
interface Desks extends java.io.Serializable {
ReservationDesk open(long start, long quantity, long limit);
}

It passes, naming the theorems the model proved and how often each outcome came up:

Terminal window
followed model Trading.reserve 0.1.0 on 100 tries (Lean; proved reserve_keeps_within, reserve_rejects_only_breaches) · outcomes fits 47 · fills 12 · breach 41
how sure: 0 of 100 tries failed, so under 3% of inputs drawn this way fail it (95% confidence)
why: https://docs.proptastic.io/concepts/how-sure-is-a-pass/

A run fails unless every outcome came up at least once, so a pass has tried each case the model tells apart. The limit is drawn beside what the order would hold, so fills, an order that exactly fills the limit, comes up often. Drawn apart, four numbers seldom meet there.

That edge is where an off-by-one lives:

/**
* The limit itself is refused: {@code <} where the calculation says
* {@code <=}.
*/
final class OffByOneDesk extends ReservationDesk {
OffByOneDesk(long start, long quantity, long limit) {
super(start, quantity, limit);
}
@Override
public boolean canExecute(long held, long amount) {
return held + amount < limit();
}
}
@Test
@Tag("failing")
void anOffByOneDeskDoesnt() {
forAll(reservations()).follows(trading(), approvedBy(OffByOneDesk::new));
}
Terminal window
does not follow model Trading.reserve 0.1.0 (Lean)
model Trading.reserve said true, code said false (outcome fills)
anOffByOneDeskDoesnt failed after 9 tries (seed 0x5eed)
shrunk counterexample: order = new Reservation(0, 0, 1, 1) // Reservation(position, reserved, quantity, limit)
pin it: .example(new Reservation(0L, 0L, 1L, 1L))
rerun: PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'ReserveFollowsTheModelTest.anOffByOneDeskDoesnt'

The model said an order that exactly fills the limit is approved; the desk said no. proptastic shrank it to the smallest such order: nothing held, an order of 1, a limit of 1.

The tests pass, and they caught the two bugs planted in them. Would they catch one nobody planted? mutastic answers that. It makes small changes to the desk, one at a time, such as <= to <, or a lease that never runs out, and runs the tests on each. A change the tests still pass on is a bug they wouldn’t notice: a step they never take, an edge they never draw, or a check too weak to see it.

Two parts of the tests above are there because changes like these slipped past the first version of this walkthrough. A step that did nothing passed the spec check, which last now prevents. The off-by-one passed when the edge was seldom drawn, so a run now fails until every outcome has come up.

In proptastic’s repository:

Terminal window
./gradlew tlcDesigns # TLC on each design, into build/tlc-designs
(cd models/lean && lake build) # the proofs, and the model
./gradlew docsTest --tests 'spec.*' --tests 'walkthrough.*' # the properties

lake comes with elan, which installs the Lean that models/lean/lean-toolchain names. ./gradlew check runs all three.

TLC checked every order of events for each design, with two orders and these numbers. Lean proved the calculation for every number a Nat can hold. The properties checked the Java against both, on the runs they drew, and mutastic checks that the properties would notice a wrong desk. None of them makes the code right on its own: the properties are what tie the spec and the proofs to the code. Writing down what the desk must do, before any of this, is a step of its own.

Starting from code that already exists? “From code to design” runs this guide backwards: it backs a spec out of the check-then-execute desk, finds the race, and keeps the fix.

Privacy