Skip to content

From code to design

You’ve inherited a trading desk. Its tests pass, it’s been in production for a year, and the person who wrote it has moved on. Nobody can say whether it’s right, only that nothing has gone wrong yet. The desk holds 80 shares of a stock and may never hold more than 100, and it checks each order before executing it. Is there any way two orders could take it past 100?

Reading the code won’t settle that, and neither will more example tests: a race needs two orders, in one order, at one moment, and an example tries the cases its author thought of. This guide answers the question for the desk, and leaves behind a test that keeps the answer true:

Step Tool
1. Write down what the code does, as a spec TLA+
2. Check the spec describes the code proptastic
3. Ask whether any order of events breaks the limit TLC, TLA+‘s model checker
4. Decide what should be true instead TLA+ and TLC
5. Fix the code, and test it against that design proptastic
6. Keep the fix, and check the tests would notice it going proptastic and mutastic

It’s “From design to code” run backwards: the same desk, the same specs and the same numbers, starting from code that exists rather than a design that doesn’t.

The desk takes an order in two steps. A worker checks it against the position, and later executes it:

TradingDesk.java
/** Approves a new order if it fits beside the position, else rejects it. */
public synchronized void check(String order) {
if (status(order) == Status.NEW) {
var fits = position + quantity <= limit;
statuses.put(order, fits ? Status.APPROVED : Status.REJECTED);
}
}
/** Executes an approved order: the position takes its quantity. */
public synchronized void execute(String order) {
if (status(order) == Status.APPROVED) {
position += quantity;
statuses.put(order, Status.DONE);
fills.add(order);
}
}

Both methods are synchronized, so no two run at once. Its tests:

TradingDeskTest.java
@Test
void anOrderThatFitsIsExecuted() {
var desk = new TradingDesk(80, 15, 100);
desk.check("A");
desk.execute("A");
assertEquals(95, desk.position());
assertEquals(List.of("A"), desk.fills());
}
@Test
void anOrderPastTheLimitIsRejected() {
var desk = new TradingDesk(90, 15, 100);
desk.check("A");
assertEquals(Status.REJECTED, desk.status("A"));
}
@Test
void theSecondOrderSeesTheFirst() {
var desk = new TradingDesk(80, 15, 100);
desk.check("A");
desk.execute("A");
desk.check("B");
assertEquals(Status.REJECTED, desk.status("B"));
}

All three pass, and they’re good tests: the last one even tries two orders. But it runs them one after the other, the way a person writes them. Whether the desk survives some other order of those calls is the question nobody has asked.

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. It’s the tool for “is there any order of events that breaks this?”

The 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

A spec of existing code isn’t a translation of it. It keeps what the question needs and leaves out the rest, so TLC has a small enough world to search every corner of. Three decisions do most of the work.

What is one step? A step is what runs without anything else happening in the middle. Here, that’s each synchronized method: check runs whole, and so does execute, but between one order’s check and its execute, any other order’s methods can run. So the spec has two steps, Check and Execute, and lets TLC take them for any order, in any interleaving. TLC tries every interleaving, so the spec doesn’t model threads at all.

What is the state? Only what a step reads or a rule depends on: the position, and each order’s status. The fills list is written but never read by any decision, so it stays out.

How big is the world? Small. Every order is 15, two orders reach the limit from 80, and the numbers are the ones the desk runs with. TLC will check every order of events in that world, and nothing beyond it.

In the code In the spec
position, a long position, a number
statuses, a map from order to Status status, a function from order to a string
check(order), synchronized the step Check(o)
execute(order), synchronized the step Execute(o)
quantity and limit, set when the desk is made the constants Quantity and Limit
fills, the threads, the order IDs’ format left out

What every desk shares goes in one module, Desk.tla. It’s the module “From design to code” starts from, so it names a few things, crashes and their settling, that this desk doesn’t have yet:

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 rule the question is about.

The desk’s two methods, as steps:

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: Check is the method’s if: a new order becomes approved if it fits beside the position as it is now, rejected if not, and the position doesn’t move. Execute is the other method: an approved order adds 15 and is done. Next says each step is one order doing one of the two. Read side by side with the Java, each line has its counterpart.

An agent can draft a spec like this from the code, and there are tools that do it for whole systems: Specula, which won the TLA+ Foundation’s 2025 GenAI challenge, writes specs from system code and then checks them against the code’s runs. The choices above are still yours to check. Hillel Wayne found a model could “sometimes convert Python into a passable spec”, but “wasn’t good at recognizing abstraction” (Computer Things, 2025): a spec that models too much is slow to check, and one that models the wrong step finds the wrong bugs. Whoever wrote it, a spec backed out of code is a claim about the code. The next step checks the claim.

If the spec doesn’t describe the code, whatever TLC says about it is about something else. So before asking TLC anything, check the code against the spec.

A stateful test draws runs of steps, here check and execute on orders A, B and C in any order, and takes them on a new desk each run. .follows(spec(…)) checks, after every step, that what the desk did is a step the spec allows from the state before it. It reads the graph of every state TLC can reach, which the build has TLC dump for the config of the spec’s own name beside it, where models go:

CheckThenExecute.cfg
\* No invariant: the graph is every state the code can reach, a breach
\* included, so the code can be followed past it.
CONSTANTS
Orders = {A, B, C}
Quantity = 15
Start = 80
Limit = 100
Crashes = FALSE
INIT Init
NEXT Next

The test names the desk’s state as the spec names it, and its steps as the spec’s actions:

InheritedDeskTest.java
/** The spec backed out of the desk: what the code does, not what it should. */
static Spec<TradingDesk> checkThenExecute() {
return spec(
"CheckThenExecute",
desk -> Map.of("position", desk.position(), "status", statuses(desk)),
desk -> true);
}
/** The desk's steps, named as the spec names them, on any of three orders. */
static Steps<TradingDesk> theInheritedDesk() {
var orders = elements(ORDERS);
return steps(() -> new TradingDesk(80, 15, 100))
.step("check", orders, TradingDesk::check)
.step("execute", orders, TradingDesk::execute);
}
@Test
void theDeskFollowsTheSpecBackedOutOfIt() {
forAll(theInheritedDesk()).follows(checkThenExecute());
}
Before reading on: the desk has a race. Will it follow the spec?

Yes. The spec describes what the code does, race and all, so every step the code takes is one the spec allows. Following a spec checks that code and spec agree, not that either is right.

Terminal window
followed spec CheckThenExecute 1 on 100 runs (TLC: 67 states, 71 of 87 edges reached) · actions Check 160 · Execute 80 · 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/

The line says what was covered: how many of TLC’s states and edges the runs reached, and how often each step came up. A spec that modelled a step the code doesn’t take, or missed one it does, fails here, at the step that differs. That’s what lets you trust what TLC says next.

Now the question itself: can any order of events take the position past 100? The config checks the invariant Within, with two orders:

designs/check-then-execute.cfg
CONSTANTS
Orders = {A, B}
Quantity = 15
Start = 80
Limit = 100
Crashes = FALSE
SPECIFICATION FairSpec
INVARIANT Within
PROPERTY EventuallyDecided
Before reading on: will TLC find a way past the limit?

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

TLC prints only the variables each step changes:

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.

Read in the code’s terms: check("A"), check("B"), execute("A"), execute("B"). Each check saw 80 and was right to say 95 fits; what neither saw was the other’s approval. The example tests called check then execute for one order before touching the next, the one order in which the bug can’t happen.

Step 2 showed the code takes only the steps this spec allows, so this trace is one to take seriously as the code’s, not just the spec’s. Step 5 watches the Java take it.

TLC has said what the desk does. What it should do is a decision, and it’s the step a spec of existing code can’t take for you. “From design to code” compares six designs for this desk and chooses reserve with leases: deciding an order takes its 15 from the room left in the same step, so the next order sees it, and a crashed worker’s reservation runs out:

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. Reserve.tla also says what the world can do to the desk: a worker can die holding a reservation, and time passes until its lease runs out (shown in the other guide).

The spec changed before the code did. TLC checks it, with crashes and leases on:

Model checking completed. No error has been found.
29 states generated, 24 distinct states found, 0 states left on queue.

Every order of events keeps the limit, and every order is settled in the end, crashes included.

5. Fix the code, and test it against the design

Section titled “5. Fix the code, and test it against the design”

Before changing the code, point the test at the design. The inherited desk has no reserved, but the spec’s reserved is something the code has all the same: 15 for each order it approved and hasn’t executed. The test computes it, and calls the desk’s check where the design says reserve:

InheritedDeskTest.java
/**
* What spec Reserve calls reserved: 15 for each approved order not yet
* executed. The inherited desk keeps no such number, but it holds the
* capacity all the same.
*/
static long reserved(TradingDesk desk) {
var statuses = ORDERS.stream().map(desk::status);
return 15 * statuses.filter(Status.APPROVED::equals).count();
}
/** Spec Reserve, the intended design, with the inherited desk's state. */
static Spec<TradingDesk> reserveSpec() {
return spec(
"Reserve",
desk ->
Map.of(
"position", desk.position(),
"reserved", reserved(desk),
"status", statuses(desk)),
desk -> true);
}
/** The inherited desk's check is where the design reserves. */
static Steps<TradingDesk> asTheDesignNamesIt() {
var orders = elements(ORDERS);
return steps(() -> new TradingDesk(80, 15, 100))
.step("reserve", orders, TradingDesk::check)
.step("execute", orders, TradingDesk::execute);
}
@Test
@Tag("failing")
void theInheritedDeskDoesntFollowTheDesign() {
forAll(asTheDesignNamesIt()).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
theInheritedDeskDoesntFollowTheDesign failed after 2 tries (seed 0x5eed)
shrunk steps:
1. reserve("A")
2. reserve("B") ← position 80, {A=APPROVED, B=APPROVED}
pin it:
.example(step("reserve", "A"), step("reserve", "B"))
// typed pins come from @StepBuilder
rerun:
PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'InheritedDeskTest.theInheritedDeskDoesntFollowTheDesign'

The spec says B is rejected with 15 already held for A; the desk approved it. proptastic drew longer runs and shrank the first that failed to the two steps that show the race. That’s TLC’s trace again, found this time in the Java rather than the spec, and it’s the test the fix has to pass.

The fixed desk is the design: check becomes reserve, which counts what’s reserved and takes its 15 in the same synchronized step. A reservation is a lease on an injected clock: if no one executes the order in time, as when its worker died, the 15 return. It’s ReservationDesk in “From design to code”:

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);
}

The desk has no method for a crash: the spec’s Crash and Expire are what the world does, a worker dying and time passing. The test takes them on a TradingFloor around the desk, whose steps crash and expire abandon an order and move a test clock past its lease. Its four steps come from Reserve, an interface of the spec’s actions marked @StepBuilder, so each is named for its action by the compiler, not by a string. The same check against the design, now with all four steps:

@Test
void theDeskFollowsTheSpec() {
var steps = theDesk(clock -> new ReservationDesk(80, 15, 100, clock));
forAll(steps).seed(0x5eed).follows(reserveSpec());
}
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/

It passes, and every action of the spec came up: a run fails when one never does, so a pass has taken each step the design allows.

The failure above ended with a pin it: line, step("reserve", "A") and step("reserve", "B"): the inherited desk’s steps are written by hand, because each is named for a spec action but calls a desk method of another name. The fixed desk’s steps come from Reserve, so on its test the same two steps are reserve(…), imported from ReserveStep, a pin the compiler checks against the interface:

KeepTheFixTest.java
@Test
void theFixKeepsTheRaceOut() {
var steps = theDesk(clock -> new ReservationDesk(80, 15, 100, clock));
forAll(steps)
.example(reserve("A"), reserve("B")) // the race, pinned
.seed(0x5eed)
.follows(reserveSpec());
}
Terminal window
followed spec Reserve 1 on 101 runs (TLC: 154 states, 36 of 204 edges reached) · actions Reserve 93 · Execute 17 · Crash 6 · Expire 1 · 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/

The example is the first of the 101 runs, on every build, whatever the seed: the race that was found is checked for ever. The 100 drawn runs after it are what catch the race coming back by another path, say a refactor that reads position where it should read held(), or a new step that approves without reserving.

A test that passes on the fix and failed on the bug is a good start. Would it fail on the next bug? mutastic answers that. It makes small changes to the fixed 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. The ones to read first are in the lines the fix added: a change there that survives is part of the fix that could go without a test failing.

In proptastic’s repository:

Terminal window
./gradlew tlcDesigns # TLC on each design, into build/tlc-designs
./gradlew tlc # the graphs the stateful tests follow
./gradlew docsTest --tests 'inherited.*' --tests 'spec.*' # the tests

./gradlew check runs all three, and fails when a committed graph or verdict isn’t what TLC finds.

TLC checked every order of events for the spec, with two orders and these numbers, and found the race. The stateful tests showed the inherited desk takes only steps that spec allows, on the runs they drew, so the race is the code’s; then that the fixed desk takes only steps the design allows, and that the race found stays out.

None of that makes the desk right everywhere. A step is a whole synchronized method, so a race inside one, between two lines no lock covers, isn’t a step any test or spec here can see. The tests take one step at a time on one thread: they check the order of steps, not that the locking is sound. Steps on threads check the locking too, by stopping a thread between two lock calls, but only at locks proptastic made: a synchronized method like this desk’s is one step to them as well. The spec was checked with two orders and the tests with three; more orders, other quantities or a different limit are a new config for TLC and a new graph for the tests, or, past 10,000 states, no graph and TLC traces. And choosing reserve with leases, and how long a lease should be, are judgements the tools inform but don’t make.

When inherited code hangs rather than breaking a rule, “Finding a deadlock” runs the same steps on two locks taken in different orders.

Privacy