Follow a model
A trading desk decides whether an order fits: what it holds, plus the order, must stay within its limit. A property can check part of that, say that an approved order never breaches the limit. But a desk that refuses every order passes that property too. What you want to say is simpler: on every order, the desk answers what the rule says it should.
That rule, written down plainly enough to trust, is a model. This page checks the desk against a
model of its decision, then checks the desk’s steps against a TLA+ spec of the order they may come
in. Both use .follows, and both fail a run that never tried each case.
The desk
Section titled “The desk”An order is what the desk holds, the order’s quantity and the limit:
/** * An order of {@code quantity} at a desk holding {@code held}, with its * {@code limit}. */record Order(long held, long quantity, long limit) {}The desk has a bug at the edge. An order that exactly fills the limit should fit; this desk refuses it:
/** * A trading desk's decision: whether an order fits beside what's held, * within the limit. */final class Desk { static boolean canExecute(long held, long quantity, long limit) { return held + quantity < limit; }}A model
Section titled “A model”A model is a program, in any language, that proptastic runs as a process of its own and talks to in lines of JSON. Its first line names it and its outcomes, the cases it tells apart. Then, for each line in, one try’s values, it answers with the outcome and what the code should say.
Here the model is a Java class, so this page’s build can run it. fits is the rule, written to be
obviously right. main hands it to Model.serve, which speaks the protocol: it writes the first
line from the outcomes, reads each try’s values as JSON (the order arrives as a map of its
components, its numbers as Long), and writes the outcome and answer the function gives back.
process() is how a test names the model: java(DeskModel.class) runs this same class as its own
process, with the tests’ Java and class path.
/** * The model of the desk's decision: a program that says, for each * order, whether it fits. A property follows it through * {@link #process()}, which runs this class's {@code main} as a * process of its own. */final class DeskModel { /** The decision, written to be obviously right. */ static boolean fits(Map<?, ?> order) { var held = number(order, "held"); return held + number(order, "quantity") <= number(order, "limit"); }
/** One of the order's components, a whole number in the JSON. */ static long number(Map<?, ?> order, String component) { return (Long) Objects.requireNonNull(order.get(component), component); }
/** This class, run with the tests' own Java: what {@code .follows} asks. */ static Model process() { return java(DeskModel.class); }
/** First the model's name and outcomes, then one answer for each order in. */ public static void main(String[] arguments) { var outcomes = List.of( outcome("fits", "the order fits within the limit"), outcome("breach", "the order would breach the limit")); Model.serve( "Desk.canExecute", outcomes, values -> { var fits = fits((Map<?, ?>) values.get(0)); return answer(fits ? "fits" : "breach", fits); }); }}The model can be any executable that speaks those lines: command(…) runs one with its arguments,
in any language.
What a model reads
Section titled “What a model reads”A model can be written in any language, so the values it reads and the answers it gives have one JSON form, the same from every edition of proptastic:
- a whole number is exact at any size, so print every digit; other numbers are 64-bit floating point
- a record is an object of its components, and an enum constant is its name
- a value of a sealed interface is tagged with its record’s name,
{"Deposit": {"amount": 5}}, or just"Close"for a record without components: the form Lean’s derivedToJsonwrites - an
Optionalis its value, ornull - a list is an array, in order
- a set is an array in no particular order, and an answer that’s a set is compared as one
- a map is an object, its keys strings
Follow it
Section titled “Follow it”The orders are drawn with their limit near what they’d hold, so an order that exactly fills the limit comes up often. Drawn apart, three numbers seldom meet there.
/** * Orders whose limit is drawn near what they'd hold, so one that * exactly fills it comes up. */static Domain<Order> orders() { return domain( longs().atLeast(0).atMost(100), longs().atLeast(1).atMost(20), longs().atLeast(-2).atMost(2), (held, quantity, slack) -> { var limit = held + quantity + slack; return new Order(held, quantity, limit); });}.follows(model, answer) takes the place of .check. For each try it asks the model, asks the code
through answer, and fails where they differ:
@Test@Tag("failing")void theDeskFollowsTheModel() { var model = DeskModel.process(); forAll(orders()).follows(model, DeskFollowsTheModelTest::approves);}
/** What the desk says of an order: the answer the model is asked for. */static boolean approves(Order order) { return Desk.canExecute(order.held(), order.quantity(), order.limit());}does not follow model Desk.canExecute (Java)model Desk.canExecute said true, code said false (outcome fits)
theDeskFollowsTheModel failed after 2 tries (seed 0x5eed) shrunk counterexample: order = new Order(0, 1, 1) // Order(held, quantity, limit) pin it: .example(new Order(0L, 1L, 1L)) rerun: PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'DeskFollowsTheModelTest.theDeskFollowsTheModel'The first line is the verdict: the desk does not follow the model, named as the model names itself, and run as a command. The second says where: the model said the order fits, and the desk said it doesn’t. proptastic shrank the order to the smallest that shows it: nothing held, an order of 1, a limit of 1. The comment after it names the record’s components, so you needn’t count; the line is still Java to paste.
Every outcome, or why not
Section titled “Every outcome, or why not”A run that never reached one of the model’s outcomes said nothing about that case, so the run
fails, naming the outcome and what it means. When an outcome truly can’t come up for what’s drawn,
say why with .unreachable:
/** Orders far below their limit: none can breach it. */static Domain<Order> smallOrders() { return domain( longs().atLeast(0).atMost(10), longs().atLeast(1).atMost(10), (held, quantity) -> new Order(held, quantity, 1_000));}
@Testvoid smallOrdersAllFit() { forAll(smallOrders()) .unreachable("breach", "these orders are all far below the limit") .follows(DeskModel.process(), DeskFollowsTheModelTest::approves);}A pass prints what it followed, how many tries each outcome got, why one was left out, and how sure it is:
followed model Desk.canExecute on 100 tries (Java) · outcomes fits 100 · breach unreachable (these orders are all far below the limit) 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/If an outcome said to be unreachable comes up after all, the run fails.
What a pass is sure of
Section titled “What a pass is sure of”A pass can’t say the code is right: it tried 100 orders, not every order. What it can say is how
rare a failure could still be among orders drawn the way these were. When none of n independent
draws fails, the share that would fail is, at 95% confidence, below 1 - 0.05^(1/n), which is
about 3/n. Medicine calls that the rule of three, for a trial in which nothing went wrong
(Hanley and Lippman-Hand, 1983).
100 tries put the share under 3%; 1,000 put it under 0.3%. Only the random tries count: an
.example(…) or a corpus entry was chosen, not drawn.
The bound is about the draws, and nothing else, which is why the line says drawn this way. The orders your desk meets in use aren’t drawn from these domains, and a bug that only they reach is outside it. Random testing’s own theory says as much: a bound like this carries over to real use only as far as the inputs are drawn as real use would draw them (Richard Hamlet, Random Testing, 1994). So read the two lines together. The counts say every outcome came up, so no case went untried; the bound says how rare a failure could still be among the inputs drawn. Widen the domains, or draw more tries, to say more. How sure is a pass? works it through one step at a time.
The model’s version is in the line too, when it has one. A model run with command(…) can give its
own, "version": "1.4.0" in its first line. A Lean model’s is its Lake package’s version, or a
hash of its sources when it has none. A TLA+ spec’s is a hash of the spec, the modules beside it
that it extends, and its config, or a \* version: 1.4.0 comment in it. A pass or a failure then
says which model it was about, so a result kept from an old run can’t be mistaken for one about
the model as it is now.
Follow a TLA+ spec
Section titled “Follow a TLA+ spec”The desk doesn’t only decide; it takes steps. An order is reserved, then executed, and a worker can die halfway. Bugs live in the order of those steps: two orders checked against the same position, say, before either is executed. A model of one answer can’t say which orders of steps are allowed. A spec can.
TLA+ is a language for describing a system as a
state, the values of some variables, and the steps that change it; that description is a
spec. TLC is TLA+‘s model checker: it takes every step in
every order from the first state, and checks what the spec says must hold in each state it reaches.
Here the spec is Reserve.tla, the desk’s design, and its Reserve step decides an order and
reserves its capacity in one go:
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"]TLC can also write down every state it reached and every step between them, the spec’s state
graph. spec(…) reads that graph, and a stateful test .follows it: after
every step the code takes, the step must be one the spec allows from the state before it.
The desk, in Java. A reservation is a lease, timed by the clock the desk is given:
/** * 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 spec has two steps the desk has no code for: Crash, a worker dying while it holds a
reservation, and Expire, time passing until that reservation runs out. They’re what the world
does to the desk, so the test takes them on a world around it, TradingFloor, which holds the
desk, the workers that died and a clock the test moves on.
A step is matched to the spec’s action of the same name, capitalized, so the steps are the
spec’s actions, written down once as an interface marked @StepBuilder. proptastic’s annotation
processor writes ReserveSteps and ReserveStep from it, the steps and a pin
(Steps from an interface), so a step can’t be named
for an action the interface doesn’t have:
/** * Spec Reserve's actions, as the test takes them: each method is one, * named for it, on an order. */@StepBuilderinterface Reserve { void reserve(String order);
void execute(String order);
void crash(String order);
void expire(String order);}The floor takes each action:
/** A worker places an order: the desk reserves it, or rejects it. */@Overridepublic void reserve(String order) { placed.add(order); desk.reserve(order);}
/** The worker executes its order. */@Overridepublic 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. */@Overridepublic void crash(String order) { if (desk.status(order) == Status.APPROVED) { abandoned.add(order); }}
/** Time passes until a dead worker's lease has run out. */@Overridepublic 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, and the action it’s checked as:
| 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.
spec(…) takes the spec’s name, the state named as the spec names it, and whether a state is
within the constants TLC checked (here every state is). It reads the graph from
models/tla/Reserve.dot, beside the spec, where models go:
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);}@Testvoid theDeskFollowsTheSpec() { var steps = theDesk(clock -> new ReservationDesk(80, 15, 100, clock)); forAll(steps).seed(0x5eed).follows(reserveSpec());}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/The spec is named with its version, sha256: and the start of a hash of Reserve.tla, the
Desk.tla it extends and Reserve.cfg, so an edit to any of them shows. The bound is over runs
now, each a sequence of steps drawn whole. Every action of the spec must come up, or the pass
fails, as every outcome of a model must. Expire takes three steps on one order, its worker’s
reserve, crash and expiry, so a hundred runs now and then have none of it; the seed draws the same
runs every build, so the test can’t fail one build in a thousand on that. A state
outside the constants is counted as having left the model, not failed, and the pass says what
share did; a spec too big for a graph is followed by
TLC traces instead, which check every step.
A planted race
Section titled “A planted race”A desk whose check forgets what’s already reserved approves two orders against the same position:
/** * 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());}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'From A approved and B new, the spec allows only B rejected, with 15 reserved; the desk approved B
and reserved 30. proptastic shrank the run to the two steps that show it. The pin is ReserveStep’s, typed:
pasted on a test of the fixed desk, it’s checked when it compiles, against the interface.
differs names just the variables the desk’s step got wrong, down to the order: reserved and
status[B], from what the spec allowed to what the desk did. Where the spec allows no such step at
all, the line is changed, from the state before the step.
keeps says which of the invariants Reserve.cfg names still hold in the desk’s state. Here both
do: the desk has broken the design, but not yet the limit, since nothing has executed. A step that
broke one would say so, breaks invariant Within: position <= Limit, with position = 110, Limit = 100, with the values the invariant reads. proptastic doesn’t evaluate TLA+ itself: it runs TLC on
a module that extends the spec, with the desk’s state as its only initial state and the constants
from the config, so any invariant TLC can check is checked as TLC means it. That needs TLC, the
tla2tools.jar your build already fetches to dump the graph: set PROPTASTIC_TLC to its path
where the tests run, as Gradle’s environment("PROPTASTIC_TLC", …) on the test task does. Without
it, the failure says the invariants weren’t checked, and why. It runs once, for the failure that’s
shown, never while shrinking, and not at all while mutastic runs your tests against a mutant.
Why the spec needs last
Section titled “Why the spec needs last”Every TLA+ spec allows a step that changes nothing, a stutter, so that it can sit inside a larger
system that takes steps of its own. That breaks a naive check. Suppose the desk’s execute silently
did nothing: the state after it equals the state before, which is a stutter, which the spec allows.
A dropped step would look exactly like a correct refusal. And TLC’s graph labels an edge with the
action’s name only, never its arguments, so Reserve("A") and Reserve("B") can’t be told apart
where they reach the same state.
So the graph needs a history variable, last, that every action sets to its own name and
arguments: last' = <<"Reserve", o>>. Then each action that can be taken makes a state of its own,
and a step that changes nothing passes only where the spec has no such step for those arguments.
You don’t write it. io.proptastic.tla.Followed writes a module that extends your spec, declares
last and records it in each action of Next, and you run TLC on that module instead: Followed models/tla/Reserve.tla models/tla/Reserve.cfg build/tlc writes ReserveFollowed.tla and its
config. Your spec stays as you designed it. Its Next must be actions joined by \/, each perhaps
under \E, as here; a Next of any other shape is refused, saying where, and then you add last
to the spec yourself, which spec(…) reads the same way. A graph without last is refused.
Adding a history variable doesn’t change what a spec allows: Lamport and Merz show it in
Auxiliary Variables in TLA+. Quint, another TLA language, adds
the same thing itself for model-based testing: quint run --mbt records
mbt::actionTaken and mbt::nondetPicks in every
state. The cost is a bigger state graph: up to one copy of each state for every action and argument
that reaches it.
Where models go
Section titled “Where models go”A model is read by more than the tests that follow it: people review a spec before the code
exists, and several tests can follow one model. Tucked into a test’s source set, or under a path
each test spells out, it’s hard to find and easy to leave behind when a test moves. So models have
a place of their own, at the top of the project beside src:
models/ tla/ Reserve.tla the spec Reserve.cfg the constants TLC checks it with Reserve.dot the state graph TLC dumped lean/ lakefile.toml a Lake project Trading.lean the calculation, and its proofs Main.lean the model's program, which Lake builds as tradingA model named without a path is looked for there:
spec("Reserve", …)readsmodels/tla/Reserve.dot. TLC checks a spec by the config of its own name unless told otherwise, soReserve.cfgbeside it is the config the graph comes from. With no graph there, as for a spec too big for one, it followsReserve.tlaby TLC traces, atReserve.cfg’s constants.lean("Trading")runs the program Lake built inmodels/lean:trading, the model’s name in lower case with a hyphen between words, aslake newnames a program (TradingDeskistrading-desk). Build it withlake buildthere before the tests run.
models is in the directory the tests run in, which under Gradle and Maven is the project’s, or
the module’s in a build of several. To keep models elsewhere, set PROPTASTIC_MODELS to the
directory (see Settings). A path still works where you
want one: spec("Reserve", Path.of("reserve.dot"), …) and lean(Path.of("lean"), "desk-model").