Over the last few weeks the reading app I’m building gained three small TLA+ models. The first covers how a reading position is saved and synced between devices, the second the object that owns an open book (who may write its position, and when a delete may hold it), and the third the app-lock session and the windows that follow it. I want to write down how they’re set up and the two habits that make a pass from one of them worth trusting.
A short intro to TLA+
TLA+ is a specification language Leslie Lamport designed for describing concurrent and distributed systems (the TLA stands for Temporal Logic of Actions). A spec in it describes the state a program holds, the states it can start in, and every step it may take from any state, and it leaves out everything else about the program. TLC, the model checker that ships with the TLA+ tools, starts from the initial states, applies every enabled step in every possible order, and checks your properties in each state it reaches. It searches breadth first, so with a single worker the trace it reports for a violation is a shortest one, which matters a lot when you have to read it.
The classic example is two tasks incrementing a shared counter, where reading the value and writing it back are separate steps. In Swift that’s the shape of an actor whose value is read and written in two awaited calls, let c = await counter.value and then await counter.set(c + 1), since the actor serializes each call but anything can run between them:
---- MODULE Counter ----
EXTENDS Naturals
VARIABLES count, tmp, pc
vars == <<count, tmp, pc>>
Procs == {1, 2}
Init == /\ count = 0
/\ tmp = [p \in Procs |-> 0]
/\ pc = [p \in Procs |-> "read"]
Read(p) == /\ pc[p] = "read"
/\ tmp' = [tmp EXCEPT ![p] = count]
/\ pc' = [pc EXCEPT ![p] = "write"]
/\ UNCHANGED count
Write(p) == /\ pc[p] = "write"
/\ count' = tmp[p] + 1
/\ pc' = [pc EXCEPT ![p] = "done"]
/\ UNCHANGED tmp
Done == /\ \A p \in Procs : pc[p] = "done"
/\ UNCHANGED vars
Next == Done \/ \E p \in Procs : Read(p) \/ Write(p)
AllCounted == (\A p \in Procs : pc[p] = "done") => count = 2
====
A primed variable (count') is the value in the next state, /\ and \/ are “and” and “or”, and each action is a condition on the current state plus a description of the next one. Done lets the finished system stay where it is, because otherwise TLC reports a state with no step out of it as a deadlock. A small config file names the formulas TLC should use, and the bounds of bigger models go there too, as constants:
INIT Init
NEXT Next
INVARIANT AllCounted
java -cp tla2tools.jar tlc2.TLC -workers 1 Counter
TLC reports that AllCounted is violated and prints the four steps that do it, where task 1 reads 0, task 2 reads 0, and both write 1. If we merge Read and Write into one Increment action, the same check passes, because the model no longer has a gap for the other task to get into.
What makes this useful for app code is that the bugs it’s good at are the ones our tests are worst at. A race needs one particular ordering, and a test either never produces it or produces it once in a few hundred runs, while TLC enumerates the orderings instead of sampling them. Within its bounds, a model with a few thousand or a few million states is checked completely, so a pass means no ordering of those steps breaks the properties. You have to be exact about what that covers, though. The properties here are safety properties (something bad never happens), checked over every reachable state and step of the model at those bounds, which says nothing about whether things eventually happen, or about the real code wherever it differs from the model. None of this is exotic either, Amazon wrote years ago about using TLA+ on S3 and DynamoDB, and getting started took the tools jar, a Java runtime and Lamport’s free video course.
How the models are set up
Each model lives in a folder next to the code it describes, and they mostly share a layout:
- the
.tlaspec, with one action per stretch of code that runs without anything else getting in (oneMutexsection, one reducer pass, or the part of an effect between twoawaits), - base configs that must pass,
- configs that must fail on a named property, either a
bug-*config that switches on one re-introduced defect through a model constant, a replay of a bug that was fixed, or a known finding that isn’t fixed yet, - a
run.shthat knows the expected verdict of every config, - a list of the source files the model describes, and a table mapping each action to the function it stands for.
The open-book and app-lock models have bug-* configs, while the position model, which is older, has its replays and two known findings instead. If you copy one thing from this setup, make it the expected verdicts. Trimmed down, the position model’s runner looks like this:
expect() {
case "$1" in
core | torn-safety | supersession) echo "pass" ;;
intent) echo "violation:LocalSaveHonored" ;;
supersession-before-*) echo "violation:ObservedSamplesCovered" ;;
esac
}
# for each config: run TLC, then read which property (if any) it reports violated
if [[ "$got" == "$want" ]]; then
echo "OK ${cfg}: ${got} (expected)"
else
echo "MISMATCH ${cfg}: got ${got}, expected ${want}"
fi
The verdict names the property, so a config that fails on the wrong property is a mismatch too. When you get a green run, it means every config gave its recorded verdict, which is not the same as every property holding, since a known finding is a config that must keep failing while the passing configs leave out the property it breaks. And because the model reads no Swift, a MISMATCH that isn’t a TLC or Java error comes from a change to the model, either someone mirroring a code fix in it or someone weakening a property until it can’t fail.
The pre-PR checks rerun a model when a branch touches one of its listed source files, which takes about a minute for the app-lock model and about five for the open-book one. That run can’t see what changed in the Swift, it only shows the model still gives its verdicts. What keeps the model in step with the code is reading the change against the action table and updating the actions that no longer match.
Steps as small as the code’s
The position model was already there when I added it to the pre-PR checks, and while doing that I added a replay of an old bug in how position samples are saved. The app coalesces samples, so a sample that turns up after a newer one has been registered counts as superseded and doesn’t replace the newer position, and the book’s record of the newest sample stays in place until every registered caller has released. The old bug was that a superseded sample could carry a higher point in the book than the one that won, and skipping it lost that point.
The rule is that every await in the code is a place where the model needs a step boundary, since anything can run there. In the position model I had first done the write’s commit and its release in one action, because they’re close together in the code, but they’re separated by an await. The commit runs inside a closure on a serial queue, and the release is a defer that runs only after the await on that queue returns, so another caller can register in between. Once I split them into two actions, TLC found a way to lose the peak that the replay didn’t cover. An older sample that saw a higher position registered after the newer sample had committed but before the release, still counted as superseded, and disappeared without its higher point being written anywhere. Here are the two actions, simplified, with the switch that re-introduces the bug for the replay config:
Drain(d) ==
/\ Len(queue[d]) > 0
/\ LET sample == Head(queue[d])
superseded == sample.at < newest[d]
IN IF superseded
THEN IF PersistSupersededPeak
THEN CommitPeak(d) \* raise the stored point, keep the winner
ELSE UNCHANGED <<row, side, clk, dirty, top>>
ELSE CommitEdit(d, sample.p)
/\ queue' = [queue EXCEPT ![d] = Tail(@)]
/\ completed' = [completed EXCEPT ![d] = @ + 1]
Release(d) ==
/\ completed[d] > 0
/\ completed' = [completed EXCEPT ![d] = @ - 1]
/\ IF completed[d] = 1 /\ Len(queue[d]) = 0
THEN /\ newest' = [newest EXCEPT ![d] = 0] \* the last release ends the record
/\ peak' = [peak EXCEPT ![d] = 0]
ELSE UNCHANGED <<newest, peak>>
The property it broke says that once everything registered has drained and released, the device’s stored floor (side[d].f) covers the highest position any registered sample carried (observed[d]):
ObservedSamplesCovered ==
\A d \in Devices :
(Len(queue[d]) = 0 /\ completed[d] = 0) => side[d].f >= observed[d]
The trace was short enough to turn straight into an integration test that holds a registration until the newer sample has committed, and that test failed on the real repository code the same way. The fix writes the higher point into storage for a superseded sample while keeping the newer position selected. The model kept both replays as configs, the original bug and the interleaving found here, and both must still violate ObservedSamplesCovered, while the current config, at 400 states, must pass.
The app-lock model needed the same split in a different place. Each window follows the session through change notices, and the follow effect’s read of the session had been folded into the reducer step that applies it. In the code the read happens in the effect, off the main actor, and its result reaches the reducer only through an await send, so other actions can be reduced in between. Splitting it was the right call and an expensive one, since a read in flight is one more piece of state per window, and the two-window config went from 728,822 to 7,712,882 distinct states (the same change also added an abandon step, so not all of that growth is the split).
What brought it back was being stingy with bounds, which is the main knob TLC gives us. Only a few configs still get two windows and generations up to 3, and the rest take either two windows up to 2 or one window up to 3. When you cut a bound, what it costs depends on the config. For a config that must fail, a bound too small to reach its defect turns it into a pass, and the runner reports that as a MISMATCH. For a config that must pass, a smaller bound is a weaker check and nothing flags it, so I chose those bounds by hand, and the passing configs now cover less than they did before the split, which I accepted to keep the run short. The run is now 21 configs and 10 properties plus a type invariant, in about 1 minute 15 seconds.
Seeing every property fail
A property is only worth something if it fails under a mutant of each behaviour it’s there to guard, and one bug-* config per property doesn’t show that. The app-lock model had its bug-* configs and they all failed, but a review that ran mutants of its own against the model’s actions found three that passed every config. The clearest one was a lock that never notified the windows. The property about windows excused any window that was merely behind the session, and with no notice ever arriving, a window that never followed anything counted as merely behind. I added properties for what those mutants broke, including one that says a window with nothing unread and no read in progress mirrors the session the authority presents, and each mutant then failed on one of them.
It helps when someone other than the property’s author picks the mutants, since I keep writing properties that are a bit too forgiving, and because a mutant is an edit to the model’s actions rather than to the Swift, trying one is quick.
Summary
The position model found a lost update that the tests didn’t have, and it found it only after its steps were as small as the code’s, with an await between commit and release becoming two actions. The app-lock model showed the cost of doing that (the two-window config’s state space grew about ten times, and the bounds had to be cut per config) and also that a property seen failing once can still be too weak. So before trusting a pass, I now check that every action covers no more than the code runs without an await in it, and that each property fails under mutants of the behaviours it guards, chosen by someone who didn’t write it.