TLA+ is a language for describing systems and asking precise questions about their behavior. This course follows Leslie Lamport's TLA+ Video Course lecture by lecture, then carries the same method into failure-prone architectures.
The whole route. Each arrow is one step harder: lectures 1 to 4 build one small spec, 5 to 7 model real protocols, 8 to 10 ask what implementing a spec means, and the last row applies the method without a video.
Follow the route in the diagram. The top row starts from nothing and ends with your first real protocol. The second row runs right to left through commit protocols and into the question of what it means for one spec to implement another. The bottom row has no videos. It applies what you learned to concurrency, large models, failures, and application design, and it ends with review.
TLA stands for Temporal Logic of Actions. A specification, or spec, is a precise description of what a system is allowed to do. It is not a program that serves requests. You decide what matters, how it can change, and what must stay true, and then a tool searches for a counterexample. The value is often finding that a design you can explain convincingly still allows a bad execution.
The video in this lesson is Lamport's talk “Thinking Above the Code.” Watch it for motivation. No later lesson depends on its details, so you can return to it at any point. Its main example, Quicksort, is worked through at the end of this lesson as a lab, as code, and as a TLA+ spec.
How to study with the videos
Each lecture has one or more lessons here, in the lecture's order and with its examples. When a lecture spans several lessons, each lesson says which part of the lecture it covers. Its “While you watch” section tells you what to look for, where to stop and try the problem yourself, and what the lesson adds. Each video is meant to be viewed along with its web page on Lamport's course site. The videos and that site need internet; the lesson text and the labs work offline.
One pass per video segment. The dashed arrow matters most: a result you did not predict is the thing to study.
Watch a segment, not a whole lecture. Lamport often tells you to stop the video and solve something. Do it.
Predict. Before you click a step or open an answer, write down what you expect.
Run it. Step the lab, or run the real tool once you have installed it.
Break it. Weaken a condition or change a step, then predict the failure.
Explain it. Close the lesson and rebuild the model or the argument from memory.
The dashed arrow in the diagram is the most useful one: a surprise means your mental model and the system differ, so go back and predict again. In your next session, recall the previous lesson before continuing. Mark a lesson studied only when you can explain its exercise without looking. The Mac app saves completed lessons, notes, and reading position on this Mac. The standalone file saves in your browser when browser storage is available.
A lab is not a verification. The interactive labs run small, purpose-built JavaScript models. They do not read TLA+ and they are not the model checker. Complete modules are printed so you can check them with the real tools, which you install in lesson 8.
Scope and prerequisites
You need basic programming intuition, not a mathematics degree. Each piece of notation is introduced when it is first needed. The lectures cover safety, liveness, and implementation. The later parts add concurrency, proof structure, model reduction, time, crash recovery, and consensus. This is a substantial foundation, not a complete language reference or a proof of any deployed system.
A first example: an upload button
Here is the kind of question the course teaches you to ask. A document-sharing app has an Upload button, and a designer says, “Disable the button while the upload is running.” That sentence hides several choices. Can the request succeed after the screen times out? Does Retry create another document?
Two paths from the same tap. Every screen on the lower path looks reasonable, yet it ends with two documents.
Each box in the diagram records only two things: where the upload is, and how many documents exist. The upper path is the one everyone pictures. On the lower path the server commits, the reply is lost, the screen times out, and the user retries. No single screen looks wrong, and the final box has two documents. Nothing about the button's appearance appears in the diagram, because the button is not what went wrong.
Keep a prediction notebook with three lines for each claim: claim, suspected breaking path, evidence needed. For this app: “one upload creates at most one document; a lost reply followed by a retry might break it; inspect how the server recognizes a repeated request.” That is a concrete question for implementation, not a vague instruction to make uploads reliable. By the end of the lectures you will be able to write this as a spec and have a tool find the lower path for you.
Predict: is disabling the Upload button enough to guarantee one document?
No. It prevents one local interaction but says nothing about the lost reply and retry in the diagram. The server needs a way to connect a repeated request to the same result. The button can improve the experience, but the server has to enforce the rule.
Quicksort, above the code
The main example in Lamport's talk is Quicksort. Most programmers describe it as a recursive procedure: partition the array, then sort each half. That describes code. Lamport describes it one level up, without recursion:
Keep a set U of index intervals that still need sorting. At the start it holds one interval, the whole array.
Remove any interval from U. If it has one element, it is already sorted.
Otherwise, partition it at some index p, so that every value in the left part is at most every value in the right part. Put both parts back in U.
When U is empty, the array is sorted.
The important word is “any.” The description doesn't say which interval to take next. A recursive program takes the newest one, so it is using a stack. A loop over a work queue takes the oldest one. Several threads could each take a different interval at the same time. All three are Quicksort, because each does something the description allows.
Three programs and one spec. Each program makes a choice that the spec leaves open, and each is still Quicksort.
Sort it yourself
Each bar is one array element, with its index underneath. The brackets under the bars are the intervals in U, and a green bar is in its final place. Press an interval in the first row to choose it yourself. The next two buttons choose for you, the way a program would. U remembers the order in which intervals were added. Newest (stack) takes the interval added most recently, like taking the top plate from a stack. That is what the code below does with pop. Oldest (queue) takes the interval that has waited longest, like the front of a line, so the array is split one level at a time. A partition adds its left part first and then its right part, so the right part is always the newest. The dashed line shows where the last partition split its interval. This runs the JavaScript code printed below one step at a time; it is not TLC.
Sort the array once with each button, then compare the two readouts. The steps come in a different order and the arrays in between differ, but both runs end with the same sorted array. Also notice when a bar turns green: only when its interval is down to one element, and after that it never moves.
The iterative code
This is the program the lab runs. The array todo plays the part of U, and pop makes it a stack. Change pop to shift and it becomes a queue, and it still sorts.
function quicksort(a) {
const todo = [[0, a.length - 1]]; // U: intervals still to sort
while (todo.length > 0) {
const [lo, hi] = todo.pop(); // choose one: here, the newest
if (lo >= hi) continue; // one element is already sorted
const p = partition(a, lo, hi);
todo.push([lo, p], [p + 1, hi]);
}
return a;
}
// Hoare's partition. Returns p with lo <= p < hi, and
// rearranges a[lo..hi] so every a[lo..p] <= every a[p+1..hi].
function partition(a, lo, hi) {
const pivot = a[Math.floor((lo + hi) / 2)];
let i = lo - 1, j = hi + 1;
for (;;) {
do i++; while (a[i] < pivot);
do j--; while (a[j] > pivot);
if (i >= j) return j;
[a[i], a[j]] = [a[j], a[i]];
}
}
Hoare's partition is the hard part to get right, with its two indexes that cross. The description doesn't care how it works, only what it guarantees: p lies between lo and hi - 1, values outside lo..hi don't move, and every value up to p is at most every value after it.
The same algorithm in TLA+
Here is the description written as a TLA+ spec. For now, read it for its shape; Lectures 2 to 4 teach the notation. Init says the array may hold any values and that U holds the whole array. Partition is one step. It chooses any interval in U, then any p and any rearranged array B that meet the three conditions of a partition. Nothing in it mentions pivots, swaps, stacks, or recursion.
------------------------------ MODULE QuickSort ------------------------------
EXTENDS Integers, FiniteSets
CONSTANTS N, Values
Idx == 0..(N-1)
VARIABLES A, U \* the array, and the set of intervals still to sort
vars == <<A, U>>
Count(B, v) == Cardinality({i \in Idx : B[i] = v})
IsPerm(B) == \A v \in Values : Count(B, v) = Count(A, v)
Sorted == \A i, j \in Idx : i < j => A[i] =< A[j]
Init == /\ A \in [Idx -> Values]
/\ U = {<<0, N-1>>}
\* Pick ANY interval in U. The spec does not say which one.
Partition == \E I \in U :
LET lo == I[1]
hi == I[2]
IN IF lo < hi
THEN \E p \in lo..(hi-1), B \in [Idx -> Values] :
/\ \A i \in Idx \ (lo..hi) : B[i] = A[i]
/\ IsPerm(B)
/\ \A i \in lo..p, j \in (p+1)..hi : B[i] =< B[j]
/\ A' = B
/\ U' = (U \ {I}) \cup {<<lo, p>>, <<p+1, hi>>}
ELSE /\ U' = U \ {I}
/\ UNCHANGED A
Done == U = {} /\ UNCHANGED vars
Next == Partition \/ Done
Spec == Init /\ [][Next]_vars /\ WF_vars(Partition)
SortedWhenDone == U = {} => Sorted
Terminates == <>(U = {})
==============================================================================
The model checker reads a small configuration file that picks sizes for the constants and names what to check:
With 4 elements and values from 1 to 3, TLC tries all 81 starting arrays and every order of choosing intervals, 731 distinct states, in about a second. SortedWhenDone says the array is sorted once U is empty, and Terminates says U does become empty. That leaves a separate and smaller question: is every step of the code a step the spec allows? lesson 26 is about that question.
Predict: a bug puts only the left part back, <<lo, p>>. Which property fails, and how long is the shortest failing behavior?
SortedWhenDone fails, and TLC needs only three states. The array 1, 1, 1, 2 is partitioned at p = 0 into 1, 1, 2, 1. The bug drops the right part, the left part has one element, and U is empty while 2 still comes before 1. Terminates still holds, since a program that forgets work finishes sooner. Tests on arrays that are already sorted would all pass.
Find the design error before there is code to debug.
The upload example in lesson 1 went wrong in the design, not in any line of code. TLA+ exists to catch that kind of error, by letting you model a system above the code level and check the model.
Two routes for the same design error. On the top route you need a test that happens to hit a rare interleaving. On the bottom route TLC finds it first, and the dashed arrow returns to the design before you have written any code.
The diagram shows the argument of this lesson. A design error can sit in a system whose every function is correct. On the top route, you find it only if a test happens to hit the right circumstances, and the errors TLA+ aims at are the ones that are extremely hard to hit by testing. On the bottom route, you write the design down precisely and a tool checks it, so the dashed arrow takes you back to the design before you have written any code.
What TLA+ is
TLA+ is a language for high-level modeling of digital systems, and it comes with tools for checking those models. The tools you will hear about in the lecture are:
TLC, the model checker. A model checker explores the states a model can reach and tests your claims about them. This is the most important tool, and the one you will use.
TLAPS, the TLA+ proof system. Writing and checking proofs is a lot of work, and few engineers will use it.
The Toolbox, an IDE for writing specs and running the tools. lesson 8 also covers the VS Code extension.
“Digital systems” includes algorithms, programs, and computer systems. “High-level” means at the design level, above the code. You can't generate code from a TLA+ spec, and that is a choice about what the language is for, as you will see below.
TLA+ was designed for concurrent and distributed systems. Lamport's advice is direct: if you design such systems and care whether they work, use TLA+ or some other method to specify and check the design precisely. For other programming, he says plainly that he doesn't know exactly how useful it is. In his own small programs it sometimes helps and sometimes doesn't. His broader claim is that it gives most engineers a new way of thinking, which helps even when the language and tools don't apply.
Abstraction is the skill you are learning
Abstraction means simplifying by removing irrelevant details. Lamport calls it perhaps the most important part of engineering, since you can't get a complex system right unless you understand it, and you understand it only through abstraction. He credits his best-known work to this ability: stating important problems that details had hidden.
What a high-level model keeps and drops. The examples on the right are illustrations; what counts as critical depends on what you are trying to get right.
In the diagram, a model keeps the left region and drops both right regions: the parts that matter less, and the lower-level details of how things are implemented. Choosing that boundary is the hard part. The former Intel engineer quoted in the lecture says the same thing: the difficulty in learning TLA+ is learning to think abstractly about the system, and doing so improves the design process.
What engineers report
The lecture gives two pieces of evidence. Treat them as reports from specific teams, not as promises.
Who
What they reported
Amazon Web Services, in the 2015 Communications of the ACM paper
Used on 10 large, complex systems when written (14 by some time in 2014, per Lamport), by 7 teams. It added significant value in each: subtle bugs they were sure they wouldn't otherwise have found, or the confidence to make aggressive optimizations. Engineers from entry level to principal got useful results in 2 to 3 weeks.
A real-time operating system team led by Eric Verhulst
The TLA+ abstraction led to a much cleaner architecture. The code was about 10 times smaller than the previous version, which flew on the Rosetta spacecraft.
The second result answers a question you may already have. If a spec doesn't produce code, why not spend the time improving the code? Because you don't get a factor of 10 from better coding. You get it from a cleaner architecture, and an architecture is a specification above the code level. That team described theirs as a TLA+ spec and debugged it with the tools. Don't expect a tenfold reduction yourself: it is one case.
What you can check
“Works right” has to become something a tool can test. The properties TLA+ can check are conditions on individual executions. A system satisfies such a property if and only if every possible execution does.
A property TLA+ can check is a yes-or-no question about one row. Execution 3 alone is enough to fail “never produces a wrong answer”. “99% are right” is about the whole collection of rows, so no single row can decide it.
Read the diagram one row at a time. “Doesn't produce a wrong answer” can be judged by looking at one row, and execution 3 fails it, so the system fails it. “99% of executions produce the right answer” can't be judged from any single row. It describes the collection, so TLA+ can't check it.
Predict: can TLC check “95% of requests finish successfully”? What about “no request is charged twice”?
The first is a statistic over many executions, so no. The second can be judged by examining one execution: did any request get charged twice in it? So yes, once you have modeled requests and charges. When a requirement is statistical, look for the per-execution rule underneath it.
While you watch
This lesson covers Lecture 1 from the start through “What can you check with TLA+?”. lesson 3 covers the rest, starting at “The basic abstraction.”
Look for: what “high-level” excludes, and the distinction between the two Amazon benefits (finding bugs, and gaining confidence to optimize).
Pause after the Amazon and Rosetta reports. Write down one design in your own work where a bug would be very hard to reach by testing.
Pause at the 99% example. Take one requirement you know and decide whether a single execution could violate it.
This lesson adds the two-routes picture and the row-by-row view of properties.
lesson 2 said TLA+ checks conditions on individual executions. To do that, an execution has to be something precise. Here it becomes a sequence of states, and a whole system becomes a state machine that allows many such sequences.
Two behaviors of the same program. Each column is a state; each move to the next column is a step. Which number someNumber returns is a choice, so several behaviors are possible.
The diagram shows two executions of the small C program you will meet below, drawn the way TLA+ sees them. Three words define that view: an execution is a sequence of discretesteps.
Discrete, sequence, step
Discrete. A digital system is a physical system whose continuous evolution we can abstract as separate events. Lamport's example is the first self-powered digital system, the escapement clock: its parts move continuously, but we can describe it as an abstract clock advancing in ticks. A computer running a program is the same kind of abstraction.
Sequence. It may seem odd to describe a concurrent system, where several things happen at once, as one sequence. It is clearly possible, since a sequential program can simulate a concurrent system. As the course goes on, you will see that it also works well.
Step. A state is an assignment of values to variables. A step is the change from one state to the next. A behavior is a sequence of states. So in the diagram, run 1 and run 2 are two behaviors, each with three states and two steps.
State machines
You want to describe all possible behaviors of a system, not just one. Programming languages, Turing machines, automata, and hardware description languages can all do that. TLA+ uses the abstraction underneath all of them, a state machine, which you describe by saying three things:
What the variables are.
Their possible initial values.
The relation between their values in the current state and their possible values in the next state.
A state machine halts if it reaches a state with no possible next state.
A tiny example, and the problem it exposes
int i;
void main()
{ i = someNumber();
i = i + 1;
}
Assume someNumber() returns an arbitrary number from 0 to 1000, possibly different on each execution. C initializes i to 0. The obvious model has one variable, i, with one initial value, 0. Now try to write item 2. What can follow i: 43?
Why i alone fails. A state machine has one rule per state, but the red state would need “no next state” for run 1 and “i: 44” for run 2.
Follow the red state in the diagram. In run 1, the call returned 42 and the increment produced 43, so the program has finished: there is no next value. In run 2, the call returned 43, so the next value must be 44. The same current state needs two incompatible rules. So this program can't be described as a state machine with i alone.
The missing part of the state says which statement runs next. It is called the control state, and we represent it with a second variable, pc, for program control. pc equal to "start" means the first assignment is next, "middle" means the second is next, and "done" means execution has finished.
The same program with control state. Four of the 1001 choices are drawn. Value 43 now lives in two different states: i: 43 with pc: middle moves on, and i: 43 with pc: done halts. The conflict is gone.
In the diagram, there are now two distinct states with i: 43, and each has its own rule. The relation can be stated, for now in English:
if current value of pc equals "start"
then next value of i in {0, 1, ..., 1000}
next value of pc equals "middle"
else if current value of pc equals "middle"
then next value of i equals current value of i + 1
next value of pc equals "done"
else no next values
That is awkward to read, and lesson 5 turns it into a formula. But notice what has already been gained. A program represents parts of its state differently because they are implemented differently: variables, control state, call stack, heap. A state machine represents every part the same way, as values of variables. Those implementation details are gone, and you have one simple abstraction.
Worked app example: a login screen
The same idea applies far from C. Model a login screen with a variable phase, whose values are idle, submitting, signedIn, and failed, and a variable for the request being processed.
Alternative next states, not a sequence. From submitting, one arrow is taken in each behavior. The dashed arrow is a rule the model must exclude.
From submitting, the diagram has two arrows. They are alternative next states, and any one behavior takes just one of them. To practice, draw the graph without code, put concrete values in each node, and name each arrow. Then invent a transition that should be impossible, like the dashed one from failed straight to signedIn. A graph is useful only if its rules exclude that arrow.
Now suppose a developer stores both phase and isLoading. The combination signedIn with isLoading true becomes representable, although it should never occur. A spinner is derived from phase equal to submitting, so unless it can really vary on its own, leave it out of the model. A state with fewer independent variables is easier to reason about.
Predict: are x = 1, y = 2 and x = 1, y = 3 the same state?
No, if both x and y are variables of the model. If you deliberately leave y out, those two situations become one state. What you choose to model decides which differences exist. In the C example, adding pc did the reverse: it split one state into two.
Predict: does a disabled Submit button mean the machine has no arrow from idle to submitting?
Only if the button is the only trigger. If a programmatic retry or another event can start a login, the arrow exists regardless of the button. Model what can actually happen, not what one control suggests.
While you watch
This lesson covers Lecture 1 from “The basic abstraction” to the end. lesson 2 covers the earlier part.
Look for: the three items that describe a state machine, and how “state” is defined exactly as it is in other sciences.
Pause when the lecture asks what can follow 43 and before pc appears. Try to find a rule for it, and watch it fail.
After the English relation appears, pause and draw the graph yourself for someNumber() returning only 0 or 1.
This lesson adds the state graph, which later lessons use constantly, and the login example.
Lecture 1: Introduction to TLA+
Problem set 1: describe a system as states and steps.
These problems practice Lecture 1: what a state, a step and a behavior are, which claims a single execution can settle, and how abstraction decides which variables a model keeps. They draw on How to study this course, Why think above the code and States, steps, and behaviors. You have no TLA+ syntax yet, so answer in English, lists of states, and drawings of state graphs.
Write your answer down before you open a hint, and open the solution only after the checked question agrees with you. When a problem says “state,” it means an assignment of values to the variables you chose, exactly as in States, steps, and behaviors.
Problem 1●○○Embedded control
Which logs are behaviors of an elevator controller?
A small building has one elevator serving floors 1 to 3. Its controller tracks two things: the floor the car is at, and the door, which is closed, opening, open or closing. The design document gives these rules:
At power-on the car is at floor 1 with the door closed.
The door goes closed → opening → open → closing → closed, one change at a time.
While the door is closing, the obstruction sensor can send it back to opening.
The car moves one floor up or down at a time, and only while the door is closed.
Each change listed above is one step. The real controller also tracks motor current, the door's position in millimetres and several timers. This model leaves them out, which is the kind of abstraction Why think above the code described: they matter for building the controller, not for the question of which orders of events are possible.
An engineer copied five sequences from the controller's logs into the figure. Each cell is one state, written as floor and door.
Five sequences from the controller's logs. Each row is a sequence of states; each cell shows the floor and the door. Which rows are behaviors?
Describe the state machine in the three parts States, steps, and behaviors uses: the variables, their initial values, and the relation between a state and its possible next states. Write the relation in English, one case per kind of step.
For each sequence A to E, decide whether it is a behavior of this state machine. For each one that isn't, name the first state or step that breaks a rule, and the rule.
How many different states can the controller reach? Does the state machine ever halt?
A field report claims the car once moved one floor with its door open. Which arrow would the state graph need for that to be a behavior? Is it there, and what does that tell you about the report?
Hint
A behavior has to start in an initial state, and every consecutive pair of states has to be one allowed step. A step either changes the door along the cycle (or from closing back to opening) and leaves the floor alone, or changes the floor by exactly one while the door stays closed.
Solution
(a) The variables are floor and door. Initially floor is 1 and door is closed. The relation has two kinds of case. A door step keeps the floor and changes the door from closed to opening, opening to open, open to closing, closing to closed, or closing to opening. A move is possible only when the door is closed; it keeps the door closed and changes the floor to one more or one less, staying within 1 to 3.
(b) A is a behavior: a full door cycle at floor 1, then a move to floor 2. C is a behavior too: the door starts closing, the sensor reopens it at state 5, and it opens. B breaks at the step from state 3 to state 4, where the floor changes while the door is opening. D breaks at its first step, from floor 1 to floor 3, which skips floor 2. E breaks before any step: its first state is floor 2, and the only initial state is floor 1 with the door closed. So 2 of the 5 are behaviors.
(c) 12. There are 3 × 4 = 12 combinations of floor and door, and each can be reached: move to the floor with the door closed, then step the door to the value you want. The machine never halts, because every door value has at least one next door value, so every state has a next state. For an elevator that is correct: it should keep running. We checked this machine with TLC, which you install in Lecture 3; it found 12 distinct states.
(d) An arrow from a state with the door open to a state on the next floor, still open. A move is allowed only when the door is closed, so no such arrow exists, and no behavior of this machine moves with the door open. If the report is true, the real elevator is not this state machine. Either the code does not follow the design, or the model left out something that matters, such as a maintenance override. The model doesn't tell you which, but it turns a vague report into a precise question to ask.
Problem 2●●○Databases
One state or a whole behavior? Claims about a transaction
A relational database runs each transaction through a short lifecycle. After BEGIN the transaction is active. COMMIT makes its writes durable and visible to other sessions; ROLLBACK discards them. Postgres also has a failed status: if a statement inside a transaction block fails, the transaction becomes failed, every further statement is rejected with “current transaction is aborted, commands ignored until end of transaction block,” and, if no savepoints are in use, the only way out is to end the transaction, which rolls it back. This model leaves savepoints out.
Model one transaction with two variables: status, one of active, failed, committed and aborted, and visible, yes when other sessions can see its writes. The figure shows the state machine.
One transaction's lifecycle, with the value of both variables in each state. Committed and aborted have no outgoing arrows: the machine halts there.
Your team wants to write down what the database promises. Someone collects these claims:
The status is always one of active, failed, committed and aborted.
If the status is committed, the writes are visible.
If the writes are visible, the status is committed.
Once a transaction is committed, its status never changes again.
A transaction that was failed is never later committed.
Every transaction eventually becomes committed or aborted.
Fewer than 2% of transactions end aborted.
Sort the claims into three groups: those you can judge by looking at each state of an execution on its own, those that need you to compare states across a whole behavior, and those that are not conditions on a single execution at all.
Use the figure to explain why every behavior of this state machine satisfies claims 4 and 5.
Which states halt? Is halting there a bug?
Claim 7 matters to the operations team. Following the advice in Why think above the code, find a rule about single executions that sits underneath it, or explain why there isn't one.
Hint
Words like “once,” “never later” and “eventually” talk about time, so they need more than one state. A claim about a percentage of transactions talks about many executions; Why think above the code showed that kind with the 99% example.
Solution
(a) One state at a time: claims 1, 2 and 3. Each can be broken by a single state, for example status committed with visible no breaks claim 2, and status active with visible yes breaks claim 3. Whole behavior: claims 4, 5 and 6. No single state breaks claim 4; you need a committed state followed later by a different status. Claim 5 needs a failed state followed later by a committed one. Claim 6 needs the whole sequence, because it says something must happen eventually. Not a condition on one execution: claim 7. One execution can't show that 2% of transactions abort, so TLA+ can't check it.
(b) A behavior moves only along arrows. No arrow leaves committed, so once a behavior reaches it, there is no later state with another status: claim 4 holds. For claim 5, the only arrow out of failed goes to aborted, and no arrow leaves aborted, so a behavior that passes through failed can never reach committed. The two claims are about behaviors, yet you proved them by looking at the arrows, one step at a time. That is the method this course builds on.
(c) Committed and aborted have no next state, so the machine halts there. That is correct: the transaction is over. States, steps, and behaviors defined halting as reaching a state with no possible next state, and nothing about it is wrong in itself. Whether a stop is intended is something you decide about each system. Notice that active has no self-arrow either. This model doesn't say how long a transaction stays active, only which status comes next. Claim 6 is about something eventually happening, a kind of claim the course treats with care later on; this model leaves the question open.
(d) A per-execution rule underneath claim 7 might be “a transaction aborts only after an error or an explicit ROLLBACK.” In this model that holds, because every arrow into aborted is labelled with one of them. The percentage itself depends on how often clients send errors and rollbacks, which is a statistic about the workload. It belongs in monitoring, not in the model.
Your design system's Button is used for every asynchronous action in the product: Save, Pay, Send invite. The page sets its disabled prop and can change it at any time. Its onClick handler returns a promise. While the promise is pending, the button shows a spinner. When the promise resolves, it shows a check mark for two seconds and then returns to its normal look. When it rejects, it shows a red outline, and the user can click again to retry. Its styles also have hover and pressed colours and a 150 ms fade between looks.
A support ticket says a customer on a slow train connection double-clicked Pay and was charged twice. Before anyone changes code, the team wants a model of what the Button does. The figure shows the phases as one designer describes them.
The Button's phases as the team describes them. The dashed loop is the question behind the double charge: what does a second click do while a request is loading?
A teammate proposes four variables: phase (idle, loading, success or error), disabled (yes or no), hovered (yes or no) and spinnerVisible (yes or no). Which do you keep? For each one you drop, say whether it is redundant (its value is fixed by the others) or irrelevant to what a click can do. Where does the fade go?
The teammate's model has 4 × 2 × 2 × 2 combinations of values. How many of them describe a screen the component can never show, given that the spinner is visible exactly when the phase is loading?
With the variables you kept, suppose a second click while loading does start a second request. Write the step it causes. Can your model tell that state apart from the state before the click? If not, add the variable you need, and state “never two requests in flight” as a condition on a single state.
Write one behavior, as a list of states, in which the page disables the button while a request is loading. What should happen when the response arrives?
Hint
States, steps, and behaviors dropped isLoading from the login screen because it was derived from the phase. Do the same test here for each variable: is it determined by the others, and does it change what can happen next? For (c), draw the dashed loop in the figure as a step between two states and compare the two states' values.
Solution
(a) Keep phase and disabled. disabled must stay because the page changes it independently of the phase, at any moment, including while loading. Drop spinnerVisible as redundant: it is just “phase is loading,” like isLoading in States, steps, and behaviors. Drop hovered as irrelevant: hover changes a colour, but no rule about clicks or requests depends on it. The pressed colour and the fade are irrelevant for the same reason, and they are also details of timing and rendering below the level of this model. If a future design made hover matter, for example a tooltip that blocks the click, you would add it back.
(b) 16. There are 32 combinations. For each choice of phase, disabled and hovered, one of the two values of spinnerVisible matches the phase and the other doesn't. Keeping a redundant variable doubles the number of combinations and makes half of them impossible, which is a good reason to leave it out.
(c) With only phase and disabled, the second click would be a step from (loading, no) to (loading, no). The two states are equal, so the model can't see the second request at all, and the double charge is invisible. Add inflight, the number of requests started and not yet finished. The click is then a step from (loading, no, 1) to (loading, no, 2), and the requirement is “in every state, inflight is 0 or 1.” That condition looks at one state, and the bad behavior idle, loading 1, loading 2 breaks it in its third state. This is the general lesson: if a requirement talks about something, the state must contain it. You now have three variables. The next problem set turns this model into formulas.
(d) One such behavior: (idle, no, 0), (loading, no, 1), (loading, yes, 1), (success, yes, 0), (idle, yes, 0). Disabling stops new clicks; it doesn't cancel a request that has already been sent, so the response still arrives and the phase still changes. Whether a disabled button should show the check mark is a design decision. The model forces you to make it.
Keep the upload example from How to study this course in mind. Even a Button that ignores clicks while loading can't prevent a double charge by itself: if the reply is lost and the user reloads and pays again, the server needs a way to recognise the repeat. The model of the Button shows what the component can promise and what it can't.
Problem 4●●●CI/CD
Two deploys, twenty interleavings, one stale release
Your team's CI/CD pipeline deploys a service on every merge to the main branch. Each pipeline run does three steps, in order:
test: run the test suite;
read: read the version currently live from the deploy registry;
write: if its own version is newer than the one it read, set the live version to its own.
The check in step 3 exists so that an old build never replaces a newer one. Two merges land a minute apart: run A builds version 41, run B builds version 42, and version 40 is live. The team has an end-to-end test that starts two pipelines a minute apart and checks that 42 ends up live. It has passed 1,000 times in a row. The figure shows the order of steps it produces every time.
The interleaving the end-to-end test produces every time: run A starts a minute earlier and finishes before run B reads. Each column is a state.
Model the pair of runs as one state machine. Each numbered step of either run is one step of the machine. Each run does its own steps in order, but the two runs' steps can interleave, meaning they can mix in any order.
Choose the variables. Each run needs its own control state, like pc in States, steps, and behaviors, and something else that the read step must leave behind for the write step.
How many different interleavings of the six steps are there?
In how many of them is 41 live after both runs finish? Describe exactly which interleavings they are.
Write one bad behavior as a sequence of states. Then explain, using the two routes in Why think above the code, why 1,000 passing runs of the end-to-end test didn't find it.
Write a prediction-notebook entry for the claim “after both runs finish, the newest version is live,” in the three lines How to study this course suggests. Is the claim a condition on a single execution?
Hint
Write an interleaving as a string such as AABBBA, where the k-th A is run A's k-th step. For (c), ask when A's write can change the live version to 41 at all, and what A must have read for its check to pass.
Solution
(a) Five variables: live, the live version; pcA and pcB, each saying which step that run does next (test, read, write or done); and readA and readB, the version each run read. The read values are easy to forget, but the write step's check uses them, so they are part of the state. Initially live is 40 and both runs are at test.
(b) 20. Each run's steps stay in order, so an interleaving is fixed by choosing which 3 of the 6 positions hold A's steps, and there are 20 such choices.
(c) 6. For 41 to end up live, A's write must change the live version, so A must have read something older than 41, which means 40. And nothing may change it afterwards, so B's write must come before A's write. If B's write came before A's read, A would read 42 and do nothing. So B's write falls between A's read and A's write, and A's write is last. That makes the last two steps B's write then A's write. The first four steps, A's test and read and B's test and read, can come in any order that keeps each run's steps in order: 6 ways, namely AABB, ABAB, ABBA, BAAB, BABA and BBAA. So 6 of the 20 interleavings are bad. We checked this with a small TLA+ model of the two runs: TLC finds a state where both runs are done and 41 is live.
One of the six bad interleavings. B's whole read and write happen between A's read and A's write, so A's check compares 41 with a stale 40 and replaces the newer version.
(d) The diagram shows ABABBA. Each column is a state, and each move to the next column is one step. In state 4 A has read 40, and B then reads 40 too. B's check passes and it writes 42. A's check compares 41 with the stale 40 it read, passes, and replaces 42 with 41. Every step did what its code says; the error is in the design, the gap between reading and writing. The end-to-end test takes the top route in the diagram of Why think above the code: it finds the error only if the timing happens to produce it. With A a minute ahead, A reads and writes seconds apart while B is still running its tests, so the test produces the interleaving in the first figure every time. A bad interleaving needs B to finish its read and write inside that short gap, for example when A's runner stalls between the two steps. That happens rarely in testing and eventually in production. The state machine contains all 20 interleavings equally, so a model checker doesn't depend on timing: TLC found a bad one in our model on its first run.
(e)Claim: after both runs finish, the newest version is live. Suspected breaking path: the newer run reads and writes between the older run's read and write. Evidence needed: whether the registry can do the comparison and the write as one step, so that no other run's step can fall between them. Yes, the claim is a condition on a single execution: look at the last state of one behavior and check which version is live. That is the kind of property TLA+ checks.
Lecture 2: State machines in TLA+
The next-state relation is a formula, not a command.
lesson 3 ended with an English description of the tiny program's state machine. It is neither precise nor practical. Rewriting it as math gives you something that is simply true or false for each pair of states.
The formula is not run; it is evaluated on a pair of states. Green: 534 is in the set and pc' is right. Red: pc' is fine, but 77 is not 534 + 1.
That is the destination, shown in the diagram: a formula, and two pairs of states it is true or false for. The rest of this lesson builds the formula and then explains these two verdicts.
Why math?
Asked what a specification language should look like, most programmers want something like their favorite programming language. TLA+ uses ordinary, simple math instead, and most programmers first find that a bad idea. The team behind the real-time operating system from lesson 2 started out biased toward a C-like language and saw the math as a hindrance. They ended up calling it a major benefit, because it forced them to reason more abstractly about the system.
The initial values
The initial values are i equal to 0 and pc equal to "start". The word “and” becomes a math operator, which is && in some programming languages and ∧ in math. In the ASCII you type, it is /\:
(i = 0) /\ (pc = "start")
Turning the relation into notation
The English relation needs a handful of replacements:
English
Notation
Note
current value of pc
pc
An unprimed variable means its value in the current state.
next value of pc
pc'
Read “pc prime”: its value in the next state.
equals
=
Plain equality, as in 2 + 2 = 4.
in
\in
“Is an element of,” written ∈ in math.
{0, 1, ..., 1000}
0..1000
“...” is informal. .. is a precisely defined operator.
the two lines of a then clause
/\
There is an implicit “and”: both must be true.
no next values
FALSE
See below.
The last row needs thought. “No next values” must become a formula that isn't true for any values of i, pc, i', and pc'. The simplest is the formula that is always false: FALSE. Most TLA+ keywords are uppercase, so the result, as you would type it in ASCII, is:
IF pc = "start"
THEN (i' \in 0..1000) /\
(pc' = "middle")
ELSE IF pc = "middle"
THEN (i' = i + 1) /\
(pc' = "done")
ELSE FALSE
How to read it
The formula relates four values: i, pc, i', and pc'. It does not mean “if pc equals start, do the THEN part, otherwise do the ELSE part.” It means that if pc equals "start", the value of the whole formula equals the value of the THEN formula, and otherwise it equals the value of the ELSE formula.
How the IF formula gets its value. Nothing happens at any branch: the tree only picks which sub-formula's truth value the whole formula takes.
Use the tree to check the two pairs in the first diagram.
The true pair:i = 17, pc = "start", i' = 534, pc' = "middle". The first test is true, so the tree goes to the first THEN formula. 534 is in 0..1000 and pc' is "middle", so both parts are true and the formula is true. You may have noticed that i = 17 with pc = "start" never occurs when the program runs, since i starts at 0. That doesn't matter here: the formula has a value for any four values you give it.
The false pair:i = 534, pc = "middle", i' = 77, pc' = "done". The first test is false and the second is true, so the tree goes to the second THEN formula. pc' is right, but 77 does not equal 534 + 1, so the formula is false.
Predict: what is the value for i = 5, pc = "middle", i' = 6, pc' = "middle"?
False. The second test is true and i' = i + 1 holds, but pc' = "done" does not. An “and” needs both parts.
Predict: what is the value for i = 43, pc = "done", i' = 44, pc' = "done"?
False. Both tests are false, so the formula equals its last ELSE, which is FALSE. Any values of i' and pc' give the same answer when pc is "done", and that is what “no next values” means here.
How many next states?
Since the formula is just true or false for each pair, you can ask, for a given current state, how many next states make it true.
The same formula allows different numbers of next states. Nondeterminism is a set with many elements, and halting is a formula with no true pairs.
In the diagram, the start state has 1001, and that is how someNumber() has been described. Nobody says how the number is chosen, only that i' is in the set. The middle state has exactly one. The done state has none, and that is how a state machine halts. Nondeterminism and termination need no special machinery, since both are just the shape of a formula.
You now have the complete description as two formulas: the initial-state formula and the next-state formula. There is a nicer way to write the second one, which comes next.
While you watch
This lesson covers Lecture 2 up to “The Complete Mathematical Description.” lesson 6 covers the rest, starting at “A nicer way to write the next-state formula.”
Look for: the slides that replace one English phrase at a time. The formula gets its shape from that sequence of small substitutions.
Pause before each of the two evaluated examples and work out the value yourself. The false example is the one to get right.
The lecture also shows the pretty-printed form, with ∧ and ∈, next to the ASCII. Both are the same formula. This course prints ASCII because it is what you type.
This lesson adds the decision tree and the count of next states.
Lecture 2: State machines in TLA+
List the cases instead of nesting them.
The IF formula from lesson 5 works, but it won't scale. Using “or” and “and” as bulleted lists turns the same formula into a tree you can read at a glance, and that form is how nearly every spec in this course is written.
Indentation is the structure. Read it left to right. Each bullet column is one node of this tree: the outer \/ column picks a case, and each inner /\ column requires all three of its formulas.
From IF to “or”
Call the two THEN formulas A and B. The IF formula is true in exactly two cases: pc = "start" and A are both true, or pc = "middle" and B are both true. So the same formula can be written with “or,” which is || in some programming languages, ∨ in math, and \/ in ASCII. The final FALSE is no longer needed, because when pc is "done" neither case holds.
((pc = "start") /\ A)
\/ ((pc = "middle") /\ B)
Now put A and B back, drop the parentheses that no longer help, and use the form TLA+ provides for lists. An extra /\ in front of the first item turns the items into a bulleted list, with a line per item. The list ends at the first token to the left of its bullets, so no closing parenthesis is needed. \/ works the same way:
Next == \/ /\ pc = "start"
/\ i' \in 0..1000
/\ pc' = "middle"
\/ /\ pc = "middle"
/\ i' = i + 1
/\ pc' = "done"
This is what the tree at the top of the lesson shows. The outer \/ column is the root, with one branch for each case. Each /\ column is a node that requires all its lines. Indentation carries the structure, and widely separated matching parentheses are gone.
The vocabulary so far
ASCII
Read it as
True when
P /\ Q
P and Q
Both are true. Such a formula is a conjunction.
P \/ Q
P or Q
At least one is true, possibly both.
~P
not P
P is false.
P => Q
P implies Q
P is false, or Q is true.
v'
next value of v
Not a truth value: it lets a formula talk about the next state.
=
equals
The two sides have the same value.
==
is defined to be
Gives a name to a formula.
The lecture needs only /\ and \/. ~ and => complete the set you need before lesson 15, which adds quantifiers.
It is still a formula
The formula may look like commands, but it isn't. The order of lines carries no meaning, because \/ and /\ are commutative, meaning order makes no difference: swapping the two cases, or moving pc' = "middle" to the top of its list, yields an equivalent formula. The = means equality as in 2 + 2 = 4, while C's = means assignment, which isn't so simple.
The C code may look simpler because it is familiar, but compare the two on what someNumber() stands for. In the formula, nondeterminism takes a single line: i' \in 0..1000. Common programming languages were not designed to express this. We need it because we can't predict the order in which things happen in a real system, and in the math it is easy.
The complete spec
A spec lives in a module. The module name matches the file name. EXTENDS Integers imports arithmetic operators such as + and ... VARIABLES declares the variables. Identifiers must be defined or declared before they are used. Init and Next are only conventional names, but use them.
--------------- MODULE SimpleProgram ---------------
EXTENDS Integers
VARIABLES i, pc
Init == (pc = "start") /\ (i = 0)
Next == \/ /\ pc = "start"
/\ i' \in 0..1000
/\ pc' = "middle"
\/ /\ pc = "middle"
/\ i' = i + 1
/\ pc' = "done"
====================================================
A real next-state formula can run to hundreds or thousands of lines. Math has a simple way to split it up: definitions. This spec doesn't need splitting, but you can see the method by naming the two cases. You could call them Fred and Mary, but descriptive names are better:
Pick == /\ pc = "start"
/\ i' \in 0..1000
/\ pc' = "middle"
Add1 == /\ pc = "middle"
/\ i' = i + 1
/\ pc' = "done"
Next == Pick \/ Add1
Names for pieces of the formula are also names for kinds of step. Every arrow out of the start state is a Pick step, and every arrow into done is an Add1 step.
This Next is completely equivalent to the earlier one. We checked with TLC, and all three versions, the IF form, the bulleted form, and this one, produce the same 2003 states. The diagram shows why the names help: they name kinds of step, so you can label every arrow in the state graph.
Worked rules for a shopping cart
A cart can be submitted only when it contains items, the customer has accepted the terms, and the goods are in stock. Define the rule before attaching any step to it, to separate “may this happen?” from “what changes if it does?” Here, items, termsAccepted, and inStock are variables.
A conjunction fails as soon as any required formula fails. Eligible is true, yet CanCheckout is false.
In the diagram, the cart has items and the terms are accepted, so Eligible is true. But inStock is false, so CanCheckout is false.
The implication trap
P => Q is true whenever P is false. Take the module this cart comes from, where ordered records that checkout happened, and the claim ordered => termsAccepted. It holds in the checked model, but note what that claim would do in a model where checkout never happens: it would hold there too, since ordered is always false. A check that passes because its left side never occurs is called vacuous. An implication doesn't make Q happen, and it doesn't show that P ever happens.
Predict: with items = 2, termsAccepted = FALSE, inStock = TRUE, what are Eligible and CanCheckout?
Both false. Eligible fails on the terms, and CanCheckout includes Eligible. Being in stock can't make up for a missing requirement in a conjunction.
While you watch
This lesson covers Lecture 2 from “A nicer way to write the next-state formula” to the end. lesson 5 covers the earlier part.
Look for: the slide where the extra /\ appears and the parentheses vanish, and the rule for where a bulleted list ends.
Pause when the lecture compares the formula with the C code. Decide for yourself what each one says about someNumber().
Lamport says he prefers simple examples studied carefully over complex ones skimmed. Before moving on, rewrite Next from memory.
This lesson adds the tree view, ~ and =>, and the cart. Quantifiers come in lesson 15.
These problems practice Lecture 2: an initial-state formula, a next-state formula with primed variables, evaluating a formula on a pair of states, and splitting Next into named cases joined by \/. They draw on From a program to a state machine and Writing Init and Next with logic, and on the models you built in Problem set 1.
You run TLC in the next chapter, so for now check your formulas by evaluating them on pairs of states, as From a program to a state machine did. One consequence of reading Next as a formula matters in every problem. A case that says nothing about x' is true whatever the next value of x is, so it allows x to change arbitrarily. Until a later lesson gives a shorthand, write x' = x for each variable a case leaves alone. Some solutions also count states: a state that occurs in at least one behavior is called reachable.
A mobile app's HTTP client makes up to three attempts to send a request, stopping at the first success. Simplified, its code is:
bool ok = false;
int attempts = 0;
void fetchWithRetry()
{ while (!ok && attempts < 3) { // test
ok = send(); // send
attempts = attempts + 1; // count
}
} // done
send() returns true on success and false on failure, and any call can do either, just as someNumber() in States, steps, and behaviors could return any number. Model the program the way that lesson modeled the tiny C program, with three variables: attempts, ok, and pc, which is "test", "send", "count" or "done" according to which statement runs next. Testing the loop condition is one step. The figure shows the control flow you are writing down.
The retry loop's control state. Each box is a value of pc, and each arrow is one case of Next. The labels say when the case applies and what it changes.
Write Init.
Write Next as Test \/ Exit \/ Send \/ Count, defining each case as a bulleted /\ list, one case per arrow in the figure. Each case must say what the next value of every variable is.
Evaluate your Next on two pairs of states. First: attempts = 2, ok = FALSE, pc = "count" and attempts' = 3, ok' = FALSE, pc' = "test". Second: attempts = 3, ok = FALSE, pc = "test" and attempts' = 3, ok' = FALSE, pc' = "send".
List every state in which the program can be when pc = "done".
Hint
In Send, the next value of ok is TRUE or FALSE, and you have no set to put it in. “Or” is \/, so write two equalities joined by it, in parentheses. Exit applies when the while condition is false: negate it with ~.
Solution
------------------ MODULE PSl2_Retry ------------------
EXTENDS Integers
VARIABLES attempts, ok, pc
Init == /\ attempts = 0
/\ ok = FALSE
/\ pc = "test"
Test == /\ pc = "test"
/\ ~ok
/\ attempts < 3
/\ pc' = "send"
/\ attempts' = attempts
/\ ok' = ok
Exit == /\ pc = "test"
/\ (ok \/ ~(attempts < 3))
/\ pc' = "done"
/\ attempts' = attempts
/\ ok' = ok
Send == /\ pc = "send"
/\ (ok' = TRUE \/ ok' = FALSE)
/\ pc' = "count"
/\ attempts' = attempts
Count == /\ pc = "count"
/\ attempts' = attempts + 1
/\ pc' = "test"
/\ ok' = ok
Next == Test \/ Exit \/ Send \/ Count
BudgetOK == attempts \in 0..3
DoneOK == pc = "done" => (ok \/ attempts = 3)
=======================================================
The four cases match the four arrows. Send is where the nondeterminism lives: (ok' = TRUE \/ ok' = FALSE) plays the role that i' \in 0..1000 played for someNumber(). Exit's guard is the negation of the while condition, so in every "test" state exactly one of Test and Exit applies. BudgetOK and DoneOK are two claims about every reachable state that you will check with TLC in the next problem set.
(c) The first pair satisfies Next through Count: pc is "count", 3 = 2 + 1, pc' is "test" and ok keeps its value. The second pair doesn't. Its pc is "test", so only Test or Exit could be true. Test needs attempts < 3, which is false, and Exit needs pc' = "done". The client has used its three attempts and can't send again.
(d) 4 states: ok = TRUE with attempts equal to 1, 2 or 3, and ok = FALSE with attempts = 3. In each, no case of Next applies, so the program halts, as From a program to a state machine's tiny program did when pc was "done". We checked this module with TLC, which you install in the next chapter. It has 20 reachable states, and BudgetOK and DoneOK are true in all of them.
Problem 2●●○Algorithms
Binary search with git bisect: which steps does Next allow?
A performance regression slipped into one of 16 commits, numbered 1 to 16 in order. Commit 16 is known to be bad, the commit before commit 1 is known to be good, and once a commit is bad every later one is bad too. git bisect finds the first bad commit by binary search: you test a commit in the suspect range, mark it good or bad, and the range shrinks. Git checks out the middle commit for you, but you can test any commit you like, for example when the middle one doesn't build, and mark it with git bisect good <rev> or git bisect bad <rev>.
This module models only the suspect range: the first bad commit is somewhere in lo..hi.
------------------ MODULE PSl2_Bisect ------------------
EXTENDS Integers
VARIABLES lo, hi
Init == /\ lo = 1
/\ hi = 16
MarkBad == /\ lo < hi
/\ hi' \in lo..(hi - 1)
/\ lo' = lo
MarkGood == /\ lo < hi
/\ lo' \in (lo + 1)..hi
/\ hi' = hi
Next == MarkBad \/ MarkGood
========================================================
In MarkBad, the tested commit is hi' and it was bad, so the range now ends there. In MarkGood, the tested commit is lo' - 1 and it was good, so the range now starts just after it. Neither case says which commit to test. Binary search tests the middle; this Next allows every choice, so it describes binary search along with every other way of bisecting. The figure shows one session.
One bisect session, drawn as states of the range lo..hi. Each arrow is one step: the commit tested and its result. The dashed arrow is the other possible answer at the first step.
Pair
lo, hi
lo', hi'
a
1, 16
1, 8
b
1, 16
9, 16
c
9, 16
9, 16
d
5, 8
6, 7
e
7, 7
7, 8
f
5, 8
5, 5
g
3, 4
4, 4
For each pair in the table, decide whether it satisfies Next, and if it does, through which case. Say in words what the step means for the person bisecting.
How many next states does the initial state have?
An implementer writes MarkBad with hi' \in lo..hi instead. Which pair in the table does this version allow that the original doesn't? What does that step mean, and why could a program built on it loop forever?
Next has no case that applies when lo = hi. What does it mean when the state machine halts?
Hint
Each case is a conjunction, so every line must be true. In MarkBad, lo must stay the same and hi' must be in lo..(hi - 1), which you can write out for the given lo and hi. A pair satisfies Next if either case is true.
Solution
(a) a: MarkBad; commit 8 was bad, so the first bad commit is in 1..8. b: MarkGood; commit 8 was good, so it is in 9..16. c: no. MarkBad needs hi' in 9..15 and MarkGood needs lo' in 10..16, and here neither end moved. d: no; both cases keep one end fixed, and here both moved. e: no; the guard lo < hi is false, since the answer is already known. f: MarkBad; commit 5 was bad, so commit 5 is the answer. g: MarkGood; commit 3 was good, so commit 4 is the answer. Four pairs satisfy Next.
(b) 30: 15 from MarkBad, one for each hi' in 1..15, and 15 from MarkGood, one for each lo' in 2..16. Binary search would choose one of these 30; the spec describes them all, as i' \in 0..1000 described every value someNumber() might return.
(c) Pair c. With hi' \in lo..hi, MarkBad allows hi' = hi: “test commit 16, find it bad.” Commit 16 was already known to be bad, so the step teaches nothing and leaves the state unchanged. It is the classic off-by-one in binary search. Code that computes the middle as (lo + hi + 1) / 2, rounding up, and sets hi = mid when the test is bad, picks mid = hi once lo + 1 = hi. If that commit is bad, nothing changes, and the loop repeats the same step forever. We ran both modules through TLC: each reaches the same 136 states, every range with 1 ≤ lo ≤ hi ≤ 16. The bug adds no new state, only a step from a state to itself, so you can't find it by asking which states are reachable. You find it by reading Next.
(d) The state machine halts when lo = hi: the range holds one commit, which is the first bad one. Here halting is the intended end, as it was for the tiny program in From a program to a state machine.
A web service talks to Postgres through a connection pool capped at 3 connections, because each Postgres connection is a separate server process and costs memory. The pool starts empty and opens connections only when needed. It counts idle connections (open, not in use) and busy ones (checked out by a request). Four things can happen:
Open: if fewer than 3 connections exist, the pool opens one; it starts idle.
Acquire: a request checks out an idle connection.
Release: a request returns its connection, which becomes idle.
Evict: the pool closes an idle connection that has been unused for too long.
The figure shows part of the state graph the authors have in mind. A teammate wrote this module. PoolOK is the pool's promise: no count is negative, and there are never more than Max connections.
Part of the connection pool's state graph, as the pool's authors intend it. Opposite arrows between the same two states are drawn as a pair of curves.
For each of the four cases, name its guard and say which variables change.
Find a pair of states that satisfies this Next, where the first state satisfies PoolOK and the second doesn't. Start from the initial state.
Which case is wrong? Describe the real bug it stands for in the pool's code, and fix the case.
With your fix, argue case by case that if a state satisfies PoolOK, every next state allowed by Next does too.
Hint
A guard should test exactly what the change needs. A case that subtracts 1 from a count needs that count to be above 0 first. Compare each case's guard with the variable it decreases.
Solution
(a)Open: guard idle + busy < Max; idle goes up by 1. Acquire: guard busy < Max; idle goes down and busy up. Release: guard busy > 0; busy goes down and idle up. Evict: guard idle > 0; idle goes down.
(b)idle = 0, busy = 0 and idle' = -1, busy' = 1. The initial state satisfies PoolOK. Acquire's guard busy < Max is true, so Acquire, and therefore Next, is true for this pair, and the second state has idle = -1. We ran the module through TLC: it reports PoolOK violated by exactly this two-state behavior.
(c)Acquire checks whether the pool has room (busy < Max) when it should check whether an idle connection exists. In code, this is a pool that tests “not at capacity” before taking from the idle list, and on an empty list gets nothing, or a connection another request already holds. The fix:
When the pool is empty, a request now has to wait for Open first, as in the figure, where the only arrow out of the initial state is Open.
(d) Suppose a state satisfies PoolOK. Open raises idle + busy by 1, but only when it is below Max, so it stays in 0..Max. Acquire and Release move one connection between the counts, so the total is unchanged, and each decreases a count only when its guard says that count is above 0. Evict lowers idle only when it is above 0, and lowers the total. So every case keeps every conjunct of PoolOK true. Arguing one step at a time like this, without listing behaviors, is how you will later show that a claim holds in every reachable state. TLC agrees: with the fix it finds 10 reachable states and no violation.
In Problem set 1, problem 3, you chose variables for the design system's Button: phase, disabled, and inflight, the number of requests started and not yet finished. Now write its spec. The rules, as the design system's documentation should state them:
Initially the phase is idle and no request is in flight. The page may have set disabled either way.
Click: possible only when the button isn't disabled and the phase is idle or error. It starts a request and the phase becomes loading.
Resolve and Reject: the request of a loading button finishes, and the phase becomes success or error.
Reset: from success, back to idle (the two seconds are left out).
Toggle: the page flips disabled, at any time.
The figure shows four sequences of states that people on the team wrote down while discussing the double-charge ticket.
Four sequences of Button states. Each cell is phase / disabled / inflight, where T and F stand for TRUE and FALSE.
Write a module with Init and Next == Click \/ Resolve \/ Reject \/ Reset \/ Toggle. Use TRUE and FALSE for disabled.
Check every step of A to D against your Next, and each first state against Init. For each sequence that is not a behavior, name the first step that fails and the case that would have to change to allow it.
Define OneRequest (inflight is 0 or 1) and LoadingOK (if the phase is loading, exactly one request is in flight). Explain what LoadingOK would tell you in a model where Click could never happen.
Sequence C is the double charge. Write the change to Click that would make C a behavior.
Hint
“Either way” in Init is a disjunction: (disabled = TRUE \/ disabled = FALSE). “Idle or error” in Click's guard is one too. Remember x' = x for every variable a case leaves alone: Toggle leaves two of them alone.
(b) A is a behavior: Click, Reject, Click again from error (the retry), then Resolve. B is a behavior: Click, then Toggle while loading, then Resolve, then Reset. Nothing in Resolve or Reset depends on disabled, so the response still lands, as you predicted in Problem set 1. C fails at step 2: the phase stays loading while inflight goes from 1 to 2, which only Click could do, and Click requires idle or error. D fails at step 3: success to loading is again a Click, from a phase Click doesn't allow. To allow D you would change Click's guard; whether a click on the check mark should start a new request is a design decision the documentation must state.
(c) Both definitions are in the module. LoadingOK is an implication, and Writing Init and Next with logic warned about it: if Click could never happen, the phase would never be loading, so LoadingOK would be true in every state without saying anything. Here it isn't vacuous, because A and B pass through loading states. We checked the module with TLC: it has 8 reachable states, 4 phases times 2 values of disabled, with inflight fixed by the phase, and OneRequest and LoadingOK hold in all of them.
(d) Replace the phase condition so that it allows loading, for example /\ ~(phase = "success"). Then C's second step satisfies Click. We ran that variant through TLC as well: OneRequest fails in a three-state behavior, idle with 0, loading with 1, loading with 2, which is exactly C. The spec turns the support ticket into a one-line difference in a guard, and the design-system documentation can now say precisely what the Button guarantees: at most one request per Button at a time. As in Problem set 1, the server still has to recognise a repeated payment that arrives some other way, such as a retry after a lost reply.
Lecture 3: Resources and tools
Know where help lives, then install something that runs TLC.
You can now read a complete module, so it is time to run one. This lesson gets the tools onto your machine and shows where to look when you are stuck. lesson 9 then uses them.
Whichever editor you use, the path is the same. A parse error means TLC never ran, so it tells you nothing about behavior. A TLC error comes with the behavior that led to it.
The diagram is what you are installing. Your module goes to a parser, which checks that the text is legal TLA+. TLC then reads the module along with a model, a small set of choices about what to run: which formulas are Init and Next, and what to check. The red boxes are the two places errors come from, and they tell you different things. If the parser complains, TLC never ran.
Where to look
Lecture 3 opens with a tour of resources. Most of them start from the TLA+ home page, and most of the documentation is in PDF.
Three questions and where each one goes. All three start from the TLA+ home page.
The Summary of TLA+ is a cheat sheet. Lamport says to download and print it, and that is good advice.
Specifying Systems, the TLA+ book, is a useful reference. It was written before the Toolbox existed, so it says nothing about the Toolbox.
The TLA+ Google group is where to find out what is happening in the community and to ask other users for help.
The diagram gives the order for a problem: the install page's “If Something Goes Wrong” section first, then the group.
Installing the tools
The lecture installs the Toolbox, the IDE for creating specs and running tools on them. The steps it describes are to install Java if you don't have it, download a zip file and extract it, and install LaTeX, which the pretty-printer needs. The pretty-printer produces the typeset form you see on the slides, with ∧ and ∈. If you follow along in the videos, the Toolbox page has the current instructions.
The current option is the official TLA+ VS Code extension. Follow its setup guide. You can also skip editors altogether: download tla2tools.jar from the official releases and run TLC from a terminal. The core tools currently require Java 11 or later.
Option
Where the model lives
Use it when
Toolbox
Forms on the Model Overview page
You want your screen to match the lectures.
VS Code extension
A .cfg file next to the module
You already work in VS Code.
Command line
A .cfg file next to the module
You want repeatable runs. This course prints its commands in this form.
Whichever you choose, the lectures' ideas are the same. When the Toolbox has you click “Add” under Invariants, a .cfg file has a line for it, as you'll see in the next few lessons. Here is the command form, for a module and config named Name:
java -cp tla2tools.jar tlc2.TLC -config Name.cfg Name
TLC checks a finite model. It can run many useful specs, but it is not a theorem prover, and a model whose states never run out, such as an unbounded counter, can't be fully searched. Keep the models small; every spec in the first lectures has few states.
Predict: your run stopped because the machine ran out of memory, with no violation so far. Did your check pass?
No. The search is incomplete, so you can report only that nothing was found in the part it reached. Shrink the model or add resources and rerun. “No error” counts only when exploration finished.
The rest of the toolkit
Help pages. In the lecture, Lamport asks you to read the Toolbox's Getting Started help before the next video and to browse the other sections when you can. If you use the extension, read its documentation the same way.
TLAPS, from lesson 2, checks formal proofs written in TLA+. It can check proofs of real algorithms, but few engineers will use it. lesson 43 comes back to proof.
Unicode display. Most engineers prefer the ASCII form of their specs; Lamport says he uses the pretty-printed form only for publication. The lecture says a Unicode option was planned for those who want to see ∈ while editing. Check the current documentation for your editor, because the lecture can't tell you what exists today.
While you watch
This lesson covers Lecture 3's resource tour, the download, the Help pages, TLAPS, and Unicode. lesson 9 covers its hands-on middle: creating a spec and running TLC.
Look for: where each resource sits on the home page. Website details may have changed since the recording, so search if a link has moved.
The lecture tells you to stop and install. Do it, either the Toolbox or the extension. Do not go on without a working TLC.
This lesson adds the VS Code and command-line routes, and the pipeline diagram that separates parser errors from TLC errors.
Tool source and releases: TLA+ tools. Consult the tool's current help rather than assuming every older tutorial matches today's interface.
Lecture 3: Resources and tools
Run a spec, meet deadlock, then write your own.
With TLC installed from lesson 8, you run the tiny program's spec exactly as the lecture does. TLC reports an error, and understanding why teaches you what TLC can and can't know. Then you write a small spec of your own and break it.
Where TLC's 2003 comes from: 1 + 1001 + 1001. All 1001 pc: done states have no next state, and each one is a place a run stops.
Run SimpleProgram
Create SimpleProgram.tla with the module from lesson 6, and next to it a config file, SimpleProgram.cfg. A config file is the text form of a model. These two lines name the formulas TLC should treat as the initial-state and next-state formulas:
INIT Init
NEXT Next
In the Toolbox, you create a model from the TLC Model Checker menu instead, and it fills these in for you. Run TLC. It stops with an error:
Error: Deadlock reached.
Error: The behavior up to this point is:
State 1: <Initial predicate>
/\ i = 0
/\ pc = "start"
State 2: ...
/\ i = 0
/\ pc = "middle"
State 3: ...
/\ i = 1
/\ pc = "done"
That output is a behavior, printed one state at a time. Which number it picks at State 2 can differ between runs. Follow it through the diagram: start, then middle, then done. The dashed red arrow is what TLC noticed: from pc = "done", no next state exists.
Deadlock and termination
Lamport's distinction is simple. Deadlock means execution stopped when it wasn't supposed to. Termination means it stopped when it was supposed to. Here the program is supposed to stop, so this is termination. But nothing in the spec says whether an execution should stop, so TLC can't tell them apart, and since most systems should not stop, it reports any stop as deadlock.
When stopping is intended, turn the check off. In the Toolbox, it is the Deadlock checkbox on the Model Overview page. In a config file, add a line:
CHECK_DEADLOCK FALSE
Now TLC reports Model checking completed. No error has been found. and 2003 distinct states found. The diagram accounts for that number: 1 start state, 1001 middle states, and 1001 done states. Disable the check only when you know stopping is correct. Otherwise you are switching off a real alarm.
Your turn: a counter
Write a spec without a C program to start from. This one describes a counter that starts at 0 and increments up to a bound. Save it as Counter.tla, since the module name and file name must match.
---------------- MODULE Counter ----------------
EXTENDS Integers
VARIABLE x
Max == 3
Init == x = 0
Next == /\ x < Max
/\ x' = x + 1
Safe == x =< Max
================================================
In ASCII, “less than or equal” is =<. The first line of Next has no prime, so it is a condition on the current state alone. A step can happen only when it is true. Such a condition is called a guard, and lesson 12 says more about it. Compare it with pc = "start" in SimpleProgram, which plays the same role.
Safe is a formula you claim is always true. A state that occurs in some behavior is reachable, and a formula true in every reachable state is an invariant. A claimed invariant goes in the config, and TLC tests it in every state it finds:
INIT Init
NEXT Next
INVARIANT Safe
CHECK_DEADLOCK FALSE
TLC finishes with no error and 4 distinct states. As with SimpleProgram, the deadlock check has to be off, or TLC stops at x = 3, because this counter is designed to stop there.
Explore the bounded model
Changing Max in the lab is like editing the definition Max == 3. “Explore all states” does a breadth-first search of a tiny JavaScript model: all states one step away, then two, and so on. It is not TLC. Now tick the box to weaken the guard, and predict what the search will find before you press the button.
Top row: the guard is x < Max. Bottom row: x =< Max allows one more step, and x = 4 breaks Safe.
The diagram compares the two guards. We ran the broken one, with x =< Max, through real TLC. It reports Invariant Safe is violated with a 5-state behavior, 0 through 4, which matches the bottom row. You can reason backward too: to reach the bad state x = 4, the predecessor must be x = 3, and the step must be allowed there. So the guard is the culprit, and you found that without reading a long trace.
Retrieve: what are the two formulas TLC needs, and what is a third thing you can ask it to check?
The initial-state formula and the next-state formula. On top of those you can name invariants. You can also decide whether a stop counts as deadlock. Later lessons add more, but this is the whole model so far.
Transfer: a retry budget
A file-upload client allows at most three attempts. Let attempts count those already started, not those remaining.
“Three attempts” has four valid values. The guard reads the old value, so the strict comparison is the one that stops at 3.
In the diagram, the guard reads the old value. At 2 it allows a step to 3, and at 3 it blocks the dashed arrow. That is why “allow three attempts” uses a strict comparison on attempts already used. Running this module through TLC gives 4 distinct states and no error. Writing the sentence out as a trace saves you from guessing whether the comparison should include equality.
Now imagine resetting attempts to zero whenever the user taps Retry. Each session still passes this check, but one logical upload can now trigger unlimited attempts. If the requirement concerns one logical request, the count must belong to that request, and every way of resetting it must appear in Next.
Exercise: instead count attempts remaining, initially 3. What would you write?
remaining > 0 /\ remaining' = remaining - 1 and the invariant remaining \in 0..3. Decide whether the first attempt consumes the budget. The variable's name can't settle that for you.
While you watch
This lesson covers the hands-on middle of Lecture 3: “Creating a spec,” “The pretty-printer,” and “Running TLC.” Those parts are a live demonstration, so do each thing as he does it and stop the video whenever you need to.
Look for: what TLC's results page shows, and the point where it reports deadlock.
Pause before the “Why does TLC report deadlock?” slide and try to answer the question yourself.
If you use the extension or the command line, your screen will differ. The results are the same: a deadlock error with the same kind of trace.
This lesson adds the config-file form, the count of 2003, and the counter, which is your first spec not taken from the lecture. The lecture introduces invariants in the next video, and lesson 13 uses them on a bigger model.
Lecture 3: Resources and tools
Problem set 3: run TLC and read what it tells you.
These problems practice Lecture 3: writing a module and its config file, running TLC, reading “distinct states found,” checking invariants, reading an error trace backward, and telling deadlock from termination. They draw on The tools and where to learn more and Your first spec through TLC, and the last problem checks a model from Problem set 2.
Every module here has been run through TLC, and every number in a checked answer is one TLC printed. Commands are in the command-line form from The tools and where to learn more, java -cp tla2tools.jar tlc2.TLC -config Name.cfg Name. In the Toolbox you enter the same things on the model's Overview page, and the VS Code extension reads the same .cfg file. Remember that the module name must match the file name.
Problem 1●○○API gateway
Does a fixed-window rate limiter keep its promise?
An API gateway lets each client make 3 requests per minute. It uses a fixed window: a counter per client that resets when each minute starts on the clock, and a request is rejected when the counter is already at the limit. The product team has told the backend team: “a client never gets more than 3 requests through in any 60 seconds.”
To see time inside a minute, the model splits each minute into two halves. half is 1 or 2, the half of the current minute it is now. a1 and a2 count the requests accepted in the first and second half of the current minute, and p2 counts those accepted in the second half of the previous minute. Here is the module without its accept steps:
Tick moves time forward half a minute. At the end of a minute it saves the second half's count in p2 and resets the window. A rejected request changes nothing, so it needs no case. The figure shows which spans of time the counters cover.
What the two invariants measure. A fixed window resets its counters at the minute boundary, so WindowOK only ever looks inside one minute. The red span crosses the boundary.
Write AcceptFirst and AcceptSecond: in the half it is now, a request is accepted when the window's total a1 + a2 is below Limit. Then define Next.
Define WindowOK, “the current window never holds more than Limit accepted requests.” Save the module as PSl3_RateLimit.tla with a config PSl3_RateLimit.cfg containing INIT Init, NEXT Next and INVARIANT WindowOK, and run TLC. How many distinct states does it find? Why does it report no deadlock?
The promise talks about any 60 seconds, including the span from the middle of the previous minute to the middle of this one. Define SlidingOK == p2 + a1 =< Limit, add a second INVARIANT line, and run again. Retell TLC's trace as a story with clock times.
Is the gateway wrong, or the promise? Say what the fixed window really guarantees.
Hint
Each accept case needs three kinds of line: the guard (which half it is, and room in the window), the counter that grows, and x' = x for the other three variables. For the deadlock question, look for a case whose guard is true in every state.
(b) TLC reports Model checking completed. No error has been found. and 56 distinct states found. You can account for the number: when half = 1, a2 is 0 and a1 and p2 each range over 0..3, giving 16 states; when half = 2, there are 10 pairs of a1 and a2 with a sum of at most 3, and 4 values of p2, giving 40. There is no deadlock because Tick has a case for each value of half, so some step is always possible. That is right for a model of time.
(c) TLC reports Invariant SlidingOK is violated. with this 7-state trace:
TLC's counterexample to SlidingOK as a grid: one column per state, with the action that produced it. The last row is not a variable; it is the value SlidingOK tests.
As a story: from 10:00:00 to 10:00:30 the client is quiet. At 10:00:40 and 10:00:50 it sends two requests, both accepted. At 10:01:00 the window resets. At 10:01:05 and 10:01:10 it sends two more, both accepted, since the new window is empty. That is 4 requests in 30 seconds, against a promise of 3 per 60 seconds. Four accepts and two ticks can't be done in fewer steps, so 7 states is the shortest possible behavior.
(d) The gateway does what a fixed window does: at most Limit accepted requests per clock minute, which is WindowOK. Near a boundary a client can get up to twice the limit in a short span: 3 just before the minute and 3 just after. To see it, change the bound in SlidingOK to 5; TLC then prints a 9-state behavior ending with p2 = 3 and a1 = 3. Either the promise should say “per clock minute,” or the gateway needs an algorithm that tracks a moving 60 seconds, such as a sliding-window log of request times. Which to choose is a product decision; the model makes the difference precise.
Problem 2●●○Concurrency
Read a TLC trace backward to find a double release
A thumbnail service runs image-resize jobs, at most 2 at a time because each job needs a lot of memory. A semaphore with 2 permits enforces this: a worker takes a permit before starting a job and gives it back when the job ends. The code that ends a job calls release() in its error handler, and again in its finally block, which also runs after an error. Java's java.util.concurrent.Semaphore, like many semaphores, does not require a release to match an earlier acquire, so an extra release simply adds a permit.
The model counts running jobs and free permits; which worker runs which job is left out.
A teammate ran TLC with INIT Init, NEXT Next and INVARIANT AtMostTwo and got:
Error: Invariant AtMostTwo is violated.
Error: The behavior up to this point is:
State 1: <Initial predicate>
/\ permits = 2
/\ running = 0
State 2: <Start line 10, col 11 to line 12, col 35 of module PSl3_Workers>
/\ permits = 1
/\ running = 1
State 3: <Start line 10, col 11 to line 12, col 35 of module PSl3_Workers>
/\ permits = 0
/\ running = 2
State 4: <Fail line 18, col 11 to line 20, col 35 of module PSl3_Workers>
/\ permits = 2
/\ running = 1
State 5: <Start line 10, col 11 to line 12, col 35 of module PSl3_Workers>
/\ permits = 1
/\ running = 2
State 6: <Start line 10, col 11 to line 12, col 35 of module PSl3_Workers>
/\ permits = 0
/\ running = 3
The trace your teammate got, one column per state, headed by the action that produced it. AtMostTwo fails only in state 6.
Which state violates AtMostTwo? Now read the trace backward, as Your first spec through TLC did for the counter: for each step, ask whether the step itself was allowed and sensible. Which step first went wrong?
Find a formula over permits and running that is true in states 1 to 3 and false from state 4 on. Why is it a sharper invariant for this design than AtMostTwo?
Fix Fail, add your formula as a second invariant, and run TLC. How many distinct states does it find?
If you run TLC with several worker threads, using its -workers option, it may print a different trace of the same length. Is that a different bug?
Hint
The state where the invariant fails is where the damage shows, not where it was done. Steps 4 to 5 and 5 to 6 are Start, and each had a permit available. So where did the extra permit come from?
Solution
(a) State 6, with 3 jobs running. Going backward: step 5 to 6 is Start with permits = 1, so its guard was true. Step 4 to 5 is Start with 2 permits, also allowed. But state 4 is already wrong: one job is running and 2 permits are free, so the semaphore will admit 2 more. Step 3 to 4 is Fail: one job ended and 2 permits came back. That is the error handler and the finally block each calling release().
(b)permits + running = MaxJobs. Each permit is either free or held by a running job, and this formula says exactly that. It fails at state 4, the moment the bookkeeping goes wrong, while AtMostTwo fails only two steps later when the extra permit happens to be used. An invariant that states why the design works catches errors closer to their cause.
(c) With Fail releasing one permit, TLC reports no error and 3 distinct states. Deadlock checking was on, and none was reported: from every state, either a job can start or one can end.
Fail and Finish are now the same formula. Keep both if you want the trace to say which way a job ended. In the code, the fix is to release only in the finally block.
(d) No. With one worker thread, TLC searches in a fixed order and printed the trace above. With several threads, our run printed Start, Fail, Start, Start, Start: the extra permit appears after the first job fails instead of the second. Both traces have 6 states and the same Fail step, so they show the same bug. Read any trace for the step that breaks the design's reasoning, not for its exact order.
Problem 3●●○Algorithms
Euclid's algorithm: termination, deadlock, and a loop that never ends
Euclid's algorithm finds the greatest common divisor (GCD) of two positive integers, the largest number that divides both. In its original form it uses only subtraction: while the two numbers differ, subtract the smaller from the larger. When they are equal, that value is the GCD of the numbers you started with. The GCD of 34 and 21 is 1.
------------------ MODULE PSl3_Euclid ------------------
EXTENDS Integers
VARIABLES x, y
M == 34
N == 21
Init == /\ x = M
/\ y = N
SubY == /\ y < x
/\ x' = x - y
/\ y' = y
SubX == /\ x < y
/\ y' = y - x
/\ x' = x
Next == SubY \/ SubX
Positive == x > 0 /\ y > 0
Answer == (x = y) => (x = 1)
========================================================
Run TLC with a config containing only INIT Init and NEXT Next. It reports a deadlock. Look at the last state of the trace: is it a deadlock or a termination, in Lamport's sense?
Add CHECK_DEADLOCK FALSE, INVARIANT Positive and INVARIANT Answer, and run again. How many distinct states does TLC find? Why is it the same as the number of states in the trace from (a)?
Answer is an implication. In which states is it true only because x = y is false? If a bug kept the algorithm from ever reaching x = y, what would TLC report about Answer?
A colleague changes SubY's guard to y =< x, “to handle equal numbers.” Predict, then run TLC twice: once with INVARIANT Positive (and deadlock checking on), and once with only INIT and NEXT. Explain each result.
Change the inputs to 12 and 18, and Answer to x = 6. Run again.
Hint
For (d), work out by hand what happens at x = 1, y = 1 with the new guard, and then at the state after it. Which case applies there, and what next state does it produce?
Solution
(a) TLC prints Error: Deadlock reached. and a trace of 8 states, shortened here:
State 1: <Initial predicate>
/\ x = 34
/\ y = 21
State 2: <SubY line 11, col 9 to line 13, col 17 of module PSl3_Euclid>
/\ x = 13
/\ y = 21
...
State 8: <SubY line 11, col 9 to line 13, col 17 of module PSl3_Euclid>
/\ x = 1
/\ y = 1
It is termination: the algorithm is supposed to stop when x = y, and x holds the GCD, 1. As Your first spec through TLC explained, nothing in the spec says stopping is intended, so TLC reports it. Here the report is even useful: it shows you where and how the algorithm stops.
The whole state graph for M = 34 and N = 21. Each state has at most one next state, so the graph is a single path, and it ends at 1, 1.
(b) No error, and 8 distinct states. The guards y < x and x < y can't both be true, so every state has at most one next state. With one initial state, the reachable states form a single path, drawn above, and the deadlock trace in (a) was that whole path.
(c) In states 1 to 7, where x and y differ, Answer is true because its left side is false. It says something only in state 8. If a bug kept the algorithm from ever reaching x = y, Answer would be true in every state and TLC would report no error: this is the vacuous check from Writing Init and Next with logic. Answer says the result is right if the algorithm stops; it does not say the algorithm stops.
(d) With INVARIANT Positive, TLC reports Invariant Positive is violated in state 9, x = 0, y = 1: at x = 1, y = 1, the guard 1 =< 1 is true, so SubY subtracts. With only INIT and NEXT, TLC reports Model checking completed. No error has been found. and 9 distinct states. There is no deadlock now, because at x = 0, y = 1, SubX applies (0 < 1) and produces y' = 1 - 0 = 1, the same state again. The algorithm subtracts zero forever. So “no deadlock” here is bad news: the deadlock check finds states with no next step, and this bug creates a state whose only next step goes nowhere. Saying “the algorithm eventually stops” is a different kind of property, which the course reaches later. For now, notice that Positive caught the bug, and the deadlock report you got in (a) was a sign of health.
(e) The path is (12, 18), (12, 6), (6, 6): TLC finds 3 distinct states and no error, and Answer holds with 6.
In Problem set 2, problem 1, you wrote the HTTP client's retry loop as Init and Next. Now check it, and then make it more realistic.
Save the solution module of that problem as PSl2_Retry.tla, with a config containing INIT Init and NEXT Next, and run TLC. It reports a deadlock. Read the last state of the trace: deadlock or termination?
CHECK_DEADLOCK FALSE would silence this, but it would also silence a real hang added later. Instead, add a case to Next that allows the finished program to take a step that changes nothing:
Done == /\ pc = "done"
/\ pc' = pc
/\ attempts' = attempts
/\ ok' = ok
Run again with deadlock checking on and with INVARIANT BudgetOK and INVARIANT DoneOK. How many distinct states does TLC find, and what does a deadlock report now mean?
Now model the network. send() becomes a request followed by a wait for the response, which may be "ok", "err", or lost. Add a variable resp, initially "none", add resp' = resp to every case that doesn't set it, and replace Send with these three cases:
Run with deadlock checking on and INVARIANT BudgetOK. What does TLC report?
Is that report a real deadlock? Which line of real client code does it correspond to? Add a case Timeout that fixes it, and run again.
The timeout counts a lost response as a failure and tries again. Using the upload example in How to study this course, say what can go wrong on the server. What did this model leave out that hides the problem?
The retry loop with a network, by value of pc. The red box is not a value of pc: it marks the states with pc = "wait" and a lost response, where no case of Next applies.
Hint
For (c), look at the figure: from wait, which values of resp have a case that leaves? For (d), a hang that the user sees as a spinner forever is exactly what an HTTP timeout is for.
Solution
(a) In our run the trace ended in the state attempts = 1, ok = TRUE, pc = "done": the first send succeeded and the loop exited. Your trace may end in another of the four done states. Either way, it is termination: the program is supposed to stop there.
(b) No error, and 20 distinct states, the same 20 as in Problem set 2. Done adds a step from each finished state to itself, so no state is left without a next state, and no new states appear. Now a deadlock report can only mean the program got stuck somewhere other than "done". This is a common way to separate the two: say in the spec that stopping at the end is intended, and leave deadlock checking on for everything else.
(c) TLC reports a deadlock with a 3-state trace:
Error: Deadlock reached.
Error: The behavior up to this point is:
State 1: <Initial predicate>
/\ resp = "none"
/\ attempts = 0
/\ ok = FALSE
/\ pc = "test"
State 2: <Test line 10, col 9 to line 16, col 23 of module PSl3_RetryNet>
/\ resp = "none"
/\ attempts = 0
/\ ok = FALSE
/\ pc = "send"
State 3: <Send line 25, col 9 to line 29, col 19 of module PSl3_RetryNet>
/\ resp = "lost"
/\ attempts = 0
/\ ok = FALSE
/\ pc = "wait"
In the figure, the red box marks these states: pc is "wait", the response was lost, and no case of Next applies.
(d) Yes, this one is real. The client waits for a response that will never come, which in code is an HTTP call with no timeout. Some popular HTTP libraries wait indefinitely unless you set a timeout, so this hang happens in production: the user sees a spinner forever. The fix is a case for the lost response:
TLC now reports no error and 38 distinct states, with deadlock checking on. That is evidence that the only place the client stops is "done", which you could not have learned with CHECK_DEADLOCK FALSE.
(e) A lost response does not mean a lost request. In the upload example of How to study this course, the server committed the document and only the reply was lost; retrying created a second document. Here, a timeout after a request that the server did process leads to a second request, and if the request was “charge this card” or “create this order,” it happens twice. The model hides this because it has no server: it records only what the client sees. To check “at most one order per click,” the state would need the server's side too, such as the number of orders created, plus a way for the server to recognise a repeated request. Later lessons build that kind of model.
Lecture 4: Die Hard
Start a spec by writing one correct behavior.
The counter in lesson 9 had one variable and one kind of step. Now for a real puzzle. To disarm a bomb, the heroes of the 1995 film Die Hard 3 must put exactly 4 gallons of water in a jug, and they have only a 3-gallon jug, a 5-gallon jug, and a faucet.
One correct behavior, written before any formula. It told us the two variables and what counts as one step.
The jugs have no markings, and it must be exactly 4 gallons, not 3.99 or 4.01. Before any formula, Lamport recommends the step in the diagram: write the start of one correct behavior, informally. Follow it from the left. They fill the small jug, pour it into the big one, fill the small jug again, and pour again. The big jug fills up and leaves 1 gallon in the small jug. Then they empty the big jug on the ground, and so on. It doesn't solve the puzzle. It isn't meant to.
What one behavior teaches you
That single behavior answers the two questions that begin every spec.
What are the variables?small and big, the number of gallons in each jug.
What is a step? Filling a jug is one step, with no state in between.
The top row is the abstraction: no partly filled state exists. The red states would add nothing to the question we are asking, so they are not in the model.
The red states in the bottom row do not exist in this model. Real water passes through 1 and 2 gallons, of course, but that doesn't matter to the problem, and this is the simplest abstraction that does the job. There is a related choice: pouring 4 gallons straight into the big jug is physically possible, but they would need to be very lucky to get exactly 4. So the model allows only behaviors where they always know how much water each jug holds. Real specs are written for a purpose, usually to eliminate some particular kinds of error. Here, the kind that gets you blown up.
Beginning the module
------------------------------ MODULE DieHard ------------------------------
EXTENDS Integers
VARIABLES small, big
TypeOK == /\ small \in 0..3
/\ big \in 0..5
Init == /\ big = 0
/\ small = 0
TLA+ has no type declarations. Type correctness means that all variables have sensible values, and it is a good idea to define a formula that says so. Lamport calls it TypeOK. It helps a reader understand the spec, and TLC can check that it is always true. The definition isn't part of the spec: removing it changes nothing about which behaviors are allowed. Init says both jugs start empty.
The next-state formula is a list of kinds of step
The next-state formula describes all permitted steps. It is usually written as one formula or another, each allowing a different kind of step. The behavior above has three kinds of step, and two jugs give each of them two versions:
Names must be defined before they are used, so the definitions of these six go above Next in the module. lesson 12 writes them. You already know enough of what they mean to explore.
Next is a choice among six kinds of step. From this state four lead elsewhere; the loop on top is two more that change nothing, since the small jug is already full.
Every step in a behavior comes from this choice. In the diagram, the state with 3 gallons in each jug has six options. Four change the state. SmallToBig leads to small 1 and big 5, because only 2 gallons fit. FillSmall and BigToSmall are also allowed but change nothing, since the small jug is already full.
Pour it yourself
Save the heroes by hand. Each button is one line of Next. Each circle is a reachable state, labeled small,big; the green-ringed circles have big = 4. Dashed arrows show where a step could go from the current state, and solid ones show your path. Small dots mark combinations that can't be reached. This is a small JavaScript model of the rules, not TLC.
Try to reach a green ring before reading on. Notice two things. Every circle you can reach has a jug that is empty or full, which is why the dots are in the middle of the grid. And you are doing by hand what TLC does in lesson 13.
Predict: can the state with small 2 and big 2 ever occur?
No. It is a dot in the lab. Each of the six kinds of step leaves at least one jug empty or full: filling and emptying do so directly, and a pour stops when the source is empty or the destination is full. Since small 2 and big 2 has neither jug empty or full, no step can produce it.
While you watch
This lesson covers Lecture 4 up to the definition of Next. lesson 12 continues with FillSmall and the pours, and lesson 13 covers “Saving our heroes” to the end.
Look for: the struck-out partial fill, and the reason for ruling out the lucky pour. Both are abstraction decisions, and neither is forced by physics.
Pause when the informal behavior is complete. Extend it by hand for a few more steps before the lecture moves on.
This lesson adds the fan-out from one state and the stepping lab, which the lecture doesn't have. Use the lab between this video segment and the next.
Lecture 4: Die Hard
A step formula must describe the whole next state.
lesson 11 left Next as six names. Writing their definitions exposes the most common beginner's mistake in TLA+, and it fixes what you need to say about every variable in every step.
Under small' = 3 alone, all three arrows are allowed, because the formula says nothing about big'. Adding big' = big removes the two red ones.
A formula like the six in Next, which relates a current state to a next state and describes one kind of step, is called an action. Start with FillSmall. Most people first write this:
FillSmall == small' = 3
Predict: why is that wrong? Decide before opening this. The diagram above is a clue.
If you didn't see it, you are reading it as a command that sets small to 3. It is a formula, true for some steps and false for others. It is true for any step where small is 3 in the second state, whatever big does. In the diagram, that includes the two red arrows, where big becomes √7 or the string "abc".
Frames: say what stays the same
The correct definition also says big doesn't change:
FillSmall == /\ small' = 3
/\ big' = big
FillBig == /\ big' = 5
/\ small' = small
A line like big' = big is called a frame condition. Most engineers feel it shouldn't be needed. Lamport's answer is that “unchanged unless mentioned” would take you out of simple math and into the more complicated world of programming languages. In math, a formula that doesn't mention big' says nothing about it.
TLC enforces this in practice. We removed the frame line and ran the spec:
Error: Successor state is not completely specified by action FillSmall
of the next-state relation. The following variable is not defined: big.
Keep the two facts separate. Mathematically, omission permits any value. In TLC, omission usually produces this error. In neither case does it preserve the old value.
Exercise: write EmptySmall and EmptyBig.
EmptySmall == /\ small' = 0 /\ big' = big and EmptyBig == /\ big' = 0 /\ small' = small, each written as a two-line bulleted list. Each one has a line for each variable.
Pouring has two cases
Now SmallToBig. There are two cases, and the behavior from lesson 11 contains both.
The two cases of SmallToBig. Which one applies depends only on the total water, big + small.
In the top row of the diagram, the big jug has room for all the water in the small one, so all of it moves and the small jug is empty. In the bottom row there isn't enough room, so the big jug ends up full and some water stays behind. Which case applies depends only on the total, so an IF formula fits:
SmallToBig == IF big + small =< 5
THEN /\ big' = big + small
/\ small' = 0
ELSE ...
Stop and solve this. Write the ELSE part of SmallToBig, and then all of BigToSmall. Write them down. As in the lecture, you will check your answer with TLC after saving the heroes, so the full definitions wait until lesson 13. You can test your arithmetic against the lab in lesson 11.
All the lines in a list describe the same pair of states, so nothing happens first. In big' = big + small, both unprimed values are from the current state. This is what lets one step swap two values:
Predict: does x' = x + 1 /\ x' = x + 2 increment x twice?
No. No integer equals both x + 1 and x + 2, so no next state satisfies the formula and this action never happens. Conjunction combines conditions. It doesn't sequence assignments.
Guards, and why the jugs have none
You saw a guard in lesson 9: a line with no primes, which an action needs to be true of the current state. x < Max is one. An action is enabled in a state when some next state satisfies it, so a false guard disables the action.
The jug actions have no guards. Every one of the six is enabled in every state, which is why the lab never greys out a button, and why TLC will never report deadlock for this spec. The IF in SmallToBig is not a guard, since it doesn't disable anything. It chooses between two descriptions of the next state, and both are possible to satisfy.
Check every action this way. No blank cells: each primed variable is either given a value or explicitly kept the same.
The matrix is a mechanical check for the frame of every action: one row per action, one column per variable, no blanks. A blank cell is a question you haven't answered. A later lecture introduces UNCHANGED, a shorthand for frame lines, once specs have more variables. For now, write each one out.
Worked action: sending a chat message
A chat composer stores a draft, a count of pending messages, the last text sent, and the selected conversation. Sending should record the draft, clear it, and leave the selected conversation alone. /= means “not equal.”
One step, constrained whole. lastSent gets the old draft even though draft is cleared in the same step.
The first line is a guard that rejects an empty draft. lastSent' = draft uses the old draft, even though the same action clears it, as the diagram shows. If you instead cleared the draft in one action and recorded it in a later one, the later action would see an empty draft unless you saved a copy. That model needs an extra variable. Where you draw the boundary of an action says whether capture and clearing are one indivisible operation or two visible steps.
Predict: Send specifies draft' but says nothing about pending'. Is pending preserved?
No. Nothing constrains its next value, and TLC would report that the successor state isn't completely specified, just as it did for FillSmall. Add the increment you want or an explicit pending' = pending.
While you watch
This lesson covers Lecture 4 from the definition of FillSmall through “Pouring between jugs.”
Look for: the three example steps that the wrong FillSmall allows. They are the three arrows in the first diagram.
Pause where the lecture says to figure out why the definition is wrong, and again where it asks you to finish the pours. Really do the second one on paper.
This lesson adds the frame matrix, guards, the swap, and the chat example. The lecture's own spec has no guards; you will see them in the transaction commit lecture too.
Lecture 4: Die Hard
Claim the puzzle is unsolvable, and TLC shows you the solution.
You have the jugs' variables from lesson 11 and their actions from lesson 12. Now run them. The trick for saving the heroes is one line: tell TLC that the big jug never holds 4 gallons, and let it prove you wrong.
The state space TLC finds. Blank cells are unreachable: after any step, one jug is empty or full. TypeOK asks that every filled cell stays inside this 4 by 6 grid. big /= 4 claims TLC never reaches a red cell, and that claim is false.
Run the module
Save the module as DieHard.tla. It contains complete definitions of SmallToBig and BigToSmall, so keep your own solutions from lesson 12 handy and don't study these until you have seen the error trace.
The complete DieHard module (open to copy; contains the pour solutions)
------------------------------ MODULE DieHard ------------------------------
EXTENDS Integers
VARIABLES small, big
TypeOK == /\ small \in 0..3
/\ big \in 0..5
Init == /\ big = 0
/\ small = 0
FillSmall == /\ small' = 3
/\ big' = big
FillBig == /\ big' = 5
/\ small' = small
EmptySmall == /\ small' = 0
/\ big' = big
EmptyBig == /\ big' = 0
/\ small' = small
SmallToBig == IF big + small =< 5
THEN /\ big' = big + small
/\ small' = 0
ELSE /\ big' = 5
/\ small' = small - (5 - big)
BigToSmall == IF big + small =< 3
THEN /\ big' = 0
/\ small' = big + small
ELSE /\ big' = small - (3 - big)
/\ small' = 3
Next == \/ FillSmall
\/ FillBig
\/ EmptySmall
\/ EmptyBig
\/ SmallToBig
\/ BigToSmall
NotSolved == big /= 4
=============================================================================
First run it with only INIT Init and NEXT Next in the config. TLC reports no error and 16 distinct states. No error means little here, because you asked it to check nothing. It shows that TLC could run the spec. The 16 are the filled cells in the grid above, the states reachable in some behavior, the same circles you saw in the lab.
Next, check type correctness by adding INVARIANT TypeOK. Remember from lesson 9 that an invariant must hold in every reachable state. Still no error, so every filled cell has values in range.
Saving our heroes
The 4 gallons must be in the big jug, since the small one holds only 3. So claim that it never happens. “Not equal” is /= or # in ASCII.
INIT Init
NEXT Next
INVARIANT TypeOK
INVARIANT NotSolved
In the Toolbox, you can type big /= 4 directly under Invariants. A config file needs a named formula, which is why the module defines NotSolved. Run it, and TLC reports Invariant NotSolved is violated, along with this behavior:
Saving our heroes. Each arrow names the line of Next that allows the step. The last step pours the big jug into the small one, leaving exactly 4 gallons.
That is the answer, in 7 states: fill the big jug; pour into the small one, leaving 2; empty the small one; pour the 2 across; fill the big jug again; and top up the small one, which holds 2 and takes exactly 1. That leaves 4. Each state in TLC's output names its action, as in State 3: <BigToSmall ...>, which is the label above each arrow in the diagram. In the Toolbox, double-clicking an action in the trace jumps to the part of Next that allowed it.
Run with one worker for the shortest trace. With -workers 1, TLC searches in strict breadth-first order, and we got the lecture's 7-state trace in each run. With several workers, states may be processed out of order. One of our runs reported a longer, 9-state trace ending at small 0, big 4. That trace is valid, but it isn't the shortest.
Predict: there are two red cells in the grid. Why does the lecture's trace end at small 3, big 4 and not small 0, big 4?
TLC searches breadth-first, so with one worker it finds a nearest violation first. Small 3, big 4 is 7 states from the start. Small 0, big 4 is further: at best you empty the small jug after reaching small 3, big 4, which takes 8 states. The 9-state trace in the callout got there by a different route.
Reading SmallToBig and BigToSmall
Now compare your definitions. Look at the ELSE of SmallToBig. The big jug is filled, so the amount poured is 5 - big, and that is what comes out of the small jug. Someone new to TLA+ might say this is wrong, since big was set to 5 on the line above. But you know better from lesson 6: /\ is commutative, and all these values of big are from the current state.
A warning follows. = is commutative too, so small' = 0 and 0 = small' are equivalent formulas, and the specs are equivalent. TLAPS treats them the same, but TLC does not. We ran the flipped version, and it stopped with:
In evaluation, the identifier small is either undefined or not an operator.
TLC can almost always handle the ways engineers naturally write specs, and later lectures explain why. For now, follow the lecture's rule: use a primed variable v' only in formulas of the form v' = ... or v' \in ..., where the right side has no primes.
Finding your own mistakes
Each stage catches a different kind of mistake, in this order. The last one is the one we wanted.
The diagram shows what catches what, from left to right. We made each of the lecture's mistakes and ran it:
Mistake
Caught by
What you see
Delete the + in big + small
Parser
A parse error: Encountered "small" at line 24, column 22
Misspell an identifier as bigg
Parser
Unknown operator: `bigg'.
Change 5 to "5" in the comparison
TLC, while running
The second argument of <= should be an integer, with the behavior so far
Claim big /= 4
TLC, checking invariants
The trace above
Execution errors come with a position, so go there first; you can read the rest of the report later if you are curious.
Check your definitions
Comment out the module's two pour definitions by placing (* and *) around them, and add your own. Fix what the parser finds, then run TLC. Your definitions are probably correct if TLC finds no execution errors, no violation of TypeOK, and a violation of big /= 4. To be sure, remove NotSolved and run again with only TypeOK, since the search stops at the first violation. If it all passes, try writing the definitions a different way. You learn most from your mistakes.
A good experiment can fail. The lecture's test expects a violation of big /= 4. A check you expect to fail shows that your setup reaches the interesting states. If a deliberately false claim passes, investigate the setup before you trust anything else.
Transfer: ask for a path through a product
The trick works on any “can this happen?” question. Here is the whole cart module from lesson 6, now with a Checkout action that you can read after lesson 12. It starts with both unknowns free: \in lets a variable begin with either value of a set, so there are 4 initial states.
With INVARIANT OrderOK and the deadlock check off, TLC finds no error in 5 distinct states. Now claim INVARIANT NeverOrdered. TLC reports a violation with a 2-state trace: a cart with the terms accepted and goods in stock, then Checkout. You now have a concrete example of a successful order, and evidence that the implication in that lesson wasn't vacuous. To reach a harder state, you state that it is unreachable and let TLC produce the steps.
While you watch
This lesson covers Lecture 4 from “Saving our heroes” to the end.
Look for: the Toolbox's error window, and the double-click that jumps from a trace step to its formula.
Pause before the trace appears and predict its length, using your experience from the lab.
The lecture types the spec into the Toolbox. If you use a config file, each click corresponds to a line as shown above.
This lesson adds the grid, the note on worker count, and the transfer to the cart. The lecture then leaves Hollywood for transaction commit, in lesson 15 and lesson 16.
Lecture 4: Die Hard
Problem set 4: write the steps, then let TLC search.
These problems practice what Lecture 4 taught: actions with guards and complete frames, and the trick of claiming that a goal is never reached so that TLC hands you the steps. They also lean on running TLC and reading its results, from lesson 9, and the last one reuses Euclid's algorithm from Problem set 3.
Write every frame line out in full: UNCHANGED arrives with Lecture 6. When a problem asks for the length of a trace, run TLC with one worker (-workers 1), as lesson 13 recommends, so that its breadth-first search returns a shortest one.
Your design system ships a Modal dialog component. While it is open, it keeps keyboard focus inside the dialog and locks page scrolling, so the page behind it doesn't move. It closes in two ways: the close button, or the Escape key. A bug report arrives: after someone closes a dialog with Escape, the page no longer scrolls. You write the component as a state machine with three variables. CloseButton was written carefully. PressEscape was added later by copying its first three lines.
The config lists INIT Init, NEXT Next, and the invariants TypeOK, LockMatches and FocusInside.
The copied frame line keeps the lock on after Escape: the red state. With no frame line at all, the next state isn't determined, which is what TLC complains about.
Before running anything: as a formula, what does PressEscape say about scrollLocked'? Which next states does it allow? The dashed arrow down in the diagram is your clue.
Run TLC. What does it report, and after which action?
A teammate makes the error go away by adding /\ scrollLocked' = scrollLocked to PressEscape. Run TLC again. What does it report now, and how long is the trace?
Write the correct PressEscape. Then draw the frame matrix from lesson 12 for the three actions: one row per action, one column per variable, and the value each action gives each variable. How many distinct states does TLC find with your fix?
Hint
A frame line is a decision about what a step does, not boilerplate. Ask what pressing Escape should do to the scroll lock, then compare with what CloseButton does.
Solution
(a)PressEscape doesn't mention scrollLocked', so as a formula it allows any value at all: TRUE, FALSE, 42, or "abc". It doesn't keep the old value.
(b) TLC stops with the error you met in lesson 12:
Error: Successor state is not completely specified by action PressEscape
of the next-state relation. The following variable is not defined: scrollLocked.
State 1: <Initial predicate> open = FALSE, focus = "page", scrollLocked = FALSE
State 2: <OpenDialog ...> open = TRUE, focus = "dialog", scrollLocked = TRUE
State 3: <PressEscape ...> open = FALSE, focus = "page", scrollLocked = null
(We put each state on one line.) The null is how TLC prints the value it couldn't determine.
(c) With the copied frame line, the spec is complete and wrong. TLC reports Invariant LockMatches is violated with a 3-state trace: the initial state, OpenDialog, then PressEscape, which ends with the dialog closed and scrollLocked = TRUE. That is the red box in the diagram, and it is exactly the bug report. The error in (b) was TLC pointing at the problem. Silencing it with the first frame line that parses turned it into the bug.
With this fix (module PSl4_ModalFixed), TLC finds no error and 2 distinct states: closed and open. Two of the three cells in the bug's row of the matrix were right. The blank one was where the bug lived. In component code the same gap appears when one close path calls the cleanup and another doesn't. Many teams avoid it by routing every way of closing through one function. In the spec, the matrix makes the gap visible.
Your team must rename users.email to users.email_address in a production Postgres database. A plain rename would break every running server that still queries email. So you use the expand and contract pattern: add the new column, deploy app v2 that writes both columns, backfill old rows, deploy v3 that reads the new column, deploy v4 that writes only the new column, and drop the old column. Each step has a precondition in the runbook. In the model below, each precondition is a guard.
missing means some row has no value in email_address. It starts TRUE: no existing row has one. SignUp is a user registering while v1 is live, which writes only email.
INIT Init
NEXT Next
INVARIANT TypeOK
INVARIANT WritesOK
INVARIANT ReadsOK
CHECK_DEADLOCK FALSE
For each of the guards NewExists in DeployV2, app = 2 in Backfill, backfilled in DeployV3, and app = 4 in DropOld, say which invariant would fail without it, and in which situation.
Run TLC with the config. How many distinct states does it find? Why must the deadlock check be off here, and is the stop it would report a deadlock or termination?
Add INVARIANT NotDone. What does TLC's trace give you?
The backfill takes hours on a big table, so a teammate wants to start it as soon as the column exists. Change the guard app = 2 in Backfill to NewExists and run again. Which invariant fails, and why?
Hint
For (a), delete one guard at a time and run TLC. That's faster than arguing, and the trace tells you the situation. For (d), look at which action can set missing back to TRUE, and when it is enabled.
Solution
(a) Without NewExists, v2 could go live before the column exists, so it would write to a column that isn't there: WritesOK. Without app = 2, the backfill could run while v1 still writes only email: that is part (d), and ReadsOK fails later. Without backfilled, v3 would read email_address while old rows have no value there: ReadsOK. Without app = 4, you could drop email while v1, v2 or v3 still writes it: WritesOK.
(b) No error, 7 distinct states. The guards leave exactly one runbook step enabled at a time, so the state graph is a single line. SignUp adds nothing, because while v1 is live missing is already TRUE. After DropOld, no action is enabled. The migration is supposed to end there, so this is termination, as in lesson 9. With the check on, TLC reports Deadlock reached at that final state.
(c) TLC reports Invariant NotDone is violated with a 7-state trace: AddColumn, DeployV2, Backfill, DeployV3, DeployV4, DropOld. That is the runbook, in an order every guard allows. It also shows the guards don't block each other: a runbook whose preconditions can never all be met would have no such trace.
(d) TLC reports Invariant ReadsOK is violated:
Backfilling before v2 is live. The sign-up in column 4 writes only email, so the backfill's work is out of date before anyone reads the new column.
The backfill copies every row that exists at the time, and the guard NewExists allows it while v1 is live. A user signs up, and v1 writes the new row's email only. The backfill already ran, so nothing ever copies that row. v2 and v3 deploy, and v3 reads email_address, which is empty for that user. In production the user would look like they had no email address. The step the trace exposes is SignUp, and you probably never thought of it as part of the migration. The guard app = 2 says the backfill starts only once every new row gets both columns, which closes that gap.
Two limits of this model are worth knowing. It deploys each version to every server in one step, while a real rolling deploy runs two versions side by side for a while. And it has one kind of write; updates and deletes of existing rows need the same reasoning. Both would be good extensions once you have more notation.
Problem 3●●○Algorithms
Tower of Hanoi: let breadth-first search find the shortest solution
The Tower of Hanoi is the textbook example of recursion. Disks of different sizes sit on peg 1, largest at the bottom. You must move them all to peg 3, one disk at a time, never putting a disk on a smaller one. The recursive algorithm moves n − 1 disks out of the way, moves the largest, then moves the n − 1 back on top, for 2n − 1 moves. A colleague reviewing your course notes asks whether any solution is shorter. Rather than prove it, let TLC look at every possibility for 3 disks.
Use one variable per disk: d1 (smallest), d2, d3 (largest), each holding the number of the peg the disk is on. You don't need to record the order of disks on a peg, because the rules force it: it is always by size.
Write the module: TypeOK, Init, and one action per disk, MoveD1, MoveD2, MoveD3. A disk can move only if no smaller disk is on its peg, and only to a peg with no smaller disk. Remember the frame lines.
Write NotSolved, the claim that the disks never all reach peg 3, and run TLC with one worker. How many states are in the trace? Compare it with the recursive algorithm's moves.
Remove NotSolved and run again. How many distinct states are there, and why exactly that many?
Add a fourth disk. Predict both numbers before you run TLC, then check.
Hint
If a and b are two different pegs among 1, 2 and 3, the third one is 6 - a - b. When can d2 move, and where can it go? The smallest disk is always on top and has two choices: use d1' \in with an IF that gives the set of the other two pegs.
Solution
(a)
------------------------------ MODULE PSl4_Hanoi ------------------------------
EXTENDS Integers
\* d1 is the smallest disk, d3 the largest. Each holds the peg (1, 2 or 3)
\* the disk is on. On any peg, the disks sit in size order.
VARIABLES d1, d2, d3
TypeOK == /\ d1 \in 1..3
/\ d2 \in 1..3
/\ d3 \in 1..3
Init == /\ d1 = 1
/\ d2 = 1
/\ d3 = 1
\* The smallest disk is always on top, and can go to either other peg.
MoveD1 == /\ d1' \in IF d1 = 1 THEN {2, 3}
ELSE IF d1 = 2 THEN {1, 3}
ELSE {1, 2}
/\ d2' = d2
/\ d3' = d3
\* d2 is on top if d1 isn't on its peg. It can't go onto d1, so it goes to
\* the one remaining peg. Pegs are 1, 2, 3, so the third one is 6 - d1 - d2.
MoveD2 == /\ d1 /= d2
/\ d2' = 6 - d1 - d2
/\ d1' = d1
/\ d3' = d3
\* d3 can move only when d1 and d2 are both on the same other peg.
MoveD3 == /\ d1 = d2
/\ d1 /= d3
/\ d3' = 6 - d1 - d3
/\ d1' = d1
/\ d2' = d2
Next == MoveD1 \/ MoveD2 \/ MoveD3
NotSolved == ~(d1 = 3 /\ d2 = 3 /\ d3 = 3)
=============================================================================
The guards come from the rules. d2 is on top of its peg exactly when d1 isn't there. It can't go onto d1, so its only legal target is the third peg, 6 - d1 - d2. d3 can move only when both smaller disks are off its peg and off the target, which means they are together on the remaining peg: d1 = d2 and d1 /= d3.
TLC's breadth-first search returns a shortest solution: 7 moves. It is the move sequence the recursive algorithm produces.
(b) With INVARIANT NotSolved and one worker, TLC reports the violation with an 8-state trace: 7 moves. The diagram shows it, one column per state. It is the recursive algorithm's sequence exactly. The smallest disk moves on every other step, and the largest moves once, in the middle. Breadth-first search examined all states 1 move away, then 2, and so on, so no solution with 6 or fewer moves exists. For 3 disks, that answers your colleague.
(c) Without NotSolved, there is no error and 27 distinct states. Every way of giving three disks a peg each is a legal position, and every legal position is reachable. The state graph is connected.
(d)MoveD4 needs d1 = d2, d2 = d3 and d1 /= d4, and every other action gains the frame line d4' = d4 (module PSl4_Hanoi4). TLC finds a 16-state trace (15 moves, which is 24 − 1) and 81 = 34 distinct states. A check on 3 and 4 disks is not a proof for every n, of course. It is strong evidence for a claim that has a short proof by induction.
A lab automation rig measures liquid with two fixed chambers and no level sensors: a 4-litre chamber and a 6-litre chamber. It can fill a chamber from the supply, drain a chamber, or pump from one chamber into the other until the source is empty or the destination is full. These are the Die Hard jugs in steel. A new recipe needs exactly 3 litres, and the controls engineer asks you whether any sequence of operations produces it.
Recall Euclid's algorithm from Problem set 3: replacing the larger of two numbers by their difference doesn't change their greatest common divisor, so it ends at gcd of the starting pair. Here gcd(4, 6) = 2.
Generalize the DieHard module. Define the capacities as Small == 4 and Big == 6, the way Counter defined Max == 3, and use those names everywhere, including in the pours.
Claim NoThree: neither chamber ever holds 3. Run TLC. How many distinct states does it find, and what does the result mean? Before you trust it, show that your setup can find a violation by claiming NoTwo == big /= 2.
Explain the result with the gcd. Write it as an invariant Even and check it.
The vendor offers a 5-litre chamber instead of the 4-litre one. Predict what changes, then change one definition and check. How many states are in the shortest trace to 3 litres?
Hint
Look at what each of the six actions does to the amounts: each one sets a chamber to 0 or to its capacity, or moves water from one chamber to the other. If both amounts are even before a step, can either be odd after it?
Solution
(a)
------------------------------- MODULE PSl4_Dosing -------------------------------
EXTENDS Integers
Small == 4 \* litres the small chamber holds
Big == 6 \* litres the big chamber holds
VARIABLES small, big
TypeOK == /\ small \in 0..Small
/\ big \in 0..Big
Init == /\ small = 0
/\ big = 0
FillSmall == /\ small' = Small
/\ big' = big
FillBig == /\ big' = Big
/\ small' = small
EmptySmall == /\ small' = 0
/\ big' = big
EmptyBig == /\ big' = 0
/\ small' = small
SmallToBig == IF big + small =< Big
THEN /\ big' = big + small
/\ small' = 0
ELSE /\ big' = Big
/\ small' = small - (Big - big)
BigToSmall == IF big + small =< Small
THEN /\ big' = 0
/\ small' = big + small
ELSE /\ big' = big - (Small - small)
/\ small' = Small
Next == \/ FillSmall \/ FillBig
\/ EmptySmall \/ EmptyBig
\/ SmallToBig \/ BigToSmall
NoThree == /\ small /= 3
/\ big /= 3
NoTwo == big /= 2
Even == /\ small \in {0, 2, 4}
/\ big \in {0, 2, 4, 6}
=============================================================================
Every state TLC reaches for 4 L and 6 L chambers. Nothing lands in the 3 row or column, and every amount is a multiple of gcd(4, 6) = 2.
(b) With INVARIANT TypeOK and INVARIANT NoThree, TLC reports no error and 10 distinct states, the filled cells of the grid. Because the model is finite and TLC examined every reachable state, “no error” here means that no sequence of operations ever puts 3 litres in either chamber. That is a real answer only if the check could have failed. Claiming NoTwo shows it could: TLC reports a violation with a 3-state trace, FillBig then BigToSmall, which leaves 2 litres in the big chamber. This is the experiment-that-fails test from lesson 13, used in reverse to trust a success.
(c) Each action sets a chamber to 0, to 4, or to 6, all even, or moves water between chambers so that the total stays the same and one chamber ends empty or full. Start with two even amounts, and every one of these steps leaves two even amounts. So Even is an invariant, and TLC confirms it: no error, 10 states. It is the same argument as Euclid's: a step that only adds or subtracts multiples of 2 can't produce an odd number. In general, every amount you can measure is a multiple of gcd(Small, Big). Euclid's algorithm computes exactly that number by repeated subtraction, much as the pumps subtract one chamber from the other.
(d) gcd(5, 6) = 1, so the argument no longer rules 3 out. Set Small == 5 (module PSl4_Dosing56) and TLC reports NoThree violated with a 9-state trace: fill 5, pump into 6, fill 5, pump until 6 is full (4 left), drain 6, pump the 4 across, fill 5, pump until 6 is full, which leaves 3 in the 5-litre chamber. Without NoThree, TLC finds 22 distinct states. So the engineer's answer is: not with these chambers; with a 5-litre chamber, yes, in 8 operations.
Notice what each chapter contributed. The state machine view turned a machine into variables and steps. TLC's exhaustive search made “impossible” a checkable claim. The invariant from Problem set 3 explains why it's impossible, and tells you which chamber sizes would work before you run anything.
Lecture 5: Transaction commit
Three pieces of math describe a whole group of processes.
Die Hard had two jugs, so naming each one was easy. The next spec has a set of processes whose size you don't fix in advance. To write about all of them at once you need sets, functions, and the quantifiers "there exists" and "for all".
One function. Each element of the domain has exactly one value at a time; the dashed arrow is r2's value after one step.
The diagram is one function, rmState. Each resource manager on the left has exactly one solid arrow to a value on the right. That is the whole idea of a function, and the dashed arrow is the only change that one step of the next spec will make.
While you watch
Lecture 5 teaches this notation in passing, while reading the TCommit spec. This lesson collects it so you can recognize it there; lesson 16 then covers the spec itself. Watch for two pauses: Lamport asks why rmState'[r] = "prepared" is wrong, and later asks you to look at what a formula says rather than what you think it should say. Stop and answer before going on. This lesson adds quantifier order and the empty-set cases.
Sets
A set is a collection with no order and no duplicates: it either contains a value or it doesn't. So {"r1", "r2", "r1"} and {"r2", "r1"} are the same set. You write membership as e \in S, and 1..3 is the set {1, 2, 3}.
In TLA+ every value is a set, even 42 and "abc", but the language doesn't say what their elements are. TLC reports an error if asked to evaluate 42 \in "abc". A module can therefore say CONSTANT RM and use RM as a set without declaring a type. A constant has the same value throughout every behavior, and you give it a value when you run TLC.
Functions are what programmers call arrays
Programming
Math and TLA+
array
function
index set
domain
f[e]
f[e] (math writes f(e))
A function's domain can be any set, including one of strings or an infinite one. There are two expressions to tell apart:
sqr == [i \in 1..42 |-> i^2] \* one function; sqr[3] = 9, DOMAIN sqr = 1..42
[RM -> {"working", "prepared"}] \* a set: all functions from RM to those values
|-> builds one function. -> builds the set of all functions with that domain and those possible values. DOMAIN f gives the domain. (^ comes from the Integers module.)
The arrow form is a set of functions. The |-> form, highlighted, is one element of it.
In the diagram, the outer box is the value of [{"r1", "r2"} -> {"a", "b"}]. The highlighted inner box is the single function [r \in {"r1", "r2"} |-> "a"], which is one element of it. A type invariant such as rmState \in [RM -> ...] uses the outer form, and an initial state uses the inner one.
Changing one entry
A next-state formula can't say only that r's entry changes. Compare the middle and right columns.
Setting one entry leaves the other entries' new values unsaid. EXCEPT says all of them.
rmState'[r2] = "prepared" says what the new value at r2 is. About every other resource manager it says nothing, which is why the middle column is full of question marks. You must give the whole new function:
rmState' = [s \in RM |-> IF s = r THEN "prepared" ELSE rmState[s]]
rmState' = [rmState EXCEPT ![r] = "prepared"] \* the same thing, shorter
In the EXCEPT form, the ! means nothing. It's just syntax. EXCEPT doesn't modify anything: it is an expression for a new function, and rmState itself keeps its value in the current state.
Quantifiers
\E r \in RM : P(r) says there exists some r in RM for which P(r) is true. \A r \in RM : P(r) says P(r) is true for all r in RM. Over a finite set they are just a long "or" and a long "and":
Over a finite set, \E is a big "or" of the rows and \A is a big "and".
Read the diagram from the top. One TRUE row makes the "or" true, and one FALSE row makes the "and" false. A few rules follow from this:
The bound name is local.\E xyz \in RM : ...xyz... means the same as \E r \in RM : ...r..., provided xyz isn't already declared or defined. TLA+ doesn't let you redefine a name that already has a meaning.
Abbreviation.\A r1, r2 \in RM : P abbreviates \A r1 \in RM : \A r2 \in RM : P.
Not and not-equal.~P is "not P", and x # y is "x doesn't equal y".
Empty set.\A r \in {} : P is always true, since there is no counterexample, and \E r \in {} : P is always false.
Scope. A quantifier reaches as far as it can: to a closing bracket, or to the end of its /\ or \/ list item. Parentheses end it sooner.
\A x \in S : x = 1
/\ \A x \in T : x = 2 \* illegal: this is inside the first \A, so x is redeclared
The parser rejects that with a multiply-defined symbol error.
Quantifier order changes the meaning
A cart holds a book and a mug. Compare two claims about shipping them.
\A i \in Items : \E w \in Warehouses : i \in CanShip[w] \* true
\E w \in Warehouses : \A i \in Items : i \in CanShip[w] \* false
Each item has a warehouse (left), but no warehouse has every item (right). Swapping the quantifiers separates these claims.
The first says each item has some warehouse, and different items may have different ones (the left of the diagram). The second says one warehouse handles everything, and the dashed arrow on the right is why it fails. When you read a nested formula, invent a tiny example like this one.
Predict: which of the formulas in this lesson changes meaning if RM is empty?
With no resource managers, every \A r \in RM formula is true and every \E r \in RM formula is false. A check that "all RMs are prepared" passes trivially. That's why a claim such as "the cart can be checked out" needs its own "the cart isn't empty" condition: \A alone can't say so.
Worked example: a group chat
A chat has members and a read position for each member. Those are two concepts, so they get two shapes: a set for membership, a function for positions.
Members == {"Ada", "Ben"}
lastRead == [p \in Members |-> 0]
lastRead2 == [lastRead EXCEPT !["Ada"] = 2] \* Ada 2, Ben still 0
lastRead2 \in [Members -> 0..3] \* true
\A p \in Members : lastRead2[p] <= 3 \* true
Because lastRead maps each person to a number, Ada and Ben can't accidentally share one cursor. Adding Cara to Members would leave the function's domain out of date, so both must change in one step. An ordered message history would need a sequence, which comes later with lesson 30. Every formula in this lesson was checked by TLC as an assumption in a small module.
Say what a wedding must accomplish, and leave out the minister.
You now have the notation for talking about a set of processes. Lecture 5 uses it on a problem from databases, transaction commit, which is simple enough to specify in about twenty lines. The spec describes only the outcome that must be reached, not any protocol for reaching it.
The states of one RM. The lecture draws the same machine for a wedding participant, with "unsure" in place of "working".
The diagram is the state machine of one participant, and it is nearly the whole problem. A participant starts out working, can prepare or abort, and from prepared can commit or abort. Committed and aborted have no outgoing arrows, so those decisions are final.
While you watch
Lamport, following Jim Gray, starts with a wedding: bride, groom, and minister. Ask yourself what the minister is for. Then follow the walk through module TCommit, whose notation you met in lesson 15. Pause where he says to stop the video. The lecture runs TLC from the Toolbox; the same run works in the VS Code extension, the current option, and this lesson shows it as a .cfg file. This lesson adds a graph of every reachable state for two participants and a broken variant of the spec.
From a wedding to a transaction
At a wedding, each of two people starts unsure, and either may say no. It must end with both believing they are committed or both believing it was aborted. The minister helps make this happen, but he is part of how the wedding works, not part of what it must accomplish. So the spec leaves him out.
Now allow any number of participants, and you have transaction commit. A database transaction is carried out by processes called resource managers (RMs). The unsure state is traditionally called working. The rules are:
The transaction can commit only if all RMs are prepared to commit.
The "TC" prefix on names such as TCTypeOK is there because a later module uses this one alongside its own definitions. Prepare(r) is the top arrow of the diagram. Decide(r) has two cases: the branch to committed needs canCommit (every RM prepared or committed), and the branch to aborted needs notCommitted (no RM committed). TCNext says some RM takes one of those steps.
canCommit and notCommitted are only names. You could paste their definitions into Decide, renaming the bound variable to s to avoid clashing with r, and the meaning would stay the same. You could also split Decide into two actions. There are many ways to decompose a next-state formula, and definitions are how you make it readable.
One Decide(r) step reads the state of every RM. No programming language gives you that in a single step, and it doesn't matter: this says what commit must achieve, not how. lesson 18 covers the how.
Every reachable state, for two RMs
All reachable states for RM = {r1, r2}: w, p, c, a stand for working, prepared, committed, aborted; each label is r1's state, then r2's. Red: states TCConsistent forbids. Nothing leads to them.
Each box is a state of two RMs: r1's state, then r2's, abbreviated w, p, c, a. Right and left arrows are r1 moving, and up and down arrows are r2 moving. The curved arrows are a prepared RM aborting. Start at the accent box and follow the guards. The commit arrows only appear once the other RM is prepared or committed. Once one RM commits, the arrows to aborted disappear, because notCommitted is false. The two red boxes have no arrows into them, which is exactly what TCConsistent claims. TLC agrees: with two RMs it finds 12 distinct states, the 12 non-red boxes.
Since the initial and next-state formulas aren't called Init and Next, you name them. A constant needs a value, and Lamport's three strings are as good as any; he'd normally start with a smaller model, but this spec is simple. A correct behavior ends when all RMs have finished, so you turn deadlock checking off.
Result of this run: no error, 94 states generated, 34 distinct states.
Be suspicious of success. Look at the state count: is it plausible? Look at the coverage report, which counts how often each part of the next-state formula produced a new state. A count of zero usually means an error in the spec.
Predict: delete notCommitted from the abort branch of Decide. What does TLC find?
It reports that TCConsistent is violated, with a 6-state trace. All three RMs prepare, r1 commits, and r2 then aborts. The trace is the bottom half of the next diagram.
Top: a behavior of TCommit. Bottom: TLC's 6-state error trace with notCommitted deleted.
The top three rows are a behavior of the real spec. The bottom three are what TLC printed for the broken one. They are identical until the last column shown for the bad run, where r2 aborts even though r1 has committed. The guard you deleted is the only thing preventing it.
Comments and layout
\* starts an end-of-line comment, and (* ... *) encloses any other comment. A line of dashes between statements is decoration.
Problem set 5: say it about every process at once.
Lecture 5 gave you sets, functions and quantifiers, and the TCommit spec, which uses them to describe any number of participants. These problems use that notation on replicas, pods, services and servers. They still rely on guards, frames and the never-reached claim from Problem set 4, and on TLC's reports from lesson 9.
UNCHANGED and records come with Lecture 6, so frames are still written out as v' = v. A function-valued variable that a step changes with EXCEPT needs no other frame. For trace lengths, run TLC with -workers 1.
A Postgres primary streams its write-ahead log to three replicas. A failover tool keeps two functions with the same domain: status, modeled loosely on the state column of Postgres's pg_stat_replication view, and lag, each replica's last reported replay lag in seconds. When the primary dies, the tool promotes a candidate: a streaming replica with the smallest lag.
status is a function: one solid arrow out of each replica. lag is a second function with the same domain. The dashed arrow is the only change Next makes.
Evaluate these by hand, before using TLC. Each is TRUE or FALSE.
E1 == \A r \in Replicas : status[r] = "streaming" => lag[r] =< 5
E2 == \E r \in Replicas : \A s \in Replicas : lag[r] =< lag[s]
E3 == \A s \in Replicas : \E r \in Replicas : lag[r] < lag[s]
E4 == \A r \in Replicas : lag[r] =< 5
E5 == \A r \in {} : lag[r] > 100
Then look at the tool's rule, as the module below writes it. Next is one event: db1 crashes.
----------------------------- MODULE PSl5_Failover -----------------------------
EXTENDS Integers
Replicas == {"db1", "db2", "db3"}
\* Replay lag in seconds, as last reported.
lag == [r \in Replicas |-> IF r = "db1" THEN 0
ELSE IF r = "db2" THEN 4
ELSE 90]
VARIABLE status
Init == status = [r \in Replicas |-> IF r = "db3" THEN "catchup"
ELSE "streaming"]
\* db1 crashes. Its last reported lag stays in the table.
Next == status' = [status EXCEPT !["db1"] = "down"]
Candidate(r) == /\ status[r] = "streaming"
/\ \A s \in Replicas : lag[r] =< lag[s]
SomeCandidate == \E r \in Replicas : Candidate(r)
=============================================================================
The config is INIT Init, NEXT Next, INVARIANT SomeCandidate.
Give the values of E1 to E5, with a one-line reason each.
How many elements does [Replicas -> {"streaming", "catchup", "down"}] have? Write a type invariant for status using it.
Which replicas satisfy Candidate in the initial state? Run TLC. What does it report, and why?
Fix Candidate so that only streaming replicas are compared, and check it again.
Hint
Over a finite set, \A is a long “and” and \E a long “or”. Write them out for db1, db2 and db3. For the bug, ask which replicas the \A s in Candidate compares against after the crash.
Solution
(a) E1 is TRUE: the streaming replicas are db1 and db2, with lags 0 and 4. For db3 the left side of => is false, so its case is true. E2 is TRUE: take r = db1. E3 is FALSE: for s = db1, no lag is below 0. E4 is FALSE because of db3's 90. Compare it with E1, where the implication excused db3. E5 is TRUE, like every \A over the empty set.
(b) 27, since each replica independently gets one of three values. The type invariant is status \in [Replicas -> {"streaming", "catchup", "down"}].
(c) Initially only db1 is a candidate: it is streaming and its lag of 0 is no larger than anybody's. TLC reports Invariant SomeCandidate is violated in a 2-state trace:
State 1: <Initial predicate>
status = [db1 |-> "streaming", db2 |-> "streaming", db3 |-> "catchup"]
State 2: <Next ...>
status = [db1 |-> "down", db2 |-> "streaming", db3 |-> "catchup"]
TLC prints a function whose domain is a set of strings in this bracket form, the notation for records, which Lecture 6 introduces. After the crash, db2 is the obvious choice, but Candidate("db2") still compares its lag with db1's last reported 0 and fails. The dead replica's old number blocks every live one. A failover tool with this rule would refuse to promote anything in exactly the situation it exists for.
(d) Restrict the comparison to streaming replicas:
With this definition (module PSl5_FailoverFixed), TLC reports no error in 2 distinct states: db1 is the candidate before the crash and db2 after it. The fix uses the same pattern as E1, an implication inside \A that excuses the elements you don't care about. (The fixed rule still has a gap: if no replica is streaming, there is no candidate, and maybe that's what you want.)
A Kubernetes Deployment can replace pods one at a time: with maxSurge: 0 and maxUnavailable: 1, its rolling update keeps at most one replica unavailable, and a new pod counts as available only once it passes its readiness probe. Your team runs a stateful service whose pods need a custom drain step, so it wrote its own rollout script with the same goal: with three replicas, at least two serve traffic at every moment. Each pod goes from v1 to stopping, to starting, to v2, and serves only in v1 and v2. The script's rule for stopping a pod is “only if no other pod is stopping”.
------------------------------ MODULE PSl5_Rollout ------------------------------
CONSTANT Pod \* the Deployment's replicas
VARIABLE pod \* pod[p] is the state of replica p
TypeOK == pod \in [Pod -> {"v1", "stopping", "starting", "v2"}]
Init == pod = [p \in Pod |-> "v1"]
Serving(p) == pod[p] \in {"v1", "v2"}
\* The controller replaces one old pod. The guard is its availability rule.
Stop(p) == /\ pod[p] = "v1"
/\ \A q \in Pod : pod[q] /= "stopping"
/\ pod' = [pod EXCEPT ![p] = "stopping"]
\* The old container has exited; the new one is scheduled.
Start(p) == /\ pod[p] = "stopping"
/\ pod' = [pod EXCEPT ![p] = "starting"]
\* The new container passes its readiness probe.
Ready(p) == /\ pod[p] = "starting"
/\ pod' = [pod EXCEPT ![p] = "v2"]
Next == \E p \in Pod : Stop(p) \/ Start(p) \/ Ready(p)
=============================================================================
Add the invariant AtMostOneDown: at most one pod is out of service. You don't have a way to count elements of a set yet, so say it with quantifiers.
Run TLC with CONSTANT Pod = {"p1", "p2", "p3"}, INVARIANT TypeOK, INVARIANT AtMostOneDown and CHECK_DEADLOCK FALSE. Explain the trace. Why is the deadlock check off?
Fix the guard of Stop. How many distinct states does TLC find now, and why that number?
Use the trick from lesson 13 to make TLC show you a complete rollout. How many steps does it take?
Hint
“At most one” means: if two pods are both down, they are the same pod. For the fix, ask what the rule should look at: whether a pod is stopping, or whether it is serving.
Solution
(a) If two pods are both out of service, they are the same pod:
AtMostOneDown == \A p, q \in Pod : (~Serving(p) /\ ~Serving(q)) => p = q
(b) TLC reports Invariant AtMostOneDown is violated:
TLC's trace for the buggy guard. In the last state p1 is still starting, so it doesn't serve, and the guard let p2 stop anyway: two of three pods are down.
p1 is stopped and its replacement is starting. That pod is not stopping, so the script's guard \A q \in Pod : pod[q] /= "stopping" is true and p2 stops too. For as long as p1's new container takes to pass its probe, only p3 serves. The rule checked the wrong state: “stopping” is one way of being out of service, not the only one. The deadlock check is off because a finished rollout, with every pod on v2, has no next step, and that stop is intended.
(c) Make the guard the property you want: stop a pod only if every pod is serving.
TLC finds no error and 32 distinct states: the 8 where every pod is v1 or v2, plus the 24 where exactly one pod is stopping or starting. Counting reachable states by hand and matching TLC's number is a good check that the model allows what you think it allows, as lesson 16 advised.
(d) Claim NotRolledOut == ~(\A p \in Pod : pod[p] = "v2") as an invariant. TLC reports it violated with a 10-state trace: Stop, Start and Ready for p1, then the same for p2, then p3. That is 9 steps, 3 per pod, done strictly one pod at a time, which is what the rule promised. Kubernetes' maxSurge exists to speed this up by starting new pods before old ones stop. Modeling it would need a variable number of pods.
Three services, orders, billing and shipping, publish and consume OrderPlaced events on a shared topic. Version 2 of the event schema renames a field. A service on v1 code can't parse a v2 event, so the platform team sets two rules. First, nobody may emit v2 until every service has deployed a reader that understands both versions. Second, any team may back out, and if one does, nobody ever emits v2.
So each service goes through four states: "v1", "ready" (reads both, still emits v1), "v2" (emits v2), and "pinned" (backed out: stays on v1 for good). This should look familiar.
Write the module, with CONSTANT Svc and one variable st, a function from services to states. Write the actions GetReady(s), Switch(s) and Cancel(s), and two invariants: Agreement (no service on v2 while another is pinned) and ReadersReady (if any service is on v2, every service is ready or on v2).
Run TLC with the three services as strings. How many distinct states does it find? Why is that number familiar?
A teammate argues that the switch guard is too strict, since a service only needs “nobody has backed out”. Replace the guard of Switch(s) by \A t \in Svc : st[t] # "pinned" and run again.
Hint
Match each state to one of TCommit's. Which TCommit formula says “everyone is ready”, and which one says “nobody has gone ahead”?
SolutionOne service's upgrade, with TCommit's name for each state in parentheses. The guards on Switch and Cancel read every service's state, exactly like canCommit and notCommitted.
(a) In the diagram, each state carries its TCommit name. The module:
---------------------------- MODULE PSl5_Schema ----------------------------
CONSTANT Svc \* services that produce and consume OrderPlaced events
VARIABLE st \* st[s] is where service s is in the upgrade
TypeOK == st \in [Svc -> {"v1", "ready", "v2", "pinned"}]
Init == st = [s \in Svc |-> "v1"]
canSwitch == \A s \in Svc : st[s] \in {"ready", "v2"}
noneSwitched == \A s \in Svc : st[s] # "v2"
\* Deploy code that can read both v1 and v2 events; still emit v1.
GetReady(s) == /\ st[s] = "v1"
/\ st' = [st EXCEPT ![s] = "ready"]
\* Start emitting v2 events.
Switch(s) == /\ st[s] = "ready"
/\ canSwitch
/\ st' = [st EXCEPT ![s] = "v2"]
\* Give up on v2 and stay on v1 for good.
Cancel(s) == /\ st[s] \in {"v1", "ready"}
/\ noneSwitched
/\ st' = [st EXCEPT ![s] = "pinned"]
Next == \E s \in Svc : GetReady(s) \/ Switch(s) \/ Cancel(s)
Agreement == \A s, t \in Svc : ~ /\ st[s] = "v2"
/\ st[t] = "pinned"
ReadersReady == (\E s \in Svc : st[s] = "v2")
=> \A t \in Svc : st[t] \in {"ready", "v2"}
=============================================================================
(b) With CONSTANT Svc = {"orders", "billing", "shipping"}, the two invariants and CHECK_DEADLOCK FALSE, TLC finds no error and 34 distinct states. That is TCommit's count for three RMs, and not by coincidence. Rename v1, ready, v2 and pinned to working, prepared, committed and aborted, and this module is TCommit with Decide split into its two branches. A schema rollout and a database commit are the same problem: a group must reach one decision, anyone may veto before it is made, and nobody may act on it early.
(c) With the weaker guard (module PSl5_SchemaEager), TLC reports Invariant ReadersReady is violated after 3 states: orders gets ready, then switches while billing and shipping are still on v1. Their consumers would choke on the first v2 event. Agreement alone doesn't catch this. Run with only Agreement and TLC finds no error, in 46 distinct states. Once orders is on v2, nobody can cancel, so the services do end up agreeing, after an outage.
This is why TCommit's commit branch requires canCommit. For a database it means that no RM commits until every RM has promised it can. Here it means that nobody emits v2 before everyone can read it. The consistency invariant TCConsistent doesn't state that requirement, which is why you want ReadersReady written down and checked too.
Two application servers run the same crontab, so that the nightly jobs still run if one server is down. There are two jobs: backup, and report, which reads the backup. Neither may run twice in a night. Each server, for each job, reads the job's row in a shared jobs table. If owner is empty, it writes its own name and runs the job; otherwise it skips. A report must wait until some server has run the backup.
The module (open to copy)
------------------------------ MODULE PSl5_Cron ------------------------------
CONSTANT Node \* servers that each run the same crontab
VARIABLES pc, \* pc[n][j]: where node n is with job j tonight
owner \* owner[j]: the node in the jobs table, or "none"
Jobs == {"backup", "report"}
TypeOK == /\ pc \in [Node -> [Jobs -> {"idle", "seen", "ran", "skipped"}]]
/\ \A j \in Jobs : owner[j] = "none" \/ owner[j] \in Node
Init == /\ pc = [n \in Node |-> [j \in Jobs |-> "idle"]]
/\ owner = [j \in Jobs |-> "none"]
\* pc with node n's entry for job j set to v
Set(n, j, v) == [pc EXCEPT ![n] = [pc[n] EXCEPT ![j] = v]]
\* The report reads the backup, so it may start only after a backup ran.
Ready(j) == j = "report" => \E n \in Node : pc[n]["backup"] = "ran"
\* SELECT owner FROM jobs WHERE name = j -- and see "none"
Check(n, j) == /\ pc[n][j] = "idle"
/\ owner[j] = "none"
/\ Ready(j)
/\ pc' = Set(n, j, "seen")
/\ owner' = owner
\* UPDATE jobs SET owner = n WHERE name = j; then run the job
Run(n, j) == /\ pc[n][j] = "seen"
/\ owner' = [owner EXCEPT ![j] = n]
/\ pc' = Set(n, j, "ran")
\* Someone else has it.
Skip(n, j) == /\ pc[n][j] = "idle"
/\ owner[j] # "none"
/\ pc' = Set(n, j, "skipped")
/\ owner' = owner
Next == \E n \in Node : \E j \in Jobs : Check(n, j) \/ Run(n, j) \/ Skip(n, j)
AtMostOnce == \A j \in Jobs : \A n, m \in Node :
(pc[n][j] = "ran" /\ pc[m][j] = "ran") => n = m
=============================================================================
The config:
INIT Init
NEXT Next
CONSTANT Node = {"n1", "n2"}
INVARIANT TypeOK
INVARIANT AtMostOnce
CHECK_DEADLOCK FALSE
pc is a function whose values are functions: pc[n] is node n's function from jobs to states, and pc[n][j] is one entry. Set(n, j, v) builds the new pc by applying EXCEPT at both levels.
Read AtMostOnce aloud. Why does it end in n = m rather than n # m?
Run TLC. Explain the trace in terms of SQL statements.
Replace Check and Run by a single action Claim(n, j) that models one conditional UPDATE jobs SET owner = n WHERE name = j AND owner IS NULL: it succeeds and runs the job only if owner is still empty. Check AtMostOnce.
The Ready guard plays the role the runbook guards played in the migration problem of Problem set 4. Use the same never-reached claim to make TLC produce a night's schedule in which both jobs run.
Run your fixed module with the deadlock check on. Is the stop TLC reports a deadlock or termination? Add an action that tells TLC which stops are intended, so that the check can stay on.
Hint
For (c), the check and the write must be one step, so the guard owner[j] = "none" and the change owner' = [owner EXCEPT ![j] = n] belong to the same action. For (e), an action whose guard says “everyone is finished” and whose frame keeps every variable the same is enabled exactly in the intended final states.
Solution
(a) “For every job, for any two nodes: if both ran it, they are the same node.” With n # m it would say that both ran it only if they are different nodes, and the case n = m would make it false in any state where some node ran the job. The \A n, m includes the pairs where n and m are equal. That is what makes “at most one” come out right.
(b) TLC reports Invariant AtMostOnce is violated with a 5-state trace:
Check, then act. Both nodes saw none before either wrote, and nothing makes the second UPDATE look again.
Both servers ran SELECT owner and saw it empty before either wrote. n1's UPDATE doesn't change what n2 already read, and n2's UPDATE overwrites the owner with its own name. The backup runs twice, and the table even says n2 owns it. This is check-then-act: the decision is based on a value that may be stale by the time the action happens.
(c) Make the check part of the write:
--------------------------- MODULE PSl5_CronClaim ---------------------------
CONSTANT Node \* servers that each run the same crontab
VARIABLES pc, \* pc[n][j]: where node n is with job j tonight
owner \* owner[j]: the node in the jobs table, or "none"
Jobs == {"backup", "report"}
TypeOK == /\ pc \in [Node -> [Jobs -> {"idle", "ran", "skipped"}]]
/\ \A j \in Jobs : owner[j] = "none" \/ owner[j] \in Node
Init == /\ pc = [n \in Node |-> [j \in Jobs |-> "idle"]]
/\ owner = [j \in Jobs |-> "none"]
Set(n, j, v) == [pc EXCEPT ![n] = [pc[n] EXCEPT ![j] = v]]
Ready(j) == j = "report" => \E n \in Node : pc[n]["backup"] = "ran"
\* UPDATE jobs SET owner = n WHERE name = j AND owner IS NULL
\* One statement: the check and the write are one step.
Claim(n, j) == /\ pc[n][j] = "idle"
/\ owner[j] = "none"
/\ Ready(j)
/\ owner' = [owner EXCEPT ![j] = n]
/\ pc' = Set(n, j, "ran")
Skip(n, j) == /\ pc[n][j] = "idle"
/\ owner[j] # "none"
/\ pc' = Set(n, j, "skipped")
/\ owner' = owner
Next == \E n \in Node : \E j \in Jobs : Claim(n, j) \/ Skip(n, j)
AtMostOnce == \A j \in Jobs : \A n, m \in Node :
(pc[n][j] = "ran" /\ pc[m][j] = "ran") => n = m
NotAllRan == ~(\A j \in Jobs : \E n \in Node : pc[n][j] = "ran")
AllFinished == \A n \in Node : \A j \in Jobs : pc[n][j] \in {"ran", "skipped"}
\* An intended stop: every node is done for the night. Nothing changes.
Finished == /\ AllFinished
/\ pc' = pc
/\ owner' = owner
NextOrDone == Next \/ Finished
=============================================================================
The module also holds the definitions for parts (d) and (e). With the config of (b), TLC finds no error and 21 distinct states. The model now says the check and the write are one step, so it is your job to make that true in the system too. A single UPDATE … WHERE owner IS NULL does it in Postgres at the default isolation level, read committed: when two such statements hit the same row, the second waits for the first to commit, then re-checks its WHERE clause against the new row and updates nothing. The server then sees that zero rows changed, and skips the job.
(d) Claim NotAllRan, which says that it never happens that every job has run somewhere. TLC reports it violated with a 3-state trace: Claim("n1", "backup"), then Claim("n1", "report"). The report comes second because Ready disables it until a backup has run, exactly as app = 2 forced the backfill after v2 in the migration runbook. The guard is the dependency, and TLC's trace is a schedule that respects it.
(e) With the deadlock check on, TLC reports Deadlock reached after a 5-state trace that ends with n1 having run both jobs and n2 having skipped both. Nothing is left to do, so this is termination, as with the counter in lesson 9. Rather than turn the check off, the module defines Finished, which is enabled only when every entry of pc is "ran" or "skipped" and changes nothing, and NextOrDone == Next \/ Finished. With NEXT NextOrDone and the deadlock check on, TLC finds no error in 21 states. That shows something the earlier run couldn't: every state with no further step is a finished night. If Ready could block the report forever, this run would report the deadlock.
The pieces came from four chapters: functions and quantifiers for “at most once across nodes”, TCommit's style of guard that reads every process, the runbook guard and never-reached claim from Problem set 4, and the deadlock-or-termination question from Lecture 3.
Lecture 6: Two-phase commit
Two-phase commit puts the minister back, as a process with messages.
TCommit let one step read every RM's state. Lecture 6 replaces that impossible step with a protocol: a transaction manager (TM) collects "prepared" messages and then announces the result. First you need one more data type, the record, because messages are records.
The normal case. Each message stays in msgs after it's read.
This is a real run of the spec below, printed by TLC with two RMs, and it has 8 states. An RM's "prepared" message and its change of state happen in one step. The TM commits only once tmPrepared holds every RM.
While you watch
Lecture 6 opens with records, then reruns the wedding with texting. Notice that he drops the minister's "are you prepared?" message because TCommit doesn't need it. When he describes each remaining action, stop the video and write the definition yourself, as he asks. Later, compare your version by rerunning TLC. This lesson adds a trace in which an RM aborts, and the commit-lab below. How the spec models messages gets its own treatment in lesson 19.
Records
r == [prof |-> "Fred", num |-> 42] \* r.prof = "Fred", r.num = 42
[prof : {"Fred", "Ted"}, num : 0..99] \* the set of all such records
[r EXCEPT !.prof = "Red"] \* same as r except field prof
A record is like a C struct, except that field order doesn't matter. It is really a function whose domain is a set of strings: r.prof abbreviates r["prof"], and !.prof abbreviates !["prof"]. So you already know how they behave.
S \cup T (or \union) is the set of elements in S or T or both.
S \subseteq T says every element of S is in T.
UNCHANGED <<a, b>> says each listed variable keeps its value. <<a, b>> is an ordered tuple; vars names the tuple of all four variables.
msgs holds every message ever sent. A Prepared record goes from r to the TM. A Commit or Abort record goes from the TM to all RMs. The formulas with no primes at the start of an action are its enabling conditions: conditions on the first state of a step. Put them first. That is easier to read, and TLC often can't handle the action otherwise. Finally, INSTANCE TCommit imports TCommit's definitions, including TCConsistent, applied to this module's rmState.
A trace where an RM aborts
An RM aborts. r2's choice is not a message; the TM aborts on its own. r2 is already aborted, so it needn't read the Abort.
r2 aborts on its own, shown as a note because no message is sent. In a real system it would tell the TM, but that is an optimization the spec omits. r1 is prepared and can't abort itself; it has to wait to hear from the TM. Nothing makes the TM wait, because TMAbort is enabled whenever tmState = "init".
This order is one of many. TLC, asked for any run with this outcome, returned a 5-state trace with TMAbort as the very first step, before anyone had done anything. That is also allowed. The diagram shows the order you would expect in practice, and the guards permit both.
Result: no error, 288 distinct states (1146 generated), the same count the lecture reports. The lecture uses that number as a test of your own definitions: paste one in, rerun, and if TLC finds no error and again 288 states, it's probably correct.
Symmetry and model values
Exchanging two RMs in a reachable state gives a reachable state, so TLC can treat the two as one case.
All RMs play the same role. Swap r1 and r3 everywhere in a reachable state, as in the diagram, and you get another reachable state. Swap them in a whole behavior and you get another allowed behavior, so TLC needn't check both. A set with this property is a symmetry set. To use one, make its elements model values: special values not equal to anything else, written as bare identifiers. In the Toolbox you tick "Symmetry set". In a .cfg file you need a small wrapper module:
RM <- RMs replaces the constant by the module's definition RMs. Permutations comes from the TLC module. Result: no error, 80 distinct states examined, out of the same 288 reachable ones. Be careful: TLC may miss errors if you declare a symmetry set falsely. For now it's safe if the model values aren't used elsewhere; lesson 22 gives the full rule.
Is it correct?
The run above also checks TCConsistent: one RM can't commit while another aborts. TwoPhase actually does more than keep that invariant: it implements TCommit. That claim needs its own definition, given in lesson 26.
Explore the TM's decision
In the lab, "coordinator" is the common industry name for the TM, and participants A and B are RMs. It is an educational model, not TLC: it leaves out msgs and tmPrepared, treating "prepared" as instantly known. Prepare both RMs and crash the coordinator. No commit can happen, and nothing lets a prepared RM move. Agreement isn't violated, but the transaction is stuck, which is the starting point of lesson 22.
Predict: both RMs are prepared and the TM has gone silent. Is it safe for an RM to abort on its own?
No. The TM may already have sent Commit, and the other RM may have received it. Not having heard is no evidence that no decision exists. The spec gives a prepared RM no way to leave that state except by receiving a message.
Worked architecture: reserve a seat and charge a wallet
A purchase spans an inventory RM and a wallet RM. Preparing means each one promises it can honor a commit and holds what it needs: the seat, the funds. That promise is what makes prepared different from "looks available".
Trace a hard run with the first diagram. Both prepare; the TM sends Commit; inventory receives it and marks the seat sold, and the wallet hasn't heard yet. For a while one RM is committed and another prepared. TCConsistent allows this, because it forbids only committed alongside aborted. If the wallet then gave up and aborted on a timeout, that would be the forbidden state: a seat sold and no money taken.
In TwoPhase, sending adds a record to msgs, and receiving removes nothing. That choice looks odd, and it's the most reusable modeling idea in lecture 6. This lesson explains why it works, then uses it to model loss, delay, and duplicates without new machinery.
P1 is r1's Prepared message and C is the Commit record. Reading from the top model removes; reading from the bottom one doesn't.
Follow both rows left to right. The top row is the obvious model: msgs is what's in transit, and receiving takes a message out. In the last column r1 has consumed the only Commit, so r2 can never get it. The bottom row is the lecture's: msgs is everything ever sent, and both RMs can read the same record.
While you watch
Find the part of lecture 6 titled "Sending Messages", and "A Simpler Method" right after it. Then stop at his explanation of TMRcvPrepared and predict what a second receipt of the same message does. Everything after the lecture's two points (one message, many readers; one reader, many receipts) is what this lesson adds.
What the spec needs from the network
A spec should describe only what the algorithm requires of message passing. Two-phase commit needs no ordering between messages, so a set is enough. Lamport compares two methods:
Simple:msgs is the set of messages in transit. Receiving removes one.
Simpler:msgs is the set of all messages ever sent. A receive action merely requires the message to be there.
Here is what TLC finds for both, with three RMs, plus a repaired version of the first.
Model of msgs
Distinct states
Can all three RMs commit?
Ever sent (the lecture's TwoPhase)
288
Yes
In transit, one Commit record
265
No: ~\A r : committed holds as an invariant
In transit, one addressed copy per RM
415
Yes: TLC finds the run, 11 states long
The second row is a warning: TLC reports no error on TCConsistent, yet the model can't do its job. It's the kind of success to be suspicious of. The third row works, but it adds a to field and more states. It also says each copy is received at most once, which real networks don't promise.
Receiving twice is harmless, here
Since a message stays in msgs, TMRcvPrepared(r) stays enabled after it runs. A later step does tmPrepared' = tmPrepared \cup {r} with r already in the set. A set can't contain two copies of r, so nothing changes. A step that leaves every variable unchanged is a stuttering step, and it makes no difference; lesson 25 explains why such steps are always allowed. This matters because a real process can receive one message twice.
The same duplicate read under two TM designs. A set absorbs it. A count turns it into a false vote.
The set is doing real work. In the diagram, the top row is TwoPhase, and the bottom row is a variant where the TM keeps a count instead and commits when the count reaches the number of RMs. TLC finds a TCConsistent violation in a 7-state trace, with two RMs: r1 prepares, the TM counts r1's message twice, commits, r1 commits, and r2, still working, aborts on its own. A message read twice made one vote look like two.
Predict: does the grow-only set break when the TM's rule is "commit once I've seen any Prepared from r1 and r2"?
No, and it's exactly what TMCommit with tmPrepared = RM says. A rule about which messages exist is automatically immune to duplicates. A rule about how many receipts happened isn't.
Extending the model: the network's freedoms
Nothing in msgs forces a process to act on a message. That one fact covers most of what a network can do, as long as you're checking safety (what can happen, not what must).
Network behavior
In the grow-only model
Delay
The message sits in msgs while other steps happen
Reordering
Any message in the set may be read next
Duplicate delivery
The receive action can run again
Loss
The receive action never runs for that message
Timeout and retry
A new message or attempt; nothing proves the first was lost
A permanently lossy channel still satisfies every safety property, because nothing happens. Saying that something must eventually be delivered is a liveness assumption, the subject of lesson 29. And if an algorithm needs ordering, a set is too weak and you'd use a sequence, as lesson 30 does.
Worked trace: the uncertain checkout response
A checkout client sends request r7. The server creates an order, but the reply is lost, and the browser times out.
A lost reply leaves the client unsure. The retry is safe only because the server recognizes the logical request.
At the X in the diagram the client knows nothing and the server has an order. A timeout only shows no reply arrived in time; it doesn't show the server did nothing. The dashed retry is what makes a double order possible. Here's the model. Attempts are records with both the logical request and the transport attempt:
------------------------------ MODULE CheckoutRetry ---------------------------
EXTENDS Integers
CONSTANTS Attempt, \* the attempts the client may send for request r7
KeyField \* the message field the server deduplicates on
VARIABLES
msgs, \* every attempt ever sent; never shrinks
applied, \* what the server has recorded as already done
orders, \* orders the server created
replied, \* the server has sent a reply
client \* "waiting" or "knows"
vars == <<msgs, applied, orders, replied, client>>
CInit == /\ msgs = {} /\ applied = {} /\ orders = 0
/\ replied = FALSE /\ client = "waiting"
\* First try, or a retry after a timeout. Nothing forces a reply to come first.
Send(a) == /\ client = "waiting"
/\ [req |-> "r7", try |-> a] \notin msgs
/\ msgs' = msgs \cup {[req |-> "r7", try |-> a]}
/\ UNCHANGED <<applied, orders, replied, client>>
\* The client learns the result only if it reads a reply.
Hear == /\ replied
/\ client' = "knows"
/\ UNCHANGED <<msgs, applied, orders, replied>>
\* Creates an order unless this message's key is recorded. Delivery leaves m
\* in msgs, so m can be delivered again; one never delivered has been lost.
Deliver ==
\E m \in msgs :
/\ m[KeyField] \notin applied
/\ orders < 2
/\ orders' = orders + 1
/\ applied' = applied \cup {m[KeyField]}
/\ replied' = TRUE
/\ UNCHANGED <<msgs, client>>
\* A repeat of work already done: just send the reply again.
Repeat ==
\E m \in msgs :
/\ m[KeyField] \in applied
/\ replied' = TRUE
/\ UNCHANGED <<msgs, applied, orders, client>>
CNext == \/ \E a \in Attempt : Send(a)
\/ Deliver \/ Repeat \/ Hear
OneOrder == orders <= 1
KnowsTruth == client = "knows" => orders >= 1
=============================================================================
The constant KeyField picks what the server deduplicates on. m[KeyField] works because a record is a function. With KeyField = "req", TLC reports no error, 10 distinct states. With KeyField = "try", OneOrder is violated in 5 states: send e1, send e2, deliver each, two orders. The retry looks like a new purchase because its transport identity is new.
Predict: the client gives every retry a fresh request ID. Is it protected?
No. That is the "try" run again: a fresh ID makes each retry a distinct purchase. The ID has to survive the ambiguous response, so it must belong to the customer's intent, not to the attempt.
Lecture 6: Two-phase commit
Problem set 6: what a commit protocol promises, and what it doesn't.
Lecture 6 turned TCommit into a protocol: records as messages, a grow-only set of messages as the network, and UNCHANGED for frames. These problems change TwoPhase the way real teams do, adding a business rule, a crash, a side effect, and see what breaks. They reuse functions and quantifiers from Sets, functions, and quantifiers, the agreement spec of Problem set 5, and TLC's deadlock check from lesson 9.
Most modules here are the lesson's TwoPhase with a few lines changed, and they end with INSTANCE TCommit, so keep TCommit.tla from lesson 16 in the same folder. For trace lengths, run TLC with -workers 1.
A travel site sells trips: a flight, a hotel and a rental car, each booked in a different supplier's system. The booking service runs two-phase commit exactly as the TwoPhase spec in lesson 18 describes. It is the TM, and the three suppliers are RMs. Preparing means a supplier holds the seat, room or car. A product manager asks for a change: “The car is optional. If the car supplier can't confirm, book the trip without it.” A developer implements it with one line in TMCommit:
Everything else is the lesson's TwoPhase, renamed PSl6_Booking. The config uses CONSTANT RM = {"flight", "hotel", "car"}, the invariants TPTypeOK and TCConsistent, and CHECK_DEADLOCK FALSE.
Run the unchanged TwoPhase with these three RMs first. What do you expect for the state count, and why?
Make the change and run TLC. Explain the trace.
Add this invariant, which says that an RM commits only after it prepared, and run again with it as the only invariant besides TPTypeOK. What does TLC find? Why does the lesson's TwoPhase get away with no guard in RMRcvCommitMsg?
Propose a design that meets the product manager's request and keeps TCConsistent true.
Hint
Once the Commit message is in msgs, what can the car do while it is still working? Look at the guards of RMChooseToAbort and RMRcvCommitMsg.
Solution
(a) No error and 288 distinct states, the lesson's count. The RMs' names don't matter, only how many there are.
(b) TLC reports Invariant TCConsistent is violated with an 8-state trace:
TLC's 8-state trace for the optional car. The flight is ticketed and the car reservation was abandoned, inside one transaction that promised all or nothing.
The flight and hotel prepare and the TM records both. That is enough for the new guard, so the TM commits, and the flight receives Commit. The car never prepared, so RMChooseToAbort("car") is still enabled, and it aborts. One RM committed and another aborted, which TCommit forbids. In business terms this might even be the outcome the product manager wanted. But the spec claimed all or nothing for three RMs, and the code now does something else. The problem is the mismatch.
(c) TLC reports Invariant CommitAfterPrepare is violated with a 7-state trace that ends in RMRcvCommitMsg("car"): the car, still working, receives Commit and becomes committed without ever having held a car. In the lesson's spec the invariant holds (TLC: no error, 288 states, module PSl6_BookingOrig), because a Commit message can only exist once every RM is in tmPrepared. RMRcvCommitMsg relies on TMCommit's guard. Change that guard and every receive action becomes wrong too, even though nobody touched it.
(d) Make the transaction say what the business means. Run two-phase commit over RM = {"flight", "hotel"}, the parts that must succeed together. TLC: no error in 56 states. Then book the car as a separate step after the trip commits, and if that fails, tell the customer. If the car really must be all-or-nothing with the rest, it has to stay an RM, and the trip aborts when the car can't be held. Either way the spec and the code agree on which RMs share a fate.
Problem 2●●○Databases
Postgres prepared transactions and a dead coordinator
An app server writes an order to one Postgres database and a payment to another, using Postgres's own two-phase commit. On each database it runs PREPARE TRANSACTION 'tx42', then COMMIT PREPARED 'tx42' on both, or ROLLBACK PREPARED 'tx42'. A prepared transaction is stored on disk, survives a database restart, and keeps every lock it holds until one of those two commands arrives. If the app server's session drops before PREPARE TRANSACTION, Postgres rolls the transaction back. Meanwhile a nightly report session wants to update a row the payment locked.
The model is TwoPhase with the app server as the TM and three changes. The TM can crash and stay down (TMCrash), and an RM can prepare only while the TM is up. A report variable models the waiting session. A Finished action marks the intended end, so that the deadlock check can stay on. A constant DBA picks what a database administrator may do by hand while the app server is down.
The module (open to copy)
---------------------------- MODULE PSl6_Prepared ----------------------------
CONSTANTS RM, \* the Postgres databases in the transaction
DBA \* the DBA's rule: "never", "blind", or "checklog"
VARIABLES
rmState, \* rmState[r] is the state of r's transaction
tmState, \* the app server: "init", "done", or "down"
tmPrepared, \* the databases the app server knows are prepared
msgs, \* every message ever sent
report \* a session on "payments" blocked on a row lock
vars == <<rmState, tmState, tmPrepared, msgs, report>>
Messages == [type : {"Prepared"}, rm : RM] \cup [type : {"Commit", "Abort"}]
TypeOK ==
/\ rmState \in [RM -> {"working", "prepared", "committed", "aborted"}]
/\ tmState \in {"init", "done", "down"}
/\ tmPrepared \subseteq RM
/\ msgs \subseteq Messages
/\ report \in {"waiting", "done"}
Init ==
/\ rmState = [r \in RM |-> "working"]
/\ tmState = "init"
/\ tmPrepared = {}
/\ msgs = {}
/\ report = "waiting"
-----------------------------------------------------------------------------
TMRcvPrepared(r) ==
/\ tmState = "init"
/\ [type |-> "Prepared", rm |-> r] \in msgs
/\ tmPrepared' = tmPrepared \cup {r}
/\ UNCHANGED <<rmState, tmState, msgs, report>>
TMCommit == \* COMMIT PREPARED on each database
/\ tmState = "init"
/\ tmPrepared = RM
/\ tmState' = "done"
/\ msgs' = msgs \cup {[type |-> "Commit"]}
/\ UNCHANGED <<rmState, tmPrepared, report>>
TMAbort == \* ROLLBACK PREPARED on each database
/\ tmState = "init"
/\ tmState' = "done"
/\ msgs' = msgs \cup {[type |-> "Abort"]}
/\ UNCHANGED <<rmState, tmPrepared, report>>
TMCrash == \* the app server dies and stays down
/\ tmState # "down"
/\ tmState' = "down"
/\ UNCHANGED <<rmState, tmPrepared, msgs, report>>
RMPrepare(r) == \* the app server's PREPARE TRANSACTION succeeds
/\ tmState = "init"
/\ rmState[r] = "working"
/\ rmState' = [rmState EXCEPT ![r] = "prepared"]
/\ msgs' = msgs \cup {[type |-> "Prepared", rm |-> r]}
/\ UNCHANGED <<tmState, tmPrepared, report>>
RMChooseToAbort(r) == \* an error, or the app server's session is lost
/\ rmState[r] = "working"
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ UNCHANGED <<tmState, tmPrepared, msgs, report>>
RMRcvCommitMsg(r) ==
/\ [type |-> "Commit"] \in msgs
/\ rmState' = [rmState EXCEPT ![r] = "committed"]
/\ UNCHANGED <<tmState, tmPrepared, msgs, report>>
RMRcvAbortMsg(r) ==
/\ [type |-> "Abort"] \in msgs
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ UNCHANGED <<tmState, tmPrepared, msgs, report>>
\* The report's UPDATE waits for the row lock until the transaction ends.
ReportRuns ==
/\ report = "waiting"
/\ rmState["payments"] \in {"committed", "aborted"}
/\ report' = "done"
/\ UNCHANGED <<rmState, tmState, tmPrepared, msgs>>
\* ROLLBACK PREPARED by hand while the app server is down. "blind": anything
\* still prepared. "checklog": only if the app server's log has no Commit.
DBARollback(r) ==
/\ \/ DBA = "blind"
\/ DBA = "checklog" /\ [type |-> "Commit"] \notin msgs
/\ tmState = "down"
/\ rmState[r] = "prepared"
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ UNCHANGED <<tmState, tmPrepared, msgs, report>>
\* An intended stop: every transaction has ended and the report has run.
Finished ==
/\ \A r \in RM : rmState[r] \in {"committed", "aborted"}
/\ report = "done"
/\ UNCHANGED vars
-----------------------------------------------------------------------------
Next ==
\/ TMCommit \/ TMAbort \/ TMCrash \/ ReportRuns \/ Finished
\/ \E r \in RM : \/ TMRcvPrepared(r) \/ RMPrepare(r) \/ RMChooseToAbort(r)
\/ RMRcvCommitMsg(r) \/ RMRcvAbortMsg(r) \/ DBARollback(r)
-----------------------------------------------------------------------------
INSTANCE TCommit
=============================================================================
The config, with the deadlock check on:
INIT Init
NEXT Next
CONSTANTS RM = {"orders", "payments"}
DBA = "never"
INVARIANT TypeOK
INVARIANT TCConsistent
Why is Finished needed for the deadlock check to mean anything here? (Compare the terminating counter in lesson 9.)
Run TLC with DBA = "never". What does it report? Describe the final state in Postgres terms: what holds locks, and who waits?
The on-call DBA's runbook says: “If the app server is down, run ROLLBACK PREPARED on anything still prepared.” Run with DBA = "blind". What breaks, and why can't the payments database alone tell the DBA what to do?
Run with DBA = "checklog", where the DBA rolls back only if the app server's log contains no Commit decision. What does TLC report?
Hint
In TwoPhase, after the TM decides, RMRcvCommitMsg or RMRcvAbortMsg stays enabled forever, so TLC never sees a stop. Here, which states have no enabled action? For (c), remember that a message in msgs may never be received: that is how the model says it was lost.
Solution
(a) A run in which both transactions end and the report finishes is supposed to stop. Without Finished, TLC would report that intended stop as a deadlock, and you would have to turn the check off, which also hides the stops you care about. Finished is enabled exactly in the good final states and changes nothing, so any deadlock TLC reports is a state where work is left undone.
(b) TLC reports Deadlock reached with a 4-state trace:
The blocking case of two-phase commit, as TLC finds it: 4 states. Nothing in the model is wrong. The protocol simply has no step that a prepared participant can take alone.
Both databases prepared, and then the app server died before deciding. Each database holds a prepared tx42 with its row locks. Nothing in Postgres will resolve it: the protocol gives a prepared participant no step of its own. The report's UPDATE waits on the payment row, indefinitely. Postgres's documentation warns against leaving transactions prepared for long, because they also stop VACUUM from reclaiming storage. You can list them in the pg_prepared_xacts view. This is the blocking problem the lab in lesson 18 showed, now as a TLC trace.
(c) TLC reports Invariant TCConsistent is violated with a 9-state trace. Both databases prepare, the app server commits and sends Commit, then crashes. Orders receives Commit and commits. Payments never gets its Commit (in the model, that message is never received), and the DBA, following the runbook, rolls it back. An order with no payment. From inside the payments database, “prepared and the coordinator is down” looks the same whether or not a Commit decision exists. The information the DBA needs is the decision, and that lives in the coordinator's log, not in this database.
(d) No error and 194 distinct states, and no deadlock. If the log has no Commit, nobody can have committed, so a rollback is safe. If it does, the Commit message stays in msgs, and receiving it models the DBA running COMMIT PREPARED. Resolving a prepared transaction by hand is safe only with the decision in hand. Real transaction managers write their decision to durable storage before sending it, so that they, or a person, can finish the job after a crash.
After an order commits, the order service publishes a “send receipt” message to a queue, and an email worker consumes it. The queue behaves like Amazon SQS standard queues: delivery is at least once, ordering is best effort, and a message that isn't acknowledged within its visibility timeout is delivered again. The model below uses the grow-only msgs from lesson 19. The constant Mode picks how the worker handles a delivery. emailed is the worker's table of orders it has emailed.
The module (open to copy)
----------------------------- MODULE PSl6_Receipts -----------------------------
EXTENDS Integers
CONSTANT Mode \* how the email worker handles a delivery:
\* "naive", "atomic", or "twostep"
Orders == {"o1", "o2"} \* o1 is placed before o2
Receipt(o) == [type |-> "receipt", order |-> o]
VARIABLES
msgs, \* every message ever published to the queue
sent, \* sent[o]: receipt emails sent for order o
emailed \* orders the worker's table records as emailed
vars == <<msgs, sent, emailed>>
TypeOK == /\ msgs \subseteq [type : {"receipt"}, order : Orders]
/\ sent \in [Orders -> 0..2]
/\ emailed \subseteq Orders
Init == /\ msgs = {}
/\ sent = [o \in Orders |-> 0]
/\ emailed = {}
\* The order service publishes after each order commits, o1 first.
Publish(o) == /\ Receipt(o) \notin msgs
/\ o = "o2" => Receipt("o1") \in msgs
/\ msgs' = msgs \cup {Receipt(o)}
/\ UNCHANGED <<sent, emailed>>
SendEmail(o) == sent' = [sent EXCEPT ![o] = sent[o] + 1]
\* The queue hands o's receipt message to the worker (again, possibly).
Deliver(o) ==
/\ Receipt(o) \in msgs
/\ sent[o] < 2 \* keeps the model finite
/\ \/ /\ Mode = "naive"
/\ SendEmail(o)
/\ UNCHANGED emailed
\/ /\ Mode = "atomic" \* check, send, record: one step
/\ o \notin emailed
/\ SendEmail(o)
/\ emailed' = emailed \cup {o}
\/ /\ Mode = "twostep" \* check and send; record later
/\ o \notin emailed
/\ SendEmail(o)
/\ UNCHANGED emailed
/\ UNCHANGED msgs
\* twostep only: the worker writes "emailed" after the provider accepts.
Record(o) == /\ Mode = "twostep"
/\ sent[o] > 0
/\ o \notin emailed
/\ emailed' = emailed \cup {o}
/\ UNCHANGED <<msgs, sent>>
Next == \E o \in Orders : Publish(o) \/ Deliver(o) \/ Record(o)
OneEmail == \A o \in Orders : sent[o] =< 1
InOrder == sent["o2"] > 0 => sent["o1"] > 0
=============================================================================
The config for the first run:
INIT Init
NEXT Next
CONSTANT Mode = "naive"
INVARIANT TypeOK
INVARIANT OneEmail
CHECK_DEADLOCK FALSE
Notice what is not in the module: no action duplicates, delays or reorders messages. Deliver(o) only requires the message to be in msgs.
Run with Mode = "naive". Where in the module does the duplicate come from?
Run with Mode = "atomic". What does TLC report? What does putting the check, the email and the record in one step claim about the real worker?
Run with Mode = "twostep", the honest version: the worker checks the table, calls the email API, and records the order afterwards. What happens?
With Mode = "atomic", add INVARIANT InOrder. What does TLC find? Does a receipt service need to care?
Hint
Look for what removes a message from msgs, or disables Deliver(o) once it has run. In "twostep", which action has to happen between the two deliveries to prevent the second email?
Solution
(a) TLC reports Invariant OneEmail is violated with a 4-state trace: Publish("o1"), Deliver("o1"), Deliver("o1"). Nothing removes a message from msgs, so Deliver("o1") stays enabled. That is the lesson's point about one reader and many receipts, with an effect, an email, that isn't harmless to repeat. You got duplicate delivery without writing a line for it.
(b) No error, 7 distinct states. The second delivery finds "o1" \in emailed and is disabled. But the step claims that checking the table, calling the email API, and writing the table happen as one indivisible event. A database transaction can make the check and the write atomic. It can't include a call to an external email service.
(c) TLC reports OneEmail violated, again in 4 states: Publish, then Deliver("o1") twice, before Record("o1") ever runs.
At-least-once delivery. The second delivery is the same message read again, which the grow-only msgs allows without any extra action.
In SQS terms, the worker took longer than the visibility timeout, or crashed after sending and before recording, and the queue handed the message to another delivery. Your table can make duplicates rarer. It can't rule them out, because the gap between the external effect and the record is real. The usual way out is to give the email provider an idempotency key such as the order id and let it deduplicate, or to accept that a customer may occasionally get two receipts. Which one is right is a product decision, and the model has made it a visible one.
(d) TLC reports InOrder violated with a 4-state trace: Publish("o1"), Publish("o2"), Deliver("o2"). The set model includes reordering for free, which matches the queue's best-effort ordering. Receipts don't need order, so you'd delete the invariant. A consumer that applies successive updates to the same record would care. It would need a sequence and an ordered channel, which the course models with the alternating bit protocol in Lecture 9.
An online shop fulfils an order from two warehouses, east and west, one unit from each. Each warehouse's inventory database is an RM in two-phase commit, and the order service is the TM. Preparing reserves a unit: it leaves the shelf count and is held for this order. Committing ships the held unit. Aborting must cancel the reservation and put the unit back. A developer adds a stock variable to TwoPhase, with these changes:
Every other action has stock in its UNCHANGED list, TypeOK requires stock \in [RM -> 0..Stock0] with Stock0 == 1, and the module ends with INSTANCE TCommit. The fixed module is in the solution; the developer's version differs only in RMRcvAbortMsg.
Write Conservation: for every warehouse, the units on the shelf plus the units held or shipped for this order equal Stock0. A helper Held(w), which is 1 when w is prepared or committed and 0 otherwise, makes it short.
Run TLC with CONSTANT RM = {"east", "west"}, listing INVARIANT Conservation first, then TypeOK and TCConsistent, with CHECK_DEADLOCK FALSE. Explain the trace.
Compare with the schema-agreement problem in Problem set 5, where Agreement and ReadersReady were the requirements. Does TCConsistent catch this bug?
A reviewer suggests releasing stock only if rmState[r] # "working". Try it. Then write a fix that works, and check it with two and with three warehouses.
Hint
Which RMs can receive an Abort message? In TwoPhase, receiving the same message twice was harmless because setting rmState[r] to "aborted" again changes nothing. Is stock[r] + 1 like that? The release should depend on what this particular step undoes.
Solution
(a)
Held(w) == IF rmState[w] \in {"prepared", "committed"} THEN 1 ELSE 0
Conservation == \A w \in RM : stock[w] + Held(w) = Stock0
(b) TLC reports Invariant Conservation is violated with a 3-state trace: TMAbort, then RMRcvAbortMsg("east") while east is still working. East never reserved anything, but the release adds a unit, so its shelf shows 2. TLC checks the invariants in the order the config lists them. With TypeOK listed first it reports TypeOK violated in the same 3 states, since 2 isn't in 0..Stock0. In TwoPhase, an Abort can reach any RM, prepared or not, and any number of times. Those receives were safe only because they had no effect beyond setting rmState.
(c) No. TCConsistent mentions only rmState, and this change never affects rmState. With shelf counts bounded at 4, TLC confirms it: no error in 245 states. The decision was abort and nobody committed, so agreement holds, and the inventory is wrong anyway. In the schema problem of Problem set 5, agreement wasn't enough either, and ReadersReady was the requirement that mattered. Here it is Conservation. A commit protocol guarantees agreement on the decision, and the effects you attach to the decision need their own invariant.
(d) The reviewer's guard isn't enough. TLC finds a 4-state trace: TMAbort, east aborts on its own with RMChooseToAbort, then receives Abort and releases a unit it never reserved.
Top: TMAbort, then RMRcvAbortMsg("east") while east is working. Bottom, with the release guarded by rmState[r] # "working": TMAbort, RMChooseToAbort("east"), RMRcvAbortMsg("east"). Either way a unit appears from nowhere.
A duplicate delivery to a prepared warehouse is a third route: prepare, TM aborts, receive Abort (correct release), receive it again (second release). The fix releases exactly when this step undoes a reservation, that is, when the RM is prepared:
------------------------------ MODULE PSl6_StockFixed ------------------------------
EXTENDS Integers
CONSTANT RM \* the warehouses; the order needs one unit from each
Stock0 == 1 \* units each warehouse has on the shelf at the start
VARIABLES rmState, tmState, tmPrepared, msgs,
stock \* stock[w]: units on the shelf at w, not reserved
vars == <<rmState, tmState, tmPrepared, msgs, stock>>
Messages == [type : {"Prepared"}, rm : RM] \cup [type : {"Commit", "Abort"}]
TypeOK ==
/\ rmState \in [RM -> {"working", "prepared", "committed", "aborted"}]
/\ tmState \in {"init", "done"}
/\ tmPrepared \subseteq RM
/\ msgs \subseteq Messages
/\ stock \in [RM -> 0..Stock0]
Init ==
/\ rmState = [r \in RM |-> "working"]
/\ tmState = "init"
/\ tmPrepared = {}
/\ msgs = {}
/\ stock = [r \in RM |-> Stock0]
-----------------------------------------------------------------------------
TMRcvPrepared(r) ==
/\ tmState = "init"
/\ [type |-> "Prepared", rm |-> r] \in msgs
/\ tmPrepared' = tmPrepared \cup {r}
/\ UNCHANGED <<rmState, tmState, msgs, stock>>
TMCommit ==
/\ tmState = "init"
/\ tmPrepared = RM
/\ tmState' = "done"
/\ msgs' = msgs \cup {[type |-> "Commit"]}
/\ UNCHANGED <<rmState, tmPrepared, stock>>
TMAbort ==
/\ tmState = "init"
/\ tmState' = "done"
/\ msgs' = msgs \cup {[type |-> "Abort"]}
/\ UNCHANGED <<rmState, tmPrepared, stock>>
\* Prepare = reserve: take a unit off the shelf and hold it for this order.
RMPrepare(r) ==
/\ rmState[r] = "working"
/\ stock[r] > 0
/\ rmState' = [rmState EXCEPT ![r] = "prepared"]
/\ stock' = [stock EXCEPT ![r] = stock[r] - 1]
/\ msgs' = msgs \cup {[type |-> "Prepared", rm |-> r]}
/\ UNCHANGED <<tmState, tmPrepared>>
RMChooseToAbort(r) ==
/\ rmState[r] = "working"
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ UNCHANGED <<tmState, tmPrepared, msgs, stock>>
\* Commit = ship the held unit. The shelf count doesn't change.
RMRcvCommitMsg(r) ==
/\ [type |-> "Commit"] \in msgs
/\ rmState' = [rmState EXCEPT ![r] = "committed"]
/\ UNCHANGED <<tmState, tmPrepared, msgs, stock>>
\* Abort = cancel the reservation and put the unit back on the shelf.
RMRcvAbortMsg(r) ==
/\ [type |-> "Abort"] \in msgs
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ stock' = IF rmState[r] = "prepared"
THEN [stock EXCEPT ![r] = stock[r] + 1]
ELSE stock
/\ UNCHANGED <<tmState, tmPrepared, msgs>>
-----------------------------------------------------------------------------
Next ==
\/ TMCommit \/ TMAbort
\/ \E r \in RM : TMRcvPrepared(r) \/ RMPrepare(r) \/ RMChooseToAbort(r)
\/ RMRcvCommitMsg(r) \/ RMRcvAbortMsg(r)
-----------------------------------------------------------------------------
INSTANCE TCommit
Held(w) == IF rmState[w] \in {"prepared", "committed"} THEN 1 ELSE 0
\* Every unit is on the shelf, or held or shipped for this order.
Conservation == \A w \in RM : stock[w] + Held(w) = Stock0
=============================================================================
TLC finds no error: 56 distinct states with two warehouses and 288 with three. These are exactly TwoPhase's counts for two and three RMs. In the fixed model, stock[w] always equals Stock0 - Held(w), which is what Conservation says, so the extra variable adds no states. When adding a variable doesn't change the count, it is a function of the others, and it is worth asking whether you need to store it at all. The general lesson: an effect attached to a receive action must be idempotent, because the network may deliver the message to any RM, any number of times.
Lecture 7: Paxos commit
Two majorities always share someone, and that's where evidence survives.
Two-phase commit depends on one TM remembering the decision. The fix in lecture 7 is to spread that memory over several processes and count on overlapping groups. This lesson teaches the set operators the lecture uses, and the quorum idea, on a simpler example: copies of a stored value.
Two majorities of three acceptors. Their intersection is not empty, and it's the only thing they have to share.
Two sets of acceptors, each a majority of three. \cap is the part in both, and in the diagram that's a2. An acceptor is just a process whose job is to record votes; lesson 22 says what they vote on. Whichever two majorities you pick, some acceptor is in both.
While you watch
The lecture gets to these operators while it reads module PaxosCommit, so here they come first. Listen for the ASSUME statement and the conjunct about Majority, which is the most important line in this lesson. He also defines Ballot \ {0} and two set constructors. This lesson adds the storage example and the read and write set lab, which aren't in the lecture; the algorithm itself is in lesson 22.
Don't confuse SUBSET S, a set of sets, with T \subseteq S, a true-or-false statement from lesson 18. Nat, from module Integers, is the set of natural numbers. The two constructors look alike: if the colon has a set on the left, it filters; if on the right, it maps.
Why majorities overlap
With the set operators you can state the property directly, rather than counting:
Majority == {Q \in SUBSET Acceptor : Cardinality(Q) = 2} \* with 3 acceptors
\A MS1, MS2 \in Majority : MS1 \cap MS2 # {} \* the property that matters
Each row is a set in Majority, each column an acceptor. Any two green rows share a column. The red row breaks the property against {a1, a2}.
Each row of the diagram is one set in Majority, and each column an acceptor. Pick any two green rows: some column is filled in both. Now look at the red row, {a3}. It shares no column with {a1, a2}. A set of "majorities" containing it fails the property even though every row looks like a reasonable group. Paxos Commit assumes only the property, not a count. You will see TLC break that assumption on purpose.
The general rule for N replicas: if a read set has R members and a write set has W, then R + W > N forces overlap, because R + W elements can't fit into N places without sharing one. That is a statement about sets and nothing more.
Worked architecture: a replicated product price
A price is stored on replicas A, B, and C, all at version 7. A write of version 8 counts as acknowledged once 2 replicas (W = 2) store it. A read afterward asks R replicas and keeps the newer version it hears.
----------------------------- MODULE PriceQuorum ----------------------------
EXTENDS Integers, FiniteSets
CONSTANTS Replica, W, R \* write-set size and read-set size
VARIABLES stored, acked, result \* result: what a read returned (0 = none yet)
vars == <<stored, acked, result>>
WriteSets == {Q \in SUBSET Replica : Cardinality(Q) = W}
ReadSets == {Q \in SUBSET Replica : Cardinality(Q) = R}
PInit == /\ stored = [n \in Replica |-> 7]
/\ acked = FALSE
/\ result = 0
Store(n) == /\ stored' = [stored EXCEPT ![n] = 8]
/\ UNCHANGED <<acked, result>>
Ack == /\ \E Q \in WriteSets : \A n \in Q : stored[n] = 8
/\ acked' = TRUE
/\ UNCHANGED <<stored, result>>
\* A read after the ack hears from one read set and keeps the newer version.
Read == /\ acked
/\ result = 0
/\ \E Q \in ReadSets :
result' = IF \E n \in Q : stored[n] = 8 THEN 8 ELSE 7
/\ UNCHANGED <<stored, acked>>
PNext == Ack \/ Read \/ \E n \in Replica : Store(n)
SeesAckedWrite == result \in {0, 8}
=============================================================================
INIT PInit
NEXT PNext
CONSTANTS Replica = {"A", "B", "C"}
W = 2
R = 2
INVARIANT SeesAckedWrite
CHECK_DEADLOCK FALSE
With R = 2: no error, 16 distinct states. With R = 1: SeesAckedWrite is violated in a 5-state trace.
TLC's trace at R = 1 stops with a read of B alone. At R = 2, each possible pair of replies includes v8.
In that trace (the diagram) version 8 reaches C and A, the write is acknowledged, and a read asks only B. Nothing has failed. No machine lost data or broke a local rule, and the client still reads the old price. With R = 2, any read set contains A or C, as the last column shows.
Find the worst-case intersection
Predict: N = 5, R = 2, W = 3. Can a read miss every written replica?
Yes. Write to {A, B, C}; read from {D, E}. Their intersection is empty, and TLC confirms such a pair exists. With R = 3, it confirms that every pair of size-3 sets intersects.
The model is deliberately easy: one writer, one write, and a version order given in advance. Overlap gives you a place to find evidence. It doesn't say how to interpret it. With two concurrent writers, "the newer version" needs a definition, and overlap alone doesn't supply one. Likewise, if a replica acknowledges before storing durably, its restart can erase what the overlap was counting on.
From stored prices to votes
Replace the pieces. The write set becomes a majority of acceptors that voted for an outcome. The read becomes a new leader asking a majority what they've voted for, because it suspects that the old leader died. Every majority it asks contains someone who voted, so if an outcome was already decided, the new leader can find out. That one sentence is the core of lesson 22: the leader can take over without the old leader's memory, because the memory was in the overlap.
Predict: R + W > N, so is every read correct, whatever else happens?
No. You still need to know which versions replies represent, how a read chooses, how concurrent writes are ordered, when a write completes, and what survives a crash. Intersection is a place to look; it isn't an answer.
Paxos Commit keeps the decision alive when the transaction manager doesn't.
In two-phase commit, one process holds the decision. If it stops, prepared RMs wait forever. Lecture 7 opens with that problem, shows why the obvious fix is wrong, and then reads the spec of Paxos Commit: a real algorithm by Jim Gray and Leslie Lamport, and a tour of the last TLA+ constructs you need.
Two-phase commit with a crashed TM. Prepared RMs may not decide alone, so they wait forever.
This is a TLC trace of TwoPhase plus one TMCrash action, with two RMs. It takes 4 states to reach the bottom of the diagram. There, r1 and r2 are prepared, and the only actions that move a prepared RM need a Commit or Abort message that only the TM can send. Checking the property "once blocked, no step changes anything" gives no error over 112 distinct states. TCConsistent holds as well: nothing is wrong except that nothing happens.
While you watch
Lamport states plainly that the lecture is about TLA+ and that the paper explains the algorithm, so he goes through the operators and doesn't explain the protocol. This lesson does the reverse order: first the idea, with diagrams, then the operators. Follow the spec alongside him at the Phase2a definition. Pause at the model values and decide whether Acceptor can be a symmetry set before he answers. lesson 23 covers one Paxos instance by itself.
The fix that fails
The textbook answer is a backup TM that takes over when the primary fails. It's simple to build and to test. Then one day the primary decides to commit and pauses. The backup concludes the primary has died.
TLC's 9-state trace with one takeover. Backup doesn't know the TM has already decided, so both decisions go out. Steps not shown: the TM reading the two Prepared messages.
This run came from TwoPhase plus a BackupAbort action, with two RMs: TLC reports a TCConsistent violation in a 9-state trace, drawn above. The backup can't distinguish slow from dead, and both TMs' messages are valid. Testing won't easily catch this, because it needs a rare pause. Finding it needs a spec.
The idea: several acceptors remember each RM's vote
Paxos Commit replaces the TM's one memory with a set of acceptors, with the overlap property from lesson 21. It runs one separate decision, called an instance, per RM, whose outcome is either "prepared" or "aborted". The field ins in each message says which RM's instance it belongs to.
A leader is any process that believes it's in charge. The spec doesn't care who it is, or how many there are; several may act at once. Here's the normal case, for one RM's instance.
Normal case for r1's instance. *Commit requires every RM's instance to have chosen prepared; r2's instance runs the same way.
r1 votes by sending a phase2a message in ballot 0, the ballot number reserved for the RM itself. Each acceptor records its vote and announces it in phase2b. Once a majority voted the same value in the same ballot, that value is chosen. a3 was slow and it didn't matter. When every instance has chosen "prepared", a leader may send Commit; if any chose "aborted", it may send Abort. No single process has to survive.
What a new ballot does
If an RM's vote seems stuck, a leader starts a higher ballot (Phase1a). An acceptor receiving that message promises to ignore lower ballots by raising mbal, and reports its last vote (Phase1b). Having heard from a majority, the leader sends one value (Phase2a):
If anyone reported a vote, it sends the value from the highest ballot reported.
If nobody did, it sends "aborted". An RM with no recorded vote can't be assumed prepared.
Left: overlap carries the vote into the new ballot. Right: with the broken Majority, a vote in {a3} can't be seen from {a1, a2}.
On the left, a1 and a2 voted "prepared" in ballot 0, so it's chosen. A leader in ballot 1 hears from a2 and a3. The overlap is a2, whose report forces the leader to send "prepared" too. So the old result survives without the old leader. On the right, no such acceptor exists, and the leader hears nothing: this is the experiment at the end of this lesson.
The spec's new constructs
Maximum(S) == IF S = {} THEN -1
ELSE CHOOSE n \in S : \A m \in S : n >= m
CHOOSE.CHOOSE v \in S : P is some value v in S satisfying P. If there are several, TLA+ doesn't say which; if none, its value is unspecified and TLC reports an error. It isn't random. Like any expression, it equals itself, so TLC gets the same answer every time. Hence x' \in 1..99 allows 99 next values and x' = CHOOSE i \in 1..99 : TRUE allows just one. Use it when exactly one v qualifies, as in Maximum, or when the larger expression doesn't depend on which you get. Here's the second kind:
Phase2a(bal, r) ==
/\ ~\E m \in msgs : /\ m.type = "phase2a"
/\ m.bal = bal
/\ m.ins = r
/\ \E MS \in Majority :
LET mset == {m \in msgs : /\ m.type = "phase1b"
/\ m.ins = r
/\ m.mbal = bal
/\ m.acc \in MS}
maxbal == Maximum({m.bal : m \in mset})
val == IF maxbal = -1
THEN "aborted"
ELSE (CHOOSE m \in mset : m.bal = maxbal).val
IN /\ \A ac \in MS : \E m \in mset : m.acc = ac
/\ Send([type |-> "phase2a", ins |-> r, bal |-> bal, val |-> val])
/\ UNCHANGED <<rmState, aState>>
LET-IN makes definitions local to one expression. mset filters and {m.bal : m \in mset} maps, the two constructors from lesson 21. Several messages in mset may have the top ballot, so CHOOSE may have several choices, but the lecture points out that in any reachable state they all have the same val. Lamport calls this the most subtle part of the algorithm.
Nested EXCEPT. The acceptor state is aState[r][a], a record per acceptor per instance, with fields mbal, bal, and val.
Read it as three programming assignments to aState[m.ins][acc]'s fields. The first form abbreviates nested EXCEPTs, one per level. Lamport's advice is to remember the idiom rather than decode it.
Show the complete module that was checked
----------------------------- MODULE PaxosCommit ----------------------------
EXTENDS Integers
Maximum(S) == IF S = {} THEN -1
ELSE CHOOSE n \in S : \A m \in S : n >= m
CONSTANTS RM, \* The set of resource managers
Acceptor, \* The set of acceptors
Majority, \* The sets of acceptors that count as a majority
Ballot \* The set of ballot numbers
ASSUME /\ Ballot \subseteq Nat
/\ 0 \in Ballot
/\ Majority \subseteq SUBSET Acceptor
/\ \A MS1, MS2 \in Majority : MS1 \cap MS2 # {}
Messages ==
[type : {"phase1a"}, ins : RM, bal : Ballot \ {0}]
\cup
[type : {"phase1b"}, ins : RM, mbal : Ballot, bal : Ballot \cup {-1},
val : {"prepared", "aborted", "none"}, acc : Acceptor]
\cup
[type : {"phase2a"}, ins : RM, bal : Ballot, val : {"prepared", "aborted"}]
\cup
[type : {"phase2b"}, acc : Acceptor, ins : RM, bal : Ballot,
val : {"prepared", "aborted"}]
\cup
[type : {"Commit", "Abort"}]
-----------------------------------------------------------------------------
VARIABLES rmState, aState, msgs
PCTypeOK ==
/\ rmState \in [RM -> {"working", "prepared", "committed", "aborted"}]
/\ aState \in [RM -> [Acceptor -> [mbal : Ballot,
bal : Ballot \cup {-1},
val : {"prepared", "aborted", "none"}]]]
/\ msgs \subseteq Messages
PCInit ==
/\ rmState = [r \in RM |-> "working"]
/\ aState = [r \in RM |->
[ac \in Acceptor |-> [mbal |-> 0, bal |-> -1, val |-> "none"]]]
/\ msgs = {}
Send(m) == msgs' = msgs \cup {m}
-----------------------------------------------------------------------------
\* Resource manager actions. RMs vote by sending a ballot 0 phase 2a message.
RMPrepare(r) ==
/\ rmState[r] = "working"
/\ rmState' = [rmState EXCEPT ![r] = "prepared"]
/\ Send([type |-> "phase2a", ins |-> r, bal |-> 0, val |-> "prepared"])
/\ UNCHANGED aState
RMChooseToAbort(r) ==
/\ rmState[r] = "working"
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ Send([type |-> "phase2a", ins |-> r, bal |-> 0, val |-> "aborted"])
/\ UNCHANGED aState
RMRcvCommitMsg(r) ==
/\ [type |-> "Commit"] \in msgs
/\ rmState' = [rmState EXCEPT ![r] = "committed"]
/\ UNCHANGED <<aState, msgs>>
RMRcvAbortMsg(r) ==
/\ [type |-> "Abort"] \in msgs
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ UNCHANGED <<aState, msgs>>
-----------------------------------------------------------------------------
\* Leader actions: any process that believes it is the leader may do these.
Phase1a(bal, r) ==
/\ Send([type |-> "phase1a", ins |-> r, bal |-> bal])
/\ UNCHANGED <<rmState, aState>>
Phase2a(bal, r) ==
/\ ~\E m \in msgs : /\ m.type = "phase2a"
/\ m.bal = bal
/\ m.ins = r
/\ \E MS \in Majority :
LET mset == {m \in msgs : /\ m.type = "phase1b"
/\ m.ins = r
/\ m.mbal = bal
/\ m.acc \in MS}
maxbal == Maximum({m.bal : m \in mset})
val == IF maxbal = -1
THEN "aborted"
ELSE (CHOOSE m \in mset : m.bal = maxbal).val
IN /\ \A ac \in MS : \E m \in mset : m.acc = ac
/\ Send([type |-> "phase2a", ins |-> r, bal |-> bal, val |-> val])
/\ UNCHANGED <<rmState, aState>>
PCDecide ==
/\ LET Decided(r, v) ==
\E b \in Ballot, MS \in Majority :
\A ac \in MS : [type |-> "phase2b", ins |-> r,
bal |-> b, val |-> v, acc |-> ac] \in msgs
IN \/ /\ \A r \in RM : Decided(r, "prepared")
/\ Send([type |-> "Commit"])
\/ /\ \E r \in RM : Decided(r, "aborted")
/\ Send([type |-> "Abort"])
/\ UNCHANGED <<rmState, aState>>
-----------------------------------------------------------------------------
\* Acceptor actions.
Phase1b(acc) ==
\E m \in msgs :
/\ m.type = "phase1a"
/\ aState[m.ins][acc].mbal < m.bal
/\ aState' = [aState EXCEPT ![m.ins][acc].mbal = m.bal]
/\ Send([type |-> "phase1b", ins |-> m.ins, mbal |-> m.bal,
bal |-> aState[m.ins][acc].bal, val |-> aState[m.ins][acc].val,
acc |-> acc])
/\ UNCHANGED rmState
Phase2b(acc) ==
/\ \E m \in msgs :
/\ m.type = "phase2a"
/\ aState[m.ins][acc].mbal <= m.bal
/\ aState' = [aState EXCEPT ![m.ins][acc].mbal = m.bal,
![m.ins][acc].bal = m.bal,
![m.ins][acc].val = m.val]
/\ Send([type |-> "phase2b", ins |-> m.ins, bal |-> m.bal,
val |-> m.val, acc |-> acc])
/\ UNCHANGED rmState
-----------------------------------------------------------------------------
PCNext ==
\/ \E r \in RM : \/ RMPrepare(r) \/ RMChooseToAbort(r)
\/ RMRcvCommitMsg(r) \/ RMRcvAbortMsg(r)
\/ \E bal \in Ballot \ {0}, r \in RM : Phase1a(bal, r) \/ Phase2a(bal, r)
\/ PCDecide
\/ \E acc \in Acceptor : Phase1b(acc) \/ Phase2b(acc)
-----------------------------------------------------------------------------
TC == INSTANCE TCommit
TCConsistent == TC!TCConsistent
=============================================================================
This was adapted from the official example to the lecture's names and its Maximum. The lecture imports with INSTANCE; here TC == INSTANCE TCommit keeps TCommit's Decide from clashing, so the leader's action is called PCDecide.
Check a small model
The lecture's model is the smallest that could reveal a non-trivial error:
Can Acceptor be a symmetry set when a1, a2, a3 appear in the value of Majority? Yes, because that expression is symmetric: swap a1 and a3, and you get the same set. This is the rule promised in lesson 18: elements of a symmetry set may be used in another constant's value only if that expression is symmetric in them, and those elements, or any constant assigned them, must not appear in a CHOOSE. The CHOOSEs here range over messages and numbers, not over RM or Acceptor.
Result: no error, 119,992 distinct states (1,545,109 generated), with PCTypeOK and TCConsistent invariant, in line with the lecture's figure. Time and space grow exponentially with model size. Lamport says one more ballot makes it vastly bigger; that model wasn't re-run here.
What good is such a small model?
Break the overlap: delete a2 from the last element, so Majority is { {a1, a2}, {a1, a3}, {a3} }. It's no longer symmetric, so Acceptor stops being a symmetry set. Comment out the conjunct in ASSUME, since TLC would otherwise reject it. TLC reports TCConsistent violated, with a 14-state trace, as in the lecture.
States
TLC's actions
What happened
2–3
RMPrepare(r1), RMPrepare(r2)
Both RMs vote prepared in ballot 0
4–6
Phase1a(1,r1), Phase1b(a1), Phase1b(a2)
A leader polls {a1, a2} for r1; no one has voted
7
Phase2a(1,r1)
So it sends "aborted" in ballot 1
8–9
Phase2b(a3) twice
a3 votes r1 prepared (ballot 0), then aborted (ballot 1)
10–11
PCDecide, RMRcvAbortMsg(r1)
{a3} "chose" aborted for r1: Abort sent, r1 aborts
12–14
Phase2b(a3), PCDecide, RMRcvCommitMsg(r2)
a3's vote for r2 means both instances "chose" prepared: Commit sent, r2 commits
Every phase2b message stays in msgs, so a3's old vote for r1 still counts. A leader that consulted {a1, a2} couldn't see a3, which is the right panel of the overlap diagram. Even a very small model catches a real error in a real algorithm.
Predict: does Paxos Commit still block if a majority of acceptors stops?
Yes. No new ballot can complete, so an undecided instance stays undecided. What improves is the failure it tolerates: any process can act as leader, and any single acceptor can fail, with three acceptors. Safety never relied on anyone being up; the checked model allows steps simply never to happen.
Read the algorithm: Consensus on Transaction Commit, Jim Gray and Leslie Lamport, ACM TODS 31(1), 2006, linked from the lecture page. The official module is in the examples repository.
Lecture 7: Paxos commit
Inside Paxos Commit is one small agreement problem.
You've seen Paxos Commit run one decision per RM. Each of those decisions is an instance of consensus: a group chooses one value, and two different values are never chosen. This lesson separates consensus from commit, then breaks its key rule so you can see why the rule exists.
Paxos Commit is one consensus per RM plus a rule on the results.
Read the diagram from the left. Each RM has its own instance with its own acceptor votes. Commit is a small rule on top of the results: all "prepared" gives Commit, and any "aborted" gives Abort. Everything difficult is in the instances, so you can study one of them alone.
While you watch
Lecture 7 doesn't teach Paxos as such; Lamport leaves it to the paper. Go back to his remark that the CHOOSE in Phase2a can have several choices that all have the same m.val, and try to explain it. This lesson's experiment gives you the means to. Everything about one instance and Raft here is added to the lecture.
One instance
The module below cuts PaxosCommit down: no RMs and no ins field. Values are just "X" and "Y", and with no reports a leader may propose either. Ballots start at 1 since no RM owns ballot 0. Its contract is:
Chosen(v) == \E b \in Ballot, MS \in Majority :
\A a \in MS : [type |-> "2b", bal |-> b, val |-> v, acc |-> a] \in msgs
Agreement == \A v, w \in Value : Chosen(v) /\ Chosen(w) => v = w
Chosen is derived from the votes in msgs, so no process has to know it. A value can be chosen while everyone is still unaware. A model where nothing is ever chosen also satisfies Agreement, so progress needs separate assumptions.
Show the complete module
----------------------------- MODULE OneDecree ------------------------------
\* One Paxos consensus instance, cut out of PaxosCommit: the ins field and the
\* RMs are gone, and with no earlier evidence a leader may propose any value.
EXTENDS Integers
Maximum(S) == IF S = {} THEN -1
ELSE CHOOSE n \in S : \A m \in S : n >= m
CONSTANTS Value, Acceptor, Majority, Ballot
ASSUME /\ Ballot \subseteq Nat \ {0}
/\ \A MS1, MS2 \in Majority : MS1 \cap MS2 # {}
VARIABLES aState, msgs
vars == <<aState, msgs>>
Init == /\ aState = [a \in Acceptor |-> [mbal |-> 0, bal |-> -1, val |-> "none"]]
/\ msgs = {}
Send(m) == msgs' = msgs \cup {m}
Phase1a(b) == /\ Send([type |-> "1a", bal |-> b])
/\ UNCHANGED aState
Phase1b(a) ==
\E m \in msgs :
/\ m.type = "1a"
/\ aState[a].mbal < m.bal
/\ aState' = [aState EXCEPT ![a].mbal = m.bal]
/\ Send([type |-> "1b", mbal |-> m.bal, bal |-> aState[a].bal,
val |-> aState[a].val, acc |-> a])
Reports(b, MS) == {m \in msgs : /\ m.type = "1b" /\ m.mbal = b /\ m.acc \in MS}
FromAll(b, MS) == \A a \in MS : \E m \in Reports(b, MS) : m.acc = a
NotUsed(b) == ~\E m \in msgs : m.type = "2a" /\ m.bal = b
\* The rule that matters: repeat the value of the highest ballot reported.
Phase2a(b) ==
/\ NotUsed(b)
/\ \E MS \in Majority, v \in Value :
LET maxbal == Maximum({m.bal : m \in Reports(b, MS)})
IN /\ FromAll(b, MS)
/\ \/ maxbal = -1
\/ \E m \in Reports(b, MS) : m.bal = maxbal /\ m.val = v
/\ Send([type |-> "2a", bal |-> b, val |-> v])
/\ UNCHANGED aState
\* The broken version: same quorum, but the reports are ignored.
Phase2aForget(b) ==
/\ NotUsed(b)
/\ \E MS \in Majority, v \in Value :
/\ FromAll(b, MS)
/\ Send([type |-> "2a", bal |-> b, val |-> v])
/\ UNCHANGED aState
Phase2b(a) ==
\E m \in msgs :
/\ m.type = "2a"
/\ aState[a].mbal <= m.bal
/\ aState' = [aState EXCEPT ![a].mbal = m.bal,
![a].bal = m.bal,
![a].val = m.val]
/\ Send([type |-> "2b", bal |-> m.bal, val |-> m.val, acc |-> a])
Next == \/ \E b \in Ballot : Phase1a(b) \/ Phase2a(b)
\/ \E a \in Acceptor : Phase1b(a) \/ Phase2b(a)
NextForget == \/ \E b \in Ballot : Phase1a(b) \/ Phase2aForget(b)
\/ \E a \in Acceptor : Phase1b(a) \/ Phase2b(a)
Chosen(v) == \E b \in Ballot, MS \in Majority :
\A a \in MS : [type |-> "2b", bal |-> b, val |-> v, acc |-> a] \in msgs
Agreement == \A v, w \in Value : Chosen(v) /\ Chosen(w) => v = w
OneValuePerBallot == \A m1, m2 \in msgs :
(m1.type = "2b" /\ m2.type = "2b" /\ m1.bal = m2.bal) => m1.val = m2.val
=============================================================================
With three acceptors, two values, and ballots {1, 2}, TLC reports no error, 3921 distinct states. That run also checks OneValuePerBallot: all votes in one ballot have the same value. The NotUsed guard allows just one 2a message per ballot, and acceptors repeat only what it says. That's why the CHOOSE Lamport points at can't matter. Messages with the same highest ballot agree.
Worked failure: a new ballot forgets the old vote
Now replace Phase2a with Phase2aForget, which still needs reports from a majority but ignores what they say:
Phase2aForget(b) ==
/\ NotUsed(b)
/\ \E MS \in Majority, v \in Value :
/\ FromAll(b, MS)
/\ Send([type |-> "2a", bal |-> b, val |-> v])
/\ UNCHANGED aState
TLC reports Agreement violated in a 13-state trace. These are its last few states, showing each acceptor's last vote.
TLC's trace with the broken rule. X @1 means "voted X in ballot 1". State 10 sends ballot 2's Y.
By state 12, A and B voted Y in ballot 2, so Y is chosen. In the last column, C votes X in ballot 1: B's X vote in ballot 1 is still in msgs, so {B, C} also chose X. In state 9 B reported "I voted X in ballot 1" to the ballot 2 leader. That report was the warning, and the broken rule ignored it. The real rule would have made ballot 2 propose X, and then both ballots agree.
Quorum overlap was present the whole time: {A, B} and {B, C} share B. So overlap alone doesn't save you. It creates a place where evidence can pass between ballots, and the protocol must also obey it. This is the point lesson 21 ended on: a place to look isn't yet an answer.
Predict: if B restarts and forgets its promise and last vote, is overlap still enough?
No. B would report no vote, and the leader of ballot 2 may then propose Y, the same failure by a different path. The spec has no action that loses aState, which is an assumption: those fields must survive a restart. A recovery action in your model must keep exactly what this argument relies on.
From one value to a log
Paxos Commit runs a fixed set of instances, one per RM. A replicated service needs an ordered list of operations, so it runs one consensus decision per log position. Replicas apply chosen operations in order.
A sketch, not a checked model. Each column is its own consensus decision.
In the diagram, a column is one decision. S3 lags behind but it holds no conflicting value in any filled column. Agreement per position is what a replicated log needs, and new questions come with it: who proposes, what happens to entries no majority has, and what can be discarded.
Raft is a widely used protocol for replicated logs. It separates leader election, log replication, and safety. A term plays a role like a ballot; it isn't a wall-clock time. To study it, follow one committed entry across a leader crash and an election, and ask what prevents an elected leader from lacking that entry. "A majority elected it" is not the whole answer: Raft restricts which logs can win. Use its published spec rather than reconstructing it from a diagram.
Four problems on quorums, consensus and Paxos Commit. You'll use the set operators and the overlap property from lecture 7 to find a stale read and to choose where cluster members live. Then you'll break a leader election by losing one field in a restart, and compare Paxos Commit with the two-phase commit booking from Problem set 6. Every problem ends in a TLC run.
Each module below is complete and was checked with TLC exactly as shown. Type it in yourself or copy it into a file of the same name. Counts like "distinct states" only match if your module is identical, so use those numbers to test your copy.
A shopping-cart service keeps each cart in a key-value store built on the design of Amazon's Dynamo paper. Every key lives on N replicas. A write counts as successful once W replicas have stored it, and a read asks R replicas and returns the newest version it hears. The team runs N = 5 with W = 3. To cut read latency, someone proposes R = 2: "three of the five replicas have every acknowledged write, so asking two will nearly always find one." Customers then report carts that lose the item they just added.
The module models one key. Every replica starts at version 1, a client writes version 2, and once the write is acknowledged a single read happens. Maximum is the definition from Paxos Commit.
---------------------------- MODULE PSl7_Quorum -----------------------------
\* One key of a Dynamo-style store with replication factor N = |Replica|.
\* Every replica holds version 1. A client writes version 2: the coordinator
\* stores it replica by replica and reports success once W replicas have it.
\* A later read asks R replicas and returns the highest version it hears.
EXTENDS Integers, FiniteSets
CONSTANTS Replica, W, R
VARIABLES version, \* version[n]: the version replica n stores
acked, \* the coordinator has told the client "write succeeded"
seen \* what the read returned (0 = no read yet)
vars == <<version, acked, seen>>
Maximum(S) == IF S = {} THEN -1
ELSE CHOOSE n \in S : \A m \in S : n >= m
WriteSets == {Q \in SUBSET Replica : Cardinality(Q) = W}
ReadSets == {Q \in SUBSET Replica : Cardinality(Q) = R}
Init == /\ version = [n \in Replica |-> 1]
/\ acked = FALSE
/\ seen = 0
Store(n) == /\ version[n] = 1
/\ version' = [version EXCEPT ![n] = 2]
/\ UNCHANGED <<acked, seen>>
Ack == /\ ~acked
/\ \E Q \in WriteSets : \A n \in Q : version[n] = 2
/\ acked' = TRUE
/\ UNCHANGED <<version, seen>>
Read == /\ acked
/\ seen = 0
/\ \E Q \in ReadSets : seen' = Maximum({version[n] : n \in Q})
/\ UNCHANGED <<version, acked>>
Next == Ack \/ Read \/ \E n \in Replica : Store(n)
ReadsLatest == seen \in {0, 2}
Overlap == \A Wq \in WriteSets, Rq \in ReadSets : Wq \cap Rq # {}
=============================================================================
INIT Init
NEXT Next
CONSTANTS Replica = {"A", "B", "C", "D", "E"}
W = 3
R = 2
INVARIANT ReadsLatest
CHECK_DEADLOCK FALSE
Before running anything, use the R + W > N rule to say which values of R from 1 to 5 make every read set meet every write set.
Run TLC with R = 1, R = 2 and R = 3. For each, report whether ReadsLatest holds, and for failures, the length of the trace and which replicas the read asked.
Add the line ASSUME Overlap after the definition of Overlap, and run it with R = 2 and with R = 3. What changes in TLC's output, and why does it appear before any state is explored?
Say in one sentence why Read takes the maximum of the versions it hears instead of the version of whichever replica answers first.
Hint
A read set of size R and a write set of size W must share an element when R + W elements can't fit into N places without repeating one. For task 3, remember that a constant formula doesn't depend on any state.
Solution
1. R + W > N means R + 3 > 5, so R ≥ 3. R = 3, 4 and 5 force overlap; R = 1 and R = 2 don't. With R = 2 the write set {A, C, D} and the read set {B, E} are disjoint.
2. R = 1 and R = 2 both violate ReadsLatest with a 6-state trace. In the R = 2 run, the trace went Store("A"), Store("C"), Store("D"), Ack, Read, ending with seen = 1. The read set must have been {B, E}, the only pair whose maximum is 1 there, as the diagram shows. Your run may store a different three replicas first. R = 3 gives no error, with 64 distinct states. That count is easy to check by hand: 32 version maps before the ack, then for each of the 16 maps with at least three 2s, one state before the read and one after it, which returns 2.
The R = 2 read in TLC's trace asks only B and E, the two replicas the write never reached. Any read of three must include A, C or D.
3. With R = 2 TLC stops at once with "Assumption … is false" and explores no states. With R = 3 the assumption holds, and the run is the same as before. Overlap mentions no variable, so it is a constant formula, and TLC evaluates assumptions before it computes the initial states. That's why Paxos Commit puts its Majority condition in an ASSUME: a bad configuration is rejected before any behavior is checked.
4. The overlap only promises that some replica asked has version 2. The read has to recognize that replica among its answers, and taking the highest version is how it does that. The quiz shows the same read with no such rule failing at R = 3. Real stores also need versions that order concurrent writes, which this one-writer model avoids.
The team's "nearly always" was correct as a probability and wrong as a guarantee. TLC doesn't weigh how likely a behavior is: it reports the one bad read that is allowed.
Your company's configuration store is a five-member cluster that uses Raft, like etcd. A write needs a quorum of three members. The cluster must keep accepting writes when a whole data centre (DC) goes dark. The infrastructure team has three proposals:
Two DCs, three members in one and two in the other.
Three DCs, with two, two and one members.
Save a machine: four members in two DCs, two in each, with a quorum of just two "so either DC can carry on alone."
In the module below DCs is a set of sets: each element is the set of members in one DC. The single variable lost is the DC that has gone dark, and Init lets TLC try every choice. Because Next changes nothing, each state is one "what if". The cfg shows the first proposal.
--------------------------- MODULE PSl7_Placement ---------------------------
\* Where to put the members of a quorum-based cluster. DCs is a set of sets:
\* each element is the set of nodes in one data centre. The variable lost is
\* the one data centre that has gone dark; Init lets TLC try each in turn.
EXTENDS Integers, FiniteSets
CONSTANTS Node, DCs, QSize
ASSUME \A d1, d2 \in DCs : d1 # d2 => d1 \cap d2 = {} \* no node in two DCs
ASSUME \A n \in Node : \E d \in DCs : n \in d \* every node placed
VARIABLE lost
Quorum == {Q \in SUBSET Node : Cardinality(Q) >= QSize}
\* The property Paxos and Raft rely on, checked before any state is explored.
QuorumsOverlap == \A Q1, Q2 \in Quorum : Q1 \cap Q2 # {}
ASSUME QuorumsOverlap
Init == lost \in DCs
Next == UNCHANGED lost
\* Some quorum is made only of nodes outside the lost data centre.
QuorumSurvives == \E Q \in Quorum : Q \cap lost = {}
=============================================================================
By hand: how many elements does Quorum have for five members with QSize = 3? Check your count by adding ASSUME Cardinality(Quorum) = n, with your n, at the end of the module: TLC rejects a false assumption before it explores anything.
Run all three proposals (for the third, use four members and QSize = 2, then QSize = 3). For each run, write down what TLC reports and which DC, if any, is fatal to lose.
The third proposal can't be fixed by choosing a quorum size. Explain why in terms of the two properties the module checks.
Find a layout of six members in three DCs, and a QSize, that passes both checks. Run it.
Hint
QuorumSurvives asks for a quorum disjoint from the lost DC. QuorumsOverlap asks every two quorums to share a member. A quorum that fits inside one DC of the 2 + 2 layout satisfies the first and is exactly what breaks the second.
Solution
1. 10 + 5 + 1 = 16. With ASSUME Cardinality(Quorum) = 16 TLC runs as before; with 15 it reports the assumption false.
2. Results of the runs:
Layout
QSize
TLC says
3 + 2
3
QuorumSurvives violated by the initial state lost = {"n1", "n2", "n3"}
2 + 2 + 1
3
No error, 3 distinct states
2 + 2
2
Assumption QuorumsOverlap is false
2 + 2
3
QuorumSurvives violated by lost = {"n1", "n2"}
2 + 2 + 2
4
No error, 3 distinct states (22 quorums)
Losing the large DC of a 3 + 2 layout leaves no quorum. In 2 + 2 + 1 every DC holds at most two members, so any single loss leaves three.
In the 3 + 2 layout, losing the small DC is fine, but losing the large one leaves two members. The diagram shows both.
3. If either DC alone must be able to write, a quorum has to fit inside each DC. But then {n1, n2} and {n3, n4} are both quorums and share nobody: during a network split, each side could elect its own leader, which is the property Paxos and Raft assume can't happen. If quorums must overlap, a quorum needs at least three of the four members, and neither DC has three. With two DCs of equal size you can't have both properties, whatever QSize you choose.
4. Three DCs of two members each with QSize = 4: two quorums of four out of six share at least two members, and losing any DC leaves exactly four. TLC reports no error. Notice that a fourth member and a third DC improve nothing by themselves. What matters is that no single DC holds more than N − QSize members, the number a quorum system can do without.
A team is writing its own Raft-style leader election for a job scheduler. A server that hears nothing from a leader times out, moves to a higher term, votes for itself, and asks the others for votes. A server grants at most one vote per term. A candidate that collects votes from a majority becomes leader of that term. As in From Paxos Commit to Paxos and Raft, a term plays the role of a ballot.
To keep the hot path fast, the implementation writes term to disk but keeps votedFor only in memory. After a deploy, the logs show two servers both acting as leader of term 1, both accepting jobs.
The module records votes as messages in a set that only grows, as in two-phase commit, and keeps the history leaders so that an invariant can talk about every election ever won. Logs are left out, so this checks only the election.
--------------------------- MODULE PSl7_Election ----------------------------
\* Leader election in the style of Raft, with votes as messages. Logs are
\* left out. A server that times out moves to a higher term, votes for
\* itself and asks for votes; it is leader of a term once a majority voted
\* for it in that term. Restart models a crash and reboot.
EXTENDS Integers
CONSTANTS Server, Majority, Term
ASSUME \A MS1, MS2 \in Majority : MS1 \cap MS2 # {}
None == "none"
VARIABLES term, \* term[s]: the highest term s has seen
votedFor, \* votedFor[s]: whom s voted for in term[s], or None
msgs, \* every message ever sent
leaders \* every [srv, term] pair that has won an election
vars == <<term, votedFor, msgs, leaders>>
Init == /\ term = [s \in Server |-> 0]
/\ votedFor = [s \in Server |-> None]
/\ msgs = {}
/\ leaders = {}
Timeout(s, t) ==
/\ t > term[s]
/\ term' = [term EXCEPT ![s] = t]
/\ votedFor' = [votedFor EXCEPT ![s] = s]
/\ msgs' = msgs \cup {[type |-> "request", term |-> t, from |-> s],
[type |-> "vote", term |-> t, from |-> s, to |-> s]}
/\ UNCHANGED leaders
\* s grants its vote for term m.term at most once, unless it forgot.
Grant(s) ==
\E m \in msgs :
/\ m.type = "request"
/\ \/ m.term > term[s]
\/ m.term = term[s] /\ votedFor[s] \in {None, m.from}
/\ term' = [term EXCEPT ![s] = m.term]
/\ votedFor' = [votedFor EXCEPT ![s] = m.from]
/\ msgs' = msgs \cup {[type |-> "vote", term |-> m.term, from |-> s, to |-> m.from]}
/\ UNCHANGED leaders
BecomeLeader(s) ==
/\ \E MS \in Majority :
\A v \in MS : [type |-> "vote", term |-> term[s], from |-> v, to |-> s] \in msgs
/\ leaders' = leaders \cup {[srv |-> s, term |-> term[s]]}
/\ UNCHANGED <<term, votedFor, msgs>>
\* The process restarts. term is on disk; votedFor was kept only in memory.
Restart(s) ==
/\ votedFor' = [votedFor EXCEPT ![s] = None]
/\ UNCHANGED <<term, msgs, leaders>>
Next == \E s \in Server : \/ \E t \in Term : Timeout(s, t)
\/ Grant(s) \/ BecomeLeader(s) \/ Restart(s)
\* Both fields on disk: a restart then changes nothing in this model.
NextDurable == \E s \in Server : \/ \E t \in Term : Timeout(s, t)
\/ Grant(s) \/ BecomeLeader(s)
OneLeaderPerTerm == \A l1, l2 \in leaders : l1.term = l2.term => l1.srv = l2.srv
=============================================================================
INIT Init
NEXT Next
CONSTANTS Server = {"s1", "s2", "s3"}
Majority = {{"s1", "s2"}, {"s1", "s3"}, {"s2", "s3"}}
Term = {1, 2}
INVARIANT OneLeaderPerTerm
CHECK_DEADLOCK FALSE
Without TLC: suppose two different servers won term t. Use the ASSUME to show that some server sent a vote for each of them in term t. What in Grant is supposed to prevent that?
Run TLC with Next. Report the length of the trace and the server whose two votes in term 1 let both candidates win.
Run it again with NEXT NextDurable, which models keeping both fields on disk. Report TLC's result.
Would keeping votedFor on disk and forgetting term on restart be safe? Decide by reading Grant, then answer the quiz.
Hint
Two winners in term t means two sets of vote messages, each from a set in Majority. Any two such sets share a server. That server sent two votes in term t to different candidates. Look for the step after which Grant's guard no longer remembers the first one.
Solution
1. If s and s' both won term t, there are majorities MS and MS' whose members all sent term-t votes to s and to s' respectively. The ASSUME says MS ∩ MS' contains some server v, so v voted for both. In term term[v] = t, Grant allows a vote only when votedFor[v] is None or the same candidate. So two votes in one term can happen only if votedFor[v] went back to None while term[v] stayed t. Restart does exactly that.
2. TLC reports OneLeaderPerTerm violated after 8 states. The run here printed:
The two majorities, {s1, s2} and {s1, s3}, overlap in s1, as they must. s1 voted in both because the restart erased its first vote.
State 2: <Timeout("s1",1)> \* s1 votes for itself in term 1
State 3: <Restart("s1")> \* votedFor["s1"] = "none", term["s1"] = 1
State 4: <Timeout("s2",1)> \* s2 votes for itself in term 1
State 5: <Grant("s1")> \* s1 votes for s2 in term 1
State 6: <BecomeLeader("s2")> \* leaders = {[term |-> 1, srv |-> "s2"]}
State 7: <Grant("s3")> \* s3 votes for s1 in term 1
State 8: <BecomeLeader("s1")> \* leaders = {[term |-> 1, srv |-> "s1"],
\* [term |-> 1, srv |-> "s2"]}
The server that voted twice is s1. Its first vote was for itself, sent in state 2 and still in msgs. In your run the servers may be named differently, but the shape is the same: the double voter sits in the overlap of the two majorities. The overlap was there all along. What failed is that the server in it forgot what it had said, which is the restart warning from From Paxos Commit to Paxos and Raft in another form.
3. No error: 1444 distinct states. The overlap argument from task 1 now goes through.
4. No. A server whose term drops to 0 treats any term-1 request as newer, and the first disjunct of Grant lets it vote without looking at votedFor. A vote record means something only together with the term it belongs to. That's why Raft requires both to reach stable storage before a server answers a vote request.
Return to the travel booking of Problem set 6: one transaction reserves a flight, a hotel room and a rental car, each held by its own resource manager (RM), coordinated with two-phase commit. Last month the coordinator's machine died after all three RMs had prepared. Each RM held its reservation and waited. Nobody could release the seat without risking a car booked for a trip with no flight. An engineer proposes Paxos Commit with three acceptors. Your job is to state precisely which failures each protocol survives, with a TLC run for each claim.
The first module is TwoPhase with RM = {flight, hotel, car} plus a crash: after Crash the TM never takes another step.
-------------------------- MODULE PSl7_TwoPCBooking -------------------------
\* Two-phase commit for the booking, plus a coordinator crash: after Crash
\* the TM takes no step ever again. RMs are unchanged from TwoPhase.
EXTENDS TwoPhase
VARIABLE tmUp
CInit == TPInit /\ tmUp = TRUE
Crash == /\ tmUp
/\ tmUp' = FALSE
/\ UNCHANGED vars
CNext == \/ Crash
\/ /\ tmUp
/\ \/ TMCommit \/ TMAbort
\/ \E r \in RM : TMRcvPrepared(r)
/\ UNCHANGED tmUp
\/ /\ \E r \in RM : \/ RMPrepare(r) \/ RMChooseToAbort(r)
\/ RMRcvCommitMsg(r) \/ RMRcvAbortMsg(r)
/\ UNCHANGED tmUp
NeverDecided == [type |-> "Commit"] \notin msgs /\ [type |-> "Abort"] \notin msgs
\* Everyone has voted yes and nobody can ever learn the outcome.
InDoubt == ~tmUp /\ NeverDecided /\ \A r \in RM : rmState[r] = "prepared"
NotInDoubt == ~InDoubt
=============================================================================
The second module extends PaxosCommit, unchanged from the lecture. Only acceptors in Up take steps. Both claims at the bottom should fail when the protocol can still make progress: a counterexample to NeverAllCommitted is a run that commits the trip.
------------------------- MODULE PSl7_PaxosBooking --------------------------
\* Paxos Commit for the booking, with some acceptors crashed for good.
\* Only acceptors in Up ever take a step; the others stay silent forever.
\* Leader actions need no "up" flag: any live process may act as leader.
EXTENDS PaxosCommit
CONSTANT Up
ASSUME Up \subseteq Acceptor
UpNext ==
\/ \E r \in RM : \/ RMPrepare(r) \/ RMChooseToAbort(r)
\/ RMRcvCommitMsg(r) \/ RMRcvAbortMsg(r)
\/ \E bal \in Ballot \ {0}, r \in RM : Phase1a(bal, r) \/ Phase2a(bal, r)
\/ PCDecide
\/ \E acc \in Up : Phase1b(acc) \/ Phase2b(acc)
\* Claims that FAIL exactly when the protocol can still make progress:
NeverAllCommitted == \E r \in RM : rmState[r] # "committed"
NeverDecided == [type |-> "Commit"] \notin msgs /\ [type |-> "Abort"] \notin msgs
=============================================================================
Run PSl7_TwoPCBooking. Using the guards of TwoPhase, explain why no step can change rmState once InDoubt holds.
Run PSl7_PaxosBooking as shown, with a3 crashed. Does the trip commit? Which acceptors' phase 2b messages does PCDecide rely on?
Now crash two acceptors: Up = {"a1"}, with INVARIANT NeverDecided instead of NeverAllCommitted. What does TLC report, and what does it mean?
Run Paxos Commit with a single acceptor: Acceptor = {"tm"}, Majority = {{"tm"}}, and Up = {}, checking NeverDecided. Compare it with task 1.
Fill in the table: for each failure, does two-phase commit, and does Paxos Commit with three acceptors, still reach a decision? The failures are: an RM crashes before voting, the TM crashes before deciding, one acceptor crashes, two acceptors crash.
Hint
For task 1, list every action and the first conjunct that is false in the InDoubt state. For task 2, Decided(r, v) in PCDecide needs phase 2b messages from every acceptor of one set in Majority, and only one of those sets avoids a3.
Solution
1. TLC reports NotInDoubt violated after 5 states: the TM crashes, then flight, hotel and car prepare (your trace may crash the TM later). In that state the TM actions are disabled by tmUp = FALSE. RMPrepare and RMChooseToAbort need "working". RMRcvCommitMsg and RMRcvAbortMsg need a decision message, and only the TM sends those. Crash isn't enabled either, and it never touches rmState anyway. All three reservations stay held forever.
A decision needs a majority of the vote-holders alive. In two-phase commit that majority is one process, the TM.
2. Yes. TLC reports NeverAllCommitted violated with a 14-state trace: the three RMPrepare steps, three Phase2b("a1") steps, three Phase2b("a2") steps, PCDecide, and three RMRcvCommitMsg steps. PCDecide uses the majority {a1, a2} for all three instances. a3 never did anything, and nobody had to notice that it was gone. (Even this run explores more than 170,000 distinct states before it stops, which is why the lecture's model has two RMs.)
3. No error, 3375 distinct states: with a1 alone, no Commit or Abort is ever sent. No majority can form, so no instance can choose a value, and leaders' ballots can't complete either. Paxos Commit blocks too, but only when a majority of acceptors is gone.
4. No error, 216 distinct states: nothing is ever decided. A single acceptor is a single memory, which is what the TM was in two-phase commit. If it's down, every prepared RM waits, exactly as in task 1. Paxos Commit with three acceptors spreads that memory over three processes and needs any two of them.
5.
Failure
Two-phase commit
Paxos Commit, 3 acceptors
An RM crashes before voting
Decides: TMAbort is always enabled while tmState = "init"
Decides: a leader runs ballot 1 for that RM's instance, hears no vote, and proposes "aborted"
TM crashes before deciding
Blocks (task 1)
There is no single TM: any process may run Phase1a, Phase2a and PCDecide
One acceptor crashes
(no acceptors)
Decides (task 2)
Two acceptors crash
(no acceptors)
Blocks (task 3)
Both protocols keep TCConsistent in every case, because no step depends on anyone being up. What changes is who you need alive to finish. The price is more messages and more state. In general, with 2F + 1 acceptors the live ones still contain a majority after F crashes, which is the numeric question above.
Lecture 8: Implementation
A whole specification can be one formula.
So far you have handed TLC two formulas: an initial one and a next-state one, as you did for TwoPhase in lesson 18. A single formula can say both, if it is true or false of a whole behavior. To write it you first sort expressions by how much of a behavior they need, then add one operator, always.
Each kind contains the one inside it. The further out you go, the more of the behavior you must see to get a value.
Implication, briefly
Everything in this lesson and the next is stated with =>, read "implies." P => Q means: if P is true then Q is true, and otherwise we know nothing. Mathematically, "we know nothing" is the value TRUE, so it equals IF P THEN Q ELSE TRUE.
P
Q
P => Q
~Q => ~P
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
FALSE
FALSE
FALSE
TRUE
TRUE
TRUE
FALSE
FALSE
TRUE
TRUE
The last two columns match, so P => Q equals ~Q => ~P. "If it's raining the ground is wet" therefore means the same as "if the ground is not wet it's not raining." That sounds wrong because in speech if suggests a cause. In math, implication asserts only that two truths go together.
Four kinds of expression
Here an expression is complete: after expanding definitions it contains only built-in operators, numbers and strings, declared constants and variables, and identifiers bound inside it. \E v \in Nat : x' = x + v is complete. Its part x' = x + v is not, because v is bound outside that part. A formula is a Boolean-valued expression. The figure sorts expressions from the inside out.
Constant. No declared variables, no ', no UNCHANGED. An ASSUME must be a constant formula.
State. May also contain declared variables, so it has a value on a state. If a state gives v the set Nat and w the value -42, then v \cup {w} has the value Nat \cup {-42} there.
Action. May also contain ' and UNCHANGED, so it has a value on a step. If s gives p the value 42 and t gives q the value 24, then p - q' has the value 18 on the step from s to t. An action formula is simply called an action.
Temporal. New here. It has a value on a behavior. TLA+ has only Boolean ones.
Each level is a special case of the next. A state expression is an action expression whose value depends only on the first state of the step. You may also prime any state expression, not just a variable: e' on a step is the value of e in the second state. So UNCHANGED <<x, y, z>> is <<x, y, z>>' = <<x, y, z>>, which is (x' = x) /\ (y' = y) /\ (z' = z).
From two formulas to one
TPSpec should be true on a behavior exactly when TPInit holds on the first state and TPNext holds on every step. The figure shows both duties on a real TLC trace. The first duty needs nothing new, because a state formula counts as a temporal formula that is true on a behavior when it is true on the first state. The second needs the always operator, typed []. []TPNext is true on a behavior when TPNext is true on every step.
A real TwoPhase behavior from TLC with RM = {r1, r2} (w = working, p = prepared, c = committed). TPInit looks only at s1. Each TPNext cell judges the step that arrives in that column.
That suggests TPSpec == TPInit /\ []TPNext. It is almost right. The definition at the end of module TwoPhase is:
Applied to a state formula, always needs no brackets or subscript: []TPTypeOK means TPTypeOK holds on every state, because its value on each step depends only on that step's first state.
The subscript allows stuttering
[TPNext]_vars abbreviates TPNext \/ UNCHANGED vars, where vars is the tuple of the spec's variables. A step that leaves all of them unchanged is a stuttering step. So the formula says every step is a TPNext step or changes nothing. In the figure, the two stutter columns are allowed and the red one is not.
Stuttering steps repeat the state and are allowed. The last step is not stuttering and is not a TPNext step: tmState changed but no Commit or Abort message was sent, so the formula is false on this behavior.
Why a spec should allow steps that do nothing is the subject of lesson 26. For now, take the two facts it implies. A formula of this form can never require anything to happen, and it can never be violated by a pause.
Predict: TPSpec has variables rmState, tmState, tmPrepared, msgs. Is a step that changes only tmPrepared always allowed?
No. It is not stuttering, because tmPrepared changed. It is allowed only if it is a TPNext step, namely TMRcvPrepared(r) for a resource manager whose Prepared message is in msgs while tmState is "init".
Stuttering is not deadlock
A deadlock report from TLC is about Next only: a reachable state with no Next successor. Take SimpleProgram from lesson 5. TLC reports "Deadlock reached" at pc = "done", as the solid arrows in the figure predict. The dashed loops don't count, even though the formula allows them.
Solid arrows are Next steps. Dashed loops are the stuttering steps the formula also allows. TLC's deadlock report counts only solid arrows, so done is reported.
You can silence that report by writing the loop into the next-state formula: Next \/ UNCHANGED vars. TLC then finishes with no error, with 2003 distinct states. Nothing got better, the program still stops there, and a blocked protocol patched this way looks healthy. Likewise, a livelock is endless Next steps with no useful progress, and neither report catches it. Properties that do catch it arrive in lesson 29.
Theorems, and checking them
THEOREM TF asserts that temporal formula TF is true on every possible behavior, not just behaviors of some spec. So implication is the way to talk about a spec:
THEOREM TPSpec => []TPTypeOK
For every behavior, if it satisfies TPSpec, then TPTypeOK holds on all its states. That is what "TPTypeOK is an invariant of TPSpec" means. TLC does not read theorems; they tell your reader what you expect. To check this one, name TPSpec as the behavior spec and []TPTypeOK as a property. In the Toolbox that is the Properties list. With the VS Code extension or the command line, a .cfg file says the same, and a property must be a defined name, so a small wrapper module adds AlwaysTypeOK == []TPTypeOK:
On this configuration TLC finds no error: 1146 states generated, 288 distinct, depth 11. Since this is an invariance property, the INVARIANT line alone would be enough. The two lines are the same assertion written at two levels.
While you watch
Look for how often the lecture reduces a new idea to substitution or to a definition. Pause at the implication example and substitute the other three pairs of values yourself.
Lamport asks you to ignore the subscript for now. This lesson has already said what it abbreviates; the next part of the lecture and the next lesson say why it must be there.
The lecture's phrase is "module-closed" and "module-complete" for what this page just calls a complete expression. The lecture's check uses the Toolbox; the .cfg above is the same check.
The previous lesson made each spec a formula. Two-phase commit was supposed to implement transaction commit, and now that claim has a one-line statement: every behavior satisfying TPSpec also satisfies TCSpec. The surprise is what must be true of states and steps for that line to make sense.
One TwoPhase behavior read through rmState alone. Outlined cells are TCNext steps. The others leave rmState alone, so they are stuttering steps of TCSpec, even though TwoPhase is hard at work in them.
The theorem
Module TCommit has one variable, so its spec has a simpler subscript: TCSpec == TCInit /\ [][TCNext]_rmState. At the end of module TwoPhase, INSTANCE imports every definition from TCommit, and a theorem follows:
INSTANCE TCommit
THEOREM TPSpec => TCSpec
Checking it follows the recipe you just learned: behavior spec on the left, property on the right.
TLC finds no error, with 288 distinct states: the same states as before, since only the question changed.
How can that formula even make sense?
TPSpec talks about four variables and TCSpec about one. The theorem looks like apples implying oranges. The answer is a fact held back until now: a state does not assign values only to the variables of your module. It assigns a value to every possible variable, infinitely many of them.
Both formulas talk about the same kind of state. Each one simply says nothing about the variables it doesn't mention.
So one state may have Mozart = <<-37, {14}>> and tmState = "ouch" alongside rmState. TCInit is true on it if rmState maps each element of RM to "working", whatever else is there. A behavior of TCSpec may even have tmPrepared changing wildly from state to state, since TCSpec is silent on it.
This feels odd only if you read a spec as a program. It is a formula. x + y = 7 does not claim there is no variable z. A useful picture: a spec describes a history of the universe in which the system and its environment behave correctly. It mentions the parts it depends on (msgs might stand for a real transport underneath the protocol), and says nothing about the rest.
Why stuttering has to be there
Both formulas now apply to the same behaviors. But how can the implication be true? TMAbort leaves rmState unchanged, while every TCNext step changes it. So a TMAbort step is not a TCNext step.
The subscript from lesson 25 is the answer. TCSpec requires only that every step satisfies TCNext or leaves rmState unchanged, and TMAbort does the second. In the first figure, each stutter cell is exactly that.
Predict: narrow what counts as stuttering, so only a step that leaves all four TwoPhase variables unchanged is excused. Property: [][TCNext]_<<rmState, tmState, tmPrepared, msgs>>. What does TLC find?
An error, immediately. TLC reports the action property violated after two states, with a TMAbort step, as the figure below shows. The property is the formula you would effectively have if specs could not stutter on variables they don't mention.
TLC's counterexample when the only stuttering permitted is that of all four variables. TMAbort is a perfectly good two-phase commit step that TCNext does not contain.
Without stuttering, TPSpec would also forbid the Timbuktu Starbucks customer count from changing except when the protocol took a step. That is one reason all TLA+ specs allow it. The most important reason is the theorem itself: because of stuttering, implementation is simply implication. There is no separate notion of implementing to define.
A check that can fail
A theorem that TLC confirms tells you more if you've seen it fail. In a copy of TwoPhase, delete one line from TMCommit, the conjunct tmPrepared = RM, so the manager can commit without hearing from anyone. Then check PROPERTY TCSpec again with two resource managers.
TLC's counterexample for the bug. The broken step itself is invisible to TCSpec. The violation appears one step later, when rmState moves from working straight to committed.
TLC reports the action property on the [][TCNext]_rmState part of TCSpec as violated, with the three-state trace above. The buggy step changes only tmState and msgs, so TCSpec lets it pass as stuttering. Only when r1 acts on the message does rmState do something no TCNext step allows, because Decide commits only from "prepared". A violation in the high-level view may show up later than its cause.
Termination, and stopping too soon
Return to SimpleProgram: Init /\ [][Next]_<<pc, i>>. Its formula allows stuttering between real steps, and after the last one, forever. That is how TLA+ represents a terminating execution: a behavior ending in infinitely many stuttering steps. The universe keeps going after your system finishes. As a result, all behaviors are infinite, and finite ones never need separate treatment.
Three behaviors that all satisfy Init /\ [][Next]_<<pc, i>>; each cell is pc, i. Termination is an infinite tail of stuttering. So is stopping early, which the formula does not forbid.
Look at the bottom row. It also satisfies the formula: it takes one step, then stutters forever. Everything you've written so far allows the system to stop at any time. These specs say what a system may do, not what it must do. That is not a defect to patch inside the next-state formula. They are very different requirements and should be stated separately, by conjoining a further temporal formula L:
Init /\ [][Next]_vars /\ L
Writing L is the main business of the next lecture, starting at lesson 29. It is the tiny part of a spec. The may part is much larger, usually more important, and already enough for useful specs.
Predict: TLC checks TPSpec => TCSpec and finds no error. Does that show two-phase commit ever commits anything?
No. A behavior that stutters forever from the initial state satisfies both formulas. The theorem says each step TwoPhase takes is one TCommit permits. Nothing here says a step must be taken.
While you watch
Lamport warns that this will feel strange, and compares it to learning the earth is round. Notice exactly which two facts do the work: states assign all variables, and all specs allow stuttering.
Pause where he asks you to add TCSpec as a property in your TwoPhase model, and run it. The bug above is something to try afterwards; it is not in the lecture.
Watch how a single behavior gets redrawn several times. First it has hidden variables, then stuttering steps, and then an infinite tail.
Problem set 8: a spec is a formula, and implementing it is implying it.
Four problems on lecture 8: stuttering, reading formulas that are true or false of whole behaviors, and checking that one spec implements another with PROPERTY. The last problem asks whether the two-phase commit booking from Problem set 6 and Problem set 7 still implements all-or-nothing agreement once operators get a manual override.
As before, every module shown was checked with TLC exactly as printed. When a problem uses TwoPhase, put the TwoPhase and TCommit modules from the lessons in the same folder.
An operations dashboard has a tile showing the current hour. The on-call team's alerting rules ("page only between 8 and 20") were written and reviewed against this tiny spec of the tile:
--------------------------- MODULE PSl8_HourClock ---------------------------
\* The "current hour" tile on an ops dashboard: a 24-hour clock.
EXTENDS Integers
VARIABLE hr
HInit == hr \in 0..23
HNext == hr' = IF hr = 23 THEN 0 ELSE hr + 1
HSpec == HInit /\ [][HNext]_hr
=============================================================================
A redesign shows hours and minutes. The designer asks whether the alert rules must be reviewed again. They don't need to be if the new tile still satisfies the old spec, that is, if Spec => HourSpec. The new module imports the old one with a named INSTANCE, as PaxosCommit did with TCommit. It also includes the daylight-saving jump that product wants next quarter.
--------------------------- MODULE PSl8_Dashboard ---------------------------
\* The redesigned tile shows hours and minutes. Does it still satisfy the
\* hour-clock spec that the alerting rules were written against?
EXTENDS Integers
VARIABLES hr, min
vars == <<hr, min>>
Init == hr \in 0..23 /\ min \in 0..59
Tick == /\ min' = IF min = 59 THEN 0 ELSE min + 1
/\ hr' = IF min = 59 THEN (IF hr = 23 THEN 0 ELSE hr + 1) ELSE hr
\* Daylight saving time starts: the local clock jumps from 01:59 to 03:00.
SpringForward == /\ hr = 1 /\ min = 59
/\ hr' = 3 /\ min' = 0
Spec == Init /\ [][Tick]_vars
DSTSpec == Init /\ [][Tick \/ SpringForward]_vars
H == INSTANCE PSl8_HourClock
HourSpec == H!HSpec
\* The same claim with stuttering allowed only when hr AND min are unchanged.
HourSpecNoStutter == H!HInit /\ [][H!HNext]_vars
=============================================================================
SPECIFICATION Spec
PROPERTY HourSpec
Take the behavior 13:58, 13:59, 14:00, 14:01. For each of its three steps, say whether it is an HNext step, a stuttering step of HSpec, or neither.
Run the cfg as shown. Report TLC's result and the number of distinct states, and explain that number.
Change the property to HourSpecNoStutter. What does TLC report, and how long is the trace?
Change the specification to DSTSpec and the property back to HourSpec. Which step does TLC reject, and what should the team do about the alert rules?
Hint
[HNext]_hr is HNext \/ UNCHANGED hr. A step that changes only min satisfies the second disjunct. HourSpecNoStutter excuses a step only when <<hr, min>> is unchanged.
Solution
1. 13:58 → 13:59 leaves hr unchanged, so it's a stuttering step of HSpec. 13:59 → 14:00 is an HNext step. 14:00 → 14:01 is stuttering again. The diagram marks each one.
From the hour spec's point of view, the minute ticks are steps where nothing happens.
2. No error, 1440 distinct states. Every state of the dashboard is reachable, as Init allows all 24 × 60. So Spec => HourSpec holds on this model: whatever the alert rules relied on about the hour tile is still true.
3. TLC reports the action property violated after 2 states, on the first Tick it tries (in this run, 0:04 → 0:05). Nearly every tick changes min but not hr. If stuttering meant "nothing changes at all", the hour spec would forbid the minutes from moving, and no clock with a finer display could ever implement it. That's the reason every spec allows steps that leave its own variables unchanged.
4. TLC reports the action property of HourSpec violated after 2 states: from 01:59, SpringForward sets hr to 3. That's neither hr' = hr + 1 nor stuttering. Any alert rule that assumed every hour is visited (for example "the 02:00 batch job always runs") must be reviewed, and that rule really does break on such a night. The spec found the one change that matters and accepted the rest.
A design system has a ConfirmDialog component: the user opens it, then confirms or cancels. Confirm runs an async request. While the request is in flight, the dialog shows a spinner, and the form must not come back. If the request fails, an error is shown with Retry and Cancel. The component team writes the contract as a spec, then writes a few properties that QA asked for as temporal formulas:
---------------------------- MODULE PSl8_Dialog -----------------------------
\* A design-system confirm dialog whose Confirm button runs an async request.
VARIABLE dialog
Status == {"closed", "open", "submitting", "error"}
Init == dialog = "closed"
Open == dialog = "closed" /\ dialog' = "open"
Cancel == dialog \in {"open", "error"} /\ dialog' = "closed"
Confirm == dialog = "open" /\ dialog' = "submitting"
Succeed == dialog = "submitting" /\ dialog' = "closed"
Fail == dialog = "submitting" /\ dialog' = "error"
Retry == dialog = "error" /\ dialog' = "submitting"
Next == Open \/ Cancel \/ Confirm \/ Succeed \/ Fail \/ Retry
Spec == Init /\ [][Next]_dialog
TypeOK == dialog \in Status
AlwaysTypeOK == []TypeOK
\* While a request is in flight the form never reappears.
NoReopenWhileBusy == [][dialog = "submitting" => dialog' # "open"]_dialog
\* An error is shown only right after a request.
ErrorOnlyAfterSubmit == [][dialog' = "error" => dialog = "submitting"]_dialog
\* Once closed, the dialog stays closed (a wrong claim, for comparison).
ClosedIsFinal == [][dialog = "closed" => dialog' = "closed"]_dialog
=============================================================================
The dialog's Next. There is no arrow from submitting to open, which is what NoReopenWhileBusy checks.
Here are four behaviors taken from bug reports and tests. Each one continues by stuttering forever after its last state.
Four behaviors to evaluate, one per row. After the last column each repeats its final state forever.
For each of B1 to B4, decide whether it satisfies Spec, AlwaysTypeOK and NoReopenWhileBusy.
Is the formula Spec => NoReopenWhileBusy true on B2? On B3?
Check the contract with TLC using the cfg below. Then add PROPERTY ClosedIsFinal and run it again. Report both results.
A state formula such as Init, used as a temporal formula, is about the first state only. [][A]_dialog is about every step, and a step where dialog doesn't change satisfies it whatever A says.
Solution
1.
Behavior
Spec
AlwaysTypeOK
NoReopenWhileBusy
B1
TRUE
TRUE
TRUE
B2
FALSE: submitting → open is no action of Next
TRUE
FALSE: that same step
B3
FALSE: Init fails on the first state
TRUE
TRUE
B4
TRUE: every step is stuttering
TRUE
TRUE
B3 shows that a property can hold on a behavior the spec rejects. Only B2 breaks the rule QA cares about, and it's the real double-submit bug: a failed request should go to "error", not reopen the form. These values were confirmed by replaying each behavior in TLC.
2. TRUE on B2 and TRUE on B3. Neither satisfies Spec, so the implication asserts nothing about them. The implication fails only on a behavior that satisfies Spec and breaks the property. TLC's run in task 3 shows there is none.
3. No error, 4 distinct states, with TypeOK invariant and both action properties holding. With ClosedIsFinal added, TLC reports it violated after 2 states: closed → open by Open. That's a step of Spec that changes dialog away from "closed", which is exactly what the property forbids. Having a deliberately wrong property fail is a cheap check that TLC is reading your properties the way you meant them.
Clients of a key-value store see two operations: put a value, and get the current value of a key. The platform team's spec of what clients may observe records in out what the last get returned:
------------------------------ MODULE PSl8_KV -------------------------------
\* What clients of the key-value store may observe. out is the value the
\* most recent Get returned ("none" before the first Get).
CONSTANTS Key, Val
VARIABLES store, out
KVInit == /\ store \in [Key -> Val]
/\ out = "none"
Put(k, v) == /\ store' = [store EXCEPT ![k] = v]
/\ out' = out
Get(k) == /\ out' = store[k]
/\ store' = store
KVNext == \E k \in Key : Get(k) \/ \E v \in Val : Put(k, v)
KVSpec == KVInit /\ [][KVNext]_<<store, out>>
=============================================================================
To cut database load, the team puts a cache in front of the store. Reads use the cached copy if there is one. Writes are write-through: the database and the cache change together. Fill and Evict are background work. A refactor accidentally replaced Put with PutNoInvalidate, which writes the database and leaves the cache alone.
----------------------------- MODULE PSl8_Cache -----------------------------
\* The same store with a cache in front of it. cache[k] is "miss" or a copy.
CONSTANTS Key, Val
VARIABLES store, out, cache
vars == <<store, out, cache>>
Init == /\ store \in [Key -> Val]
/\ out = "none"
/\ cache = [k \in Key |-> "miss"]
\* Write-through: the database and the cache change in one step.
Put(k, v) == /\ store' = [store EXCEPT ![k] = v]
/\ cache' = [cache EXCEPT ![k] = v]
/\ out' = out
\* The bug: write to the database and forget the cached copy.
PutNoInvalidate(k, v) == /\ store' = [store EXCEPT ![k] = v]
/\ UNCHANGED <<cache, out>>
Fill(k) == /\ cache[k] = "miss"
/\ cache' = [cache EXCEPT ![k] = store[k]]
/\ UNCHANGED <<store, out>>
Evict(k) == /\ cache[k] # "miss"
/\ cache' = [cache EXCEPT ![k] = "miss"]
/\ UNCHANGED <<store, out>>
Get(k) == /\ out' = IF cache[k] = "miss" THEN store[k] ELSE cache[k]
/\ UNCHANGED <<store, cache>>
Next == \E k \in Key : \/ Get(k) \/ Fill(k) \/ Evict(k)
\/ \E v \in Val : Put(k, v)
BugNext == \E k \in Key : \/ Get(k) \/ Fill(k) \/ Evict(k)
\/ \E v \in Val : PutNoInvalidate(k, v)
Spec == Init /\ [][Next]_vars
BugSpec == Init /\ [][BugNext]_vars
KV == INSTANCE PSl8_KV
KVSpec == KV!KVSpec
THEOREM Spec => KVSpec
=============================================================================
For each action of Next (Put, Get, Fill, Evict), say whether its steps are KVNext steps or stuttering steps of KVSpec.
Run the cfg as shown and report the result.
Change the specification to BugSpec. Report the trace, and for each step in it say what KVSpec makes of it.
Another team builds a write-back cache: Put writes only the cache, and a later Flush copies it to the database. Without running it, predict whether TLC would accept PROPERTY KVSpec for that design. Does the answer mean the write-back cache is wrong?
Hint
KVSpec sees only store and out. A Get step is a KVNext step only if the new out equals store[k]. When can cache[k] differ from store[k]?
Solution
1.Put(k, v) is a KV!Put(k, v) step: store changes the same way and out is unchanged. Fill and Evict change only cache, so they're stuttering steps. Get(k) sets out to the cached copy or to store[k]. It's a KV!Get(k) step as long as every cached copy equals the stored value, which holds in every reachable state of Spec, because Put updates both.
2. No error, 48 distinct states: 4 stores × 4 consistent caches (each key missing or equal to the store) × 3 values of out.
3. TLC reports the action property of KVSpec violated after 4 states:
The bug is in the third state, but KVSpec rejects only the fourth, when a client sees the stale copy.
Fill("k1") copies "v2": stuttering. PutNoInvalidate("k1","v1") sets the store to "v1": a KV!Put step, still fine. Get("k1") returns the cached "v2" while store["k1"] is "v1", so out changes to a value KV!Get doesn't allow. The bug happens in step 2, and the client sees it in step 3. That's typical: the high-level spec flags a problem only when it becomes observable.
4. TLC would reject it. A write-back Put leaves store and out unchanged, so KVSpec treats it as stuttering. The next Get returns the new value while store still holds the old one, and that's not a KV!Get step. A hidden run of this design gives exactly that 3-state trace. But the design may be perfectly correct: what a client observes as "the store" is the cached value when it is dirty, not the database row. The check failed because the implementation's variable store isn't the right thing to compare with the spec's store. Lecture 10 shows how to state that comparison with an expression in place of a variable of the same name.
The trip booking (flight, hotel, car) still runs two-phase commit. After the coordinator outage in Problem set 7, operations wrote a runbook step: "If a reservation has been prepared for more than ten minutes, roll it back by hand." Some transaction managers offer exactly this escape hatch for in-doubt participants, often called a heuristic decision. Your job is to check it against all-or-nothing agreement, written in the style of TCommit as in Problem set 5, and now as one formula.
The booking module extends the lesson's TwoPhase. It defines its spec as a formula and adds the operator's action. Because PSl8_Agreement has the same variable rmState and constant RM, INSTANCE matches them by name.
---------------------------- MODULE PSl8_Booking ----------------------------
\* Two-phase commit for the trip booking, plus the operator's escape hatch:
\* a participant stuck in "prepared" can be forced to roll back by hand.
EXTENDS TwoPhase
BookSpec == TPInit /\ [][TPNext]_vars
HeuristicAbort(r) == /\ rmState[r] = "prepared"
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ UNCHANGED <<tmState, tmPrepared, msgs>>
OpsNext == TPNext \/ \E r \in RM : HeuristicAbort(r)
OpsSpec == TPInit /\ [][OpsNext]_vars
AG == INSTANCE PSl8_Agreement
Agreement == AG!ASpec
THEOREM BookSpec => Agreement
=============================================================================
Run the cfg as shown. Report the result, and say one thing the theorem guarantees and one thing it doesn't.
Without TLC: all three RMs are prepared and nothing has been decided. Is a HeuristicAbort("flight") step from there an ANext step?
Change the specification to OpsSpec. Report the trace length and the first step that is neither an ANext step nor stuttering for Agreement.
A reviewer suggests a guard: allow HeuristicAbort only while no Commit message has been sent. Would that make OpsSpec implement Agreement? What guard would, and who can check it?
Hint
Write out Decide(r)'s abort branch and evaluate it on the state in task 2. For task 4, ask whether the TM could still send Commit after the guard was checked. What has the TM already recorded?
Solution
1. No error, 288 distinct states: BookSpec => Agreement holds on this model. It guarantees that every step the protocol takes changes rmState in a way agreement allows. It doesn't guarantee that anything is ever decided. A behavior that stutters forever satisfies both sides, and the coordinator crash of Problem set 7 is still possible.
2. Yes. The abort branch of Decide("flight") needs rmState["flight"] \in {"working", "prepared"} and notCommitted, and both hold. Taken alone, the operator's step looks like a legal abort.
3. TLC reports the action property of Agreement violated after 10 states. The run here:
The operator's step is a legal abort. The coordinator's commit was already determined by what it had recorded, and the failure shows up only at a receipt.
States 2 to 5: hotel and flight prepare and the TM records both. State 6: HeuristicAbort("flight"), an allowed abort. States 7 to 9: car prepares, the TM records it, and TMCommit sends Commit, because tmPrepared = RM no matter what flight did afterwards. That's stuttering for Agreement. State 10: RMRcvCommitMsg("flight") moves flight from aborted to committed. TwoPhase's receive action has no guard on the RM's state, since in the real protocol a prepared RM can't have aborted. Your run may end instead with hotel or car committing while flight is aborted. Either way, the step that breaks the high-level spec is a commit receipt, three steps after the cause.
4. No. TLC rejects the guarded version too, again in 10 states. The TM recorded flight's Prepared before the operator acted, and nothing tells it to forget. The only safe guard is that the TM has decided Abort, and then the heuristic is just RMRcvAbortMsg. In other words, the decision has to be made at the coordinator, which is the process that's down. The check shows why the runbook step is dangerous: once you allow it, all-or-nothing is no longer a property of the system, and any mixed outcome has to be found and repaired by hand.
Lecture 9: Alternating bit protocol
First say what a channel should accomplish.
You now have two ways to read a spec: as what a system may do, and as a formula another spec can imply. The next lessons use one small protocol for sending data across a channel that loses messages. Before seeing how it works, you write what it should achieve, and that takes one more data structure: sequences.
The high-level view: A puts a value in AVar (outlined), then B copies it to BVar (green). In the last two steps Mary is sent again. Only the flipped bit makes that a change anyone can see.
Finite sequences
A finite sequence is another name for a tuple, and programmers would call it a list. <<-3, "xyz", {0, 2}>> has length 3. A sequence of length N is simply a function with domain 1..N, so <<-3, "xyz", {0, 2}>>[2] is "xyz", and [i \in 1..N |-> i^2] is the sequence of the first N squares. The standard module Sequences defines the operators. These values come from TLC, using the evaluation trick described below:
Expression
Value
Head(<<"Fred", "Mary", "Ted">>)
"Fred"
Tail(<<"Fred", "Mary", "Ted">>)
<<"Mary", "Ted">>
Append(<<3, 2, 1>>, "a")
<<3, 2, 1, "a">>
<<3, 2, 1>> \o <<"a", "b">>
<<3, 2, 1, "a", "b">>
Len(<<3, 2, 1>>)
3
1..0, the domain of <<>>
{}
Seq(S) is the set of all finite sequences with elements in S. It is infinite: Seq({3}) contains <<>>, <<3>>, <<3, 3>>, and so on. Sequences are the last commonly used data type you need.
The protocol will need to delete a message from the middle of a channel. No built-in does this, so define it, by writing a function on a shorter domain and working out what each position holds:
Remove(i, seq) ==
[j \in 1..(Len(seq) - 1) |-> IF j < i THEN seq[j] ELSE seq[j + 1]]
Remove(3, <<1, 2, 3, 4>>) position by position. Its domain shrinks to 1..3. Positions before the removed one copy across, and later ones shift down.
A definition like that deserves a test, and there's no need for a behavior to run one. In the Toolbox, type an expression into a model's results page and TLC computes it. In a plain module, write ASSUME PrintT(Remove(3, <<1, 2, 3, 4>>)) after EXTENDS TLC, and TLC prints <<1, 2, 4>> while checking assumptions.
The Cartesian product
S \X T is the set of all pairs <<a, b>> with a in S and b in T. So (1..3) \X {"a", "b"} has six elements. Keep the parentheses. Without them it parses as 1..(3 \X {"a", "b"}), and TLC stops with an error. S \X T \X U is the obvious set of triples.
What must the protocol accomplish?
Sender A sends a sequence of data items to receiver B. An obvious model uses two variables, AVar and BVar. A sets AVar to the string it wants to send. Then B sets BVar equal to it. Watching that, you would see Fred, Mary, Ted, Ann. But suppose A meant to send Mary twice. Nothing would change, and a value can't have been sent if nothing changed.
So something must change when a value is sent again. The lecture lets each variable be a pair: the value, and one bit that flips every time A chooses a value. The top figure sends Fred, Mary, Mary this way. The spec is short:
------------------------------- MODULE ABSpec -------------------------------
EXTENDS Integers
CONSTANT Data
VARIABLES AVar, BVar
TypeOK == /\ AVar \in Data \X {0, 1}
/\ BVar \in Data \X {0, 1}
vars == <<AVar, BVar>>
Init == /\ AVar \in Data \X {1}
/\ BVar = AVar
A == /\ AVar = BVar
/\ \E d \in Data : AVar' = <<d, 1 - AVar[2]>>
/\ BVar' = BVar
B == /\ AVar # BVar
/\ BVar' = AVar
/\ AVar' = AVar
Next == A \/ B
Spec == Init /\ [][Next]_vars
Inv == (AVar[2] = BVar[2]) => (AVar = BVar)
FairSpec == Spec /\ WF_vars(Next)
=============================================================================
The last line uses WF, which lesson 29 explains; ignore it for now. 1 - AVar[2] complements the bit. A step of A needs the two variables equal, because B must have received the last value. A step of B needs them unequal and copies. There's no channel, no message, and no retransmission here, since those belong to how, not what.
All of ABSpec when Data = {d}; TLC finds exactly these 4 states. In the two highlighted states the bits agree and the values agree, which is what Inv says. Each A arrow becomes one arrow per data value when Data grows.
Check it
Type correctness alone doesn't make a spec right. To find errors, check formulas that ought to be invariants. Here that is Inv: if the bits agree, the pairs agree. Make sure you see why before running it. The bits differ exactly between an A step and the following B step.
d1, d2, d3 are model values, as you used for RM. TLC finds no error: 39 states generated, 24 distinct, depth 4.
Predict: where do the 24 states come from?
There are 3 × 2 = 6 possible pairs. When the variables agree there is one state per pair, giving 6. When they differ, the bits must differ, by Inv, so AVar is any of 6 pairs and BVar any of the 3 pairs with the other bit, giving 18. And 6 + 18 = 24.
Like every spec so far, Spec says only what may happen. A behavior may stop right after A sets AVar, so nothing is ever received. lesson 29 fixes that.
While you watch
This lesson covers the first half of the lecture's first part: sequences, the product, ABSpec, and the type and Inv checks. The second half goes with lesson 29.
Pause at Remove and try to fill in the dots yourself before he reveals the definition. Pause again at the animation with Mary sent twice, and say what you'd add to make it visible.
He downloads ABSpec, makes a model with a few model values, and has you run it. Do so, in the Toolbox as he shows or in VS Code with the configuration above.
ABSpec's Spec allows a value to be sent and then never received, because a behavior may stutter forever, as you saw in lesson 26. This lesson adds what a system must do. You write the requirement as a temporal formula, then add fairness conditions that make it true.
A safety formula is violated at a point (red), and nothing later can repair it. A liveness formula has no such point: after any prefix, a later state could still make x equal 5.
Safety and liveness
A safety formula says what may happen. If a behavior violates it, the violation occurs at some particular point, and nothing later can undo it. Init /\ [][Next]_vars is one: it fails on a bad first state or on a step that is neither Next nor stuttering. A liveness formula says what must happen, and no point in a behavior can violate it, because the rest of the behavior could always make it true. Remember that a behavior here is any infinite sequence of states, not just one allowed by some spec.
The figure's second row uses a new operator. <>P, read eventually P, says P is true on some state. It equals ~[]~P; convince yourself of that. For a sequential program, the one liveness property is termination: <>Terminated. Concurrent systems have many others, written with these forms:
Formula
Meaning
<>P
P holds at some state.
[]<>P
P holds infinitely often.
<>[]P
There comes a point after which P always holds.
P ~> Q
P leads to Q, which abbreviates [](P => <>Q). Whenever P holds, Q holds then or later.
For the channel, we'd like every value being sent to be received. The lecture gives this formula to copy; here it has a name, defined in a small wrapper module that extends ABSpec:
Delivered == \A v \in Data \X {0, 1} : (AVar = v) ~> (BVar = v)
Eventually is not a deadline. It has no time bound at all. Also, with changing requests, the predicate must identify which request. Here the pair v plays that role, while an imprecise "some request completed" could be satisfied by an old one.
Enabled, and weak fairness
Action A is enabled in state s when some state t makes s → t an A step. A conjunct with no primes is an enabling condition, so ABSpec's A is enabled when AVar = BVar and Data is non-empty.
Weak fairness of A says: if A ever remains continuously enabled, an A step must eventually occur. Equivalently, A cannot stay enabled forever without another A step. It is written WF_vars(A), in ASCII exactly like that, and read "WF of A". It is a liveness property, because an A step or a state where A is disabled can always make it true.
Strong fairness, SF_vars(A), is stronger: if A is repeatedly enabled, even with gaps, an A step must eventually occur. The difference is the flicker shown in run 2 below.
The cells marked step show where a required A step must fall: one step, somewhere among them. Run 1 stays enabled forever, so weak fairness demands a step. Run 2 never stays enabled, so weak fairness demands nothing, and only strong fairness does.
Inspect repeating schedules
Predict: Serve is enabled every other step and never runs. Does weak fairness reject the behavior?
No. It never stays enabled continuously forever. Strong fairness rejects that particular infinite behavior. Whether strong fairness is a justified system assumption is a separate question.
What the subscript means
WF_vars(A) is weak fairness of the action A /\ (vars' # vars), a non-stuttering A step. It makes no sense to require a stuttering step, since nobody could tell whether it happened.
Adding liveness to a spec
A spec with liveness has the form Init /\ [][Next]_vars /\ Fairness. Fairness is a conjunction of WF and SF formulas, each on a subaction of Next, meaning every step of it is a Next step. Now you can read the last line of ABSpec:
FairSpec == Spec /\ WF_vars(Next)
Behaviors must keep taking Next steps while Next is enabled. The safety part never reaches a state where it isn't, so A keeps sending and B keeps receiving forever. A second possible spec says something weaker, using WF_vars(B) alone: every sent value is received, but the sender may stop. Here are the checks, with Data = {d1, d2, d3}. All explore the same 24 states; only the question differs. FairAB abbreviates Spec /\ WF_vars(A) /\ WF_vars(B).
SPECIFICATION
PROPERTY
TLC says
Spec
Delivered
Violated. A step, then stuttering.
FairSpec
Delivered
No error.
Spec /\ WF_vars(B)
Delivered
No error.
Spec /\ WF_vars(B)
FairAB
Violated. Stuttering from the first state: the sender stops.
FairSpec
FairAB
No error.
FairAB
FairSpec
No error.
TLC's counterexample when Spec has no fairness. After State 3 TLC reports only Stuttering, meaning forever. B stays enabled throughout, and this is exactly the behavior WF_vars(Next) forbids.
The last two rows solve the lecture's exercise by checking both directions: weak fairness of Next and of A and B separately are equivalent here. A liveness check must not use a symmetry set, a TLC reduction some models use. These don't.
Worked architecture: a background upload worker
A mobile app has accepted upload U. The worker can Send(U) whenever the device is online and U is pending. Take a behavior where the phone keeps reconnecting and disconnecting before U is selected. As the figure shows, the upload was enabled many times, and weak fairness still doesn't require it to run.
Repeated opportunities satisfy enabled infinitely often, not continuously enabled from some point on. Weak fairness of Send(U) accepts this behavior, and strong fairness rejects it.
For Pending(U) ~> Uploaded(U), decide what the environment promises. If the device eventually stays online, Send(U) becomes continuously enabled and weak fairness suffices. Strong fairness would let recurring opportunities suffice, but background execution limits on the platform may make that assumption false. And sending still isn't delivery: a separate assumption is needed if the network can drop every attempt.
Fairness also needs the right granularity. With uploads U and V pending, WF_vars(SendAny) can be satisfied by sending V forever while U waits. Attach fairness per request, such as \A p \in Processes : WF_vars(Serve(p)). Never add fairness merely to silence a counterexample. Fairness is not a scheduler, a response-time bound, or a delivery guarantee. It states what you assume, and permanent partitions can make the assumption false.
Predict: a worker is weakly fair, but every request is dropped. Does "pending leads to delivered" follow?
No. Worker scheduling and network delivery are different actions with different assumptions. A correct argument must connect retries, eventual delivery, acknowledgement, and durable completion instead of jumping from "worker runs" to "request succeeds".
While you watch
This lesson covers the second half of the lecture's first part. It only names strong fairness. The definition comes in part 2, right after the counterexample that needs it; this lesson shows it earlier so the lab can compare the two, and lesson 30 supplies the need.
Pause at the eventually exercise. Then, at the two fair specs, explain to yourself why the sender may stop in one but not the other.
lesson 28 said what should happen and lesson 29 said it must. Now comes how. Sender A and receiver B talk over two channels that can lose messages, and all they have to work with is the one bit from ABSpec. You'll check that the protocol implements its spec, then see weak fairness fail on a real counterexample and strong fairness repair it.
The protocol on its two lossy channels. A and B both resend forever. Only the green arrows change anything; the bit tells each side which arrivals are news.
How it works
A repeatedly sends its current AVar on channel AtoB, since any copy might be lost. B repeatedly sends the bit of BVar on channel BtoA, as an acknowledgement. Then the bits do all the work:
When B receives a message whose bit differs from its own, it's a new value, so B sets BVar to it. A message with the same bit is one B already has.
When A receives a bit equal to its own, its current value has been acknowledged, so it chooses a new value and flips its bit. A different bit is a stale ack for the previous value.
Step the protocol yourself
You are the scheduler and the network. This is an educational model, not TLC. Click a message to lose it. A channel holds at most 3 messages here, as in the lecture's model.
AtoB
BtoA
Try this in the lab. Send, lose the message, and send again, watching the high-level view stay at stuttering until one copy gets through. Then tick the box, send acks, and receive them with nothing delivered.
The specification
Module AB has nothing new except sequence operators. A send appends to a channel, a receive takes the head, and LoseMsg uses Remove to delete any message.
The new line is ABS == INSTANCE ABSpec. A plain INSTANCE ABSpec is illegal here, because it would import a second Spec; TLC reports multiple definitions. Naming the instance imports everything with a prefix, so ABS!Spec is ABSpec's formula. The variables AVar and BVar carry over by name. This is the theorem pattern from lesson 26 again.
Checking safety needs a bound
A and B can send faster than messages are received or lost, so channels can grow without limit. There are infinitely many reachable states, and TLC would run forever. You could change the spec, but you shouldn't have to change a spec to check it. Instead, give TLC a state constraint:
Bound == (Len(AtoB) <= 2) /\ (Len(BtoA) <= 2)
How TLC uses Bound, drawn by length of AtoB only. A state failing the constraint is simply not explored further. The spec is unchanged, and only this model's search is cut.
Normally TLC takes an unexplored state, computes its successors, and repeats. With a constraint, it first tests the state, and if the test fails it doesn't go on from there. That is a limit on what was checked, so say so when reporting a result. A cfg can't name ABS!Spec directly, so a small wrapper module extends AB and defines HighSafety == ABS!Spec. The Toolbox accepts ABS!Spec in its property list.
TLC finds no error: 1286 states generated, 216 distinct, depth 13. With the lecture's model, three data values and channel length at most 3, it finds no error in 960 distinct states.
Predict: delete the bit test from ARcv, so any ack makes A choose a new value. And separately, delete the test from BRcv, so B always copies the head. Which breaks?
Only the first. With A broken, TLC reports ABS!Spec violated in five states, shown below. With B broken, this model still gives no error, with the same 216 states. Channels are first-in first-out, so on this model a message carrying B's own bit always equals BVar, and copying it changes nothing. The test that does the work on this model is the one at A. B's test only says, in the spec's terms, when nothing new arrived.
TLC's counterexample for a broken ARcv that moves on after any ack. Its second new value overwrites one B never got, which ABS!Spec rejects because A needs AVar = BVar.
Liveness: which fairness?
The complete spec should imply ABS!FairSpec, with messages that keep getting sent and received. Try the natural candidates, always with the same 216-state model:
Added to Spec
Checked against
TLC says
nothing
Delivered
Violated: stops after a value is sent, then stutters.
WF_vars(Next)
ABS!FairSpec
Violated: BSnd, LoseMsg, forever.
WF on all four, no LoseMsg
ABS!FairSpec
Violated: the loop below.
FairSpec as printed
ABS!FairSpec and Delivered
No error.
WF_vars(Next) is too weak, because Next keeps being satisfied by something useless. So each of the four real actions needs its own requirement. There is none on LoseMsg, since nothing requires messages to be lost. Weak fairness on all four looks plausible, and here is what TLC found:
TLC's counterexample with weak fairness everywhere, where m = <<d1, 1>>. The loop repeats forever. ARcv is enabled once per lap and disabled by LoseMsg before it can run, so WF_vars(ARcv) is satisfied, and AVar and BVar never change.
Read the fairness conditions against it. ASnd, BSnd and BRcv steps keep occurring. ARcv is enabled in State 3 and disabled again in State 4, so it's never continuously enabled and weak fairness asks nothing of it. Your run may find a different loop; the lecture shows one where messages in both directions get lost. Both have the same cause: LoseMsg keeps disabling a receive.
Strong fairness from lesson 29 closes the gap. BSnd is always enabled, so weak fairness makes B keep sending. Each send enables ARcv, so ARcv is repeatedly enabled, and SF_vars(ARcv) requires it to happen, however often loss disables it. The argument from A to B is symmetric. Strong fairness doesn't stop losses. It says that if you keep sending, something eventually gets through, which is the assumption a lossy channel has to meet to be usable at all.
What good is eventually?
Something that happens a million years from now is no use, and you could never observe strong fairness failing. But a spec is a compromise between accuracy and simplicity. Requiring receipt within 4.7 ms would mean specifying delivery times, loss rates, and retransmission rates. And if a message is never received, it isn't received in 4.7 ms. So for systems without hard real-time requirements, liveness checking finds errors that prevent things from happening. Timeouts that exist only so that something eventually happens can be plain actions with weak fairness and no clocks. A failed liveness check can also reveal a safety part that's too strict.
While you watch
Stop before he runs TLC and predict why the model won't finish. Then change the two SF to WF as he asks and run it.
His TLC run may produce a different trace from the one above. Check any trace you get the way he does, condition by condition.
The lab, the five-state bug, and the BRcv experiment are additions; the rest follows the lecture's order.
Problem set 9: say what must happen, and what it assumes.
Four problems on lecture 9: liveness properties, weak and strong fairness, and the alternating bit protocol. Each one asks TLC whether something eventually happens and then asks you why the answer depends on the fairness you assumed. The last problem returns to the trip booking of Problem set 6, Problem set 7 and Problem set 8, now over a network that loses messages.
Every module shown was checked with TLC exactly as printed. Liveness counterexamples aren't unique: TLC may show you a different loop from the one described here, so check yours condition by condition, as The alternating bit protocol does. None of these models uses a symmetry set, since liveness checking must not.
A web app pushes slow work (sending receipts, resizing images) onto a background-job queue with a single worker. Support asks for a guarantee: every job that is submitted is eventually processed. The worker also sends a heartbeat to the scheduler, so a monitor can tell it's alive. Last week a customer's receipt never went out, although the job sat in the queue and the worker's heartbeat stayed green on the monitor the whole time. The module below has no deadlines, because "eventually" has none.
Run TLC with SPECIFICATION Spec. What does the counterexample end with, and why is it allowed?
Run it with FairNext. Describe the loop TLC reports, and explain why it satisfies WF_vars(Next).
Run it with FairWorker, as in the cfg shown. Report the result.
Nothing is fair about Submit. Should it be? Say what WF_vars(\E j \in Job : Submit(j)) would claim about the users of the app.
Hint
WF_vars(Next) needs Next steps to keep happening while Next is enabled. Is there any state where some Next step is not possible? Which action is always enabled?
Solution
1. TLC reports EveryJobProcessed violated. In this run, some jobs are submitted and processed, and the trace ends with j1 still in the queue followed by "Stuttering". Spec says only what may happen, so a behavior may stop at any point. TLC even warns that the stuttering counterexample may come from a missing fairness condition.
2. TLC again reports a violation, this time ending in a loop. In the run here, j1 is submitted and processed, j3 and j2 are submitted, and then states 5 and 6 alternate by Heartbeat steps forever while j3 and j2 wait in the queue. Every step is a Next step, so WF_vars(Next) is satisfied. It requires only that Next steps keep happening, not that any particular one does. This is the same weakness The alternating bit protocol found in WF_vars(Next) for the alternating bit protocol.
Every step is a Next step, so WF_vars(Next) is satisfied, but the worker never processes j3.
3. No error, 76 distinct states. In a state where some job is in the queue, Process is enabled and stays enabled until it runs, so weak fairness forces a Process step. The queue is first-in first-out, so a submitted job reaches the head after the jobs before it have been processed.
4. No. That condition would say that users keep submitting jobs as long as some job hasn't been submitted, which is a claim about the environment, not the system, and it's false. Fairness belongs on actions the system promises to take. The property is already conditional: it talks only about jobs that are submitted.
A database's lock manager lets many queries hold a table lock in shared mode, while a schema migration (ALTER TABLE) needs it exclusively. The first version grants a shared lock whenever no writer holds the table. On a busy table the migration has been waiting for an hour. The team's first idea is "make the scheduler fairer". The module below lets you test that idea. Queries release the lock eventually (weak fairness on every release), and the three specs differ only in the fairness of WriteAcquire and in one guard.
Run WFSpec with Reader = {"q1", "q2"}. Is WriteAcquire ever enabled in the loop TLC reports? Why doesn't weak fairness force it?
Run SFSpec, first with Reader = {"q1"}, then with two readers. Explain why strong fairness helps with one reader and not with two.
Run QWFSpec with two readers. What changed, and why is weak fairness enough now?
PostgreSQL behaves like the fixed version: once a statement is waiting for an ACCESS EXCLUSIVE lock, later requests that conflict with it, even a plain SELECT's ACCESS SHARE, wait behind it. What does the fix cost while a long query holds the table, and why do migration guides recommend setting lock_timeout?
Hint
Write down, for each state of the loop, whether readers = {}. Weak fairness needs an action enabled continuously; strong fairness needs it enabled infinitely often. Neither says anything about an action that is never enabled.
Solution
1. TLC reports WriterProgress violated. In this run the writer requests the lock, then q2 acquires and releases forever. WriteAcquire is enabled in the states where readers = {} and disabled whenever q2 holds the lock. It is never continuously enabled, so weak fairness asks nothing of it. That's the flicker from Liveness and fairness.
2. With one query, SFSpec gives no error (5 distinct states). Each release by q1 makes the table free, so WriteAcquire is enabled infinitely often, and strong fairness forces it to happen. With two queries TLC again reports a violation:
The two queries overlap, so the table is never free. Neither weak nor strong fairness says anything about an action that is never enabled.
q1 and q2 overlap, so one of them always holds the lock. readers is never empty, WriteAcquire is never enabled, and strong fairness, which talks only about enabled actions, doesn't apply. Each query still releases the lock infinitely often, so the release fairness holds too. No scheduler policy fixes this, because it isn't a scheduling problem.
3. No error (9 distinct states). ReadAcquireQueued refuses new shared locks while the writer is waiting. The current holders release because of their weak fairness, readers becomes empty and stays empty, and WriteAcquire is then continuously enabled, so weak fairness is enough. The fix changed the protocol, not the fairness.
4. While the migration waits behind one long-running query, every new query on that table waits behind the migration. To users, a slow report plus a migration looks like a table outage. Setting lock_timeout limits how long the migration waits in the queue: if it can't get the lock quickly, it fails and is retried later, and the other queries proceed. That's the same trade-off as the model: whoever waits blocks those behind it.
Problem 3●●○Networking
The alternating bit protocol over a link that reorders
A battery-powered temperature sensor (A) sends readings to a gateway (B) using the alternating bit protocol, the way the firmware team learned it. On the test bench, over a serial link that delivers in order, everything works. In the field the link is UDP, and UDP datagrams can be lost, duplicated, and delivered out of order. Now and then, the dashboard shows an old reading as new.
The module is the lesson's AB with one change: when Reorder is TRUE, a receiver may take any message in its channel, not just the head. PSl9_LinkSpec is ABSpec from The high-level spec of a channel, unchanged except for its name.
----------------------------- MODULE PSl9_Sensor ----------------------------
\* The alternating bit protocol between a sensor (A) and a gateway (B).
\* As module AB, except a receiver may take ANY message in its channel when
\* Reorder is TRUE, as over UDP. With Reorder = FALSE it is exactly AB.
EXTENDS Integers, Sequences
CONSTANTS Data, Reorder
Remove(i, seq) ==
[j \in 1..(Len(seq) - 1) |-> IF j < i THEN seq[j] ELSE seq[j + 1]]
VARIABLES AVar, BVar, AtoB, BtoA
vars == <<AVar, BVar, AtoB, BtoA>>
TypeOK == /\ AVar \in Data \X {0, 1}
/\ BVar \in Data \X {0, 1}
/\ AtoB \in Seq(Data \X {0, 1})
/\ BtoA \in Seq({0, 1})
Init == /\ AVar \in Data \X {1}
/\ BVar = AVar
/\ AtoB = <<>>
/\ BtoA = <<>>
\* The positions a receiver may take a message from.
Pick(ch) == IF Reorder THEN 1..Len(ch) ELSE 1..1
ASnd == /\ AtoB' = Append(AtoB, AVar)
/\ UNCHANGED <<AVar, BtoA, BVar>>
ARcv == /\ BtoA # <<>>
/\ \E i \in Pick(BtoA) :
/\ IF BtoA[i] = AVar[2]
THEN \E d \in Data : AVar' = <<d, 1 - AVar[2]>>
ELSE AVar' = AVar
/\ BtoA' = Remove(i, BtoA)
/\ UNCHANGED <<AtoB, BVar>>
BSnd == /\ BtoA' = Append(BtoA, BVar[2])
/\ UNCHANGED <<AVar, BVar, AtoB>>
BRcv == /\ AtoB # <<>>
/\ \E i \in Pick(AtoB) :
/\ IF AtoB[i][2] # BVar[2]
THEN BVar' = AtoB[i]
ELSE BVar' = BVar
/\ AtoB' = Remove(i, AtoB)
/\ UNCHANGED <<AVar, BtoA>>
LoseMsg == /\ \/ /\ \E i \in 1..Len(AtoB) : AtoB' = Remove(i, AtoB)
/\ BtoA' = BtoA
\/ /\ \E i \in 1..Len(BtoA) : BtoA' = Remove(i, BtoA)
/\ AtoB' = AtoB
/\ UNCHANGED <<AVar, BVar>>
Next == ASnd \/ ARcv \/ BSnd \/ BRcv \/ LoseMsg
Spec == Init /\ [][Next]_vars
ABS == INSTANCE PSl9_LinkSpec
HighSafety == ABS!Spec
Bound == (Len(AtoB) <= 2) /\ (Len(BtoA) <= 2)
=============================================================================
Run it with Reorder = FALSE and check that you get the lesson's result.
Run it with Reorder = TRUE, as shown. Report the length of the trace, and say which message is delivered out of order.
In The alternating bit protocol, deleting B's bit test changed nothing on the in-order model. Which test does the reordered trace defeat, and why does a single bit not suffice?
Describe a change to the messages that would let B tell a stale copy from a new value. What makes it hard to check with TLC on a finite model?
Hint
A keeps sending its current value, so old copies can stay in AtoB after the value has been acknowledged. With one bit, "different from my bit" means "new" only if nothing older than the previous value can still arrive.
Solution
1. No error, 216 distinct states, the same as module AB in The alternating bit protocol. With Reorder = FALSE, Pick is 1..1, so each receive takes the head, exactly as before.
2. TLC reports the action property of PSl9_LinkSpec violated after 7 states:
With one bit, a stale copy of the previous value looks exactly like the next new value.
B acknowledges with bit 1 (state 2). A sends <<d1, 1>>, a copy of the value B already has (state 3), then receives the ack, picks the new value <<d1, 0>> (state 4), and sends it (state 5). B takes the newer message first, out of order (state 6). Then it takes the old <<d1, 1>>, sees a bit different from its own, and accepts it as new (state 7). The data happens to be d1 both times, but B has gone back to a stale copy of the previous value and treated it as a new one. With different readings, the dashboard shows an old reading as new, as in the field.
3. B's test: "the bit differs from mine, so this is new". On a first-in first-out channel, the old copies of the previous value were ahead of the new value in the channel, so by the time B accepts the new value they have been received or lost. With reordering, an old copy can arrive after the new value. Because the bit only alternates, a copy of the previous value carries the same bit as the next new value, so B can't tell them apart. One bit distinguishes a value only from its immediate neighbours.
4. Number each value with a counter instead of a bit, and have B accept only the number after the last one it accepted. That is the idea behind sequence numbers in protocols such as TCP. The counter grows without bound, so a TLC model needs another constraint on it, and you must say that the result holds only within that bound, just as with channel lengths in The alternating bit protocol. A counter that wraps around has the same weakness, if an old copy can survive until the counter comes back to its number.
The trip booking from Problem set 6 (flight, hotel and car RMs, one TM, two-phase commit) is moving to a network that loses messages. Problem set 8 showed that its steps keep agreement, and Problem set 7 showed how a coordinator crash blocks it. Product now asks the liveness question: does every reservation eventually end up committed or aborted, so that held seats, rooms and cars are always released?
In the module below, net holds messages in flight. Receiving or losing a message removes it, unlike msgs in TwoPhase. Messages are addressed to one RM, and the TM may abort at any time while undecided, which models a timeout. RMResend and TMResend are retries. Because net is a set of finitely many possible messages, the channel is bounded without a state constraint.
-------------------------- MODULE PSl9_BookingLive --------------------------
\* Two-phase commit for the trip booking over a network that loses messages.
\* net holds the messages in flight: receiving or losing one removes it, so
\* a lost message is gone unless someone sends it again. net is a set, so it
\* never holds more than the finitely many different messages.
CONSTANT RM
VARIABLES rmState, tmState, tmPrepared, net
vars == <<rmState, tmState, tmPrepared, net>>
Prep(r) == [type |-> "Prepared", rm |-> r]
Dec(r) == [type |-> IF tmState = "commit" THEN "Commit" ELSE "Abort", rm |-> r]
Init == /\ rmState = [r \in RM |-> "working"]
/\ tmState = "init" \* then "commit" or "abort"
/\ tmPrepared = {}
/\ net = {}
-----------------------------------------------------------------------------
RMPrepare(r) == /\ rmState[r] = "working"
/\ rmState' = [rmState EXCEPT ![r] = "prepared"]
/\ net' = net \cup {Prep(r)}
/\ UNCHANGED <<tmState, tmPrepared>>
RMChooseToAbort(r) == /\ rmState[r] = "working"
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ UNCHANGED <<tmState, tmPrepared, net>>
RMRcvCommit(r) == /\ [type |-> "Commit", rm |-> r] \in net
/\ rmState' = [rmState EXCEPT ![r] = "committed"]
/\ net' = net \ {[type |-> "Commit", rm |-> r]}
/\ UNCHANGED <<tmState, tmPrepared>>
RMRcvAbort(r) == /\ [type |-> "Abort", rm |-> r] \in net
/\ rmState' = [rmState EXCEPT ![r] = "aborted"]
/\ net' = net \ {[type |-> "Abort", rm |-> r]}
/\ UNCHANGED <<tmState, tmPrepared>>
TMRcvPrepared(r) == /\ tmState = "init"
/\ Prep(r) \in net
/\ tmPrepared' = tmPrepared \cup {r}
/\ net' = net \ {Prep(r)}
/\ UNCHANGED <<rmState, tmState>>
\* The TM decides and sends one copy of the decision to every RM.
TMDecide ==
/\ tmState = "init"
/\ \/ /\ tmPrepared = RM
/\ tmState' = "commit"
/\ net' = net \cup {[type |-> "Commit", rm |-> r] : r \in RM}
\/ /\ tmState' = "abort" \* e.g. after a timeout
/\ net' = net \cup {[type |-> "Abort", rm |-> r] : r \in RM}
/\ UNCHANGED <<rmState, tmPrepared>>
Lose == \E m \in net : /\ net' = net \ {m}
/\ UNCHANGED <<rmState, tmState, tmPrepared>>
\* Retries.
RMResend(r) == /\ rmState[r] = "prepared"
/\ net' = net \cup {Prep(r)}
/\ UNCHANGED <<rmState, tmState, tmPrepared>>
TMResend(r) == /\ tmState # "init"
/\ net' = net \cup {Dec(r)}
/\ UNCHANGED <<rmState, tmState, tmPrepared>>
-----------------------------------------------------------------------------
Core == \/ TMDecide \/ Lose
\/ \E r \in RM : \/ RMPrepare(r) \/ RMChooseToAbort(r)
\/ RMRcvCommit(r) \/ RMRcvAbort(r) \/ TMRcvPrepared(r)
Next == Core \/ \E r \in RM : RMResend(r) \/ TMResend(r)
NoTMRetryNext == Core \/ \E r \in RM : RMResend(r)
NoRMRetryNext == Core \/ \E r \in RM : TMResend(r)
Base == /\ WF_vars(TMDecide)
/\ \A r \in RM : WF_vars(RMPrepare(r) \/ RMChooseToAbort(r))
WFRcv == \A r \in RM : /\ WF_vars(TMRcvPrepared(r))
/\ WF_vars(RMRcvCommit(r) \/ RMRcvAbort(r))
SFRcv == \A r \in RM : /\ SF_vars(TMRcvPrepared(r))
/\ SF_vars(RMRcvCommit(r) \/ RMRcvAbort(r))
RMRetry == \A r \in RM : WF_vars(RMResend(r))
TMRetry == \A r \in RM : WF_vars(TMResend(r))
WFSpec == Init /\ [][Next]_vars /\ Base /\ WFRcv /\ RMRetry /\ TMRetry
SFSpec == Init /\ [][Next]_vars /\ Base /\ SFRcv /\ RMRetry /\ TMRetry
NoTMRetrySpec == Init /\ [][NoTMRetryNext]_vars /\ Base /\ SFRcv /\ RMRetry
NoRMRetrySpec == Init /\ [][NoRMRetryNext]_vars /\ Base /\ SFRcv /\ TMRetry
Decided(r) == rmState[r] \in {"committed", "aborted"}
EveryoneDecides == \A r \in RM : <>Decided(r)
Consistent == \A r1, r2 \in RM : ~(rmState[r1] = "aborted" /\ rmState[r2] = "committed")
=============================================================================
Run WFSpec. Describe the loop in TLC's counterexample, and name the fairness condition that the loop escapes and why.
Run SFSpec, as in the cfg shown. Report the result and connect it to the argument in The alternating bit protocol.
Run NoTMRetrySpec and NoRMRetrySpec. One retry is essential and the other isn't. Which, and why?
Add the coordinator crash of Problem set 7: after Crash, no TM action is enabled. Can any fairness condition on the TM's actions bring back EveryoneDecides? Answer, then check the quiz.
Hint
Every loop TLC can report under WFSpec must satisfy each WF condition. Look for a receive action that the loop keeps enabling with a retry and then disabling with Lose. For task 3, ask what the TM does if a Prepared message never arrives.
Solution
1. TLC reports EveryoneDecides violated, with a loop. In the run here the TM has decided abort, flight and car have aborted, and hotel is still prepared. Inside the loop, TMResend("hotel") puts an Abort for hotel into net, other steps follow, and Lose removes it before hotel takes it, again and again:
Hotel's receive action keeps flickering: enabled by each resend, disabled by each loss. Weak fairness lets it wait forever; strong fairness doesn't.
RMRcvAbort("hotel") is enabled for a while each time around and then disabled by Lose, so it is never continuously enabled. WF_vars(RMRcvCommit("hotel") \/ RMRcvAbort("hotel")) therefore asks nothing of it. The retries still happen as their weak fairness requires, so every condition of WFSpec holds on this behavior.
2. No error, 6560 distinct states. Retries make each receive action enabled infinitely often, and strong fairness on receives then forces it to happen. This is the argument for SF_vars(ARcv) and SF_vars(BRcv) in The alternating bit protocol: strong fairness doesn't stop losses, it says that a message sent again and again eventually gets through.
3.NoTMRetrySpec is violated: in the run here the TM aborts, Abort messages for flight and hotel are lost, and those two RMs stay prepared forever. Nothing would ever send them the decision again. NoRMRetrySpec gives no error (2933 distinct states). A lost Prepared message can't block anyone, because the TM may abort while it is undecided, and weak fairness on TMDecide makes it decide. Losing a vote costs a commit that could have happened. It doesn't cost liveness. The retry that matters is the one that carries the decision, because a prepared RM can't leave that state on its own, as Two-phase commit and records showed.
4. No, as the quiz explains: a hidden run that adds Crash to SFSpec reports EveryoneDecides violated, ending with hotel prepared and the TM down. Fairness is an assumption about steps that can happen. It can't make a stopped process act. The booking can only be live if the decision survives the TM, either in a log that a restarted TM reads back, or in Paxos Commit's acceptors from Problem set 7, which needs a majority of them to keep working.
Lecture 10: Implementation with refinement
Implication runs out when the variables differ.
Implementation as implication, from lesson 26, worked because every variable of the high-level spec also appeared in the low-level one. TwoPhase had rmState, and AB has AVar and BVar. This lesson builds a protocol where that fails for an obvious pair of specs, and collects the two tools needed to repair it, recursion and substitution, in time for lesson 33.
Why THEOREM Spec => ABS!Spec still works for AB2, and why the same trick can't claim AB2 implements AB. Nothing in AB2 constrains AtoB and BtoA.
Recursive definitions
Suppose you want an operator that removes every "X" from a sequence of strings. There's no single formula for the position of each element, as there was for Remove. Define it in terms of itself on a shorter sequence, and declare first that you are doing so:
RECURSIVE RemoveX(_)
RemoveX(seq) == IF seq = <<>>
THEN <<>>
ELSE IF Head(seq) = "X"
THEN RemoveX(Tail(seq))
ELSE <<Head(seq)>> \o RemoveX(Tail(seq))
Each line applies the definition once, to a shorter sequence, until the base case stops it. Without that case the definition would never bottom out.
The _ marks one argument. If you've used a functional language, this will feel natural. Otherwise, reach for it where a program would use a loop. TLC evaluates RemoveX(<<"Tom", "X", "Dick", "Harry", "X">>) to <<"Tom", "Dick", "Harry">>.
Substitution, and when it's allowed
For this lecture only, write f WITH v <- e for f with expression e substituted for symbol v. This is not TLA+ notation. For example, (y^3 - y) WITH y <- x + 2 is (x + 2)^3 - (x + 2). Ordinary math has a basic law, which the lecture calls the Simple Substitution Law:
THEOREM (v = e) => (f = (f WITH v <- e))
It holds for declared constants and constant expressions, the only things ordinary math has. It fails for declared variables. Take f to be y', v to be y, and e to be x + 2. The law then says (y = x + 2) => (y' = (x + 2)'): if y = x + 2 holds in the first state, it holds in the second. Run 1 in the figure refutes that. Adding always gives the Temporal Substitution Law, which holds when v is a variable and e a state expression:
THEOREM [](v = e) => (f = (f WITH v <- e))
Run 1 is why the simple law fails: y = x + 2 holds in s1, but y' is 3 and (x + 2)' is 4. Run 2 satisfies [](y = x + 2), and there you may substitute anywhere, primes included.
It generalizes to several variables at once, f WITH v1 <- e1, v2 <- e2. The substitutions are simultaneous, not one after the other. You'll use this general form in lesson 33.
Predict: is the simple law true when v is a constant and e a constant expression, even with no always?
Yes. Their values don't depend on the state, so v = e is true on the first state exactly when it's true on all of them. [](v = e) says the same as v = e, and the temporal law reduces to the ordinary one.
The AB2 protocol
AB2 is AB with one change. Messages are detectably corrupted instead of lost. A corrupted message is represented by a constant Bad, assumed unequal to any real message, and the action that hurts messages replaces them in place:
Init, ASnd, and BSnd only rename the channels. ARcv needs no change beyond that: Bad isn't 0 or 1, so the test Head(BtoA2) = AVar[2] is false and A ignores it. BRcv gets a new conjunct, because Head(AtoB2)[2] means nothing when the head is Bad. Next has CorruptMsg where AB had LoseMsg.
In AB2 a damaged message still arrives, as Bad, and keeps its slot in the channel. Receiving it does nothing except consume it. The resending from lesson 30 still does the rest.
A value for Bad
The obvious model sets Bad to the string "Bad". TLC stops while evaluating the assumption:
Attempted to check equality of integer 0 with non-integer:
"Bad"
You think "Bad" differs from 0, but the semantics of TLA+ don't say so, and TLC won't guess. The answer is a model value, which TLC assumes unequal to any value you'd expect it to differ from. In a cfg file that's CONSTANT Bad = Bad, and the Toolbox has a model value option for it.
Checking AB2 against ABSpec
As in lesson 30, the model needs data values and a state constraint. The lecture uses three values and channel lengths below 4. A smaller instance shows the same thing quickly:
SPECIFICATION Spec
CONSTANT Data = {d1, d2}
CONSTANT Bad = Bad
CONSTRAINT Bound
INVARIANT TypeOK
PROPERTY HighSafety
With Bound limiting both channels to length 2, and HighSafety naming ABS!Spec in a wrapper module, TLC finds no error: 6926 states generated, 1008 distinct, depth 16.
Liveness needs something imaginary
Copy AB's FairSpec onto AB2 and check it against ABS!FairSpec. TLC reports a violation:
TLC's counterexample with Data = {d1, d2} and channels of length at most 2 (m = <<d1, 1>>; channels shown without brackets). Every ack gets corrupted before A reaches it, and BVar never changes. ARcv does keep happening, so SF_vars(ARcv) is satisfied.
Strong fairness can't help, since ARcv steps do occur. Each one just receives Bad. Lamport says he believes fairness on subactions of Next can't guarantee that any message is received before it's corrupted. So the safety spec has to change. The idea is that sending a message also decides whether it may ever be corrupted.
The real channel and its imaginary shadow, kept in separate variables: one flag per message, decided when the message is sent.
These flags are imaginary variables: not meant to be implemented, used only to state fairness. Choosing in advance doesn't change what AB2's own variables can do, so ignoring AtoBgood and BtoAgood, SpecP and Spec allow the same behaviors. Lamport's module AB2P extends AB2 this way. What follows is this course's own version, written to test the idea, and it may differ from his download. Corruption requires a false flag, and weak fairness applies to the receives and to sending a good message:
On the same bound, TLC finds no error against ABS!FairSpec and against AB2's Spec, with 4212 distinct states. Requiring only that some message keeps being sent, whether good or not, brings the violation back.
Predict: AB needed strong fairness on its receives. Why does weak fairness suffice for ARcvP and BRcvP here?
Corruption doesn't remove messages. Once a channel is non-empty, only a receive can empty it, so the receive stays continuously enabled, and there's no flicker for strong fairness to handle.
The question from the top of the page is still open: AB2 clearly behaves like AB, yet AtoB and BtoA don't exist in it. lesson 33 says what "implements" means in that case.
While you watch
This is the first part of the lecture. Run the model with the string "Bad" first, so you see the error he describes, then change to a model value.
Pause at the TypeOK line for AtoB2 when he asks you to, and read the set out loud.
He leaves AB2P for you to read. His version is the reference.
A refinement mapping says how one state stands in for another.
lesson 32 ended with AB2 behaving like AB although it has no AtoB or BtoA. Ordinary implication can't say so. The fix is small: write down how the missing variables are computed from the ones that exist. That expression is a refinement mapping, and it's the general meaning of implementation.
The lecture's example, one state at a time. AVar and BVar carry across. Each channel loses its Bad entries.
What "AB2 implements AB" means
The claim is stronger than the one you checked last lesson. AB2 doesn't just implement ABSpec. It implements the AB protocol, with each CorruptMsg step implementing a LoseMsg step. Losing a message may feel like something the environment does, not the protocol. But specs say nothing about who performs a step; that is an interpretation we put on the formula.
Here's the meaning. Take any behavior of AB2 and change each state as in the figure, deleting Bad from each channel. The result must be a behavior of AB.
One AB2 behavior through two mappings. Under RemoveBad, corrupting a message is losing it, and receiving the corrupted slot is stuttering. Under the wrong mapping, TLC's counterexample stops at State 3, since no AB step leads there.
The top half of this figure shows it on one behavior. A corrupting step maps to a LoseMsg step, since a message disappears from the mapped channel. An ARcv that consumes Bad maps to stuttering, because the mapped state doesn't change. This is the same idea as TMAbort in lesson 26.
From meaning to something checkable
To make it a formula, invent a spec SpecH whose states also contain AtoB and BtoA, always equal to the cleaned channels. Module AB2H defines it:
RemoveBad is RemoveX from last lesson, with Bad in place of "X". Here AtoB and BtoA are imaginary variables, with no effect on what the other four can do. So THEOREM SpecH => AB!Spec says just what we want. But TLC can't check it, because SpecH doesn't have the standard form of an initial formula and [][Next]_vars. You could rewrite it, and module AB2H does so as SpecHH. The lecture instead takes a longer path that teaches more.
Four equivalent theorems. The first one defines what we mean, but TLC can't check it. The last one TLC can check. Each arrow is one small justified step.
Follow the figure from the top. SpecH implies the always formula, so by the Temporal Substitution Law, AB!Spec may be replaced by its substituted version. That version no longer mentions AtoB or BtoA, so the always conjunct of SpecH has nothing left to do, and it goes. SpecH has now vanished. Only AB2!Spec remains on the left, and inside module AB2 that's plain Spec, which TLC can handle.
INSTANCE ... WITH
One problem remains: WITH so far is lecture notation, not TLA+. But the real INSTANCE statement has a WITH clause. After expanding definitions, formula Spec of AB contains only operators and AB's declared symbols, Data, AVar, BVar, AtoB, BtoA. To import it elsewhere, you give an expression for each. Omitting one means "the symbol of the same name," which is what every INSTANCE so far has done without saying so. So these lines go at the end of AB2:
RECURSIVE RemoveBad(_)
RemoveBad(seq) == IF seq = <<>>
THEN <<>>
ELSE IF Head(seq) = Bad
THEN RemoveBad(Tail(seq))
ELSE <<Head(seq)>> \o RemoveBad(Tail(seq))
AB == INSTANCE AB WITH AtoB <- RemoveBad(AtoB2),
BtoA <- RemoveBad(BtoA2)
THEOREM Spec => AB!Spec
These substitutions are the refinement mapping, and AB2 implements AB under it. Check it like any other implementation, with a model whose behavior spec is Spec and whose property is AB!Spec. With Data = {d1, d2}, Bad a model value, and channels of length at most 2, TLC finds no error: 6926 states generated, 1008 distinct, depth 16.
Predict: map AtoB <- AtoB2 and BtoA <- BtoA2, keeping the Bad slots. What does TLC say?
It reports the action property of AB violated after three states: BSnd, then CorruptMsg. That is the bottom half of the figure above. A mapped channel containing Bad changes in a way that no AB action allows, because LoseMsg removes a message and doesn't rewrite one.
A mapping that discards information fails too. Map both channels to <<>>, and TLC finds the violation in three states: BSnd, then an ARcv in which A chooses a new value while the mapped channel is empty. No AB step could do that.
What implementation means, in general
If Spec2 doesn't contain all the variables of Spec1, then Spec2 can implement Spec1 only under a refinement mapping that assigns expressions of Spec2 to the missing variables. This is the usual case. Even a variable they share may be mapped to something other than itself.
So what does it mean for a program to implement a TLA+ spec? That you could, in principle, write a spec of the program which implements the spec under a suitable mapping. In practice that spec would be far too long. But you can still explain informally how the spec's variables are represented by the program's state. Writing it down, perhaps as comments in the code, explains what the program does, and can expose errors in it.
Imaginary variables
You've now seen two uses: AtoBgood and BtoAgood to state liveness, and AtoB and BtoA to explain implementation. Adding imaginary variables to a spec means the new and old specs allow the same behaviors if you ignore those variables. They need not describe real state, they aren't meant to be implemented, and if their values can be computed from the original variables, you don't need them, as this lesson's mapping shows. But they may be necessary. As the quiz above shows, AB can implement AB2 only with added variables recording where lost messages were. They are usually called auxiliary variables, and the lecture points to the paper Auxiliary Variables in TLA+.
Extension: choosing a mapping in a real product
This section goes beyond the lecture and isn't model-checked. A document editor shows "ca". The user types "t" and immediately sees "cat". A request goes out, the server durably commits it, and an acknowledgement comes back. The draft on screen, the durable log, and what the client knows are three different states. Which belongs in the abstract contract is your first decision.
Choosing the mapping chooses the contract. With savedText mapped from the durable log, only the commit is an abstract edit. Everything else is stuttering, as with ARcv of a Bad message above.
Suppose the abstract object promises durable edits, with one variable savedText. Map it to the result of applying the durable log in order. In the figure, only the commit is an abstract edit. If the server commits but the reply is lost, a retry must not insert a second "t", so requests need identities, and the mapped text should stay "cat", not "catt". Mapping savedText to the draft instead describes a different contract, speculative display. A later rejection could then remove the "t", which a durable-only abstract spec forbids. That's a failed mapping, not necessarily an editor bug.
Linearizability is a related but specific contract, and a generic refinement check doesn't give it to you automatically. It gives each completed operation one point between its invocation and response, with a legal sequential order that respects the real-time order of non-overlapping operations. To check for it, the abstract interface must include invocations, responses, and the treatment of pending operations. With several editors, refining to one sequential text object promises more than replicas eventually converging.
Transfer exercise: an editor shows "Saved" before the server commits. Which property exposes the problem?
Represent the status change as an acknowledgement event and require that each acknowledged operation is durable under the modeled failures. Crash after showing "Saved" and before committing. If recovery loses the edit, the client-visible durability contract fails, however good the optimistic draft looked.
While you watch
Lamport warns the path is long and may not always seem to be heading anywhere. The chain figure above is the map. Stop at each step and find your place on it.
He writes WITH with a left arrow in lecture notation, then shows the real INSTANCE form. Notice when the first becomes the second.
This is the last lecture. His closing list of what's left (more TLA+, Toolbox features, PlusCal) is where the rest of this course goes, starting with lesson 36. The checks with wrong mappings and the editor extension are additions.
Four refinement problems. Each gives you an implementation with more machinery than its spec, such as shards, files on disk, replicas or an optimistic screen. You write the refinement mapping, check it with TLC, and decide what a failed check means. You'll use RECURSIVE and INSTANCE … WITH from lecture 10. The last problem adds the message sets of lecture 6 and the fairness of lecture 9.
Every module below was checked with TLC exactly as shown. To check a refinement, do what lesson 33 did: put the implementation's Spec under SPECIFICATION, and the instantiated abstract spec under PROPERTY. Keep the abstract module in the same folder, because INSTANCE looks for it there. Counts like "distinct states" only match if your copy is identical.
A social app keeps the like count of each post in one database row. A popular post turns that row into a hot spot: every like is an update of the same row, and concurrent updates of one row wait for each other. The team splits the counter into shards. Each like increments one shard, chosen at random, and the page shows the sum of the shards. The product promise is unchanged: the number on the page goes up by one per like and never goes down.
Add a recursive operator SumOver(f, S), the sum of f[s] over all s in a finite set S. Then add the refinement mapping as an instance C of PSl10_Counter, define CounterSpec == C!Spec, and run the model above.
To keep reads cheap, a job periodically folds a shard into a stored base value: it adds the shard's count to base and resets the shard to 0. Add a base variable and a Fold(s) action, map count to base plus the shard sum, and check again. You'll need a state constraint, because shards can now refill forever.
The shards are moved to an in-memory cache without persistence. Model a cache restart as Restart(s), which sets one shard back to 0. What does TLC report?
A teammate maps count <- shard[Home], where Home is the shard their app server writes to. TLC finds no error. Why is that result worthless as evidence for the product promise?
A behavior of PSl10_ShardedRestart. The first three steps map to Inc. The restart lowers the sum, and no step of the counter spec can lower it.
Hint
Write SumOver like RemoveX in lesson 32: an empty set sums to 0, and otherwise pick one element with CHOOSE, add its value, and recurse on the rest. For the restart, ask what happens to the mapped count, and whether any step of PSl10_Counter can do that.
Solution
(a) The completed module. TLC finds no error, with 55 states generated and 27 distinct states.
---------------- MODULE PSl10_Sharded ----------------
EXTENDS Naturals
CONSTANTS Shards, MaxPerShard
VARIABLE shard
Init == shard = [s \in Shards |-> 0]
Inc(s) == /\ shard[s] < MaxPerShard
/\ shard' = [shard EXCEPT ![s] = shard[s] + 1]
Next == \E s \in Shards : Inc(s)
Spec == Init /\ [][Next]_shard
RECURSIVE SumOver(_, _)
SumOver(f, S) == IF S = {} THEN 0
ELSE LET s == CHOOSE x \in S : TRUE
IN f[s] + SumOver(f, S \ {s})
Total == SumOver(shard, Shards)
C == INSTANCE PSl10_Counter WITH count <- Total
THEOREM Spec => C!Spec
CounterSpec == C!Spec
======================================================
The cfg line CHECK_DEADLOCK FALSE matters here: once every shard reaches MaxPerShard no step is enabled, which is the end of the model, not a bug. CHOOSE is safe in SumOver because addition doesn't care which element comes first. Every Inc(s) raises the sum by exactly one, so it is an Inc step of the counter.
(b) With a base value and a fold:
---------------- MODULE PSl10_ShardedFold ----------------
EXTENDS Naturals
CONSTANTS Shards, MaxPerShard
VARIABLES shard, base
vars == <<shard, base>>
Init == /\ shard = [s \in Shards |-> 0]
/\ base = 0
Inc(s) == /\ shard[s] < MaxPerShard
/\ shard' = [shard EXCEPT ![s] = shard[s] + 1]
/\ UNCHANGED base
Fold(s) == /\ shard[s] > 0
/\ base' = base + shard[s]
/\ shard' = [shard EXCEPT ![s] = 0]
Next == \E s \in Shards : Inc(s) \/ Fold(s)
Spec == Init /\ [][Next]_vars
RECURSIVE SumOver(_, _)
SumOver(f, S) == IF S = {} THEN 0
ELSE LET s == CHOOSE x \in S : TRUE
IN f[s] + SumOver(f, S \ {s})
Total == base + SumOver(shard, Shards)
Bound == Total <= 4
C == INSTANCE PSl10_Counter WITH count <- Total
CounterSpec == C!Spec
==========================================================
TLC finds no error: 220 states generated, 55 distinct. A fold changes the implementation's state but not the mapped count, so it maps to stuttering, as the quiz says. This is the same move as TMAbort in lesson 26 and as the ARcv of a corrupted message in lesson 33: internal work is invisible in the abstract spec.
(c) Add Restart(s) == shard[s] > 0 /\ shard' = [shard EXCEPT ![s] = 0] as a disjunct of Next (module PSl10_ShardedRestart). TLC reports that the action property of PSl10_Counter is violated, with three states: shards all 0; Inc(s1), so the count is 1; Restart(s1), so the count is 0 again. The figure shows a longer behavior of the same module. The count fell, and the abstract spec only allows count' = count + 1 or no change. The product consequence is that a like disappears from the page. A cache restart that forgets data is exactly a step the contract forbids, so the shards need persistence, or a recovery step that restores them.
(d) With Home = s1, TLC finds no error (27 distinct states). Every step either raises shard[s1] by one or leaves it alone, so every step is an Inc or a stutter. The check is correct; the claim is just weak. Under this mapping the abstract "count" ignores two thirds of the likes. A refinement theorem is only as meaningful as its mapping: the mapping says what the implementation's state means, and here it means the wrong thing. TLC can tell you a mapping works, but not that it is the one your users read.
Storage engines such as LevelDB and RocksDB are log-structured merge trees. A write goes into an in-memory table, the memtable. When the memtable is big enough, it is flushed to disk as an immutable file. Compaction later merges files, keeping the newer value of each key. A read checks the memtable first, then the files from newest to oldest. The application sees none of this. It sees a map from keys to values:
---------------- MODULE PSl10_KV ----------------
CONSTANTS Keys, Vals, NoVal
VARIABLE store
Init == store = [k \in Keys |-> NoVal]
Put(k, v) == store' = [store EXCEPT ![k] = v]
Next == \E k \in Keys, v \in Vals : Put(k, v)
Spec == Init /\ [][Next]_store
=================================================
The engine, with tables[1] the oldest file and at most MaxTables files:
Write Get(k), the value a read returns, using a recursive helper that searches the files from newest to oldest. Then add the mapping KV == INSTANCE PSl10_KV WITH store <- … and KVSpec == KV!Spec, and check it.
Which actions of the engine map to stuttering? Say why for each.
A refactoring swaps the arguments of Merge in Compact, so the older file wins. Check the buggy engine with Keys = {k1, k2}, and then with Keys = {k1}.
Explain the difference between the two runs. What does it say about how strong PSl10_KV is as a contract?
Five selected states from the eight-state trace. Each flush moves data without changing the mapped store, and the buggy compaction rolls back two keys in one step.
Hint
Give the helper the index of the file to look at: Find(k, i) looks in tables[i] and, if the key isn't there, in tables[i - 1]. Start it at Len(tables); index 0 means "not found". For (d), ask which steps of PSl10_KV could explain a one-key rollback.
Solution
(a) The added definitions:
RECURSIVE Find(_, _)
Find(k, i) == IF i = 0 THEN NoVal
ELSE IF tables[i][k] # NoVal THEN tables[i][k]
ELSE Find(k, i - 1)
Get(k) == IF mem[k] # NoVal THEN mem[k] ELSE Find(k, Len(tables))
KV == INSTANCE PSl10_KV WITH store <- [k \in Keys |-> Get(k)]
THEOREM Spec => KV!Spec
KVSpec == KV!Spec
TLC finds no error: 3277 states generated, 657 distinct.
(b) Flush and Compact map to stuttering. A flush moves the memtable into the newest file, and a read finds the same values there, because nothing newer exists. A correct compaction replaces the two oldest files by one in which the newer value of each key wins, which is what a read of those two files returned anyway. So does a Put of the value a read already returns.
(c) With two keys, TLC reports the action property of PSl10_KV violated after eight states. The figure shows the important ones: Put(k1, v1), Put(k2, v1), Flush, Put(k1, v2), Put(k2, v2), Flush, and then Compact, which leaves only <<(k1 :> v1 @@ k2 :> v1)>>. The mapped store went from both keys at v2 to both at v1 in one step. Each Put changes one key, so no step of the map spec can do that.
(d) With one key, TLC finds no error, in 21 distinct states. The rollback of k1 from v2 to v1 is the same pair of mapped states as Put(k1, v1), and the map spec lets anyone put any value at any time. The bug was real in both runs; the refinement check could only see it when no abstract step explained it. PSl10_KV says nothing about who writes or which value, so data loss that looks like a write passes. To catch it with one key, put the client into the model, for example a variable recording the last value the client wrote, and require each mapped change to equal it. A weak abstract spec makes refinement easy to pass, and so says less.
In Raft-style replication, clients send commands to a leader, which appends them to its log and copies them to followers. An entry counts as committed once a majority of servers store it, and the leader's commit index says how far that goes. The guarantee to clients is an append-only log: committed entries appear one after another and never change.
The model has one fixed leader and two followers, so a majority is two of three. Its mapping says the abstract log is the leader's log up to the commit index:
---------------- MODULE PSl10_RLog ----------------
EXTENDS Naturals, Sequences, FiniteSets
CONSTANTS Vals, Followers, MaxLen
VARIABLES llog, flog, commit
vars == <<llog, flog, commit>>
Init == /\ llog = <<>> \* the leader's log
/\ flog = [f \in Followers |-> <<>>] \* each follower's log
/\ commit = 0 \* the leader's commit index
Request(v) == /\ Len(llog) < MaxLen
/\ llog' = Append(llog, v)
/\ UNCHANGED <<flog, commit>>
Replicate(f) == /\ Len(flog[f]) < Len(llog)
/\ flog' = [flog EXCEPT ![f] =
Append(flog[f], llog[Len(flog[f]) + 1])]
/\ UNCHANGED <<llog, commit>>
\* Entry n is on a majority: the leader plus at least half the followers.
OnMajority(n) == 2 * (1 + Cardinality({f \in Followers : Len(flog[f]) >= n}))
> 1 + Cardinality(Followers)
AdvanceCommit == /\ \E n \in (commit + 1)..Len(llog) :
/\ OnMajority(n)
/\ commit' = n
/\ UNCHANGED <<llog, flog>>
Next == \/ \E v \in Vals : Request(v)
\/ \E f \in Followers : Replicate(f)
\/ AdvanceCommit
Spec == Init /\ [][Next]_vars
Committed == [i \in 1..commit |-> llog[i]]
L == INSTANCE PSl10_Log WITH log <- Committed
LogSpec == L!Spec
===================================================
Run it. TLC reports a violation. Is any committed entry lost or changed in the trace? Say exactly which abstract step is missing.
Fix it in two ways: change AdvanceCommit to move the index by one, and, separately, keep the implementation and weaken the abstract spec so one step may append several entries. Check both.
Add a failover step: a new leader that holds only the committed prefix takes over, and uncommitted entries are discarded everywhere. (Real Raft is subtler; this is the part that matters here.) Check the mapping again, and then the mapping log <- llog.
TLC's shortest counterexample. Replication steps map to stuttering. The jump of the commit index from 0 to 2 would need two abstract appends in one step.
Hint
A refinement maps each implementation step to one abstract step or to a stutter. For the weaker spec, say "the new log is longer and keeps every old entry" with a quantifier over 1..Len(log), and use log' \in Seq(Vals) rather than an existential over Seq(Vals), which TLC can't enumerate.
Solution
(a) TLC's shortest trace has six states, shown in the figure: two Request(a) steps, two Replicate(f1) steps, and AdvanceCommit setting commit from 0 to 2. Both entries are on a majority, the leader and f1, so committing them is safe, and nothing is lost or changed. But the mapped log went from <<>> to <<a, a>> in one step, and PSl10_Log appends one entry per step. Refinement doesn't let one implementation step stand for two abstract steps. The implementation isn't wrong; the abstract spec's steps are finer than the implementation's.
(b) First fix, in the implementation (module PSl10_RLogOne):
Second fix, in the spec. The model keeps the jumping AdvanceCommit and maps to this module instead (PSl10_RLogBatch):
---------------- MODULE PSl10_LogBatch ----------------
EXTENDS Naturals, Sequences
CONSTANT Vals
VARIABLE log
Init == log = <<>>
\* One step may append one or more entries; earlier entries never change.
Extend == /\ log' \in Seq(Vals)
/\ Len(log') > Len(log)
/\ \A i \in 1..Len(log) : log'[i] = log[i]
Spec == Init /\ [][Extend]_log
=======================================================
TLC finds no error with either: 1197 states generated and 503 distinct for the one-at-a-time commit, 1425 and 503 for the batch spec. Which fix is right depends on what clients can observe. If a client can watch the committed log grow, the batch spec is honest about what it will see. If the abstract spec is shared with other components that assume one entry at a time, change the implementation.
(c) The failover step, together with the one-at-a-time commit (module PSl10_RLogFix):
With the Committed mapping, TLC finds no error: 1617 states generated, 503 distinct. Failover discards only entries past commit, so the mapped log doesn't change, and it is a stutter. With log <- llog (module PSl10_RLogLeader), TLC reports a violation in three states: Request(a) makes the leader's log <<a>>, and Failover empties it. Without failover, log <- llog passes too (module PSl10_RLogOneLeader, 503 distinct states), because a single leader's log only grows. That's the real reason the commit index exists: it marks the part of the log that survives a change of leader.
A design system ships a tag input, used to put labels on issues. When the user adds a tag, it appears at once, greyed out as pending, and a request goes to the server. If the server accepts, the tag turns solid. If it rejects, for example because the user may not use that label, the tag disappears and a toast explains why. The server's own contract is simple: an issue's tags are only ever added. Messages are a set that only grows, as in lesson 19, so the model allows any delay, reordering and duplicate delivery.
Check the three mappings: what the user sees (ShownRefines), the solid tags (ConfirmedRefines), and the server's tags (ServerRefines). Which ones hold? For any that fails, describe TLC's trace as the user would see it.
Is the failing one a bug in the component? Say which abstract spec the screen does refine, in one sentence.
Problem set 9 asked whether every request is eventually decided. Ask it here: check Settles with Spec instead of FairSpec, and explain the result. Then replace Fairness by two conditions: weak fairness of "the server answers some tag" and of "the client processes some reply". Is that enough here? Would it be enough for a lock that two processes take over and over?
Explain why UserAdd needs the guard ~Sent(t). What could an old rejected message do if the user re-added the same tag?
The rejected path. The user saw t1 (pending), then saw it removed. The server never stored it, so the server's list never shrank.
Hint
Run each mapping in its own model with one PROPERTY line. For (c), the aggregate condition only forces some enabled step. Ask whether any tag can be passed over forever when each tag needs just one answer and one reply.
Solution
(a) With the cfg as given, TLC finds no error: ConfirmedRefines, ServerRefines, Settles and Converges all hold, as do TypeOK and ConfirmedOnServer, in 36 distinct states. With PROPERTY ShownRefines, TLC reports the action property of PSl10_TagSet violated in four states: UserAdd(t1), ServerReject(t1), ClientRollback(t1). The user typed t1, saw it greyed out, then saw it vanish, as in the figure. The last step removes t1 from Shown, which no Add step can do.
(b) It's not a bug. It is the speculative-display contract from the editor example in lesson 33: the screen shows a guess, and a guess can be withdrawn. The screen refines "tags are added, and pending ones may be withdrawn", a different spec with a Withdraw action. What must not happen is a solid tag disappearing, and ConfirmedRefines together with ConfirmedOnServer rules that out. The design-system rule that follows is "only solid tags are promises". So pending tags need a visibly different style, and anything that copies the list, such as an export, should read confirmed.
(c) With SPECIFICATION Spec, TLC reports Settles violated. Its counterexample has both tags accepted by the server, t2's reply received, and then stuttering forever with t1 still pending, although the ok for t1 is in msgs. TLC also warns that the stuttering counterexample may be caused by a missing fairness constraint. Without fairness, nothing requires the client to process a reply. FairSpec asks for weak fairness of "answer t" and "process the reply to t" for each tag t. That suffices: once t's request is in msgs, answering it stays enabled until it happens, and so does processing the reply while t is pending.
The aggregate version also suffices here (module PSl10_TagListAgg):
With SPECIFICATION AggSpec, TLC finds that Settles and Converges hold, in the same 36 states. Each tag is answered once and its reply processed once, and each such step disables itself. So "some answer happens" can only pick a different tag each time, and with finitely many tags every one gets its turn. A lock is different: if B can acquire, release and acquire again forever, "some process acquires" is satisfied by B alone, and A may wait forever. Per-item fairness is still the safer habit, because it keeps working if you later add retries that make an item's steps repeat.
(d) Messages are never removed, so after a rejection [type |-> "rejected", tag |-> t1] stays in msgs. If the user could add t1 again, ClientRollback(t1) would be enabled at once by the old message, and the new attempt would be rolled back before the server saw it. This is the stale-response problem: replies need to identify the request they answer, not just the tag. A real component would put a request id in each message, and the guard would compare ids.
Beyond the lectures I: Concurrency
Find the interleaving that breaks the design.
In lesson 12, one action was one indivisible step, and in lesson 18 TLC tried the resource managers’ steps in every order. Here you use both ideas on purpose: you decide where one step ends, and TLC finds the order that breaks the design.
The split model, drawn from its 9 reachable states. Each node reads: A’s stage, B’s stage, tickets left. An edge is one step by the buyer named on it. The red edges start at the state where both buyers hold a stale check.
An interleaving is one order in which independent actors’ steps can happen. TLC does not simulate CPU instructions. It explores whichever steps you wrote, so choose the step boundaries from the guarantee your system actually has. The diagram shows why that matters: two buyers, one ticket, and a check that happens separately from the reservation. If A or B reserves before the other checks, that path dead-ends safely, as at the top and bottom. If both check first, the middle node, then the sale goes through twice.
Start with the guarantee you want
This module makes checking and updating one step, so Reserve is one edge in the graph.
TLC finds 3 distinct states and no error. The diagram below is all of them.
The atomic model has 3 reachable states. After either reservation the other buyer’s guard is false, so there is no path to a double sale.
This abstraction promises nothing about a database. It describes the guarantee a design must provide. Whether a real multi-step implementation provides it is the question from lesson 26.
Now split the step
Add a per-buyer stage. Check reads the stock and remembers the answer in the stage. Reserve relies on that memory and does not look again.
The invariant is unchanged. TLC reports NoOverselling violated after 4 steps: both buyers check, then both reserve, leaving remaining = -1 and booked = {A, B}. With the invariant removed, the whole graph has the 9 states in the first diagram.
Predict: if you add remaining > 0 back to Reserve, what happens to the split model?
The second reservation is disabled, so the double sale goes away. In doing so you moved the real decision back into one atomic step, because the test and the update now happen together in Reserve. The earlier Check no longer decides anything.
Check before committing
Buyer A
Inventory
Buyer B
The lab replays one path through each model. It is an educational replay, not TLC.
Exercise: name an implementation guarantee needed by Reserve.
The availability test and the successful update must form one indivisible decision. A conditional update can provide this if the database enforces the required concurrency semantics and the application checks whether it succeeded. A transaction boundary alone is not a proof: isolation and retries matter.
Concrete architecture: a shopping cart is not a reservation
Suppose a storefront has one camera left. Ada adds it to a cart, and Ben adds it to another cart. That is not overselling if carts only express interest. Two carts are allowed; two successful reservations of the one unit are not. Naming both concepts “selected” makes the design harder to reason about, so checkout must be the step that decides.
Represent a reservation as a durable record keyed by request ID. On success, the stock count falls and the reservation appears in the same abstract step. Cancelling is the same move in reverse:
Cancel(b) == \* also models expiry of the hold
/\ b \in held
/\ held' = held \ {b}
/\ remaining' = remaining + 1
/\ UNCHANGED <<confirmed, paying>>
The guard blocks cancellation when no hold exists, and the two updates move the unit back. Cancelling the same hold twice is disabled, so stock cannot increase twice.
Real products add expiry and payment. Then ask whether a delayed payment callback can confirm a hold that has already expired. The TicketHold model tests this with Reserve, StartPayment, Cancel (which also stands for expiry) and LatePayment:
LatePayment(b) ==
/\ b \in paying
/\ b \in held \* delete this line to get the bug
/\ confirmed' = confirmed \cup {b}
/\ held' = held \ {b}
/\ paying' = paying \ {b}
/\ UNCHANGED remaining
With the guard b \in held, TLC finds 16 states and OnePromise holds. Delete that line and it fails in the 5 steps shown below.
TLC’s 5-step trace for the hold bug. In the last column, B holds the ticket and A is confirmed for it.
Look at the fourth step: A’s hold is gone and the ticket is back on sale, but A’s payment is still arriving. Confirmation checked only that a payment had started. Rechecking the hold closes this path. If the same buyer can reserve again after expiry, buyer identity is not enough, because an old callback would match the new hold. You would then need a reservation identity or generation.
Exercise: does adding Cancel preserve the property “once booked, always booked”?
No, and that may be intended. Conservation can still hold while bookings are removed. Choose properties that match the lifecycle: “at most one live reservation” is different from “a buyer never loses a reservation.”
Beyond the lectures I: Concurrency
Write an algorithm; inspect its translation.
In lesson 5 you turned a small program into a state machine by hand, with a control variable pc saying what runs next. PlusCal does that translation for you. You still decide what one step is, as you just did in lesson 35.
TicketPC has 5 reachable states. Each node shows both pc values, then stock and bookings. On the right-hand edges the second buyer’s if is false: only its pc moves.
PlusCal is an algorithm language written inside a comment in a TLA+ module. Its translator generates ordinary TLA+ after the comment: Init, Next, Spec, and a pc function for processes. The language is convenient for algorithms that read as sequential steps. It does not replace the state machine, and the diagram above is the state machine you get from the source below.
---------------- MODULE TicketPC ----------------
EXTENDS Integers, FiniteSets
CONSTANT Buyers
(*--algorithm Ticket
variables remaining = 1, booked = {};
define
Safe == Cardinality(booked) <= 1
end define;
process Buyer \in Buyers
begin
Reserve:
if remaining > 0 then
remaining := remaining - 1;
booked := booked \cup {self};
end if;
end process;
end algorithm; *)
=================================================
That is the source before translation. To translate, run java -cp tla2tools.jar pcal.trans -nocfg TicketPC.tla or use your editor’s translate command. -nocfg keeps the translator from writing its own config file over yours. The generated text appears between translation markers before the closing line. TLC then finds 5 distinct states and no error.
self identifies the current process. Each label starts an atomic step, and everything up to the next label runs in that one step. So the if and both assignments under Reserve are one edge in the diagram. Inside a step, := runs in order, so a later statement sees an earlier statement’s value. Do not confuse this with the simultaneous primed equations in raw TLA+.
Move a label, change the model
Add one label, Take:, in front of the decrement, and rename the first label Check. The translator now produces two actions for each buyer. This is its real output for that change:
One buyer’s control flow after the split. These are the values of pc[self], and each arrow is one translated action. Between Check and Take, the other buyer can run.
The diagram is pc[self] for one buyer. You could have written this translation yourself: it is the same pattern as lesson 5. Between the two actions, the other buyer can run, so TLC now reports Safe violated after 4 steps, the same race as InventorySplit. When reading an error trace, look at pc first. It tells you which labeled step each process is about to run.
Three more statements cover most algorithms. await P blocks a step until P holds, but does not promise P ever will. either … or … is a choice among alternatives. with x \in S do … picks a value nondeterministically. Each of these translates into guards and existential quantifiers you already know.
Predict: where does the deadlock go when both buyers finish?
Nowhere. The translator adds a Terminating action that stutters once every process is at Done, so TLC does not report termination as deadlock. A process stuck on an await is still reported.
Worked interleaving: two event handlers increment a count
Consider two workers that each read a shared notification count, compute one more, and write it back. In a single JavaScript event loop, a synchronous increment has no await inside it. But reading the value, awaiting remote work, and later writing the captured value does let another handler intervene. So it gets two labels, and the captured value becomes a per-process variable.
---------------- MODULE LostUpdate ----------------
EXTENDS Naturals
CONSTANT Workers
(*--algorithm LostUpdate
variables count = 0;
define
AllDone == \A w \in Workers: pc[w] = "Done"
NoLostUpdate == AllDone => count = 2
end define;
process Worker \in Workers
variable local = 0;
begin
Read:
local := count;
Write:
count := local + 1;
end process;
end algorithm; *)
===================================================
The 13 reachable states of the lost update model. Nodes show the two pc values; edges name the worker that stepped. The red edges leave the one state where both workers hold a read of 0.
Read the graph from the left. If one worker gets both of its steps in before the other reads, the top and bottom paths, the count reaches 2. If both read first, the middle node, both write 1. TLC finds the 13 states and reports NoLostUpdate violated.
TLC’s trace. Two increments completed and count is 1.
For an atomic abstraction, replace the two labels with one, Increment: count := count + 1;. TLC then finds 4 states and no error. This is correct only if the actual operation has that guarantee, such as a synchronous local update or a suitable atomic database update.
To find a real async boundary, annotate the implementation: what is captured before an await, what can change during the wait, and what is rechecked after it? Captured values become local variables. Each interaction point becomes a label. A familiar callback race is now a state machine.
Predict: will making the whole process fair repair the lost update?
No. PlusCal’s fair process asks for the fairness from lesson 29. With it, TLC confirms <>AllDone: both workers do finish. But NoLostUpdate still fails in the same 13-state graph. Fairness rules out stopping early. It removes no order of steps, and this is a safety failure.
lesson 30 used sequences, with Append and Tail, to model message channels. Give a sequence a capacity and you have a queue, a first architecture with ordering, backpressure and boundary cases but no complicated network.
All 7 reachable queues. Enqueue appends on the right and dequeue removes from the left, so ⟨A, B⟩ goes to ⟨B⟩ and ⟨B, A⟩ goes to ⟨A⟩. Those two edges are what FIFO means.
Here, duplicate values are distinct entries, since q is a sequence. TLC finds 7 distinct states and no error, and they are the 7 nodes above: 1 + 2 + 4. Seq(Values) contains sequences of every finite length, but the capacity guard bounds the reachable ones. The diagram also shows the two boundaries: from a length-2 node only dequeue leaves, and from ⟨⟩ only enqueue. Capacity blocks insertion, and the empty queue blocks removal.
TypeOK does not say first-in, first-out
Nothing in this module would notice a queue that hands out the wrong item, because it has no output. In the diagram, swap the targets of the two middle deq edges and TypeOK still holds. To state the contract, record what went in and what came out. Bound the history so the state space stays finite.
---------------- MODULE FIFOOrder ----------------
EXTENDS Naturals, Sequences
CONSTANTS Values, Capacity, MaxSends
VARIABLES q, sent, received
vars == <<q, sent, received>>
Init == q = <<>> /\ sent = <<>> /\ received = <<>>
Enqueue(v) == /\ Len(q) < Capacity
/\ Len(sent) < MaxSends
/\ q' = Append(q,v)
/\ sent' = Append(sent,v)
/\ UNCHANGED received
Dequeue == /\ Len(q) > 0
/\ received' = Append(received, Head(q))
/\ q' = Tail(q)
/\ UNCHANGED sent
Next == (\E v \in Values: Enqueue(v)) \/ Dequeue
Spec == Init /\ [][Next]_vars
TypeOK == /\ q \in Seq(Values)
/\ Len(q) <= Capacity
InOrder == received \o q = sent
===================================================
InOrder says everything sent is either received already or still queued, in the same order. The operator \o is sequence concatenation. This is close in spirit to the refinement mappings of lesson 33: it relates internal state to what an outside observer can see. TLC finds 41 distinct states and no error.
Predict: make Dequeue take the last item instead of the first. Which invariant fails?
Only InOrder. With TypeOK alone, the mutated module passes with 69 distinct states, because length and element types are still correct. With InOrder, TLC reports a violation after 3 steps, shown below.
The correct dequeue on top, and on the bottom TLC’s 3-step trace of the one that removes the last item. Both keep the same queue length.
Worked architecture: upload processing
A photo app accepts uploads A and B, then generates thumbnails in the background. Give each upload an immutable job ID. The user-visible contract is that accepted jobs do not disappear. FIFO ordering is a separate scheduling promise. A job moving from the waiting queue to a worker must not be mistaken for a completed upload.
One job’s lifecycle. Every solid edge moves it from one place to exactly one other. The dashed edge is the crash that breaks ownership.
This comes from the complete UploadJobs module with Jobs = {A, B}, which also has Accept and Finish. Claim removes the head and records it as active in one step, and TLC finds 17 distinct states with ExactlyOnePlace holding. The disjointness lines matter: a count alone could hide one missing job and one duplicate.
Now try the bad implementation, the dashed edge. A is removed from waiting and the worker crashes before recording it as active:
TLC reports the violation in 2 steps: Accept(A), then the crash, leaving accepted = {A} and A nowhere else. A durable claim, or a visibility protocol that permits redelivery, changes the model so this edge no longer exists.
Do not combine “FIFO” with “completion order” by accident. Two workers can claim A before B while B’s thumbnail finishes first, because Finish takes any active job. If ordered completion is required, add a publication barrier rather than asserting an order the architecture cannot provide.
Predict: the worker writes A’s thumbnail and crashes before acknowledging A. Where should A go?
Redelivery is reasonable if processing is idempotent or detects the existing result by job ID. The queue may deliver A again; the user-visible result should still be recorded once. Model claim attempts separately from logical upload identities.
Beyond the lectures I: Concurrency
Separate exclusive access from eventual access.
lesson 29 separated safety from liveness, and lesson 30 introduced strong fairness. A lock needs all of it: no two owners at once, and waiters eventually served. One can hold without the other, and the second depends on which fairness you assume.
All 8 reachable states. Columns are A’s stage, rows are B’s. Both critical is the empty corner: no edge goes there. The red cycle is the starvation TLC finds: B keeps winning while A waits.
Begin with an abstract owner variable. Acquire assumes an atomic primitive that claims an unowned lock.
With Processes = {A, B}, TLC finds 8 distinct states and both safety invariants hold on Spec. Those are the grid’s 8 nodes. The corner where both are critical has no incoming edge, because Acquire requires owner = NoOwner. The useful invariant is the relation OwnerAgrees: a process in the critical section must be the owner.
Now the liveness question
Safety says nothing about the red cycle. A waits; B requests, acquires and releases; B requests again. NoStarvation uses leads-to from lesson 29, so it asks about every waiter. Here are TLC’s answers:
Specification
Assumption added
NoStarvation
SpecAggregate
Weak fairness of “some process acquires”
Violated
SpecWF
Weak fairness of each process’s Acquire
Violated
SpecSF
Strong fairness of each process’s Acquire
Holds
Predict: why is per-process weak fairness not enough here?
Weak fairness only forces an action that stays enabled continuously. On the red cycle, Acquire(A) is enabled in “A wait, B wait” but disabled in “A wait, B crit”, so it is never continuously enabled and A can be skipped forever. Strong fairness also forces an action that is enabled again and again, which is the case here.
Strong fairness here is an assumption about the lock. It does not build anything. A real system earns it with a queueing discipline, or with an algorithm that does the work itself.
Without the primitive
Suppose the lock is just a shared value, checked in one step and written in the next. This is Look and Take in place of Acquire:
TLC’s trace when the check and the set are separate steps. The last column has two processes in the critical section.
It is the lesson 35 race again, and TLC reports it after 4 steps. Peterson’s algorithm gets mutual exclusion with only single reads and writes, using a flag for each process and a shared turn. Written in PlusCal from lesson 36:
---------------- MODULE Peterson ----------------
EXTENDS Integers
(*--algorithm Peterson
variables flag = [p \in {0, 1} |-> FALSE], turn = 0;
define
MutualExclusion == ~(pc[0] = "cs" /\ pc[1] = "cs")
NoStarvation == \A p \in {0, 1}: (pc[p] = "wait") ~> (pc[p] = "cs")
end define;
fair process P \in {0, 1}
begin
ncs: while TRUE do
setf: flag[self] := TRUE;
sett: turn := 1 - self;
wait: await ~flag[1 - self] \/ turn = self;
cs: skip;
exit: flag[self] := FALSE;
end while;
end process;
end algorithm; *)
=================================================
TLC finds 42 distinct states; MutualExclusion holds, and NoStarvation holds with just the weak fairness of fair process. The strong fairness that the abstract lock had to assume is unnecessary here, because turn stops one process winning forever. The order of the writes matters. Swap the setf and sett steps and TLC reports a violation after 8 steps with both processes at cs.
Worked architecture: concurrent checkout
Two browser requests try to reserve the final concert seat. Request A acquires the lock, reads stock = 1, and pauses. Request B arrives. A lock contract must disable B’s Acquire until A releases, and must not merely discourage it by convention.
The critical section includes the decision and the update. Locking only the read would leave the reservation race open.
The guard on owner proves nothing about writes that bypass the protocol. In the diagram every arrow to Stock comes from whoever holds the lock, and every stock-changing action in your system must obey that rule.
Now put A and B on different application servers. A process-local mutex on server 1 does not exclude server 2. Represent that as two owner variables and both requests can enter. Either put ownership in a shared authority with the necessary atomic semantics, or use a storage operation that directly enforces the inventory constraint. The model should describe the shared resource you actually use.
The failure model comes next. If the owner crashes, owner stays set and everyone waits forever. Clearing it on a timeout is unsafe if the old process can still reach the resource, because a paused process is not a dead one. lesson 46 takes this up with leases and fencing tokens.
Predict: can we recover from A crashing by unconditionally clearing owner?
Only under assumptions that ensure A cannot continue writing under its old authority. A delayed or paused process is not necessarily dead. Model the resumed write explicitly; otherwise the recovery action may conceal the violation.
Four concurrency problems. In each one the bug or the fix is a step boundary: a statement that is or isn't atomic, a check separated from its write, a counter published before its data, a lock that expires. You'll write PlusCal, read traces by their pc values, state a queue contract as a refinement, and ask the fairness questions of lecture 9 about a lock.
PlusCal modules are shown as you write them, before translation. Translate each one with java -cp tla2tools.jar pcal.trans -nocfg File.tla or your editor's command, then run TLC. Every count below is from the translated module, run exactly as shown.
A payments service credits refunds to a wallet stored in Postgres. The handler reads the balance, adds the refund in application code, and writes the result back:
SELECT balance FROM accounts WHERE id = 1; -- returns 100
UPDATE accounts SET balance = 110 WHERE id = 1; -- 100 + 10, computed in the app
A customer returns two items and gets two refunds of 10, handled by two requests at the same moment. Support finds the wallet at 110 instead of 120. Each SQL statement is atomic on its own, so each becomes one labeled step, and the value carried between them becomes a process variable:
---------------- MODULE PSb1_Wallet ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Clients
(*--algorithm Wallet
variables balance = 100;
define
AllDone == \A c \in Clients : pc[c] = "Done"
NoLostUpdate == AllDone => balance = 100 + 10 * Cardinality(Clients)
end define;
process Refund \in Clients
variable local = 0;
begin
Select: \* SELECT balance FROM accounts WHERE id = 1
local := balance;
Update: \* UPDATE accounts SET balance = $1 WHERE id = 1, with $1 = local + 10
balance := local + 10;
end process;
end algorithm; *)
====================================================
Translate and run it. Write down TLC's trace as a list of steps, and say at which step the refund was lost.
Replace the two statements by one, UPDATE accounts SET balance = balance + 10 WHERE id = 1. Write it as one label and check it. Why is one label an honest model of that statement in Postgres?
Keep two statements, but read with SELECT balance FROM accounts WHERE id = 1 FOR UPDATE, which locks the row until the transaction ends. Model the row lock with a variable holder and a Commit label that releases it. Check it with two clients and with three.
TLC's five-state trace. The two Select steps both happen before either Update, so the second write overwrites the first with the same stale sum.
Hint
For (c), put await holder = "none", holder := self and the read under one label, since SELECT … FOR UPDATE both waits for the lock and returns the row. A label starts a new atomic step, as in lesson 36, so the waiting, locking and reading must not be split.
Solution
(a) TLC reports NoLostUpdate violated after five states, shown in the figure: Select(A), Select(B), Update(A), Update(B). The refund is lost at the second Select, when B reads a balance that A is about to change. The write that makes it visible comes two steps later. This is the lesson 36LostUpdate race, with SQL statements as the steps. Without the invariant, the full graph has 13 distinct states.
(b) One label:
---------------- MODULE PSb1_WalletAtomic ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Clients
(*--algorithm WalletAtomic
variables balance = 100;
define
AllDone == \A c \in Clients : pc[c] = "Done"
NoLostUpdate == AllDone => balance = 100 + 10 * Cardinality(Clients)
end define;
process Refund \in Clients
begin
Update: \* UPDATE accounts SET balance = balance + 10 WHERE id = 1
balance := balance + 10;
end process;
end algorithm; *)
==========================================================
TLC finds 4 distinct states and no error. One label is honest because of what Postgres does with that statement. An UPDATE locks the row it changes. Under the default isolation level, READ COMMITTED, a second UPDATE of the same row waits for the first transaction to finish, then re-evaluates its WHERE clause on the new row version and computes balance + 10 from it. So no other write can come between reading and writing the balance. The label is a claim about the database; it is only true because the database makes it true.
(c) With the row lock:
---------------- MODULE PSb1_WalletLock ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Clients
(*--algorithm WalletLock
variables balance = 100, holder = "none";
define
AllDone == \A c \in Clients : pc[c] = "Done"
NoLostUpdate == AllDone => balance = 100 + 10 * Cardinality(Clients)
end define;
process Refund \in Clients
variable local = 0;
begin
Select: \* SELECT balance FROM accounts WHERE id = 1 FOR UPDATE
await holder = "none";
holder := self;
local := balance;
Update: \* UPDATE accounts SET balance = $1 WHERE id = 1
balance := local + 10;
Commit: \* COMMIT releases the row lock
holder := "none";
end process;
end algorithm; *)
========================================================
TLC finds no error: 13 distinct states with two clients, 46 with three (Clients = {A, B, C}). The lock makes Select wait while another client is between its read and its commit, so every read sees the latest committed balance. Note what the model assumes: every writer of this row uses FOR UPDATE. A plain SELECT doesn't take the lock and isn't blocked by it, which is why the quiz's version still fails (module PSb1_WalletLockLate, violation found).
An airline's seat picker checks whether a seat is free and then inserts a booking. Two passengers, Ada and Ben, click 14C at the same moment, and both boarding passes say 14C. The team's first answer is a unique constraint on the seat column: the database rejects a second row for 14C, whatever the application does. This problem checks that fix, and then the code around it.
---------------- MODULE PSb1_Seat ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Users
(*--algorithm Seat
variables bookings = {}, told = [u \in Users |-> "waiting"];
define
OneBooking == Cardinality(bookings) <= 1
Honest == \A u \in Users : told[u] = "confirmed" => u \in bookings
end define;
process User \in Users
variables free = FALSE, inserted = FALSE;
begin
Check: \* SELECT 1 FROM bookings WHERE seat = '14C'
free := (bookings = {});
Insert: \* INSERT INTO bookings (seat, user_id) VALUES ('14C', ...)
if free then
bookings := bookings \cup {self};
inserted := TRUE;
end if;
Reply: \* the page the user sees
told[self] := IF inserted THEN "confirmed" ELSE "taken";
end process;
end algorithm; *)
==================================================
told is what each passenger's page says. Honest says no page claims a booking the database doesn't have.
Run it and give TLC's trace in terms of the labels.
Model the unique constraint: the Insert step adds the row only if no row for 14C exists, and otherwise does nothing, leaving inserted false. (In Postgres the insert fails with a unique-violation error, which the application catches.) Check it.
A teammate writes the reply as told[self] := IF free THEN "confirmed" ELSE "taken", since "we already checked the seat was free". Which invariant fails, and what does Ben see?
With the constraint in place, delete the Check label and the free variable entirely. Does anything fail? What was the check for?
The trace for the buggy reply. The database keeps one row for 14C, but the page uses the stale result of the check instead of the result of the insert.
Hint
The constraint makes the test and the insert one indivisible decision, like moving remaining > 0 into Reserve in lesson 35. So the test belongs inside the Insert label. For (c), ask which value Ben's process holds in free when it replies.
Solution
(a) TLC reports OneBooking violated after five states: Check(A) and Check(B) both set free to TRUE, then Insert(A) and Insert(B) both add a row, leaving bookings = {A, B}. It is the split check and reserve from lesson 35.
(b) With the constraint:
---------------- MODULE PSb1_SeatUnique ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Users
(*--algorithm SeatUnique
variables bookings = {}, told = [u \in Users |-> "waiting"];
define
OneBooking == Cardinality(bookings) <= 1
Honest == \A u \in Users : told[u] = "confirmed" => u \in bookings
end define;
process User \in Users
variables free = FALSE, inserted = FALSE;
begin
Check:
free := (bookings = {});
Insert: \* UNIQUE (seat): the INSERT fails if a row for 14C exists
if free then
if bookings = {} then
bookings := bookings \cup {self};
inserted := TRUE;
end if;
end if;
Reply:
told[self] := IF inserted THEN "confirmed" ELSE "taken";
end process;
end algorithm; *)
========================================================
TLC finds 32 distinct states and no error. The inner test sits in the same label as the insert, because the database performs it atomically with the insert.
(c) Honest fails; OneBooking still holds. TLC's trace, shown in the figure: both check, Ada inserts, Ben's insert is rejected so his inserted stays false, and Reply(B) sets told[B] to "confirmed" while bookings = {A}. Ben sees a confirmation and arrives at a seat that is Ada's. The constraint protected the data, not the page. The reply must be based on the result of the step that decides, the insert, never on the check.
---------------- MODULE PSb1_SeatNoCheck ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Users
(*--algorithm SeatNoCheck
variables bookings = {}, told = [u \in Users |-> "waiting"];
define
OneBooking == Cardinality(bookings) <= 1
Honest == \A u \in Users : told[u] = "confirmed" => u \in bookings
end define;
process User \in Users
variables inserted = FALSE;
begin
Insert: \* INSERT ... ; the unique constraint rejects a second row
if bookings = {} then
bookings := bookings \cup {self};
inserted := TRUE;
end if;
Reply:
told[self] := IF inserted THEN "confirmed" ELSE "taken";
end process;
end algorithm; *)
=========================================================
Once the insert decides, the check decides nothing. It is still useful for the interface, for example to grey out seats that are already taken, but it is a hint. Postgres also offers INSERT … ON CONFLICT DO NOTHING, which reports zero rows inserted instead of raising an error; either way, the application has to read that result.
A logging agent hands records from one producer thread to one consumer thread through a ring buffer: an array of N slots and two counters. tail counts records written and head counts records read, so tail - head records are waiting, and record number i lives in slot i % N. (a % b is the remainder, defined in Naturals.) There is no lock. Only the producer changes tail and only the consumer changes head. When the buffer is full the producer waits, which is the backpressure. The contract is the bounded FIFO queue of lesson 37, written here as its own module:
The producer sends 1, 2, …, K, so InOrder can check the order by value. The lines after the algorithm map the slots to the abstract queue.
---------------- MODULE PSb1_Ring ----------------
EXTENDS Naturals, Sequences
CONSTANTS N, K \* N slots; the producer sends 1, 2, ..., K
(*--algorithm Ring
variables buf = [i \in 0..(N - 1) |-> 0], head = 0, tail = 0, got = <<>>;
define
InOrder == \A i \in 1..Len(got) : got[i] = i
end define;
process Producer = "prod"
variable next = 1;
begin
P1: while next <= K do
P2: await tail - head < N; \* full: wait (backpressure)
buf[tail % N] := next; \* write the slot
P3: tail := tail + 1; \* publish it
next := next + 1;
end while;
end process;
process Consumer = "cons"
begin
C1: while Len(got) < K do
C2: await tail > head; \* empty: wait
got := Append(got, buf[head % N]);
C3: head := head + 1; \* free the slot
end while;
end process;
end algorithm; *)
\* Refinement: the occupied slots, oldest first, are the abstract queue.
Queued == [i \in 1..(tail - head) |-> buf[(head + i - 1) % N]]
Q == INSTANCE PSb1_Queue WITH Values <- 1..K, Capacity <- N, q <- Queued
QueueSpec == Q!Spec
==================================================
SPECIFICATION Spec
CONSTANTS N = 2
K = 3
INVARIANT InOrder
PROPERTY QueueSpec
Translate and run it. Which labeled steps map to Enqueue, which to Dequeue, and which to stuttering?
Change the full test to await tail - head <= N. Run it with both checks, then with only INVARIANT InOrder. Which check fails first, and why earlier?
Restore the test, and make the producer publish before writing: tail := tail + 1 under P2, then buf[(tail - 1) % N] := next under P3. What does each check report?
Each label is atomic, and the labels of one process run in order. Which of these assumptions does a real CPU not give you for free?
Four states from the off-by-one trace. The refinement check fails at the third column, when the slot is overwritten. InOrder fails only at the fourth, when the consumer reads it.
Hint
The mapped queue only covers slots from head to tail - 1. Writing to slot tail % N is outside that range, unless the buffer is already full. For (d), think about what another core sees when one core writes buf and then tail.
Solution
(a) TLC finds no error: 96 states generated, 58 distinct. P3 (raise tail) maps to Enqueue(next), since the slot it exposes already holds next. C3 (raise head) maps to Dequeue. P2 writes a slot outside the occupied range, and C2 only copies the head into got, so they map to stuttering, as do the loop tests P1 and C1. This mapping is the one lesson 37 hinted at: InOrder related the queue to an observer's history, and Queued says which part of the array is the queue.
(b) With both checks, TLC reports the action property of PSb1_Queue violated after nine states: the producer publishes 1 and 2, then, with two records unread, its P2 writes 3 into slot 0. The mapped queue goes from ⟨1, 2⟩ to ⟨3, 2⟩, which no queue step does. With InOrder alone, the trace has eleven states and ends with the consumer receiving 3 first, as in the figure. The refinement check sees the damage when it happens; the invariant sees it only when someone reads the result.
(c) The refinement check fails after three states: P1, then the early P2 makes tail = 1 while slot 0 still holds 0, so the mapped queue is ⟨0⟩. With InOrder alone, TLC needs five states: the consumer reads slot 0 before the producer writes it, and got = <<0>>. The order of the write and the publish is the whole algorithm.
(d) The model assumes each process's steps happen in program order as seen by the other process. Compilers and CPUs may reorder the writes to buf and tail, which turns the correct code into the bug in (c). Real ring buffers publish tail with a release store and read it with an acquire load, or use a language's atomic types, so that the order the model assumes is the order other threads see. The label structure is your statement of which orderings the code must guarantee.
Return to the wallet of Problem 1, but now it lives in a document store with no row locks, and workers on several servers apply refunds to it. The team guards the read-modify-write with a lock in Redis. A worker runs SET wallet:7:lock <worker id> NX, which sets the key only if it doesn't exist, retrying until it succeeds, and later deletes the key. committed counts writes, only so the invariant can say what the balance should be.
---------------- MODULE PSb1_RedisLock ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Workers
(*--algorithm RedisLock
variables balance = 100, lock = "none", committed = 0;
define
NoLostUpdate == balance = 100 + 10 * committed
Holding == {w \in Workers : pc[w] \in {"Read", "Write", "Release"}}
MutualExclusion == Cardinality(Holding) <= 1
end define;
fair process Worker \in Workers
variable local = 0;
begin
Acquire: \* SET wallet:7:lock <worker id> NX
await lock = "none";
lock := self;
Read:
local := balance;
Write:
balance := local + 10;
committed := committed + 1; \* bookkeeping for the check only
Release: \* DEL wallet:7:lock
lock := "none";
end process;
end algorithm; *)
=======================================================
Run it. Then let a worker crash at Release: either lock := "none"; or skip; end either;. What does TLC report, and why isn't it a liveness violation?
Locks that outlive their owner are why Redis locks get an expiry: SET … NX PX 10000 deletes the key after 10 seconds. Drop the crash, and add a process that can expire the lock whenever it is held. Check MutualExclusion, then only NoLostUpdate. Can any fairness assumption remove the violation?
The workers become a background loop: acquire, work, release, forever. In the module below, check NoStarvation with Spec, then with SpecSF. Explain TLC's counterexample, and say what a real lock would need to justify SpecSF.
---------------- MODULE PSb1_RedisLockLoop ----------------
CONSTANT Workers
(*--algorithm RedisLockLoop
variable lock = "none";
define
NoStarvation == \A w \in Workers :
(pc[w] = "Acquire") ~> (pc[w] = "Work")
end define;
fair process Worker \in Workers
begin
Loop:
while TRUE do
Acquire: \* SET wallet:7:lock <worker id> NX, retried until it succeeds
await lock = "none";
lock := self;
Work:
skip; \* read and write the balance
Release:
lock := "none";
end while;
end process;
end algorithm; *)
\* Strong fairness for each worker's Acquire, on top of fair process.
SpecSF == Spec /\ \A w \in Workers : SF_vars(Acquire(w))
===========================================================
The cycle TLC reports for looping workers. A's Acquire is enabled in the top two states, where the lock is free, and disabled in the bottom two, so it is never continuously enabled and weak fairness never forces it.
Hint
For (b), write the expiry as its own process, process Expiry = "ttl", with a while TRUE loop that awaits a held lock and clears it. For (c), compare the four abstract lock specs in lesson 38: which one is fair process giving you here?
Solution
(a) TLC finds no error: 17 distinct states, and Termination holds because of fair process. With the crash (module PSb1_RedisLockCrash), TLC reports Deadlock reached after five states: A acquires, reads, writes, and crashes at Release with the key still set. A is at Done, B waits at Acquire forever, and no step is enabled. That is a safety failure, a reachable state with no way out, so TLC reports it before it looks at any temporal property.
(b) The expiry process (module PSb1_RedisLockTTL, which also drops fair, since this part checks only safety):
process Expiry = "ttl" \* the key's PX timeout runs out
begin
Expire:
while TRUE do
await lock # "none";
lock := "none";
end while;
end process;
MutualExclusion fails after four states: A acquires, the lock expires, B acquires, and both are past Acquire. With only NoLostUpdate, TLC reports eight states, the lost update of Problem 1 again: A acquires, the lock expires, A reads 100, B acquires and reads 100, A writes 110, B writes 110. In production, A is a worker paused by garbage collection or a slow network after its lock expired, not a dead one, the case lesson 38 warned about. No fairness assumption helps. Fairness only says some steps must eventually happen; it never forbids an order of steps, and this violation is a finite prefix. The fix has to be in the protocol: the store must reject a write from a worker whose lock has expired. The model also exposes a second problem: A's later Release deletes the key while B holds it. The Redis documentation recommends releasing with a script that deletes the key only if it still holds your own value.
(c) With Spec, TLC reports NoStarvation violated, with the cycle in the figure: A waits at Acquire while B loops, acquires, works and releases, forever. fair process is weak fairness of each worker's whole step, close to the SpecWF row of lesson 38. A's Acquire is enabled only in the two states where the lock is free, so it is never continuously enabled, and weak fairness never forces it. With SpecSF, which adds strong fairness of each Acquire, TLC finds that NoStarvation holds, in the same 12 distinct states.
But SpecSF is an assumption about the lock, not something SET NX provides. A retry loop gives no priority to the worker that has waited longest, and if B's retries tend to be faster, A can lose every race. To justify strong fairness, a real lock needs a queue of waiters served in order, or another mechanism that the model would then include as steps.
Beyond the lectures II: Reasoning at scale
Find the fact that makes the guarantee inevitable.
Since lesson 16 you have used invariants like TCConsistent, and TLC checks them by visiting every reachable state. Now ask a stronger question: why does the invariant hold? The answer is usually a larger fact, one that holds even in states no behavior reaches.
The Transfer states, written alice · transit · bob. Green is what TLC can reach. Blue, Inv, adds three states that no behavior visits, and still no arrow leaves it. The dashed arrow leaves the fact bob ≤ 1, though every reachable state satisfies it.
An invariant holds in all reachable states. An inductive invariant Inv also survives every Next step from any state satisfying it, including states Init never reaches. In the diagram, Inv is the blue box: no arrow leaves it. That is the condition that replaces walking an unbounded graph with one local argument. There are three obligations:
\* Proof obligations, not a standalone module:
Init => Inv
Inv /\ [Next]_vars => Inv'
Inv => Safety
First establish Inv initially. Then show every allowed step preserves it. Finally show it implies what you wanted. For a state predicate, stuttering preserves truth automatically, so the middle line is often written with Next alone.
Exercise: what if Inv is so strong that Init does not imply it?
It cannot establish the intended theorem. A preservation argument about an unreachable region says nothing about your actual initial states. Check the base case before the step case.
Worked example: money in transit
An app moves one unit from Alice to Bob through a worker. Debit and Credit are separate actions, as the steps in lesson 35 were.
---------------- MODULE Transfer ----------------
EXTENDS Naturals
VARIABLES alice, transit, bob
vars == <<alice, transit, bob>>
Init == alice = 2 /\ transit = 0 /\ bob = 0
Debit == /\ alice = 2 \* one transfer only
/\ alice' = alice - 1
/\ transit' = transit + 1
/\ UNCHANGED bob
Credit == /\ transit > 0
/\ transit' = transit - 1
/\ bob' = bob + 1
/\ UNCHANGED alice
Next == Debit \/ Credit
Spec == Init /\ [][Next]_vars
TypeOK == /\ alice \in 0..2
/\ transit \in 0..2
/\ bob \in 0..2
Naive == alice + bob = 2
BobAtMostOne == bob <= 1
Inv == TypeOK /\ alice + transit + bob = 2
\* Start TLC from every state a candidate allows:
IndCandidate == TypeOK /\ BobAtMostOne
=================================================
A legal run. alice + bob fails while the unit is in transit. Adding the third place makes a quantity that every step preserves.
The natural first guess fails: TLC reports Naive (alice + bob = 2) violated after one step. The money is not lost, it is just somewhere your invariant was not looking. Inv counts the third place and holds, and the normal check visits only the 3 states in the green box.
Asking TLC whether a fact is inductive
TLC can test preservation directly on a finite type. Replace the initial predicate with the candidate, so it starts from every state the candidate allows.
INIT Inv
NEXT Next
INVARIANT Inv
CHECK_DEADLOCK FALSE
This run starts from all 6 states in the blue box, and TLC reports no error, so Inv is inductive on this finite set of values. Now try BobAtMostOne. It holds in all 3 reachable states, so as an invariant it passes. Starting from TypeOK /\ BobAtMostOne instead, TLC finds the dashed arrow: from alice = 0, transit = 1, bob = 1, Credit gives bob = 2.
A counterexample like that one is called a counterexample to induction. It does not mean the system has a bug, because that start state is unreachable. It means your fact is too weak to explain itself, and you must strengthen it or give it up.
Predict: mutate Credit so it raises bob without lowering transit. And Debit so it lowers alice without raising transit. Does Inv catch both?
Yes, and differently. TLC’s trace for the bad Credit has total 3, after two steps; for the bad Debit it has total 1, after one. These are different bugs caught by one conservation equation. With several transfers, identify them separately: one scalar transit cannot tell you that one transfer was credited twice and another never.
Hand-check the argument too. Init gives 2 + 0 + 0 = 2. In Debit, subtracting and adding one cancel. In Credit, the guard transit > 0 keeps the result in type, and they cancel again. Each action moves a unit’s location and keeps the total.
Back to the ticket
NoOverselling from lesson 35 looks like the property you want, and it is true. Is it inductive? Start TLC from all states satisfying TypeOK /\ NoOverselling, and it reports a violation from remaining = 1, booked = {B}, then Reserve(A).
All 6 states satisfying TypeOK /\ NoOverselling. Green is reachable. The red edges start from states that are safe but never occur: one ticket left, and someone already booked.
The red edges start where stock and bookings disagree. The missing fact relates the two variables: Conservation, remaining + Cardinality(booked) = 1. Start from TypeOK /\ Conservation and TLC finds 3 states and no error. Because remaining is at least 0, Conservation also implies at most one booking. Relational facts like this one usually do more work than bounding each variable alone.
This check covers only the values you gave TLC. It can refute a candidate quickly, and a pass is good evidence, but it is not a theorem for all values. lesson 43 builds the proof itself.
Predict: does this conservation proof establish that Bob eventually receives the money?
No. The behavior may stay at alice = 1, transit = 1, bob = 0 forever. Credit is possible but not required. Safety says where the money is; reaching the destination needs the fairness of lesson 29.
In lesson 26 you read a specification as a formula, and used INSTANCE to compare two of them. Formulas can also be conjoined. That is how you combine components, and it behaves differently from what you might expect from running programs.
Two components, one bit each. Interleaved has only the solid steps. OwnVars also has the dashed one. Conjoined has none of these: it never leaves x=0, y=0.
Composition needs a shared step convention
Writing SpecA /\ SpecB intersects the allowed behaviors. It is not a request to interleave two programs. Here is the experiment behind the diagram, with each component written first as if it owned the whole state:
---------------- MODULE Frames ----------------
VARIABLES x, y
vars == <<x, y>>
Init == x = 0 /\ y = 0
\* Each component written as if it owned the whole state:
A == x = 0 /\ x' = 1 /\ y' = y
B == y = 0 /\ y' = 1 /\ x' = x
SpecA == Init /\ [][A]_vars
SpecB == Init /\ [][B]_vars
Conjoined == [A]_vars /\ [B]_vars
Interleaved == A \/ B
\* Each component constrains only its own variable:
OwnX == x = 0 /\ x' = 1
OwnY == y = 0 /\ y' = 1
OwnVars == [OwnX]_x /\ [OwnY]_y
===============================================
Next-state relation
Distinct states
Steps allowed
Conjoined (what SpecA /\ SpecB means)
1
Only stuttering
Interleaved (A \/ B)
4
The solid arrows
OwnVars
4
The solid and dashed arrows
The first row is the trap: A requires y unchanged and B requires y to change, so no step satisfies both, and all the system can do is stutter. TLC reports no error, because a system that does nothing violates no safety property. For an interleaving composition, write global actions with compatible frames. If you want simultaneous steps, each component must constrain only the variables it owns.
Assume-guarantee reasoning says a component guarantees G provided its environment satisfies A. Check that the other components establish A. Two components that each assume the other eventually responds may prove nothing useful when combined: circular progress assumptions need an actual argument.
Predict: is the Conjoined run’s clean TLC result good news?
No. It found no error in 1 state. A state count far below what you expected is a result to investigate. A liveness property would have failed here.
Module tools you have not needed yet
You know EXTENDS and named instances. Substituting parameters lets you reuse a whole model. This puts the queue from lesson 37 into a job system:
What INSTANCE … WITH does: every occurrence of the left name in BoundedFIFO is read as the right one.
TLC finds the same 7 states as before, since only the names changed. Queue!TypeOK is the qualified name for a definition in that instance.
You have also met LET, CHOOSE and RECURSIVE in the lectures. Two more belong beside them. This module runs under TLC, and its ASSUME lines pass:
---------------- MODULE LangTools ----------------
EXTENDS Naturals
Outcome(x) == CASE x = 0 -> "empty"
[] x > 0 -> "ready"
Pick == CHOOSE x \in {"A", "B"}: TRUE
RECURSIVE Fact(_)
Fact(n) == IF n = 0 THEN 1 ELSE n * Fact(n-1)
LOCAL Helper == 41
Exported == Helper + 1
ASSUME Outcome(0) = "empty" /\ Outcome(3) = "ready"
ASSUME Pick = Pick /\ Pick \in {"A", "B"}
ASSUME Fact(4) = 24 /\ Exported = 42
VARIABLE v
Spec == v = Pick /\ [][v' = Pick]_v
Stable == v = Pick
==================================================
LOCAL keeps a helper from being exported to modules that use this one. It does not make state thread-local. CASE chooses a branch whose guard is true. Do not rely on branch order when guards overlap, and add OTHER if no guard might be true, because otherwise TLC stops with “Attempted to evaluate a CASE with no conditions true”.
\EE h : F, temporal existential quantification, hides a variable at the level of whole behaviors: a behavior satisfies it if some sequence of values for h makes F true. That differs from the state-level \E. It is how you state a specification with internal variables hidden, but TLC does not accept it (“TLC cannot handle the temporal formula”).
Predict: does CHOOSE x \in {"A","B"}: TRUE mean TLC will try both at every step?
No. It denotes one unspecified value, the same every time, which is why Stable holds above and TLC finds 1 state. To explore both, write \E x \in S: Action(x).
Worked example: compose search, selection, and caching
A search screen has query text, an asynchronous request, displayed results, and a selected result. You could verify each alone: the service returns matches, the cache stores responses, and selection picks an existing row. The composition can still be wrong when responses arrive out of order.
Each component behaved as specified. The composition is wrong in the red step, and the guard is the contract that repairs it.
TLC finds 16 distinct states and all three invariants hold. Status uses CASE and needs no OTHER because the guards cover every reachable state, which StatusKnown confirms. SettlesOnLatest says that once nothing is in flight, the screen shows the latest generation.
Two one-line mutations each break a different contract:
Delete the guard r.gen = generation, and TLC reports SettlesOnLatest violated after 4 steps: the red arrow in the diagram.
Replace selected' = NoSelection with UNCHANGED selected, and SelectionValid fails after 5 steps: the user picks a row from gen 1, gen 2 arrives, and the selection names a row no longer on screen.
The request component’s guarantee is “every response carries its original generation”. The display relies on that and guarantees it never accepts an obsolete one. The cache must preserve the relevant key too: if results depend on query, tenant, locale and permissions, caching by query alone breaks the composition, even though each lookup is consistent with its own incomplete key.
If the UI intentionally keeps old results while loading, the "loading" status above says so. That is better than asserting a stricter invariant and then hiding its violations. A policy is part of the model.
Transfer exercise: why might a query-only cache expose another account’s results?
Two accounts can issue the same query with different authorized result sets. If account identity or an equivalent authorization scope is missing from the key, one account’s cached response may be reused for the other. Model two accounts, one shared query, and two distinct expected result sets to expose the missing key component.
Specifying Systems, especially composition, module meaning, and language operators. Keep its published corrections alongside the book.
Beyond the lectures II: Reasoning at scale
Reduce the model without removing the question.
In lesson 18, a symmetry set took three-manager two-phase commit from 288 states to 80. Now you look at what happens as the model grows, and at when a reduction quietly stops testing what you meant to test.
Distinct states TLC found for two-phase commit, on a logarithmic axis. On this axis, a straight line means exponential growth.
Here are real TLC runs of the same two-phase commit spec. If each of n independent variables has k values, their product has kⁿ combinations, and per-process state, messages and histories add dimensions quickly. Good modeling is not a contest to reproduce production. It is a search for the smallest model that still permits the failure you suspect.
Resource managers
Distinct states
With symmetry
3
288
80
5
8,832
314
7
296,448
920
8
1,745,408, in 7 s
1,461, in 2 min 9 s
The last row is a surprise worth noticing. Symmetry cut the states by a factor of over a thousand and made this run slower, because TLC must consider all 8! = 40,320 permutations to recognize that two states are equivalent. Times are from one laptop; yours will differ, but measure them instead of assuming.
Four reductions with different meanings
Technique
What changes
Question to ask
Smaller constants
Checks a smaller instance
Can the bug require another participant or round?
Abstraction
Removes distinctions
Are all relevant concrete behaviors represented?
Symmetry
Collapses interchangeable identities
Are those identities interchangeable in the properties too?
State and action constraints
Limits exploration
Which paths have been excluded?
A constraint, written CONSTRAINT P in the config, tells TLC not to explore states where P is false. An invariant is a property you test. A constraint prunes the experiment.
A distinguished leader, a fixed account, or a process-specific progress formula breaks the symmetry you assumed. Do not combine symmetry with liveness checks unless your tools and reasoning explicitly support it; default to unreduced liveness runs.
Worked example: a CDN invalidation that loses a race
A content service publishes a new article version and invalidates cached copies. The origin serves version 2, but a fetch for version 1 began earlier. One key, one edge cache, two versions and one delayed fetch are enough.
The race, in the order TLC’s 4-step trace finds it. Removing a cached object does not cancel an older response already in flight.
Here floor records that everything through that version is invalidated, and Fill rejects anything at or below it. A deletion-only design remembers nothing, so it cannot tell a stale fill from a fresh one. Delete the guard v > floor to get that design, and run these experiments:
Model
Settings
Distinct states
NotResurrected
Guarded
MaxVersion = 2
18
Holds
No guard
MaxVersion = 2
stopped at the error
Violated in 4 steps
No guard
MaxVersion = 1
2
“Holds”
No guard
MaxVersion = 2, CONSTRAINT Fresh
2
“Holds”
The two runs in quotation marks are false comfort. With one version nothing can be stale. The constraint case looks more reasonable: Fresh sounds like just the states you care about. But it removes the first state after Publish, so TLC reports “No error has been found” on the buggy design.
The same failing path as the previous diagram, seen by a constrained run. TLC keeps only the first two states; the dashed path is never explored.
Only 2 states explored, on a model with at least two actions you meant to exercise, is the warning sign. Whenever you add a bound, compare what the run visited with what you expected.
Exercise: you bound retries to one and a duplicate-charge bug disappears. What next?
Check whether at least two deliveries are needed to trigger it. Restore that behavior, then reduce some unrelated dimension. A useful reduction preserves the causal path to the property of interest.
The useful reduction here keeps that path and removes the rest. One key is enough, since a thousand URLs add volume but no new cause. Two versions distinguish stale from fresh. A second edge becomes necessary only when the property concerns divergence between edges. This is a causal argument for the bound, not proof that every other bug fits it. The guarded model at MaxVersion 2, 3, 4 and 5 has 18, 82, 290 and 898 states, so raise it to check your argument, while you can still afford to.
Measure the right work
Track distinct states, generated states, search depth and whether the search finished. TLC stores a fingerprint of each visited state, which is a hash, not the state. Two different states could collide, and one would then go unexplored. So it prints an estimate, for example calculated (optimistic): val = 1.3E-13 for the 898-state run. This is why a completed run is a search, not a symbolic proof. Simulation mode (-simulate) samples behaviors and can find bugs in models too large to finish, but a sample with no violation is weaker evidence than a completed search.
Transfer exercise: can you remove message identities from this model?
Possibly for the single delayed response, but justify it. If duplicate delivery or retry identity affects whether the cache fills twice, keep enough identity to distinguish those events. Remove fields only after explaining why two states differing solely in that field have equivalent behavior for the property you are checking.
Replace a finite search with an explicit argument.
lesson 8 named TLAPS, the proof system, and lesson 40 gave you the three obligations it needs. A finished TLC run covers the instances you gave it, and lesson 42 showed how little that may be. A proof can cover every instance, provided its assumptions and steps are correct.
The structure of the proof below. Read it top down: each node is proved from its children. The two leaves at the bottom are what the Reserve case rests on: a lemma about finite sets, and arithmetic.
The hard part is usually finding the invariant that carries the design argument, which you did with TLC in the previous lessons. What remains is the structure in the diagram: a claim, split into smaller claims, until each one is small enough to check on its own.
A worked proof
Return to Inventory. Let Inv combine TypeOK and Conservation. Initially remaining = 1 and booked is empty. In Reserve(b), the guard ensures b is not already in booked, so adding b raises its cardinality by exactly one. The action lowers remaining by one, preserving the sum, and its positive-stock guard preserves the lower bound. Stuttering preserves both. Inv implies NoOverselling because remaining is nonnegative.
That is the informal outline. Written as a TLA+ hierarchical proof, the same argument has numbered steps. <1>2 is a top-level step, and its <2> steps are the children that prove it:
---------------- MODULE InventoryProof ----------------
EXTENDS Inventory, TLAPS
Inv == /\ TypeOK
/\ IsFiniteSet(booked)
/\ Conservation
LEMMA CardEmpty == IsFiniteSet({}) /\ Cardinality({}) = 0
PROOF OMITTED
LEMMA CardNat == \A S : IsFiniteSet(S) => Cardinality(S) \in Nat
PROOF OMITTED
LEMMA CardAdd == \A S, x : IsFiniteSet(S) /\ x \notin S =>
/\ IsFiniteSet(S \cup {x})
/\ Cardinality(S \cup {x}) = Cardinality(S) + 1
PROOF OMITTED
THEOREM Safety == Spec => []NoOverselling
<1>1. Init => Inv
BY CardEmpty DEF Init, Inv, TypeOK, Conservation
<1>2. Inv /\ [Next]_vars => Inv'
<2> SUFFICES ASSUME Inv, [Next]_vars PROVE Inv'
OBVIOUS
<2>1. ASSUME NEW b \in Buyers, Reserve(b) PROVE Inv'
BY <2>1, CardAdd, CardNat
DEF Reserve, Inv, TypeOK, Conservation
<2>2. CASE UNCHANGED vars
BY <2>2 DEF vars, Inv, TypeOK, Conservation
<2>3. QED
BY <2>1, <2>2 DEF Next
<1>3. Inv => NoOverselling
BY CardNat DEF Inv, TypeOK, Conservation, NoOverselling
<1>4. QED
BY <1>1, <1>2, <1>3, PTL DEF Spec
=======================================================
How far this was checked: the module parses under SANY with a stand-in for the TLAPS module, and TLC confirms Inv is inductive for Buyers = {A, B}, with 3 states and NoOverselling holding. It has not been run through TLAPS, so a prover may ask for more detail in some steps. Treat it as the shape of a proof. The three OMITTED lemmas are facts about finite sets that a complete proof must import or prove.
BY lists the facts a step may use and DEF lists the definitions it may expand. Nothing else is visible, which is the point: every use of an assumption is on the page. PTL names propositional temporal logic, the reasoning that gets from “preserved by every step” to [].
Exercise: remove b \notin booked from Reserve. Is the one-ticket model enough to expose a bug?
Not in this one-ticket model. TLC still finds 3 states and no error. Inv plus remaining > 0 implies booked is empty, so the membership guard is redundant here and the proof can recover that fact. With more tickets, the same buyer could reserve twice: adding that buyer again does not increase the cardinality while remaining decreases. The broader conservation proof then needs the guard or a different booking representation. Test assumptions at the size where they become relevant.
Where TLAPS helps
TLAPS checks hierarchical proofs by sending each step’s obligation to backend provers. Break large obligations into named claims, and expose the definitions each one needs. An informal outline is not a checked proof. Consult the supported-feature list: the documented system focuses on safety reasoning and does not generally discharge arbitrary temporal liveness arguments.
Use TLC to attack a candidate invariant before you spend time proving it, as in lesson 40. A finite run can refute a candidate quickly. It cannot prove the unbounded theorem.
Worked example: prove a cache cannot roll back a version
An app fetches a product description twice. Version 5 and version 4 are in flight, and the network delivers 5 first. A naive cache that accepts every response replaces the fresh value with the old one.
cacheVersion across the same arrival order. The bottom row is TLC’s counterexample after the guard is removed.
This time the property is about steps, not states: Monotonic says every step keeps or raises the version. TLC finds 4 distinct states and no error. Delete the guard v >= cacheVersion and it reports the bottom row of the diagram.
The proof is short. For Accept, the guard gives cacheVersion' >= cacheVersion directly. For Reject and stuttering, cacheVersion is unchanged. An action that resets cacheVersion must join this case split, even if it lives in another component, and this is where a proof tends to find what a design forgot.
It assumes one key, one monotonically increasing version scheme, and immutable content for a given version. Incomparable version vectors or reused version numbers need a different model.
What the proof forces you to decide
Split cacheVersion into what is in memory and what is on disk, with Persist and Restart actions. Now there is a new case to prove, and it fails:
TLC’s counterexample to monotonicity when accepted versions are not persisted before they are shown.
TLC reports Monotonic violated in 2 steps. You must either persist the accepted version before showing it, weaken the contract to permit rollback after restart, or hold back older data until resynchronization. The proof makes that a design choice instead of a surprise.
A proof of one property establishes exactly that property. A server could send version 100 with the wrong product’s text and Accept would take it. Add a key-match property and a mapping from version to content if you need them. And checking versions 3 to 5 with TLC can reveal a counterexample, but does not establish the claim for all numbers: the argument above does, because no step of it depends on which numbers they are.
Transfer exercise: can a cache safely delete its version record on logout?
It depends on the contract and scope. If the next login begins a new cache epoch with no promised cross-session monotonicity, clearing it may be valid. If old responses can still arrive and populate the new session, include session identity in the acceptance guard; otherwise an old authenticated response can cross the reset boundary.
Problem set 12: make the argument, not just the run.
Four problems about reasoning beyond one TLC run. You'll find the inductive invariant behind a ledger, shrink a connection pool's state space without hiding a bug, compose a client with a rate limiter, and write a hierarchical proof for the locked wallet from Problem set 11. They draw on this chapter's four lessons, and on PlusCal and refinement from the two chapters before it.
Every module below was checked with TLC exactly as shown, including the inductiveness checks that start from INIT Inv. No proof in this set was checked by a prover: TLAPS wasn't available where these problems were checked, so the proof in Problem 4 was only parsed by SANY, and its invariant checked by TLC.
A payments ledger moves money between accounts in two steps, because the accounts may live in different database shards. Debit takes the amount from the sender and marks the transfer debited. Credit later pays the receiver. Auditors care about one promise above all: the ledger never creates money, so the balances never add up to more than the money that was put in. Transfer 1 moves 1 from alice to bob, and transfer 2 moves 2 back.
---------------- MODULE PSb2_Ledger ----------------
EXTENDS Naturals
Accounts == {"alice", "bob"}
Xfers == {1, 2}
From == [x \in Xfers |-> IF x = 1 THEN "alice" ELSE "bob"]
To == [x \in Xfers |-> IF x = 1 THEN "bob" ELSE "alice"]
Amt == [x \in Xfers |-> IF x = 1 THEN 1 ELSE 2]
Total == 3
VARIABLES bal, status
vars == <<bal, status>>
Init == /\ bal = [a \in Accounts |-> IF a = "alice" THEN 2 ELSE 1]
/\ status = [x \in Xfers |-> "new"]
Debit(x) == /\ status[x] = "new"
/\ bal[From[x]] >= Amt[x]
/\ bal' = [bal EXCEPT ![From[x]] = bal[From[x]] - Amt[x]]
/\ status' = [status EXCEPT ![x] = "debited"]
Credit(x) == /\ status[x] = "debited"
/\ bal' = [bal EXCEPT ![To[x]] = bal[To[x]] + Amt[x]]
/\ status' = [status EXCEPT ![x] = "credited"]
Next == \E x \in Xfers : Debit(x) \/ Credit(x)
Spec == Init /\ [][Next]_vars
RECURSIVE SumOver(_, _)
SumOver(f, S) == IF S = {} THEN 0
ELSE LET s == CHOOSE e \in S : TRUE
IN f[s] + SumOver(f, S \ {s})
InFlight == [x \in Xfers |-> IF status[x] = "debited" THEN Amt[x] ELSE 0]
TypeOK == /\ bal \in [Accounts -> 0..Total]
/\ status \in [Xfers -> {"new", "debited", "credited"}]
NoMint == SumOver(bal, Accounts) <= Total
Conservation == SumOver(bal, Accounts) + SumOver(InFlight, Xfers) = Total
IndNoMint == TypeOK /\ NoMint
IndCons == TypeOK /\ Conservation
====================================================
Run the cfg above. Then check whether NoMint is inductive, starting TLC from every state of IndNoMint. Describe the counterexample, and say whether it is a bug.
Check IndCons the same way. Then argue by hand that Conservation is preserved by Debit(x) and Credit(x), and that it implies NoMint.
Support asks for a Refund(x) action that returns a transfer's amount to its sender and marks it "refunded". Write it with the guard status[x] # "new", check it with the normal cfg and with INIT IndCons, then find the right guard.
The reachable states in green, and the counterexample to induction that TLC finds for TypeOK /\ NoMint, which starts outside them.
Hint
For the inductiveness checks, use a cfg with INIT IndNoMint, NEXT Next, INVARIANT IndNoMint and CHECK_DEADLOCK FALSE, as in lesson 40. NoMint ignores money that has left one account but not arrived in the other. Where is it?
Solution
(a) The normal check finds no error in 5 distinct states, the top row of the figure. Starting from IndNoMint, TLC computes 90 initial states and reports a violation after two: from alice = 0, bob = 2 with transfer 2 debited, Credit(2) pays alice 2 and the balances add up to 4. That start state satisfies NoMint (0 + 2 ≤ 3) but is unreachable: transfer 2 has taken 2 from bob, so 4 units exist in all. It isn't a bug. It shows that NoMint doesn't constrain money in flight, so it can't explain why a credit is safe.
(b) Starting from IndCons, TLC computes 27 initial states and finds no error, so Conservation is inductive for these values. By hand: Debit(x) lowers one balance by Amt[x] and moves x from "new" to "debited", which adds Amt[x] to the in-flight sum. Credit(x) moves x from "debited" to "credited", removing Amt[x] from the in-flight sum, and adds it to a balance. Each step moves money between places, as in Transfer from lesson 40. Since in-flight amounts are never negative, balances plus in-flight equal to 3 implies balances at most 3, which is NoMint. TypeOK needs no separate argument: the guard of Debit keeps balances nonnegative, and Conservation keeps each one at most 3.
(c) With the guard status[x] # "new" (module PSb2_LedgerRefundBug), the normal check reports NoMint violated after four states: Debit(1), Credit(1), then Refund(1) returns 1 to alice although bob was already paid, and the balances add up to 4. That is a real bug, refunding a completed transfer. Starting from IndCons, TLC also finds a counterexample to induction, with a refund of a credited transfer. The right guard is status[x] = "debited":
With it (module PSb2_LedgerRefund), the normal check finds 7 distinct states, and the check from IndCons starts from 52 states and finds no error. A refund takes money out of flight and returns it, just as a credit does; Conservation told you which guard to write before any trace did.
An application server keeps a pool of database connections. Clients request one, wait, check one out, and return it, or give up waiting. The pool must never hand one connection to two clients, and a client is busy exactly when it holds one connection. Clients are interchangeable, and so are connections, which makes this a natural place for symmetry.
Fill in distinct states for 3 clients and 2 connections, 4 and 2, 5 and 3, and 7 and 3, with and without SYMMETRY Sym. Also note how long the 7-and-3 runs take.
Explain why the symmetry is sound here, using the rule from lesson 22.
The pool now keeps one connection for an admin client that runs health checks: other clients may check out a connection only if at least two are free. Add CONSTANT Admin with ASSUME Admin \in Clients, the guard, and the invariant AdminCanConnect below. Then make the bug of writing >= 1 in place of >= 2, and check the buggy pool with Admin = c1 and 3 clients and 2 connections, with and without SYMMETRY Sym.
Write a symmetry that is sound for the admin pool, and check the buggy pool again.
One symmetry class, two members. TLC explores one member of each class, so whether it ever checks the violating one depends on the order of the search, and here it never does.
Hint
A symmetry set is sound only if swapping its elements maps behaviors to behaviors and leaves the property's truth unchanged. Look for a constant that names one particular client. For (d), only the clients that are really interchangeable may be permuted.
Solution
(a) TLC's counts:
Clients × connections
Distinct states
With SYMMETRY Sym
3 × 2
44
9
4 × 2
128
12
5 × 3
992
18
7 × 3
8,864
26
On the machine these were checked on, the 7 × 3 run took about 1 second without symmetry and 17 seconds with it. The reduction is large, but TLC must try 7! × 3! = 30,240 permutations on each state it stores, the same effect lesson 42 showed for two-phase commit. Symmetry pays when states are expensive and identities few.
(b) No client or connection is named anywhere in the spec or in TypeOK and HoldsOne. They appear only through quantifiers and set operations over Clients and Conns, so swapping two clients, or two connections, turns any behavior into another behavior and doesn't change whether an invariant holds. Free is a separate model value and isn't permuted.
(c) Without symmetry, the correct admin pool passes in 40 distinct states, and the buggy one fails: TLC reports AdminCanConnect violated after six states, in which c1 (the admin) and c2 request, c2 checks out k1, c3 requests and checks out k2, and the admin is left waiting with nothing free. With SYMMETRY Sym, TLC reports no error in 9 distinct states. Admin breaks the symmetry: swapping c1 and c2 turns a violating state into one that satisfies the invariant, as in the figure. TLC explores only one state of each class, so it can miss the violating member entirely, and here it does. Nothing in TLC's output warns you.
With SYMMETRY SymSafe, TLC reports the violation in the buggy pool again, and the correct admin pool passes in 15 distinct states. The general rule: any constant that singles out an element, like a leader, an admin or a home region, removes that element from the symmetry set.
An API gateway protects a service with a token bucket. The bucket holds up to Cap tokens and is refilled over time; each admitted request spends one token, and when the bucket is empty the gateway answers 429 Too Many Requests. One team wrote the bucket and another wrote a client, each as its own module:
The gateway composes them, renaming the client's variables and fixing the constants with INSTANCE … WITH. Admitting a request is a shared step: the client's GotOk and the bucket's Take happen together.
---------------- MODULE PSb2_Gateway ----------------
EXTENDS Naturals
VARIABLES reqs, served, throttled, tokens, refills
vars == <<reqs, served, throttled, tokens, refills>>
C == INSTANCE PSb2_Client WITH MaxReqs <- 4, issued <- reqs,
ok <- served, limited <- throttled
B == INSTANCE PSb2_Bucket WITH Cap <- 2, MaxRefills <- 1
Init == C!Init /\ B!Init
\* Shared step: the gateway forwards the request and spends a token.
Admit == C!GotOk /\ B!Take
\* Gateway answers 429 only when the bucket is empty.
Throttle == C!Got429 /\ B!Empty /\ UNCHANGED <<tokens, refills>>
Next == \/ C!Send /\ UNCHANGED <<tokens, refills>>
\/ Admit
\/ Throttle
\/ B!Refill /\ UNCHANGED <<reqs, served, throttled>>
Spec == Init /\ [][Next]_vars
\* Every admitted request spent a token.
TokensAccounted == served + tokens = 2 + refills
=====================================================
Run it. Then add ClientContract == C!Spec and BucketContract == B!Spec and check both as properties. Why must they hold for any composition written this way?
Someone suggests composing more simply, with each component stepping its own variables: [C!Next]_<<reqs, served, throttled>> /\ [B!Next]_<<tokens, refills>> as the next-state relation. Check TokensAccounted on that spec and explain the counterexample.
The client's assumption about the gateway is that a 429 means the bucket was really empty. Write that as an action property HonestThrottle, check it, then delete B!Empty from Throttle and check again.
The solid path is the composed gateway. The dashed step is allowed only by the naive composition, and it breaks TokensAccounted at once.
Hint
TLC accepts only one [][…]_v conjunct in a behavior spec, so write the simpler composition as one next-state relation, like OwnVars in lesson 41. For (c), an action property has the form [][P]_vars, where P may mention primed variables.
Solution
The complete module:
---------------- MODULE PSb2_Gateway ----------------
EXTENDS Naturals
VARIABLES reqs, served, throttled, tokens, refills
vars == <<reqs, served, throttled, tokens, refills>>
C == INSTANCE PSb2_Client WITH MaxReqs <- 4, issued <- reqs,
ok <- served, limited <- throttled
B == INSTANCE PSb2_Bucket WITH Cap <- 2, MaxRefills <- 1
Init == C!Init /\ B!Init
\* Shared step: the gateway forwards the request and spends a token.
Admit == C!GotOk /\ B!Take
\* Gateway answers 429 only when the bucket is empty.
Throttle == C!Got429 /\ B!Empty /\ UNCHANGED <<tokens, refills>>
Next == \/ C!Send /\ UNCHANGED <<tokens, refills>>
\/ Admit
\/ Throttle
\/ B!Refill /\ UNCHANGED <<reqs, served, throttled>>
Spec == Init /\ [][Next]_vars
\* Every admitted request spent a token.
TokensAccounted == served + tokens = 2 + refills
\* A 429 is sent only when the bucket is empty.
HonestThrottle == [][throttled' > throttled => tokens = 0]_vars
ClientContract == C!Spec
BucketContract == B!Spec
\* The naive composition: conjoin the components, each stepping its own variables.
NaiveNext == [C!Next]_<<reqs, served, throttled>> /\ [B!Next]_<<tokens, refills>>
Naive == Init /\ [][NaiveNext]_vars
=====================================================
(a) TLC finds no error: 24 states generated, 19 distinct. With PROPERTY HonestThrottle ClientContract BucketContract added (the cfg PSb2_Gateway.cfg), it still finds none. Every disjunct of Next is a step of the client and a step or stutter of the bucket, and the other way round. Send and Throttle leave the bucket's variables unchanged, Refill leaves the client's unchanged, and Admit is a step of both. So each component's spec is implied, by the argument of lesson 26, with the WITH renaming as the refinement mapping.
(b) With SPECIFICATION Naive, TLC reports TokensAccounted violated after two states: one NaiveNext step in which reqs becomes 1 and tokens becomes 1. The client did Send and the bucket did Take in the same step, and nothing ties a Take to a served request. The conjunction of lesson 41 is still intersection: each conjunct allows its own component's steps, so their intersection allows every combination of them, including simultaneous steps that shouldn't be connected. It also allows GotOk with no Take at all. The fix is to say which steps are shared, as Admit does.
(c) HonestThrottle == [][throttled' > throttled => tokens = 0]_vars holds for the gateway. Without B!Empty (module PSb2_GatewayLoose), TLC reports HonestThrottle violated after three states: the client sends, and the gateway answers 429 with 2 tokens in the bucket. TokensAccounted still holds, because a throttle spends nothing. This is assume-guarantee reasoning made concrete: the client's correctness argument may assume a 429 means "slow down", and the gateway must guarantee it. Each guarantee needs its own property, because the conservation invariant can't see this one.
Problem set 11 fixed the lost refund with SELECT … FOR UPDATE and checked it for two and three clients. A proof covers any number. Here is that wallet again, module PSb1_WalletLock: each client locks the row and reads the balance, writes the balance plus 10, and commits, which releases the lock.
---------------- MODULE PSb1_WalletLock ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Clients
(*--algorithm WalletLock
variables balance = 100, holder = "none";
define
AllDone == \A c \in Clients : pc[c] = "Done"
NoLostUpdate == AllDone => balance = 100 + 10 * Cardinality(Clients)
end define;
process Refund \in Clients
variable local = 0;
begin
Select: \* SELECT balance FROM accounts WHERE id = 1 FOR UPDATE
await holder = "none";
holder := self;
local := balance;
Update: \* UPDATE accounts SET balance = $1 WHERE id = 1
balance := local + 10;
Commit: \* COMMIT releases the row lock
holder := "none";
end process;
end algorithm; *)
========================================================
The translator produces these actions, with Refund(self) their disjunction and Next the usual (\E self \in Clients : Refund(self)) \/ Terminating:
Nat is infinite, so for TLC replace Money by a finite set: add MoneyModel == {0, 100, 110, 120} and the cfg line CONSTANT Money <- MoneyModel. Check that Inv is inductive for two clients, starting from INIT Inv.
Drop FreshRead, and separately LockHeld, and check each weaker candidate the same way. Explain each counterexample to induction.
Write a hierarchical proof of THEOREM Spec => []NoLostUpdate, in the style of lesson 43, with a case for each action. State the facts about Cardinality you need as lemmas with PROOF OMITTED. Make SANY parse it.
Say exactly what your answer to (c) establishes, and what it doesn't.
The structure of the proof in the solution. Each leaf is one obligation small enough to discharge by expanding definitions.
Hint
Only Update changes Paid: it adds self, which wasn't there because pc[self] was "Update". So you need "adding a new element to a finite set raises its cardinality by one" and "a subset of a finite set is finite", plus IsFiniteSet(Clients) as an assumption. For the step case, copy the shape of <1>2 in InventoryProof.
Solution
(a) The cfg (PSb2_WalletProof.cfg):
INIT Inv
NEXT Next
CONSTANT Clients = {A, B}
CONSTANT Money <- MoneyModel
INVARIANT Inv
INVARIANT NoLostUpdate
CHECK_DEADLOCK FALSE
TLC computes 144 initial states and finds no error, so Inv is inductive for two clients on this finite set of values, and it implies NoLostUpdate in each of them. With three clients and {0, 100, 110, 120, 130}, it finds 2800 states and no error.
(b) Without FreshRead, TLC starts from a state where A holds the lock at "Update" with local[A] = 0 and the balance 100, and Update(A) writes 10. Nothing in the weaker candidate says A's local value is current. Without LockHeld, TLC starts with both clients at "Update", both holding 100. Update(A) writes 110, and B's FreshRead fails, because B's read is now stale. Both are unreachable states. FreshRead carries the argument about values, and LockHeld is why no one else can make a fresh read stale.
(c) The proof, in the tree of the figure:
---------------- MODULE PSb2_WalletProof ----------------
EXTENDS PSb1_WalletLock, TLAPS
ASSUME ClientsOK == IsFiniteSet(Clients) /\ "none" \notin Clients
Money == Nat
Paid == {c \in Clients : pc[c] \in {"Commit", "Done"}}
TypeOK == /\ balance \in Money
/\ local \in [Clients -> Money]
/\ holder \in Clients \cup {"none"}
/\ pc \in [Clients -> {"Select", "Update", "Commit", "Done"}]
LockHeld == \A c \in Clients : (pc[c] \in {"Update", "Commit"}) <=> (holder = c)
FreshRead == \A c \in Clients : pc[c] = "Update" => local[c] = balance
Ledger == balance = 100 + 10 * Cardinality(Paid)
Inv == TypeOK /\ LockHeld /\ FreshRead /\ Ledger
LEMMA CardEmpty == Cardinality({}) = 0
PROOF OMITTED
LEMMA CardSubset == \A S, T : IsFiniteSet(T) /\ S \subseteq T => IsFiniteSet(S)
PROOF OMITTED
LEMMA CardAdd == \A S, x : IsFiniteSet(S) /\ x \notin S =>
Cardinality(S \cup {x}) = Cardinality(S) + 1
PROOF OMITTED
THEOREM Safety == Spec => []NoLostUpdate
<1>1. Init => Inv
BY ClientsOK, CardEmpty DEF Init, ProcSet, Inv, TypeOK, Money,
LockHeld, FreshRead, Ledger, Paid
<1>2. Inv /\ [Next]_vars => Inv'
<2> SUFFICES ASSUME Inv, [Next]_vars PROVE Inv'
OBVIOUS
<2>1. ASSUME NEW self \in Clients, Select(self) PROVE Inv'
\* holder goes from "none" to self, and local[self] gets balance.
BY <2>1, ClientsOK DEF Select, Inv, TypeOK, Money, LockHeld,
FreshRead, Ledger, Paid
<2>2. ASSUME NEW self \in Clients, Update(self) PROVE Inv'
\* FreshRead gives balance' = balance + 10, and self joins Paid.
<3>1. self \notin Paid /\ Paid' = Paid \cup {self}
BY <2>2 DEF Update, Inv, TypeOK, Paid
<3>2. IsFiniteSet(Paid)
BY ClientsOK, CardSubset DEF Paid
<3>3. Cardinality(Paid') = Cardinality(Paid) + 1
BY <3>1, <3>2, CardAdd
<3>4. QED
BY <2>2, <3>3 DEF Update, Inv, TypeOK, Money, LockHeld,
FreshRead, Ledger
<2>3. ASSUME NEW self \in Clients, Commit(self) PROVE Inv'
\* holder returns to "none"; Commit and Done are both in Paid.
BY <2>3, ClientsOK DEF Commit, Inv, TypeOK, LockHeld, FreshRead,
Ledger, Paid
<2>4. CASE Terminating \/ UNCHANGED vars
BY <2>4 DEF Terminating, vars, Inv, TypeOK, LockHeld, FreshRead,
Ledger, Paid
<2>5. QED
BY <2>1, <2>2, <2>3, <2>4 DEF Next, Refund
<1>3. Inv => NoLostUpdate
\* When all are Done, Paid = Clients.
BY DEF Inv, Ledger, Paid, NoLostUpdate, AllDone
<1>4. QED
BY <1>1, <1>2, <1>3, PTL DEF Spec
\* For TLC only: a finite stand-in for Money, and the weaker candidates.
MoneyModel == {0, 100, 110, 120}
NoFresh == TypeOK /\ LockHeld /\ Ledger
NoLock == TypeOK /\ FreshRead /\ Ledger
MoneyModel3 == {0, 100, 110, 120, 130}
=========================================================
SANY parses this module with no errors, using a stand-in for the TLAPS module that defines PTL, since TLAPS itself wasn't available. The definitions after the comment For TLC only serve the checks in (a) and (b). In <2>2, FreshRead gives balance' = local[self] + 10 = balance + 10, and <3>3 gives one more paid client, so Ledger is preserved. In <2>1, LockHeld and holder = "none" mean no client is at "Update" or "Commit", so the new holder is the only one. In <1>3, when every client is "Done", Paid = Clients.
(d) What was done: TLC checked that Inv is inductive and implies NoLostUpdate for two and three clients, and SANY checked that the proof is well formed. What was not done: no prover checked any step, so a step may need more facts or definitions than its BY lists, and the three lemmas are omitted. With TLAPS installed, you would run it on this module and add detail wherever a step fails. Even a complete proof would establish only this safety property, under the model's assumptions: that every writer takes the row lock, and that SELECT … FOR UPDATE really is one atomic step that waits, locks and reads. It says nothing about the client finishing, and nothing about a writer that bypasses the lock.
Beyond the lectures III: Failure-prone systems
Make retrying safe across a crash.
A retry is only safe if the effect and the record of that effect cannot be separated by a crash.
This builds on lesson 19, where a client could not tell a lost request from a lost reply and so had to retry, and on lesson 35, where a check and an action in separate steps let another process slip between them. Now the thing that slips between them is a crash.
Suppose a worker processes charge request r and records “seen r” so retries can return the earlier result. A durable value survives a crash; a volatile one does not. In each row of the diagram, the arrow labelled “crash, retry” starts from what is left on disk.
The gap between two durable writes is where a crash lands. Only the third row has no gap, so a retry finds either nothing or everything.
In the top row the charge is on disk with no ID, so the retry charges again. In the middle row the ID is on disk with no charge, so the retry is told the work is done when it is not. Only the bottom row has no gap between the two writes. Step through the top and bottom rows here. This lab is an educational model, not TLC.
Crash after the effect
Request roriginal + retry→Durable store
The contract
Start with what the system should appear to do, ignoring workers entirely. One atomic step records the request and applies its effect.
---------------- MODULE Once ----------------
EXTENDS Naturals
CONSTANT Requests
VARIABLES seen, effects
vars == <<seen,effects>>
Init == /\ seen = {}
/\ effects = [r \in Requests |-> 0]
Apply(r) ==
/\ r \notin seen
/\ seen' = seen \cup {r}
/\ effects' = [effects EXCEPT ![r] = @ + 1]
Next == \E r \in Requests: Apply(r)
Spec == Init /\ [][Next]_vars
TypeOK == /\ seen \subseteq Requests
/\ effects \in [Requests -> 0..1]
Consistent == \A r \in Requests:
(r \in seen) <=> (effects[r] = 1)
=============================================
TLC finds 4 distinct states and 5 generated, with both invariants holding. Duplicate deliveries do not appear here: at this level a repeated request is a stuttering step.
A worker that can crash
Now the implementation. effects and seen are durable, so Crash leaves them alone and resets only the volatile pc. Mode selects a design. Begin also models a redelivery, because it can run again whenever the worker is idle. The last two lines use a refinement mapping from lesson 33 to state that this worker should implement Once.
The two invariants split the problem. AtMostOnce says no duplicate effect. ReplyHonest says the client is never told “done” for work that did not happen. Each is easy to satisfy alone, so check both. The configuration for the safe design:
Bound is a state constraint from lesson 42. It only keeps the buggy designs finite, since a crash loop could otherwise raise effects forever. Changing Mode and Workers gives these results:
Mode
Workers
TLC result
EffectFirst
1
AtMostOnce violated, 4-state trace
IdFirst
1
ReplyHonest violated, 5-state trace
Atomic
1
Passes, including Refines: 5 distinct states, 8 generated
CheckThenCommit
1
Passes the two invariants: 6 distinct states, 10 generated
CheckThenCommit
2
AtMostOnce violated, 5-state trace
Atomic
2
Passes, including Refines: 9 distinct states, 27 generated
Trace lengths in these lessons come from TLC with one worker (-workers 1), which searches breadth-first and so reports a shortest trace. With more workers you may get a different trace of the same violation.
TLC’s counterexample for the effect-first design. The crash erases pc; nothing durable says the charge happened.The same crash against the atomic design, stepped by hand through the module’s actions. The second Begin reads seen and skips the charge.
Compare the two grids at the Crash column. It changes the same variable in both. The difference is what seen says afterwards. Checking Refines against EffectFirst also fails, at its very first step: effects changes while seen does not, and Once has no such step.
Predict: is “record the ID, then charge” safe, since it can never charge twice?
It is safe for AtMostOnce, and that is the trap. TLC’s trace for IdFirst is Begin, Crash, Begin, Reply: the ID is saved, the worker dies, the retry sees the ID and replies, and effects is still 0. You need both properties: no duplicate effect, and accepted work not silently lost.
A crash is not the only way in
The fourth row of the table is the instructive one. With one worker, CheckThenCommit passes, because its commit writes both values at once. Add a second worker and it fails with no crash at all. The diagram draws TLC’s trace.
TLC’s two-worker counterexample, drawn as messages. Nothing crashed: the check and the commit were separate steps.
Each worker’s commit is atomic, but the check came earlier, so this is the last-ticket race again. In a real store the fix is often a unique key on the request ID, so the second commit fails, or an equivalent compare-and-commit. Translate exactly that guarantee into your atomic boundary. The lesson for modeling: if the deployment has competing workers, a one-worker model can pass while the design is wrong.
Worked architecture: process an uploaded receipt once
A receipt-scanning service awards loyalty points after processing an image. Job r42 may be delivered twice. Define the business effect as a durable credit row keyed by r42, and define attempts as separate worker executions. “Exactly once” at the application boundary concerns the credit, not whether a worker ever repeats the computation.
A crash after the commit costs one repeated read. The dashed redelivery is harmless because the store already holds the answer.
In the diagram, a crash between OCR and the commit would lose only temporary work. The crash shown comes after the commit, so the acknowledgement is lost and the queue redelivers along the dashed arrow. The worker then finds a saved answer.
That is why the store keeps a result, not just a flag. A bare seen boolean can suppress a duplicate, but it cannot reconstruct the points awarded. Define a retention policy too: deleting r42’s record while late attempts remain possible reopens the duplicate path.
If the effect sits at an external payment provider, a local transaction cannot include it. The provider needs compatible request-ID semantics, or you need a different protocol. A transactional outbox commits a local data change together with an intent to publish an event, which makes those two atomic. Downstream consumers still need their own duplicate handling.
Predict: the points credit is committed locally, but an email is sent before the transaction completes. Is the whole operation atomic?
No. The email is an external side effect. An outbox can durably record the intention to send alongside the credit, but delivery may repeat unless the email boundary has its own identity or repetition is acceptable. Specify each observable effect separately.
Beyond the lectures III: Failure-prone systems
A former owner can still send a write.
A lease says who should own a resource. Only the resource can stop a former owner’s write from landing.
This builds on lesson 38, where one holder at a time was a property you could check, and on lesson 19, where messages could be delayed arbitrarily. Put those together and “one holder” is no longer enough: a former holder can have work still on its way.
A lease grants authority for an interval under assumptions about time. It does not erase a worker’s memory or retract its messages. If A pauses, the coordinator may grant the resource to B, and A may later resume believing it still owns the resource. Follow the red arrow.
No fence: the resource takes whichever write arrives. The red write is legal to send and wrong to accept.
A fencing token is an ordered number issued with each grant. The resource remembers the last token it accepted and refuses lower ones. Here is the same order of events with that rule.
Same events, with the fence. The check happens at the resource, so it works however late A’s write arrives.
The difference between the two charts is one comparison in the last two rows. Notice where it lives. The coordinator’s lease table cannot reject a write already in flight; only the resource sees that write.
The model
In this module a token stands for its holder. AcceptWrite(t) can run for any token ever granted, because to the resource a paused holder and a delayed message look identical. Tokens come from a single counter, so two holders cannot share one and nobody can invent a larger one. Those are requirements on the real issuing authority.
---------------- MODULE Fencing ----------------
EXTENDS Naturals
CONSTANTS MaxToken, Fenced
ASSUME Fenced \in BOOLEAN
VARIABLES issued, \* highest token the authority has granted
fence, \* token of the last write the resource accepted
staleAccepted \* history: did it accept a superseded token?
vars == <<issued, fence, staleAccepted>>
Init == /\ issued = 0
/\ fence = 0
/\ staleAccepted = FALSE
Grant == /\ issued < MaxToken
/\ issued' = issued + 1
/\ UNCHANGED <<fence, staleAccepted>>
\* Any token ever granted can still try to write: its holder may have
\* paused, or its message may have been delayed.
AcceptWrite(t) ==
/\ t \in 1..issued
/\ Fenced => t >= fence
/\ fence' = t
/\ staleAccepted' = (staleAccepted \/ t < issued)
/\ UNCHANGED issued
Next == Grant \/ \E t \in 1..MaxToken: AcceptWrite(t)
Spec == Init /\ [][Next]_vars
TypeOK == /\ issued \in 0..MaxToken
/\ fence \in 0..MaxToken
/\ staleAccepted \in BOOLEAN
FenceNeverRegresses == [][fence' >= fence]_fence
RevokedAtGrant == ~staleAccepted
================================================
FenceNeverRegresses is an action property, not an invariant, because “did not go down” compares two states. A state predicate such as fence >= 0 would pass in every design and prove nothing. With Fenced = TRUE, TLC finds no error: 15 distinct states, 34 generated. With Fenced = FALSE the property fails on the trace in the first chart: Grant, Grant, AcceptWrite(2), AcceptWrite(1).
What fencing does not promise
Predict: B holds token 2, but its write has not reached storage. Can storage still accept A’s token 1?
Yes. Add INVARIANT RevokedAtGrant with Fenced = TRUE and TLC reports a violation: Grant, Grant, AcceptWrite(1). Storage has never seen token 2.
TLC’s trace for RevokedAtGrant with fencing on. Storage has not heard of token 2, so it has no reason to refuse token 1.
So state the requirement precisely. Rejecting tokens below the highest accepted token is weaker than revoking A at the instant a new lease is issued. The stronger meaning needs another mechanism, such as installing the new epoch at the resource as part of the grant, or stronger timing assumptions.
Introduce time explicitly
Notice that the module has no clock. Fencing does not need one, because tokens are logical epochs. A lease model does. Untimed TLA+ does not secretly advance a clock, so add a variable such as now, a Tick action, expiration fields, and guards. Decide whether clocks are shared or local, how drift is bounded, whether processes can pause, and whether time must keep advancing. If now may stop forever, an eventual-expiration property can fail.
For a finite experiment, bound time or use a justified abstraction of “before expiry” and “after expiry.” Avoid wrapping timestamps modulo a small bound when ordering matters: the wrap can invent or hide stale-token bugs.
Worked example: a mobile session after logout
A mobile app starts uploading a profile change under session epoch 12. The user logs out, and the server revokes that session by advancing its epoch to 13. The old upload reaches the server afterward. Deleting the token from the phone does not recall the request.
Logout changes the server’s authority. It cannot recall the request already on the network.
Here the server’s test is equality with the current epoch, not “at least the last accepted,” because the server itself performs the revocation. That closes the gap from the previous section. The module has one request and one revocation, so you can see every step. Split chooses whether the comparison and the write are one step or two.
---------------- MODULE Session ----------------
CONSTANT Split
ASSUME Split \in BOOLEAN
VARIABLES sessionEpoch, profile, pc,
acceptedEpoch, epochAtAcceptance
vars == <<sessionEpoch, profile, pc, acceptedEpoch, epochAtAcceptance>>
Req == [epoch |-> 12, value |-> "new"] \* the delayed upload
Init == /\ sessionEpoch = 12
/\ profile = "old"
/\ pc = "sent"
/\ acceptedEpoch = 0
/\ epochAtAcceptance = 0
Revoke == /\ sessionEpoch = 12
/\ sessionEpoch' = 13
/\ UNCHANGED <<profile, pc, acceptedEpoch, epochAtAcceptance>>
Install == /\ profile' = Req.value
/\ acceptedEpoch' = Req.epoch
/\ epochAtAcceptance' = sessionEpoch
/\ pc' = "done"
/\ UNCHANGED sessionEpoch
\* One step: compare and write inside the same boundary.
Accept == /\ ~Split /\ pc = "sent"
/\ IF Req.epoch = sessionEpoch
THEN Install
ELSE /\ pc' = "rejected"
/\ UNCHANGED <<sessionEpoch, profile,
acceptedEpoch, epochAtAcceptance>>
\* Two steps: the check's result can outlive the authority it saw.
Check == /\ Split /\ pc = "sent"
/\ pc' = IF Req.epoch = sessionEpoch THEN "checked" ELSE "rejected"
/\ UNCHANGED <<sessionEpoch, profile,
acceptedEpoch, epochAtAcceptance>>
Write == /\ pc = "checked" /\ Install
Next == Revoke \/ Accept \/ Check \/ Write
Spec == Init /\ [][Next]_vars
AcceptedWithCurrentAuthority == acceptedEpoch = epochAtAcceptance
================================================
The two recorded epochs describe the last acceptance event. Do not instead require every past request’s epoch to equal today’s sessionEpoch: a legitimate past write does not become invalid when the user later logs out.
With Split = FALSE, TLC finds no error: 5 distinct states, 5 generated. With Split = TRUE, it fails.
TLC’s counterexample when the check and the write are separate steps. The last column shows a write accepted under authority that had already ended.
Read the grid from the left. The check was correct when performed, and its result outlived the authority it represented. This is the stale-check structure of lesson 35, applied to authorization. A fix must make the acceptance boundary enforce current authority, or deliberately document weaker revocation.
In a real app, include the user, tenant, and session in the credential’s scope. An epoch comparison does not authenticate a request or prevent cross-account access. Likewise, if a cached token validation stays valid for five minutes, immediate revocation is not your contract, and the model’s time and cache assumptions must say so.
Transfer exercise: where should a background photo upload be rejected after workspace switching?
First ask whether it is still authorized for the original workspace. Switching the visible UI is not necessarily revocation. If the product promises cancellation, model an upload or session generation checked by the receiving service at acceptance. Always preserve the original workspace identity in the request, rather than interpreting it using whichever workspace is currently selected.
Specifying Systems, chapter 9, develops explicit real-time specifications. Compare your lease model with an untimed fencing model before combining them.
Beyond the lectures III: Failure-prone systems
Two safe configurations can have an unsafe handoff.
Quorum overlap protects you inside one membership. Changing the membership needs its own argument.
This builds on lesson 21, where any two majorities of one set had to intersect, and on lesson 23, where that intersection carried decisions forward. Here the proof’s premise stops being true, because the two quorums come from different sets.
Suppose the old cluster is {A,B,C} and the new cluster is {C,D,E}. Each uses majorities of two.
Node C is in both configurations, but the old quorum does not use it. The two red quorums share nothing.
The diagram shows the problem: the configurations share C, yet the quorums {A,B} and {C,D} share nothing. A proof that every pair of quorums intersects within one configuration says nothing about this pair.
The joint rule, and what it does not do
Joint consensus requires decisions during the transition to satisfy both old and new quorum rules. For this pair the smallest such sets are {A,C,D}, {A,C,E}, {B,C,D}, {B,C,E}, and {A,B,D,E}. Each contains a majority of Old, so each intersects any earlier old quorum.
Any joint acknowledgement holds a majority of Old, so it must contain A or B. Here the two sets overlap at A.
That overlap, shown in the diagram at A, blocks a conflicting decision during the transition. It does nothing after the switch, when New is on its own. A joint phase with no further rule still fails, as you will see below. The bridge is the transition protocol: when old-only decisions stop, and what the new majority must hold before it takes over.
The safe path has two guards. The dashed path is the handoff that fails.
A model of the handoff
This module tracks one decision. A node stores at most one value. Decide is the acknowledgement, under whatever rule the current phase uses. Copy is state transfer: it brings a new node up to the decided state as it is at that moment. Copying is separate from voting authority, because a caught-up replica does not vote until the phase says so.
---------------- MODULE Reconfig ----------------
EXTENDS Naturals, FiniteSets
CONSTANT Mode
ASSUME Mode \in {"Direct", "CopyOnly", "JointNoEvidence", "Joint", "OldLingers"}
Old == {"A", "B", "C"}
New == {"C", "D", "E"}
Nodes == Old \cup New
Values == {"X", "Y"}
VARIABLES phase, \* "old", "joint", or "new"
val, \* val[n]: the value node n has durably stored
decided, \* values acknowledged as decided
copied \* new nodes that have run the state copy
vars == <<phase, val, decided, copied>>
Init == /\ phase = "old"
/\ val = [n \in Nodes |-> "none"]
/\ decided = {}
/\ copied = {}
Holding(v) == {n \in Nodes : val[n] = v}
Majority(s, c) == Cardinality(s \cap c) * 2 > Cardinality(c)
JointAck(s) == Majority(s, Old) /\ Majority(s, New)
\* The rule this phase uses to acknowledge a decision.
CanDecide(v) ==
\/ phase = "old" /\ Majority(Holding(v), Old)
\/ phase = "joint" /\ JointAck(Holding(v))
\/ phase = "new" /\ Majority(Holding(v), New)
\/ Mode = "OldLingers" /\ Majority(Holding(v), Old)
Voters == CASE phase = "old" -> Old
[] phase = "joint" -> Nodes
[] phase = "new" ->
IF Mode = "OldLingers" THEN Nodes ELSE New
Store(n, v) == /\ n \in Voters
/\ val[n] = "none"
/\ val' = [val EXCEPT ![n] = v]
/\ UNCHANGED <<phase, decided, copied>>
Decide(v) == /\ CanDecide(v)
/\ decided' = decided \cup {v}
/\ UNCHANGED <<phase, val, copied>>
\* Copy the decided state, as it is right now, to a new node.
Copy(n) == /\ n \in New
/\ copied' = copied \cup {n}
/\ val' = IF decided = {} THEN val
ELSE [val EXCEPT ![n] = CHOOSE v \in decided : TRUE]
/\ UNCHANGED <<phase, decided>>
UsesJoint == Mode \in {"JointNoEvidence", "Joint", "OldLingers"}
EnterJoint == /\ UsesJoint /\ phase = "old"
/\ phase' = "joint"
/\ UNCHANGED <<val, decided, copied>>
\* What must be true before the new configuration takes over.
ReadyToActivate ==
CASE Mode = "Direct" -> phase = "old"
[] Mode = "CopyOnly" -> phase = "old" /\ Majority(copied, New)
[] Mode = "JointNoEvidence" -> phase = "joint"
[] Mode \in {"Joint", "OldLingers"} ->
/\ phase = "joint"
/\ \A v \in decided : Majority(Holding(v), New)
Activate == /\ ReadyToActivate
/\ phase' = "new"
/\ UNCHANGED <<val, decided, copied>>
Next == \/ \E n \in Nodes, v \in Values : Store(n, v)
\/ \E v \in Values : Decide(v)
\/ \E n \in New : Copy(n)
\/ EnterJoint \/ Activate
Spec == Init /\ [][Next]_vars
TypeOK == /\ phase \in {"old", "joint", "new"}
/\ val \in [Nodes -> Values \cup {"none"}]
/\ decided \subseteq Values
/\ copied \subseteq New
Agreement == Cardinality(decided) <= 1
================================================
Agreement is the global property: it spans configurations, rather than being checked inside each one. Each Mode removes one part of the handoff.
Mode
What it does
TLC result
Direct
Switches with no copy and no joint phase
Violated, 8-state trace
CopyOnly
Waits for a new majority to run the copy, while old quorums keep deciding
Violated, 10-state trace
JointNoEvidence
Uses the joint phase, then activates without the evidence guard
Violated, 9-state trace
OldLingers
Keeps every guard, but the old rule still counts after the phase changes
Violated, 9-state trace
Joint
Stops old-only decisions, then requires the evidence guard
Passes: 6372 distinct states, 39293 generated
TLC’s counterexample for Direct. C is the shared member and it did not help: it was outside the old quorum, then inside the new one.
Read the Direct grid by rows. X is decided while A and B hold it. Then the phase flips, and C and D, a majority of New that has never heard of X, decide Y.
The other three failures each match a slogan you may have heard. CopyOnly is “wait until copying finishes”: in TLC’s trace, C runs the copy before anything is decided and keeps its Y, X is decided next, D copies X, and the switch goes ahead because two nodes have “copied.” C and E then decide Y. JointNoEvidence is “use joint consensus” with no statement of what the switch requires. OldLingers is “raise the epoch” while old servers still accept old-epoch work. Each is a real action, so TLC can refute it.
Know the limits. The model has one decision, no crashes, and no delayed messages beyond what OldLingers stands for. A value that was stored but never acknowledged may be discarded. It is a study model of the handoff, not of any particular protocol.
Exercise: why is “add one node at a time” not a full specification?
It leaves unanswered when the change becomes authoritative, which voters count, how state is transferred, what a leader persists, and how concurrent or interrupted changes recover. A slogan can guide design; an action relation must define the handoff.
Worked example: moving an inventory shard
A shopping service moves one stock record from {A,B,C} to {C,D,E}. All old replicas know there are three units. The new replicas are copied from an earlier snapshot. The team changes a routing configuration so that new clients use the new cluster, while some old clients keep cached routes.
The worked example. Each cluster’s local majority was satisfied; the overselling only appears in the global total.
Follow the chart from the top: copy stock = 3 to D and E; A and B acknowledge r1 for one unit; routing switches; D and E acknowledge r2 for three units from their copy. This is CopyOnly in business terms. Read X as r1 and Y as r2: two acknowledgements that cannot both stand, because together they promise four units out of three. The old route was not merely inefficient. It kept decision authority during a handoff that lost evidence.
Checking each cluster’s local stock misses this, so the property must be global: total acknowledged quantity never exceeds three. The evidence rule must connect to what future decisions actually read. It cannot mean that some isolated new node has the record. Activate asks for a majority of New because that is the set every later new quorum must intersect.
A complete design says when the authoritative configuration changes, how that decision is persisted, how new authority learns all committed state, and where stale authority is rejected. Inject a crash between each pair of those steps as a next experiment. A client’s routing cache can affect availability and placement, but it must not decide whether an obsolete server may still commit.
Transfer exercise: does reducing the DNS cache TTL solve the unsafe handoff?
No. It shortens some clients’ stale-routing period but does not prove all stale requests disappear. Safety should follow from server-side authority and evidence rules even when an old route is used. A route refresh or redirect can then restore progress under the appropriate network assumptions.
For one concrete protocol, study membership changes in the extended Raft paper and compare them with its log and election rules.
Beyond the lectures III: Failure-prone systems
Problem set 13: failures that outlive the step that caused them.
Every module below is complete and was checked with TLC exactly as shown, so your state counts should match if your copy is identical. When a problem asks for the length of a trace, run TLC with one worker (-workers 1) so that its breadth-first search reports a shortest one. Each trace length counts the initial state.
Problem 1●○○Payments
An idempotency key that doesn't stop a double debit
A wallet service stores balances in Postgres and exposes POST /debit. Following the convention of many payment APIs, the mobile app sends an Idempotency-Key header and, after a timeout, retries with the same key. The handler looks like this:
const prior = await db.query("SELECT response FROM idem WHERE key = $1", [key]);
if (prior.rows.length) return prior.rows[0].response;
await db.query("INSERT INTO ledger (account, amount) VALUES ($1, $2)", [acct, -amt]);
await db.query("INSERT INTO idem (key, response) VALUES ($1, 'ok')", [key]);
return "ok";
Each statement commits on its own. Support finds customers debited twice for one purchase, always during deploys, when a handler process can be killed mid-request. The module below models one key. ledger and stored are durable; each handler's pc is volatile, so Crash resets it. Receive can run whenever a handler is idle, so it stands for the first attempt and for every retry. Mode selects a design: NoTx is the code above, KeyThenDebit swaps the two INSERTs, TxAfterCheck wraps both INSERTs in one transaction after the SELECT, and KeyFirstTx runs one transaction that begins by inserting the key, which is the primary key of idem.
---------------- MODULE PSb3_Wallet ----------------
EXTENDS Naturals
CONSTANTS Handlers, Mode
ASSUME Mode \in {"NoTx", "KeyThenDebit", "TxAfterCheck", "KeyFirstTx"}
VARIABLES ledger, \* durable: debit rows written for key k
stored, \* durable: does the idem row for k exist?
pc, \* pc[h]: volatile position of handler h
replied \* the client has received "ok"
vars == <<ledger, stored, pc, replied>>
Init == /\ ledger = 0
/\ stored = FALSE
/\ pc = [h \in Handlers |-> "idle"]
/\ replied = FALSE
Go(h, where) == pc' = [pc EXCEPT ![h] = where]
\* An attempt (the first try or a retry with the same key) reaches h.
Receive(h) == /\ pc[h] = "idle"
/\ Go(h, "select")
/\ UNCHANGED <<ledger, stored, replied>>
\* SELECT response FROM idem WHERE key = k
Select(h) == /\ pc[h] = "select" /\ Mode # "KeyFirstTx"
/\ Go(h, IF stored THEN "reply" ELSE "write")
/\ UNCHANGED <<ledger, stored, replied>>
\* NoTx: two autocommitted INSERTs.
Debit(h) == /\ pc[h] = "write" /\ Mode = "NoTx"
/\ ledger' = ledger + 1
/\ Go(h, "key")
/\ UNCHANGED <<stored, replied>>
SaveKey(h) == /\ pc[h] = "key"
/\ stored' = TRUE
/\ Go(h, "reply")
/\ UNCHANGED <<ledger, replied>>
\* KeyThenDebit: the same two INSERTs, in the other order.
KeyFirst(h) == /\ pc[h] = "write" /\ Mode = "KeyThenDebit"
/\ stored' = TRUE
/\ Go(h, "debit")
/\ UNCHANGED <<ledger, replied>>
DebitLast(h) == /\ pc[h] = "debit"
/\ ledger' = ledger + 1
/\ Go(h, "reply")
/\ UNCHANGED <<stored, replied>>
\* TxAfterCheck: both INSERTs in one transaction, after the SELECT.
Commit(h) == /\ pc[h] = "write" /\ Mode = "TxAfterCheck"
/\ ledger' = ledger + 1
/\ stored' = TRUE
/\ Go(h, "reply")
/\ UNCHANGED replied
\* KeyFirstTx: BEGIN; INSERT INTO idem (k is its primary key);
\* INSERT INTO ledger; COMMIT. If k already exists the INSERT fails,
\* nothing is written, and the handler returns the stored response.
KeyTx(h) == /\ pc[h] = "select" /\ Mode = "KeyFirstTx"
/\ IF stored THEN UNCHANGED <<ledger, stored>>
ELSE /\ ledger' = ledger + 1
/\ stored' = TRUE
/\ Go(h, "reply")
/\ UNCHANGED replied
Reply(h) == /\ pc[h] = "reply"
/\ replied' = TRUE
/\ Go(h, "idle")
/\ UNCHANGED <<ledger, stored>>
\* The process dies: its position is lost, the database is not.
Crash(h) == /\ pc[h] # "idle"
/\ Go(h, "idle")
/\ UNCHANGED <<ledger, stored, replied>>
Next == \E h \in Handlers :
\/ Receive(h) \/ Select(h) \/ Debit(h) \/ SaveKey(h)
\/ KeyFirst(h) \/ DebitLast(h)
\/ Commit(h) \/ KeyTx(h) \/ Reply(h) \/ Crash(h)
Spec == Init /\ [][Next]_vars
AtMostOnce == ledger <= 1
OkMeansDebited == replied => ledger >= 1
Bound == ledger <= 2 \* keeps the buggy designs finite
====================================================
TLC’s trace for NoTx, as messages. The key exists to remember the debit, but a separate commit writes it, so the crash lands in the gap.
Run NoTx with one handler. Which invariant fails? Match each step of TLC's trace to a line of the handler code.
A teammate proposes KeyThenDebit: "if the key is saved first, a retry can never debit again." Predict which invariant fails, then run it.
Run TxAfterCheck with Handlers = {h1} and then with {h1, h2}. Explain the difference. What real event does a second handler stand for?
Run KeyFirstTx with two handlers. Explain why one KeyTx step is a fair model of a Postgres transaction even though two of them can run at the same time.
Hint
Look at what is durable at the moment of the crash, as in the three-row diagram of Architecture: durable idempotent worker: the debit, the key, both or neither. For task 3, a second handler can be the retry arriving while the first attempt is still running, not only after a crash.
Solution
Mode
Handlers
TLC result
NoTx
1
AtMostOnce violated, 8-state trace
NoTx
2
AtMostOnce violated, 7-state trace, no crash
KeyThenDebit
1
OkMeansDebited violated, 8-state trace
KeyThenDebit
2
OkMeansDebited violated, 7-state trace, no crash
TxAfterCheck
1
No error: 9 distinct states
TxAfterCheck
2
AtMostOnce violated, 7-state trace, no crash
KeyFirstTx
1
No error: 8 distinct states
KeyFirstTx
2
No error: 22 distinct states
1.AtMostOnce fails. The trace is Receive(h1) (the request arrives), Select(h1) (no key), Debit(h1) (the ledger INSERT commits), Crash(h1) (the deploy kills the process before the second INSERT), then the retry: Receive(h1), Select(h1) finds no key, Debit(h1) and ledger = 2. The diagram draws it. The key exists to remember the debit, but the two are written by separate commits, so a crash can separate them.
2.OkMeansDebited fails, and AtMostOnce never does. With one handler: KeyFirst(h1) saves the key, Crash(h1), then the retry's Select finds the key and Reply tells the client "ok" with ledger = 0. The customer is told they paid and the merchant ships for free. This is the ID-first trap from Architecture: durable idempotent worker, and it is why the module checks two invariants: each design can pass one by failing the other.
3. One handler passes, two fail without any crash: both run Select while no key exists, then both Commit. A second handler is what a client timeout produces. The app gives up after ten seconds and retries, while the first attempt is still waiting on a slow query. A transaction makes the two INSERTs atomic, but the SELECT ran earlier, outside it. That is the stale check of Atomicity and the last ticket.
4.KeyFirstTx passes with two handlers. The fix:
BEGIN;
INSERT INTO idem (key, response) VALUES ($1, 'ok'); -- key is the primary key
INSERT INTO ledger (account, amount) VALUES ($2, $3);
COMMIT;
-- on unique_violation: ROLLBACK, then SELECT the stored response and return it
Postgres enforces the unique index across concurrent transactions. If a second transaction inserts a key that an uncommitted transaction has already inserted, it waits; if the first commits, the second fails with a unique violation and writes nothing. So the outcome is always as if one whole transaction ran before the other, and a single atomic step models it. The check is no longer a separate read: the database performs it as part of the write. A crash at any point either rolls back both rows or leaves both.
This works because the debit is a row in the same database. If the effect were a charge at an external card network, no local transaction could include it, and you would need the provider's own idempotency contract, as Architecture: durable idempotent worker says.
A nightly compaction job rewrites a table's data file in object storage. Two instances run for availability, and only the one holding a lease from a lock service may write. Each instance checks that its lease is still valid just before writing. One night instance c1 checks its lease, then stops for a long stop-the-world garbage-collection pause. Its lease expires, c2 gets the lease and writes, and then c1 wakes up and sends its write anyway. The file ends up with c1's stale data on top of c2's.
The module adds time explicitly, as Architecture: leases, fencing, and time recommends: now is the lock service's clock and Tick advances it. A lease lasts LeaseLen ticks. The pause is simply that any number of Tick steps may happen between Check(c) and Send(c). Writes travel over a network modeled as a set, so they can be delayed and reordered. Storage keeps log, the sequence of tokens whose writes it applied, so the property is an ordinary invariant. Fenced turns on the storage-side token check.
---------------- MODULE PSb3_Lease ----------------
EXTENDS Naturals, Sequences
CONSTANTS Clients, LeaseLen, MaxTime, Fenced, CheckAndSend
ASSUME Fenced \in BOOLEAN /\ CheckAndSend \in BOOLEAN /\ LeaseLen >= 1
VARIABLES now, \* the lock service's clock
holder, \* the client the service granted the lease to
expires, \* the time at which that lease ends
issued, \* the highest fencing token issued so far
token, \* token[c]: the token client c received
pc, \* pc[c]: "idle", "checked" or "sent"
net, \* tokens of writes still on the network
fence, \* the highest token storage has accepted
log \* tokens of the writes storage accepted, in order
vars == <<now, holder, expires, issued, token, pc, net, fence, log>>
Tokens == 1..(MaxTime + 1) \* at most one grant per tick, plus one at time 0
Init == /\ now = 0
/\ holder = "none"
/\ expires = 0
/\ issued = 0
/\ token = [c \in Clients |-> 0]
/\ pc = [c \in Clients |-> "idle"]
/\ net = {}
/\ fence = 0
/\ log = <<>>
Tick == /\ now < MaxTime
/\ now' = now + 1
/\ UNCHANGED <<holder, expires, issued, token, pc, net, fence, log>>
\* The service grants a lease when there is none or it has expired.
\* (Renewal is left out: a client never takes over its own lease.)
Acquire(c) == /\ holder = "none" \/ now >= expires
/\ holder # c
/\ pc[c] # "checked"
/\ holder' = c
/\ expires' = now + LeaseLen
/\ issued' = issued + 1
/\ token' = [token EXCEPT ![c] = issued + 1]
/\ pc' = [pc EXCEPT ![c] = "idle"]
/\ UNCHANGED <<now, net, fence, log>>
\* The client checks that its lease is still valid ...
Check(c) == /\ ~CheckAndSend
/\ pc[c] = "idle" /\ holder = c /\ now < expires
/\ pc' = [pc EXCEPT ![c] = "checked"]
/\ UNCHANGED <<now, holder, expires, issued, token, net, fence, log>>
\* ... and later (after a pause of any length) sends its write.
Send(c) == /\ pc[c] = "checked"
/\ net' = net \cup {token[c]}
/\ pc' = [pc EXCEPT ![c] = "sent"]
/\ UNCHANGED <<now, holder, expires, issued, token, fence, log>>
\* The variant with no gap between the check and the send.
CheckSend(c) == /\ CheckAndSend
/\ pc[c] = "idle" /\ holder = c /\ now < expires
/\ net' = net \cup {token[c]}
/\ pc' = [pc EXCEPT ![c] = "sent"]
/\ UNCHANGED <<now, holder, expires, issued, token, fence, log>>
\* Storage receives a write. With fencing it refuses old tokens.
Deliver(t) == /\ t \in net
/\ net' = net \ {t}
/\ IF Fenced /\ t < fence
THEN UNCHANGED <<fence, log>>
ELSE /\ log' = Append(log, t)
/\ fence' = IF t > fence THEN t ELSE fence
/\ UNCHANGED <<now, holder, expires, issued, token, pc>>
Next == \/ Tick
\/ \E c \in Clients : Acquire(c) \/ Check(c) \/ Send(c) \/ CheckSend(c)
\/ \E t \in Tokens : Deliver(t)
Spec == Init /\ [][Next]_vars
\* Storage never applies an older lease's write after a newer one.
WritesInLeaseOrder ==
\A i, j \in 1..Len(log) : i < j => log[i] <= log[j]
====================================================
The pause sits between the check and the send, and the network adds more delay after it. Both are invisible to c1, and only storage sees the order in which writes land.
Run the configuration above (Fenced = FALSE, CheckAndSend = FALSE). Write out TLC's trace. Where is the pause, and at what time did c1's lease expire?
Someone proposes removing the pause window: check the lease and send the write in one step (CheckAndSend = TRUE). Predict whether that fixes the bug, then run it. What takes the pause's place in the trace?
Set Fenced = TRUE and run both values of CheckAndSend. Report the distinct states.
A check that was true when it ran tells you nothing about the moment the write lands. Ask where the write is between the check and the moment storage applies it. For task 4, look at which variable remembers the past.
Solution
1.WritesInLeaseOrder fails with an 11-state trace. Acquire(c1) at time 0 gives token 1 and expires = 2. Tick to 1, then Check(c1): the lease is valid, since 1 < 2. Tick to 2: the lease has now expired, and c1 has not written. That gap is the pause. Send(c1) puts token 1 on the network. Acquire(c2) gives token 2, c2 checks and sends, and storage applies Deliver(2) and then Deliver(1): log = <<2, 1>>. The diagram draws this.
2. It still fails, now with a 9-state trace: Acquire(c1), Tick, CheckSend(c1), Tick, Acquire(c2), CheckSend(c2), Deliver(2), Deliver(1). The write leaves c1 while the lease is valid, but it waits in net while time passes. To storage, a paused process and a slow message look the same, which is the point Architecture: leases, fencing, and time makes. No client-side check can close a gap that lies after the client.
3. No error in either run: 186 distinct states with CheckAndSend = FALSE and 124 with TRUE. Storage drops token 1 because its fence is already 2.
4.log is a history variable: it records every accepted write, in order. "Never accepted a lower token after a higher one" is then a fact about the current value of log, so a state predicate can express it. The fence alone forgets the past, so with only fence you need an action property that compares two states. Both work. The history version gives a trace that ends with the evidence on screen.
The model still leaves things out: the clocks of c1 and c2 do not appear, because the lock service's clock decides expiry, and renewals are omitted. Fencing makes those questions matter less for safety: the order of writes no longer depends on any clock being right.
A configuration store runs on nodes A, B and C and decides with majority quorums. Load is growing and the team wants five nodes. One engineer edits the member list from three to five in one step. Another says that is unsafe and proposes two steps, adding D and then E, "because the old and new majorities of each step overlap". Before arguing, measure. The first module checks quorum overlap between two fixed memberships, using Init as a search over pairs of quorums.
---------------- MODULE PSb3_Quorums ----------------
EXTENDS Naturals, FiniteSets
CONSTANTS Old, New
Majorities(S) == {Q \in SUBSET S : 2 * Cardinality(Q) > Cardinality(S)}
VARIABLES q1, q2 \* an old-configuration quorum and a new one
InitAll == /\ q1 \in Majorities(Old)
/\ q2 \in Majorities(New)
InitDisjoint == InitAll /\ q1 \cap q2 = {}
Next == UNCHANGED <<q1, q2>> \* only the initial states matter
Overlap == q1 \cap q2 # {}
=====================================================
INIT InitAll
NEXT Next
CONSTANTS Old = {"A", "B", "C"}
New = {"A", "B", "C", "D", "E"}
INVARIANT Overlap
The second module tracks one decision across a sequence of memberships, in the style of Architecture: changing membership's Reconfig. A node stores at most one value, a value is decided when a majority of the active configuration stores it, and Activate moves to the next configuration in Configs. Guarded adds one condition to Activate.
---------------- MODULE PSb3_Grow ----------------
EXTENDS Naturals, Sequences, FiniteSets
CONSTANTS Plan, Guarded
ASSUME Plan \in {"3to4", "3to5", "3to4to5"} /\ Guarded \in BOOLEAN
C3 == {"A", "B", "C"}
C4 == {"A", "B", "C", "D"}
C5 == {"A", "B", "C", "D", "E"}
Configs == CASE Plan = "3to4" -> <<C3, C4>>
[] Plan = "3to5" -> <<C3, C5>>
[] Plan = "3to4to5" -> <<C3, C4, C5>>
Nodes == C5
Values == {"X", "Y"}
VARIABLES cfg, \* index of the active configuration in Configs
val, \* val[n]: the value node n has durably stored
decided \* values acknowledged as decided
vars == <<cfg, val, decided>>
Init == /\ cfg = 1
/\ val = [n \in Nodes |-> "none"]
/\ decided = {}
Majority(S, c) == 2 * Cardinality(S \cap c) > Cardinality(c)
Holding(v) == {n \in Nodes : val[n] = v}
Store(n, v) == /\ n \in Configs[cfg]
/\ val[n] = "none"
/\ val' = [val EXCEPT ![n] = v]
/\ UNCHANGED <<cfg, decided>>
Decide(v) == /\ Majority(Holding(v), Configs[cfg])
/\ decided' = decided \cup {v}
/\ UNCHANGED <<cfg, val>>
\* Switch to the next configuration. Guarded: only once a majority of
\* the next configuration already stores every decided value.
Activate == /\ cfg < Len(Configs)
/\ Guarded => \A v \in decided :
Majority(Holding(v), Configs[cfg + 1])
/\ cfg' = cfg + 1
/\ UNCHANGED <<val, decided>>
Next == \/ \E n \in Nodes, v \in Values : Store(n, v)
\/ \E v \in Values : Decide(v)
\/ Activate
Spec == Init /\ [][Next]_vars
Agreement == Cardinality(decided) <= 1
==================================================
The two quorums from TLC’s "3to4to5" trace. Configuration 2 (A, B, C, D) sat between them and overlapped both, but nothing forced it to hold X.
By hand, find a majority of {A, B, C} and a majority of {A, B, C, D, E} that share no node. Can you do the same for {A, B, C} and {A, B, C, D}?
Run PSb3_Quorums as shown, then with New = {A, B, C, D}. Then replace INIT InitAll with INIT InitDisjoint and drop the invariant: the number of distinct states is the number of disjoint pairs. Report it for both memberships.
Run PSb3_Grow with each Plan and Guarded = FALSE. Which plans fail? For "3to4to5", say which nodes decided X, which decided Y, and in which configurations.
Set Guarded = TRUE and rerun all three. Say in one sentence what the guard requires, and why it repairs the chain of two safe-looking steps.
Hint
Overlap is a fact about two particular quorums. In task 3, ask which two quorums actually decided, not which configurations are adjacent. For task 4, a decided value must be present wherever the next configuration's quorums can look.
Solution
1. {A, B} is a majority of three, and {C, D, E} is a majority of five; they are disjoint. For four nodes a majority has 3 members, and 2 + 3 > 4 means any old majority of 2 and new majority of 3 must share a node among the four, so no disjoint pair exists.
2. With five nodes TLC reports Overlap violated by an initial state, q1 = {"A", "B"} and q2 = {"C", "D", "E"}. With four, no error on 20 distinct states, which is every pair: 4 majorities of {A, B, C} times 5 of {A, B, C, D}. With InitDisjoint, five nodes give 3 distinct states and four give 0.
Plan
Guarded = FALSE
Guarded = TRUE
"3to4"
No error, 164 distinct states
No error, 140
"3to5"
Agreement violated, 9-state trace
No error, 386
"3to4to5"
Agreement violated, 10-state trace
No error, 485
3. In the chain, A and B store X and C stores Y. X is decided in configuration 1 by {A, B}. Activate moves to {A, B, C, D}; D stores Y, so Y has 2 of 4, not a majority, and nothing is wrong yet. Activate again; E stores Y, and in configuration 3 Y holds C, D, E: 3 of 5, decided. The diagram shows that {A, B} and {C, D, E} miss each other. Each step's majorities did overlap. But the overlap argument from Set operations and quorums only protects a decision if the quorum that made it intersects the quorum that might contradict it. Here those quorums are two configurations apart.
4. The guard says: switch to the next configuration only when a majority of it already stores every decided value. Then any quorum of the new configuration meets a node that holds X, and that node can never store Y. Applied at each step, the evidence is carried forward one configuration at a time, which repairs the chain. Raft's single-server changes rely on a similar fact supplied by the log. A change starts only after the previous configuration entry is committed in its configuration, and a log is ordered, so a majority that stores that entry also stores every entry before it. "Add one node at a time" is safe only together with that rule, which is the exercise in Architecture: changing membership made concrete.
A checkout service writes orders to Postgres. A shipping service prints a label for each order it hears about through a message broker. The first version commits the order and then publishes an OrderPlaced event, and some orders never ship: the process died between the commit and the publish. This is a dual write, two systems updated by separate steps. The team switches to a transactional outbox. The order and an outbox row are inserted in one transaction, and a relay process reads outbox rows, publishes them, and deletes them afterward. The broker delivers at least once. The shipping service deduplicates by inserting the order ID into a processed table in the same transaction that creates the label.
The broker is modeled as a set that Consume never removes from, as in Messages, failures, and retries. That covers redelivery, the same idea you used for at-least-once delivery in Problem set 6. MaxCrashes bounds how many process crashes can happen. Shipped is the liveness requirement: every committed order eventually gets a label.
---------------- MODULE PSb3_Outbox ----------------
EXTENDS Naturals
CONSTANTS Orders, Mode, Dedup, MaxCrashes
ASSUME Mode \in {"DualWrite", "Outbox"} /\ Dedup \in BOOLEAN
VARIABLES orders, \* order service DB: committed orders
outbox, \* order service DB: outbox rows not yet relayed
handler, \* handler[o]: "new", "publish" or "done" (volatile)
relay, \* the relay's in-memory work: "idle" or an order
broker, \* orders whose event the broker holds
processed, \* shipping DB: orders recorded as handled
labels, \* labels[o]: shipping labels printed for o
crashes \* crashes so far
vars == <<orders, outbox, handler, relay, broker,
processed, labels, crashes>>
Init == /\ orders = {}
/\ outbox = {}
/\ handler = [o \in Orders |-> "new"]
/\ relay = "idle"
/\ broker = {}
/\ processed = {}
/\ labels = [o \in Orders |-> 0]
/\ crashes = 0
\* The checkout handler commits the order. In Outbox mode the same
\* transaction inserts the outbox row.
Place(o) == /\ handler[o] = "new"
/\ orders' = orders \cup {o}
/\ IF Mode = "Outbox"
THEN outbox' = outbox \cup {o} /\ handler' = [handler EXCEPT ![o] = "done"]
ELSE UNCHANGED outbox /\ handler' = [handler EXCEPT ![o] = "publish"]
/\ UNCHANGED <<relay, broker, processed, labels, crashes>>
\* DualWrite: after the commit, the handler publishes to the broker.
Publish(o) == /\ handler[o] = "publish"
/\ broker' = broker \cup {o}
/\ handler' = [handler EXCEPT ![o] = "done"]
/\ UNCHANGED <<orders, outbox, relay, processed, labels, crashes>>
\* Outbox: a relay publishes a row, then deletes it in a second step.
RelayPublish(o) == /\ relay = "idle" /\ o \in outbox
/\ broker' = broker \cup {o}
/\ relay' = o
/\ UNCHANGED <<orders, outbox, handler, processed, labels, crashes>>
RelayDelete == /\ relay # "idle"
/\ outbox' = outbox \ {relay}
/\ relay' = "idle"
/\ UNCHANGED <<orders, handler, broker, processed, labels, crashes>>
\* A process crash loses in-memory state; databases and broker survive.
Crash == /\ crashes < MaxCrashes
/\ crashes' = crashes + 1
/\ \/ \E o \in Orders : /\ handler[o] = "publish"
/\ handler' = [handler EXCEPT ![o] = "done"]
/\ UNCHANGED relay
\/ /\ relay # "idle"
/\ relay' = "idle"
/\ UNCHANGED handler
/\ UNCHANGED <<orders, outbox, broker, processed, labels>>
\* The broker delivers at least once: an event stays available, so the
\* consumer can receive it again. With Dedup, printing the label and
\* recording the order happen in one shipping-DB transaction.
Consume(o) == /\ o \in broker
/\ Dedup => o \notin processed
/\ labels[o] < 2
/\ labels' = [labels EXCEPT ![o] = @ + 1]
/\ processed' = processed \cup {o}
/\ UNCHANGED <<orders, outbox, handler, relay, broker, crashes>>
Next == \/ \E o \in Orders : Place(o) \/ Publish(o) \/ RelayPublish(o) \/ Consume(o)
\/ RelayDelete \/ Crash
Spec == Init /\ [][Next]_vars
Fairness == /\ \A o \in Orders : WF_vars(Publish(o)) /\ WF_vars(RelayPublish(o))
/\ WF_vars(Consume(o))
/\ WF_vars(RelayDelete)
FairSpec == Spec /\ Fairness
OneLabel == \A o \in Orders : labels[o] <= 1
NoLostEvent == \A o \in orders :
o \in outbox \/ o \in broker \/ handler[o] = "publish"
Shipped == \A o \in Orders : (o \in orders) ~> (labels[o] >= 1)
====================================================
Duplicates arrive from two places, a relay retry and a broker redelivery. Only the consumer’s check stops both.
Run Mode = "DualWrite", Dedup = TRUE with PROPERTY Shipped. Read TLC's counterexample, including its last line. Then check the same design with INVARIANT NoLostEvent instead, and compare the two traces.
Run Mode = "Outbox", Dedup = FALSE with both invariants. Which fails? A relay crash between publish and delete is the obvious source of duplicates. Is it in TLC's trace? Explain.
Run the configuration shown, with the outbox and deduplication. Report the distinct states.
Remove one conjunct of Fairness at a time and rerun Shipped. Which conjunct can go? For the others, describe the behavior TLC reports.
Why must crashes be bounded for Shipped to hold, and what would you assume about a real relay instead?
Hint
A liveness failure ends in a state the system can stay in forever. Ask what fact about that state already shows the order is lost: that fact is a safety property you can check much sooner. For task 2, adding an element to a set that already contains it changes nothing.
Solution
1.Shipped is violated: Place(o1), Crash (the handler dies before publishing), Place(o2), Publish(o2), Consume(o2), then "Stuttering". The behavior stays forever in a state where o1 is committed and nothing will ever ship it. Fairness cannot help, because no action that could deliver o1 is enabled. NoLostEvent says every committed order is in the outbox, in the broker, or about to be published by a live handler. It fails after 3 states: Place(o1), Crash. This is the method of Safety and inductive invariants: find the state fact that explains why the good thing will happen. A violation of it is found sooner, reads more easily, and needs no fairness.
2.OneLabel fails with Place(o1), RelayPublish(o1), Consume(o1), Consume(o1). No crash is needed. The broker never forgets an event, so any delivered event can be delivered again. A relay crash would republish o1, but adding o1 to broker again changes nothing, because duplicate sends and redeliveries look the same in a set model. That is why the model needs no separate duplicate action, and why the consumer, not the relay, must be idempotent. NoLostEvent holds: the outbox fixed the lost event.
3. No error, 84 distinct states, with OneLabel, NoLostEvent and Shipped all holding.
4. The fairness of Publish(o) can go: that action belongs to the dual-write design and is never enabled here. The run still finds 84 states and no error. Without WF_vars(RelayDelete), TLC's counterexample ends with the relay holding o2 forever after a republish, so RelayPublish(o1) is never enabled and o1 is never published. Without fairness on Consume, a crash makes the relay publish o2 twice and then everything stops, with o1's event sitting in the broker unconsumed. Each fairness condition is a claim about a real process: the relay keeps polling, and the consumer keeps reading.
5. If the relay could crash after every publish, forever, then RelayDelete would never happen, and o2 would block o1 indefinitely. Real systems assume that crashes eventually stop long enough for progress, or that a supervisor restarts the relay and it eventually completes a cycle. MaxCrashes is a finite stand-in for "finitely many crashes"; it is an assumption, not a fact about the relay. Notice too where exactly-once holds. Labels are at most once because the label row and the processed row commit together. If printing were an external call, you would be back in Problem 1.
Beyond the lectures IV: Applied models
Keep an old response from replacing a newer choice.
A search screen can show the wrong results even when every request succeeds. Model which response is allowed to change the current view.
This builds on lesson 19, where messages arrive in any order, and on lesson 46, where a resource refused superseded work. Here the resource is your screen, and the token is a request ID.
The concrete bug
A user searches for cats, then dogs. The cats request is slow; dogs returns first. A handler that displays every successful response shows dogs, then replaces it with cats.
Each response is correct on its own. The bug is in what the screen does with the one that arrives last.
The HTTP responses in the chart are individually correct. The screen is wrong because it has forgotten which request represents the user’s current choice. A debounce reduces how often requests start, but it does not establish response ordering.
State the contract
Use a fresh increasing request ID whenever a search begins. latest records that ID, and pending contains requests whose responses can still arrive. The UI is a tagged record: idle has no request, loading identifies the current request, and ready contains its request and result. These variants rule out combinations such as idle = TRUE with resultsLoading = TRUE.
The property is precise: whenever the UI is ready, it shows the result of latest. Compare the same delivery order with and without the guard.
Without the guard. Request order and response order are independent, and the last column breaks the contract.With the guard, the same delivery order. Only pending changes in the last step.
The two grids differ in one cell. We also clear the old view on Start on purpose. A product that keeps previous results while loading needs a different contract, such as a separate displayedRequest field and an explicit “updating” state.
Choose the response order
User choice→Screen
A complete bounded model
Save as AppState.tla for the real tools. There are two possible requests with fixed results. Start issues them in order, but Deliver may select either pending response. Errors, cancellation, and duplicated responses are omitted to isolate the stale-response race.
Start’s LET names the new request number; all three primed equations describe the same step. Deliver always removes the arriving request from pending but updates ui only if the ID still equals latest. CurrentView reads the tagged record’s fields only when they exist.
TLC completes with 7 distinct states and 9 generated, with both invariants and Settles holding. That is small enough to draw completely.
The whole state space of the module, each state written as latest, pending, ui. TLC’s count of 7 distinct and 9 generated is these seven boxes, eight arrows, and the initial state. The dashed arrows are where the guard does its work.
Follow the two dashed arrows: they are the only places where a stale response arrives. Each changes pending and leaves ui alone. Settles uses fairness from lesson 29: each pending Deliver stays enabled until executed, and only two Start steps exist, so a current request cannot be postponed forever. Real applications cannot promise this over a permanently failed network; add error and timeout outcomes for their progress contract.
Make the bug appear
Replace the entire IF expression in Deliver with the ready record, unconditionally. Check TypeOK and CurrentView under Spec.
Predict: does TLC need dogs to arrive first to break the view?
No. TLC’s trace is shorter than the story: Start, Start, Deliver(1). Cats arrives while dogs is still loading, and the screen shows ready 1 with latest = 2. The dogs-first order in the chart also fails, but the guard was never about dogs arriving. It was about any response that is not the latest.
The implementation boundary
let latest = 0;
let ui = { tag: "idle" };
async function search(query) {
const request = ++latest;
ui = { tag: "loading", request };
render(ui);
try {
const value = await searchApi(query);
if (request !== latest) return;
ui = { tag: "ready", request, value };
render(ui);
} catch (error) {
if (request !== latest) return;
ui = { tag: "error", request, error };
render(ui);
}
}
The synchronous increment and loading update correspond to Start. The await permits arbitrary interleaving. Checking the ID and committing the view form one synchronous callback segment with no await between them, which is why one Deliver step can stand for them. The error variant extends the small module; apply the same test to failures. Cancellation can save work, but correct ID handling must not assume cancellation always prevents a response.
Predict: dogs fails, then the old cats request succeeds. Should cats replace the error?
Under this contract, no. The latest user choice is still dogs. An old success and an old failure must both be rejected. To show fallback results intentionally, model that as an explicit product rule rather than letting callback order decide.
Next, translate this into PlusCal as in lesson 36 and inspect its pc, or compare two UI implementations using lesson 33. Language reference: Specifying Systems.
Beyond the lectures IV: Applied models
A late cache fill can undo an invalidation.
An asynchronous read can finish after the data changed. Model the in-flight result as state; otherwise a stale-fill race is invisible.
This builds on lesson 49, where a late response overwrote a newer choice, and on lesson 35, where a check went stale before the action it guarded. Here the late response lands in a store that many readers trust, so it outlives the screen.
The concrete app
A shopping app caches a product’s price. A miss starts a database read. While that read is in flight, an administrator updates the price and invalidates the cache. The old read then returns and repopulates the cache.
The invalidation was delivered correctly. The fill path restored the old value afterwards.
In the chart, the writer’s two arrows are correct. The red arrow comes later and restores the old value. This can happen in one process when tasks interleave around await, or across several servers. A single-threaded event loop does not make a whole asynchronous operation atomic, so track BeginFill and FinishFill separately rather than drawing one instantaneous “read and cache” arrow.
Choose the exact contract
The property below is deliberately strong: whenever the cache is marked valid, its contents belong to the current source version. Version tags stand for payload identity. An invalid cache may hold old bytes because callers must not use them, so the predicate is conditional on valid.
The model assumes one authoritative source, increasing versions, one in-flight fill, and at most two writes. Write plus invalidation is one atomic action here, and so are the freshness check and publication. These are explicit abstraction boundaries, not guarantees that an ordinary database and remote cache provide. Later in this lesson you will break both.
With Fence = TRUE, TLC completes with 15 distinct states and 20 generated, with both invariants holding. Change only the constant to Fence = FALSE, and TLC reports FreshWhenValid violated.
Read the counterexample
TLC’s counterexample, one column per state. The fill carries version 0 across the write.
Read the grid by columns. BeginFill copies version 0 into fillVersion; this is the old response waiting to complete. The write advances the source to 1 while fillVersion stays at 0, because it is a copy. FinishFill without a fence then sets cacheVersion to 0 and valid to TRUE, with the source at 1.
A rejected fill is allowed. Safety does not need every fill to succeed; a later one can restore availability.
In the fenced design, FinishFill sees that fillVersion differs from sourceVersion, discards the result, and clears loading. A later BeginFill captures version 1. Safety does not require every fill to succeed. This model also proves no response deadline: writes or scheduling can keep useful completion from occurring.
Break the two atomic boundaries
A generation counter serves a similar purpose in real caches: capture a generation before fetching, increment it when invalidating, publish only if it has not changed. The modeling question is whether compare-and-publish and write-and-invalidate are truly one step. The module CacheSplit below makes each optional. With neither split, it matches Cache exactly: 15 distinct states, 20 generated. Each split alone fails.
Mutation exercise: split the fence check from publication. What extra state is necessary, and does the fence still help?
You need a phase recording “checked,” here fill = "checked". The fence no longer helps: TLC’s 5-state trace appears below, where the check passes and a write then lands before the install. Restore an atomic conditional publication, or make invalidation also cancel previously authorized fills.
The fence passed, then stopped being true. A check whose result outlives the state it read is the same stale-check shape as in the earlier lessons.Predict: the fence stays atomic, but the database write and the invalidation are two separate steps. Does the invariant hold?
No. TLC’s trace is BeginFill, FinishFill, Write: a valid version 0 is in the cache when the source moves to 1, before the invalidation runs. This has nothing to do with the fill race. Either strengthen coordination or state a weaker contract, such as bounded staleness or freshness after a completed invalidation.
The full CacheSplit module
---------------- MODULE CacheSplit ----------------
EXTENDS Naturals
CONSTANTS SplitCheck, SplitInvalidate
ASSUME SplitCheck \in BOOLEAN /\ SplitInvalidate \in BOOLEAN
VARIABLES sourceVersion, cacheVersion, valid, fill, fillVersion, wrote
vars == <<sourceVersion, cacheVersion, valid, fill, fillVersion, wrote>>
\* fill: "none", "loading", or "checked". The check is always fenced here.
\* wrote: TRUE between a source write and its separate invalidation.
Init == /\ sourceVersion = 0
/\ cacheVersion = 0
/\ valid = FALSE
/\ fill = "none"
/\ fillVersion = 0
/\ wrote = FALSE
BeginFill ==
/\ fill = "none" /\ ~valid
/\ fill' = "loading"
/\ fillVersion' = sourceVersion
/\ UNCHANGED <<sourceVersion, cacheVersion, valid, wrote>>
\* The write and its invalidation, in one step or two.
Write ==
/\ sourceVersion < 2 /\ ~wrote
/\ sourceVersion' = sourceVersion + 1
/\ IF SplitInvalidate
THEN wrote' = TRUE /\ UNCHANGED valid
ELSE valid' = FALSE /\ UNCHANGED wrote
/\ UNCHANGED <<cacheVersion, fill, fillVersion>>
Invalidate ==
/\ wrote
/\ wrote' = FALSE
/\ valid' = FALSE
/\ UNCHANGED <<sourceVersion, cacheVersion, fill, fillVersion>>
Publish ==
/\ cacheVersion' = fillVersion
/\ valid' = TRUE
/\ fill' = "none"
/\ UNCHANGED <<sourceVersion, fillVersion, wrote>>
\* The fence check and the publication, in one step or two.
FinishFill ==
/\ fill = "loading" /\ ~SplitCheck
/\ IF fillVersion = sourceVersion
THEN Publish
ELSE /\ fill' = "none"
/\ UNCHANGED <<sourceVersion, cacheVersion, valid,
fillVersion, wrote>>
CheckFence ==
/\ fill = "loading" /\ SplitCheck
/\ fill' = IF fillVersion = sourceVersion THEN "checked" ELSE "none"
/\ UNCHANGED <<sourceVersion, cacheVersion, valid, fillVersion, wrote>>
Install == fill = "checked" /\ Publish
Next == BeginFill \/ Write \/ Invalidate \/ FinishFill \/ CheckFence \/ Install
Spec == Init /\ [][Next]_vars
FreshWhenValid == valid => cacheVersion = sourceVersion
===================================================
Avoid reusing generations while old fills remain outstanding, or an old generation can appear current again. And do not describe this small model as proof of a replicated cache protocol.
Predict: a 60-second TTL makes every cached read current. Is that true?
No. TTL can limit how long an entry is used under suitable clock and refresh assumptions; it does not prevent returning an old value during its lifetime. Delayed fills can also begin a new lifetime for an old result unless their version or generation is checked. “Current” and “not older than a chosen bound” are different contracts.
Further study: the caching-memory example in Specifying Systems develops a different, richer cache architecture. Compare its stated contract and abstraction boundaries instead of assuming every cache has this lesson’s semantics.
Beyond the lectures IV: Applied models
Design a system whose failures cross boundaries.
No single pattern protects a payment service. The work is building a sequence of contracts and connecting their assumptions.
This brings together lesson 45 for retries, lesson 46 for stale authority, lesson 47 for membership, lesson 18 for shared outcomes, and lesson 33 for connecting the layers. Each of those lessons isolated one failure. Here they meet.
You are building a payment service with two account shards, regional leaders, retried requests, a durable decision service, asynchronous events, and membership changes. The architecture is a study design, not a verified payment protocol.
Each band has its own failure and its own property. Authority cuts across all three, so a stale leader can damage any of them.
Read the diagram by bands. A failure in one band has a different cure from a failure in the next, and the authority column can damage any of them. Do not attempt one enormous model first.
Start with a precise contract
For each transfer ID t, fix source, destination, and amount. The same ID with different arguments must be rejected or assigned an explicit policy. Distinguish accepted, prepared, committed, applied, and acknowledged. The client’s reply is an observation; it does not define when money moved.
At the simplest level, a transfer atomically updates both balances or leaves them unchanged. Refining that takes care: if concrete debit and credit happen at different times, map reserved or in-transit amounts appropriately. Checking visible balances during a partly applied transfer may report an intentional intermediate state as a bug, or hide one if you simply exclude that state.
Make the properties pull their weight
Conservation: spendable, reserved, and in-transit money sum to the initial total under your accounting abstraction.
No overdraft: no concurrent preparation spends funds already reserved elsewhere.
Decision agreement: a transfer never has both a committed and an aborted durable outcome.
At-most-once effects: each debit, credit, and consumer effect occurs no more than once under its identity contract.
Durable acknowledgement: a successful response has the required surviving evidence after the modeled crashes.
Eventual resolution: under stated recovery, communication, and scheduling assumptions, every accepted transfer reaches a terminal response.
A sequence of manageable experiments
Atomic ledger. Two accounts, integer amounts, two request IDs. Check conservation and no overdraft.
Prepare and decide. Split the transfer across shards. Add reservation ownership and a shared durable decision. Check conflicting preparation and duplicate application.
Crash recovery. Erase volatile state at every persistence boundary. Recover solely from the records you actually persist.
Regional leadership. Model stale leaders and enforce epochs at write acceptance. Keep the decision service abstract at first, with a stated contract.
Refine replication. Replace that contract with a bounded protocol model. Connect its guarantees to the transaction layer.
Reconfiguration. Transfer authority and evidence while old messages remain in flight.
Outbox and consumer. Retry publication after lost acknowledgements. Preserve local atomicity and downstream duplicate handling.
Worked checkout: two regions, one order, and one last item
An online store has one remaining camera. Order r42 reserves the camera and requests a $100 charge. Region East applies the charge, but its response to the browser is lost. The user reloads and retries through Region West. Meanwhile a shipping worker consumes payment events. This story crosses identity, inventory, durability, and delivery.
Trace A with a stable ID. The region changed; the logical order did not. The dashed retry is an extra delivery, not a new order.
The dashed arrow in the chart is the point of the story: the retry is a new delivery of the same logical order. The module below starts one layer up, where both regions consult the same durable records, so it has no East or West variable. It models three things: a retry that may or may not keep its ID, stock, and a consumer that may or may not deduplicate.
---------------- MODULE CameraCheckout ----------------
EXTENDS Naturals, FiniteSets
CONSTANTS InitialStock, NewIdOnRetry, ConsumerDedup
ASSUME /\ InitialStock \in 1..2
/\ NewIdOnRetry \in BOOLEAN
/\ ConsumerDedup \in BOOLEAN
Orders == {"r42", "r43"}
VARIABLES attempts, \* order IDs the browser has sent so far
stockFree, stockReserved,
charges, \* charges[r]: effects at the payment provider
decision, \* decision[r]: "pending", "commit", "abort"
outbox, \* events durably saved with the decision
shipments \* shipments[r]: shipping effects, counted
vars == <<attempts, stockFree, stockReserved,
charges, decision, outbox, shipments>>
Init == /\ attempts = {"r42"}
/\ stockFree = InitialStock
/\ stockReserved = {}
/\ charges = [r \in Orders |-> 0]
/\ decision = [r \in Orders |-> "pending"]
/\ outbox = {}
/\ shipments = [r \in Orders |-> 0]
\* The reply was lost. The retry may reach either region; both consult
\* the same durable records, so the region does not appear as state.
\* Resending the same ID changes nothing here: it is a stuttering step.
Retry == /\ attempts' = attempts \cup
{IF NewIdOnRetry THEN "r43" ELSE "r42"}
/\ attempts' # attempts
/\ UNCHANGED <<stockFree, stockReserved, charges,
decision, outbox, shipments>>
Reserve(r) == /\ r \in attempts
/\ decision[r] = "pending"
/\ r \notin stockReserved
/\ stockFree > 0
/\ stockFree' = stockFree - 1
/\ stockReserved' = stockReserved \cup {r}
/\ UNCHANGED <<attempts, charges, decision, outbox, shipments>>
SoldOut(r) == /\ r \in attempts
/\ decision[r] = "pending"
/\ r \notin stockReserved
/\ stockFree = 0
/\ decision' = [decision EXCEPT ![r] = "abort"]
/\ UNCHANGED <<attempts, stockFree, stockReserved,
charges, outbox, shipments>>
\* One durable boundary: the charge, the decision, and the outbox event.
Pay(r) == /\ r \in stockReserved
/\ decision[r] = "pending"
/\ charges' = [charges EXCEPT ![r] = @ + 1]
/\ decision' = [decision EXCEPT ![r] = "commit"]
/\ outbox' = outbox \cup {r}
/\ UNCHANGED <<attempts, stockFree, stockReserved, shipments>>
\* The event can be delivered again until the consumer's record says stop.
Consume(r) == /\ r \in outbox
/\ ConsumerDedup => shipments[r] = 0
/\ shipments[r] < 2
/\ shipments' = [shipments EXCEPT ![r] = @ + 1]
/\ UNCHANGED <<attempts, stockFree, stockReserved,
charges, decision, outbox>>
Next == \/ Retry
\/ \E r \in Orders :
Reserve(r) \/ SoldOut(r) \/ Pay(r) \/ Consume(r)
Spec == Init /\ [][Next]_vars
TypeOK == /\ attempts \subseteq Orders
/\ stockFree \in 0..InitialStock
/\ stockReserved \subseteq Orders
/\ charges \in [Orders -> 0..2]
/\ decision \in [Orders -> {"pending", "commit", "abort"}]
/\ outbox \subseteq Orders
/\ shipments \in [Orders -> 0..2]
OneChargePerId == \A r \in Orders : charges[r] <= 1
OneChargePerCheckout == charges["r42"] + charges["r43"] <= 1
StockConserved == stockFree + Cardinality(stockReserved) = InitialStock
ShipOnlyCommitted == \A r \in Orders :
shipments[r] > 0 => decision[r] = "commit"
OneShipmentPerId == \A r \in Orders : shipments[r] <= 1
=======================================================
This passes with 4 distinct states and 4 generated. That is correct, not suspicious: with a stable ID, Retry is never enabled, because resending r42 changes nothing, so the behavior is one line of Reserve, Pay, Consume. The contract from lesson 45 turned retries into stuttering. Now break it.
Constants
Invariants checked
TLC result
Stock 2, new ID
OneChargePerCheckout
Violated, 6-state trace
Stock 2, new ID
The other four
Pass: 20 distinct states, 32 generated
Stock 1, new ID
OneChargePerCheckout
Passes: 17 distinct states, 24 generated
Stock 1, no consumer dedup
OneShipmentPerId
Violated, 5-state trace
Stock 1, no consumer dedup
The other four
Pass: 5 distinct states, 5 generated
TLC’s counterexample when the browser mints a new ID. Each ID is charged once, so a per-ID check passes while the buyer pays twice.
Read the bottom two rows of the grid. Each ID is charged once, so per-ID idempotency passes, and the buyer has paid twice. The model needs an explicit boundary for “same logical checkout” if that is the product requirement. Conversely, blindly reusing an ID after changing the amount is also wrong; add the arguments to the model and require each attempt to match the original request.
Predict: with one camera in stock and a new ID on retry, OneChargePerCheckout passes. Is the design fine?
No. It passes because the second order finds no stock and takes SoldOut, so one order commits while the other aborts. The buyer can be charged and also told “sold out.” The invariant held by accident of a constant. Raising the stock to 2 exposes the double charge, which is why you vary constants and keep the reason for each result.
These checks are independent. OneChargePerId can hold while a shipment repeats. StockConserved can hold while the buyer pays twice. Choose representations that can express each failure: shipments is a count because a set of shipped IDs would collapse duplicates and hide this bug.
Attack three seams
Trace A is the retry above: can the second region identify the original decision? Trace B asks where a delayed worker from an old epoch is rejected.
Trace B. The rejection happens at the shard, where the write is accepted, as in lesson 46.
Trace C asks whether a retry can repeat an external effect after the consumer crashes before recording completion.
Trace C with no consumer record, matching TLC’s trace: two Consume("r42") steps and two shipments.Reveal a starting answer to Trace C
If the effect and completion record are independent, a duplicate is possible, as TLC’s trace shows. Put them in one durable atomic boundary when feasible. If the effect is external, use the external system’s identity or transaction contract, or design a compensating workflow with explicitly weaker semantics. Calling delivery “exactly once” does not supply the missing boundary.
Extend the model one failure at a time. Add a second buyer, then let both reserve against stale stock during a migration to test the authority handoff. Split Pay into a charge and a decision, and find what the provider must promise. These are different counterexamples; one giant run without separate properties makes them hard to interpret.
Transfer exercise: where can a refund fit when reservation succeeds but payment is uncertain?
Do not equate “no response” with “no charge.” Model the provider outcome as unknown until reconciled using the original request ID. If the workflow uses compensation, specify a durable refund identity and allowed states such as charged, refund-pending, refunded. Compensation is another operation with failure and retry semantics, not an eraser that makes an earlier charge never have happened.
Your reviewable result
Produce the state definitions, every atomic boundary, complete actions with frames, safety properties, liveness assumptions, small constants, saved counterexamples, and the mapping to the abstract ledger. Explain each reduction and each layer still treated as an assumption. A capstone succeeds when another person can reproduce the experiment and identify exactly what it establishes.
Self-review rubric
Can you reproduce a broken trace before its fix? Is each acknowledged outcome tied to durable evidence? Can an old authority still perform an effect? Do deduplication records survive the relevant crashes? Are cross-shard intermediate amounts accounted for? Can every component assumption be justified by another component or a deployment condition? Are progress claims impossible under any admitted permanent failure? Unanswered questions are the next modeling tasks.
All the modules are complete and were checked with TLC exactly as shown. Trace lengths come from TLC with one worker (-workers 1) and count the initial state. In every problem the bug is the same shape: a result that was correct when produced arrives where something newer already decided. Look for that shape before you run anything.
Problem 1●○○Design systems
The combobox that shows options for "al" after you typed "ali"
Your design system's Combobox loads its options asynchronously: on every keystroke it calls the product team's loadOptions(query) and renders the result in the listbox. A bug report: in the "Assign to" field, a user typed "al", then quickly "ali", pressed Enter, and assigned the ticket to Alan instead of Alice. The listbox was showing the options for "al".
The component team already aborts the previous request with an AbortController on each keystroke, and believes that rules this out. In the module, inflight holds requests still on the network, which an abort can cancel. queued holds responses whose body has already been read, so their continuation is waiting to run and an abort no longer stops it. Mode is "Plain" (render every response), "Abort" (cancel everything in flight on each keystroke) or "RequestId" (render only if the response's ID is still latest, as in App state: stale async responses).
---------------- MODULE PSb4_Combobox ----------------
EXTENDS Naturals
CONSTANT Mode
ASSUME Mode \in {"Plain", "Abort", "RequestId"}
Requests == 1..2
Query == [r \in Requests |-> IF r = 1 THEN "al" ELSE "ali"]
VARIABLES latest, \* id of the request for the text now in the input
inflight, \* requests still on the network (abortable)
queued, \* responses received; their callbacks have not run
list \* the listbox: [tag |-> "closed"], [tag |-> "loading"]
\* or [tag |-> "open", query |-> the query it shows]
vars == <<latest, inflight, queued, list>>
Init == /\ latest = 0
/\ inflight = {}
/\ queued = {}
/\ list = [tag |-> "closed"]
\* The user types a character: a new request starts. In Abort mode
\* the component aborts every request still on the network.
Type == /\ latest < 2
/\ latest' = latest + 1
/\ inflight' = IF Mode = "Abort" THEN {latest + 1}
ELSE inflight \cup {latest + 1}
/\ list' = [tag |-> "loading"]
/\ UNCHANGED queued
\* The response body has been read; the callback is queued.
Arrive(r) == /\ r \in inflight
/\ inflight' = inflight \ {r}
/\ queued' = queued \cup {r}
/\ UNCHANGED <<latest, list>>
\* The callback runs and (perhaps) renders the options.
Render(r) == /\ r \in queued
/\ queued' = queued \ {r}
/\ list' = IF Mode = "RequestId" /\ r # latest
THEN list
ELSE [tag |-> "open", query |-> Query[r]]
/\ UNCHANGED <<latest, inflight>>
Next == Type \/ \E r \in Requests : Arrive(r) \/ Render(r)
Spec == Init /\ [][Next]_vars
\* An open listbox shows options for the text in the input.
MatchesInput == list.tag = "open" => list.query = Query[latest]
======================================================
An abort reaches the network, not the event loop. A response already read has escaped it.
Run "Plain". Describe the trace in terms of keystrokes and network events.
Run "Abort". What had already happened to request 1 when the user typed "ali"?
Run "RequestId" and report the distinct states. Then explain whether the component should still abort old requests.
MatchesInput is a property of what the listbox shows. Say in one sentence why that, and not "no stale response is ever received", is the property to check.
Hint
An abort acts on the network request. Ask what it can do to a response that has already been read.
Solution
1.MatchesInput fails after 5 states: Type ("al", request 1), Type ("ali", request 2), Arrive(1), Render(1). The listbox is open with the options for "al" while the input says "ali". Request 2 has not even arrived, so the stale render does not need responses to cross; any old response landing while a newer request is pending is enough.
2. Also 5 states, in a different order: Type, Arrive(1), Type, Render(1). Request 1's response had been read, so its continuation was already queued; the abort on the second keystroke had nothing on the network to cancel. The diagram draws it. In real code this is the window between await response.json() resolving and the continuation that calls setOptions running.
3. No error, 13 distinct states. The ID check sits in the same synchronous step as the render, so no later event can come between them; that is the boundary App state: stale async responses identified. Keep the abort as an optimization. It saves bandwidth and server work for requests that are still on the network, but correctness must not depend on it, because it cannot reach a response that has already arrived.
4. Stale responses are normal and harmless; the user only sees the listbox. A property about receipt would fail in the correct design too, and a property about the screen fails exactly when a user could pick the wrong person. In a design system this matters doubly: the component owns the guard, so every product team that passes a loadOptions gets it.
Problem 2●●○Databases
Cache-aside with leases: the stale set and the write order
A product service reads prices with the cache-aside pattern. A reader does GET from a memcached-style cache; on a miss it reads the database and SETs the value. A writer updates the database and then DELETEs the key. Prices occasionally stay wrong until the key's TTL runs out. Facebook's paper "Scaling Memcache at Facebook" (NSDI 2013) describes a fix it calls leases. On a miss the cache hands the reader a lease token. A DELETE of the key invalidates the token, and a SET carrying an invalid token is refused.
In the module, versions stand for values. One reader and one writer run, and the writer makes up to two updates. Leases turns the tokens on, and DeleteFirst makes the writer delete the key before updating the database instead of after. The property allows a stale cache only while a write is in progress: once the writer is idle, a cached value must be current.
---------------- MODULE PSb4_CacheAside ----------------
EXTENDS Naturals
CONSTANTS Leases, DeleteFirst, MaxVersion
ASSUME Leases \in BOOLEAN /\ DeleteFirst \in BOOLEAN
VARIABLES db, \* the row's version in the database
cache, \* the cached version, or 0 for a miss
lease, \* the cache's outstanding lease token, 0 for none
tokens, \* lease tokens issued so far
rpc, \* reader: "idle", "reading" or "setting"
rtoken, \* the lease token the reader holds
rval, \* the version the reader read from the database
wpc \* writer: "idle", "updated" or "deleted"
vars == <<db, cache, lease, tokens, rpc, rtoken, rval, wpc>>
Init == /\ db = 1 /\ cache = 0 /\ lease = 0 /\ tokens = 0
/\ rpc = "idle" /\ rtoken = 0 /\ rval = 0
/\ wpc = "idle"
\* Reader: GET misses. With leases, the cache hands out a token.
Miss == /\ rpc = "idle" /\ cache = 0
/\ IF Leases THEN /\ tokens' = tokens + 1
/\ lease' = tokens + 1
/\ rtoken' = tokens + 1
ELSE UNCHANGED <<tokens, lease, rtoken>>
/\ rpc' = "reading"
/\ UNCHANGED <<db, cache, rval, wpc>>
\* Reader: SELECT from the database.
Read == /\ rpc = "reading"
/\ rval' = db
/\ rpc' = "setting"
/\ UNCHANGED <<db, cache, lease, tokens, rtoken, wpc>>
\* Reader: SET the value. With leases, only if the token is still valid.
Set == /\ rpc = "setting"
/\ IF ~Leases \/ lease = rtoken
THEN cache' = rval /\ lease' = 0
ELSE UNCHANGED <<cache, lease>>
/\ rpc' = "idle"
/\ UNCHANGED <<db, tokens, rtoken, rval, wpc>>
\* Writer: UPDATE the database and DELETE the cache key, in either order.
\* A delete also invalidates any outstanding lease.
Update == /\ db < MaxVersion
/\ wpc = IF DeleteFirst THEN "deleted" ELSE "idle"
/\ db' = db + 1
/\ wpc' = IF DeleteFirst THEN "idle" ELSE "updated"
/\ UNCHANGED <<cache, lease, tokens, rpc, rtoken, rval>>
Delete == /\ wpc = IF DeleteFirst THEN "idle" ELSE "updated"
/\ (DeleteFirst => db < MaxVersion)
/\ cache' = 0 /\ lease' = 0
/\ wpc' = IF DeleteFirst THEN "deleted" ELSE "idle"
/\ UNCHANGED <<db, tokens, rpc, rtoken, rval>>
Next == Miss \/ Read \/ Set \/ Update \/ Delete
Spec == Init /\ [][Next]_vars
\* Once the writer has finished, a cached value is the current one.
FreshAfterWrite == (wpc = "idle" /\ cache # 0) => cache = db
=========================================================
The lease is a fencing token issued by the cache, and the delete moves the fence. The refusal happens where the stale value would land.
Run with Leases = FALSE, DeleteFirst = FALSE. Write the trace as a sequence of reader and writer operations.
Run the configuration shown (leases, update then delete). Report the distinct states, and say which step of the task 1 trace the lease refuses.
A teammate says deleting first is safer, "because the cache is already empty when the database changes". Run DeleteFirst = TRUE with and without leases, and explain the result.
Why is the property not simply cache # 0 => cache = db?
Hint
A lease is a fencing token issued by the cache. It protects a fill only if something invalidates it after the database has changed. Find which writer step does that in each order.
Solution
Leases
Order
TLC result
no
update, delete
Violated, 6-state trace
no
delete, update
Violated, 6-state trace
yes
update, delete
No error: 70 distinct states
yes
delete, update
Violated, 6-state trace
1.Miss, Read (version 1), Update (the database is now 2), Delete (the cache was already empty), Set: the cache holds 1, the writer is idle, the database holds 2. The fill began before the write and landed after the invalidation, as in Cache: stale fills and invalidation. The stale value then stays until the TTL expires or the next write.
2. No error, 70 distinct states. In the same order of events, Miss takes token 1, Delete sets lease to 0, and the final Set presents token 1 and is refused: lease # rtoken. The diagram shows this. The reader gets nothing cached and misses again next time, which is safe.
3. Without leases: Miss, Read (1), Delete, Set (1), Update (2). The stale value lands between the two writer steps, and nothing deletes it afterward. With leases it still fails, with a different trace: Delete, Miss (a fresh token, issued after the delete), Read (1), Set (accepted), Update. The token is valid because the only invalidation came before it was issued. A lease rejects a fill that overlapped a later invalidation, so the invalidation must come after the change it announces. Delete-first fails for the same reason as splitting write and invalidation in Cache: stale fills and invalidation.
4. In cache-aside, the database update and the delete are two steps in two systems. Between them the cache necessarily holds the old value, so the strong property fails in every design, including the correct one. The contract you can deliver is "fresh once the invalidation has run", which is what FreshAfterWrite says. Choosing the property is part of the design: Cache: stale fills and invalidation made the write and invalidation atomic to get the strong version, and said so.
Two readers would show the paper's second use of leases, rate-limiting how many clients may fill the same key at once. That is a performance property, not one this invariant can see.
A web app runs a Postgres primary with two asynchronous streaming replicas and sends reads to the replicas. A user saves their profile, the page reloads, and the old profile appears. The team's fix: after each commit, store the primary's WAL position from pg_current_wal_lsn() in the session. Then read only from a replica whose pg_last_wal_replay_lsn() is at least that value. A week later a new report: the profile flickers between two versions as the user clicks around.
In the module LSNs are small integers. OtherWrite is another user's commit, and Replay(r) advances replica r by one record. The variables last, need and before record the most recent read, so both session guarantees become invariants. Routing is "AnyReplica" (the original app), "WriteLsn" (the fix: the token is the session's last write) or "SessionLsn" (the token also rises to whatever a read has returned).
---------------- MODULE PSb4_Replica ----------------
EXTENDS Naturals
CONSTANTS Replicas, MaxLsn, Routing
ASSUME Routing \in {"AnyReplica", "WriteLsn", "SessionLsn"}
VARIABLES primary, \* the primary's current WAL position (LSN)
replay, \* replay[r]: the LSN replica r has replayed
token, \* the LSN the session carries in its cookie
wrote, \* the LSN of the session's last write
seen, \* the highest LSN the session has read so far
last, \* the LSN the most recent read returned
need, \* ... the value of wrote at that read
before \* ... the value of seen just before that read
vars == <<primary, replay, token, wrote, seen, last, need, before>>
Max(a, b) == IF a >= b THEN a ELSE b
Init == /\ primary = 0
/\ replay = [r \in Replicas |-> 0]
/\ token = 0 /\ wrote = 0 /\ seen = 0
/\ last = 0 /\ need = 0 /\ before = 0
\* The session commits a write on the primary.
MyWrite == /\ primary < MaxLsn
/\ primary' = primary + 1
/\ wrote' = primary + 1
/\ token' = IF Routing = "AnyReplica" THEN token ELSE primary + 1
/\ UNCHANGED <<replay, seen, last, need, before>>
\* Another session commits a write.
OtherWrite == /\ primary < MaxLsn
/\ primary' = primary + 1
/\ UNCHANGED <<replay, token, wrote, seen, last, need, before>>
\* Asynchronous streaming: replica r replays one more WAL record.
Replay(r) == /\ replay[r] < primary
/\ replay' = [replay EXCEPT ![r] = @ + 1]
/\ UNCHANGED <<primary, token, wrote, seen, last, need, before>>
\* The session reads from replica r. Except in AnyReplica, the router
\* uses a replica only if it has replayed up to the session's token.
Read(r) == /\ Routing # "AnyReplica" => replay[r] >= token
/\ last' = replay[r]
/\ need' = wrote
/\ before' = seen
/\ seen' = Max(seen, replay[r])
/\ token' = IF Routing = "SessionLsn" THEN Max(token, replay[r])
ELSE token
/\ UNCHANGED <<primary, replay, wrote>>
Next == MyWrite \/ OtherWrite \/ \E r \in Replicas : Replay(r) \/ Read(r)
Spec == Init /\ [][Next]_vars
FairSpec == Spec /\ \A r \in Replicas : WF_vars(Replay(r))
ReadYourWrites == last >= need \* the read saw the session's own write
MonotonicReads == last >= before \* the read did not go back in time
\* Some replica is (again and again) able to serve the session.
Servable == []<>(\E r \in Replicas : replay[r] >= token)
=====================================================
The flicker in TLC’s trace. The session never wrote, so a token built from writes stays 0 and both replicas qualify.
Run "AnyReplica". Which property fails first, and how?
Run "WriteLsn". Explain the flicker from TLC's trace.
Run "SessionLsn" and report the distinct states.
With "SessionLsn", a read waits until some replica has caught up to the token. Check PROPERTY Servable under Spec and under FairSpec. What does the fairness condition assume about replication, and what should the app do if that assumption fails?
Hint
Read-your-writes compares a read with the session's writes. Monotonic reads compares a read with the session's earlier reads. A token built from writes only knows about the first.
Solution
1.ReadYourWrites fails in 3 states: MyWrite (primary at 1), Read(r1) while r1 has replayed nothing. That is the stale profile after saving.
2.MonotonicReads fails after 5 states: OtherWrite (someone else commits LSN 1), Replay(r1), Read(r1) returns 1, Read(r2) returns 0. The session has not written, so its token is 0 and every replica qualifies. The page shows the newer profile and then the older one. The diagram draws the trace. Read-your-writes holds throughout; the token answers the wrong question.
3. No error, 157 distinct states. Raising the token to the highest LSN read means a later read goes only to a replica at least as fresh as anything already shown. It is the same rule as the fence in Architecture: leases, fencing, and time: accept only something not older than what you have already accepted. Here the session is the one keeping the fence.
4. Under Spec, Servable fails: MyWrite, OtherWrite, then stuttering, with no replica ever replaying. Under FairSpec it holds, again with 157 states. WF_vars(Replay(r)) says a replica that is behind keeps replaying, so once writes stop it catches up. A replica that stops streaming, or lags for minutes during a long-running query, breaks that assumption. The fix belongs in the design: wait with a timeout, then read from the primary, which always satisfies the token. That keeps safety from depending on replication speed, and makes progress depend only on the primary being up.
An email client deletes optimistically. The message disappears at once and a design-system Toast offers "Undo" for a few seconds. The team has tried four designs. "Deferred" sends DELETE only when the toast's timer fires, and removes Undo at that moment. "UndoWhileSending" keeps Undo on screen until the server answers, because the button looked unresponsive otherwise. "Immediate" sends DELETE at once and makes Undo send a separate RESTORE. "ImmediateSeq" does the same, but the server skips a request whose sequence number is lower than one it already applied. A request can fail with no effect when CanFail is true. When the client's latest request fails, it rolls back its optimistic change and shows an error toast.
Requests and responses travel in sets, so they can be reordered. The user deletes at most once and undoes at most once. AgreeWhenQuiet says that when nothing is in flight and no Undo is offered, the inbox shows the truth. Converges says the screen eventually agrees with the server for good.
---------------- MODULE PSb4_UndoToast ----------------
EXTENDS Naturals
CONSTANTS Design, CanFail
ASSUME /\ Design \in {"Deferred", "UndoWhileSending", "Immediate", "ImmediateSeq"}
/\ CanFail \in BOOLEAN
Immediate == Design \in {"Immediate", "ImmediateSeq"}
VARIABLES server, \* does the email exist on the server?
shown, \* is it shown in the inbox list?
toast, \* "none", "undo" or "error"
sent, \* Deferred designs: has the timer sent the DELETE?
seq, \* number of the client's latest request
net, \* requests in flight: [seq, op]
resp, \* responses in flight: [seq, op, ok]
applied, \* ImmediateSeq: highest request seq the server applied
clicks \* user actions so far (bounds the model)
vars == <<server, shown, toast, sent, seq, net, resp, applied, clicks>>
Init == /\ server = TRUE /\ shown = TRUE /\ toast = "none"
/\ sent = FALSE /\ seq = 0 /\ net = {} /\ resp = {}
/\ applied = 0 /\ clicks = 0
Send(op) == /\ seq' = seq + 1
/\ net' = net \cup {[seq |-> seq + 1, op |-> op]}
\* The user deletes the email: it disappears at once, with an Undo toast.
Delete == /\ clicks = 0 /\ shown /\ toast = "none"
/\ shown' = FALSE /\ toast' = "undo" /\ clicks' = 1
/\ IF Immediate THEN Send("delete") ELSE UNCHANGED <<seq, net>>
/\ UNCHANGED <<server, sent, resp, applied>>
\* The user clicks Undo.
Undo == /\ clicks = 1 /\ toast = "undo"
/\ shown' = TRUE /\ toast' = "none" /\ clicks' = 2
/\ IF Immediate THEN Send("restore") ELSE UNCHANGED <<seq, net>>
/\ UNCHANGED <<server, sent, resp, applied>>
\* The toast's timer fires. Deferred designs send the DELETE now;
\* UndoWhileSending keeps showing Undo until the response arrives.
Timeout == /\ toast = "undo" /\ ~sent
/\ IF Immediate
THEN /\ toast' = "none"
/\ UNCHANGED <<sent, seq, net>>
ELSE /\ sent' = TRUE /\ Send("delete")
/\ toast' = IF Design = "UndoWhileSending" THEN "undo"
ELSE "none"
/\ UNCHANGED <<server, shown, resp, applied, clicks>>
\* The server handles a request: it succeeds or fails without effect.
\* ImmediateSeq skips (but acknowledges) a request older than one applied.
Serve(m) == /\ m \in net
/\ net' = net \ {m}
/\ \/ /\ IF Design = "ImmediateSeq" /\ m.seq < applied
THEN UNCHANGED <<server, applied>>
ELSE /\ server' = (m.op = "restore")
/\ applied' = m.seq
/\ resp' = resp \cup {[seq |-> m.seq, op |-> m.op, ok |-> TRUE]}
\/ /\ CanFail
/\ UNCHANGED <<server, applied>>
/\ resp' = resp \cup {[seq |-> m.seq, op |-> m.op, ok |-> FALSE]}
/\ UNCHANGED <<shown, toast, sent, seq, clicks>>
\* The client handles a response. A failure of its latest request rolls
\* back the optimistic change and shows an error toast; others are ignored.
Receive(m) == /\ m \in resp
/\ resp' = resp \ {m}
/\ IF ~m.ok /\ m.seq = seq
THEN /\ shown' = (m.op = "delete")
/\ toast' = "error"
ELSE /\ UNCHANGED shown
/\ toast' = IF toast = "undo" /\ sent THEN "none" ELSE toast
/\ UNCHANGED <<server, sent, seq, net, applied, clicks>>
Dismiss == /\ toast = "error" /\ toast' = "none"
/\ UNCHANGED <<server, shown, sent, seq, net, resp, applied, clicks>>
Msgs == [seq : 1..2, op : {"delete", "restore"}]
Next == \/ Delete \/ Undo \/ Timeout \/ Dismiss
\/ \E m \in Msgs : Serve(m)
\/ \E m \in [seq : 1..2, op : {"delete", "restore"}, ok : BOOLEAN] : Receive(m)
Spec == Init /\ [][Next]_vars
FairSpec == /\ Spec
/\ WF_vars(Timeout) /\ WF_vars(Dismiss)
/\ \A m \in Msgs : WF_vars(Serve(m))
/\ \A m \in [seq : 1..2, op : {"delete", "restore"}, ok : BOOLEAN] :
WF_vars(Receive(m))
Quiet == net = {} /\ resp = {} /\ toast # "undo"
AgreeWhenQuiet == Quiet => shown = server
Converges == <>[](shown = server)
=======================================================
TLC’s complete state graph for "Deferred". Undo exists only before the request leaves, and every final state, in green, agrees with the server.
Run "Deferred" with CanFail = TRUE. Report the distinct states, and find each of them in the diagram.
Run "UndoWhileSending". Tell the user's story from TLC's trace. What does the user see at the end, and what is true on the server?
Run "Immediate" with CanFail = FALSE, then with TRUE. Explain both traces.
Run "ImmediateSeq" with both values of CanFail. Which bug did the sequence numbers fix, and what is wrong with the client's rollback rule? Propose a fix and say what you would have to model to check it.
FairSpec includes WF_vars(Timeout). What real assumption is that? What happens to a deleted message in "Deferred" if the user closes the tab while the toast is showing, and is that acceptable?
Hint
For each design, ask two questions from earlier lessons. Can a request that the user has already cancelled in the UI still change the server? That is a stale write, as in Architecture: leases, fencing, and time. Does a rollback assume something about the server that the client does not actually know?
1. No error, 9 distinct states, and Converges holds. The diagram is TLC's whole state graph. It has three final states, each agreeing with the server: undone before sending, deleted, and kept after a failure with an error the user dismissed.
2.Delete, Timeout (DELETE sent, Undo still shown), Undo (the message reappears), Serve (the server deletes it), Receive (success, nothing to do). The user sees the message in the inbox, and it no longer exists. They will find out when they try to open it. Undo was offered after the decision had left the client, which is the stale-authority shape of Architecture: leases, fencing, and time: the UI granted a choice it could no longer enforce. Removing Undo when the request is sent is exactly "Deferred".
3. Without failures: Delete (DELETE 1 sent), Undo (RESTORE 2 sent), the server handles RESTORE 2 first, then DELETE 1, and both succeed. The message is shown and deleted. This is the reordering of Messages, failures, and retries. With failures TLC reports a different 7-state trace: both requests fail, so the server still has the message, and the client handles failure 2 last. Rolling back a failed RESTORE means hiding the message. It guessed that the DELETE had succeeded.
4. With CanFail = FALSE, "ImmediateSeq" passes with 16 states. The server ignores DELETE 1 after applying RESTORE 2, which is a fence on request numbers. With failures it fails on the same double-failure trace as "Immediate", because the fence cannot fix the client's rollback rule. A rollback encodes an assumption about server state that the client never observed. One fix is to answer a failure with the resource's current state, or to refetch it, and render that instead of guessing. To check it you would model the refetch as another request whose response can be stale too. Then you would need the request-ID rule of App state: stale async responses on the client as well as the sequence fence on the server. That is a layered contract, in the sense of Capstone: multi-region payments.
5. It assumes the client survives until the timer fires. If the tab closes during the toast, Timeout never happens, the DELETE is never sent, and the message is still in the inbox next time. In the model, that is a behavior allowed by Spec but excluded by FairSpec. Whether it is acceptable is a product decision. "Close the tab to undo" is often fine for email, but not for a payment. If it is not acceptable, send the request immediately and accept the problems of tasks 3 and 4, or have the server run the delay. Fairness should be a property the product actually has, not a convenience that makes TLC pass.
Practice
Make the ideas retrievable.
You have seen everything once. Now practise recalling it, and use the map below to find your way back.
This closes the course and depends on all of it, from the first state machine in lesson 3 to the crossed boundaries of lesson 51. Recognition is easier than recall, so most of this page asks you to produce answers rather than read them. The video above is the full playlist, for going back to a lecture you want to hear again.
Each stage uses the one before it. The accent box and the green box are where the earlier tools meet failure.
Recall deck
Before revealing a card, say the answer aloud or write it in your notes. Use “Study again” for a missed answer and “Remembered” only if you reconstructed the reason. Cards you miss return later in this session. This is retrieval practice, not a certification score.
Recall deck
The course on one page
Use this to go back. Each row names what to retrieve, so try to state the concepts before clicking through.
Write Counter from memory, including vars and Spec. Introduce a bug and predict the first bad state.
Write the inventory conservation invariant and explain what makes Reserve atomic.
Draw a retry trace that duplicates an effect; repair it without pretending two independent stores share a transaction.
Explain a weak-fairness counterexample involving an intermittently enabled action.
Map a multi-step queue implementation to an abstract enqueue/dequeue operation. Identify its linearization point and its stuttering steps.
Propose a cross-shard payment invariant and name the exact durable state needed after a coordinator crash.
A working vocabulary
Term
Meaning
Enabled
An action has a suitable successor; fairness typically considers a non-stuttering successor.
Invariant
A state predicate true in every reachable state.
Safety
A violation has a finite bad prefix. Invariants are a common special case.
Liveness
Every finite prefix can still be extended to satisfy the property; the violation requires an infinite behavior.
Refinement
A detailed behavior satisfies an abstract contract under a mapping and the stated assumptions.
Linearizability
Concurrent operations appear to take effect in a legal sequential order that respects real-time order of non-overlapping operations.
Assumption
A restriction on the behaviors for which a guarantee is claimed.
Constraint
A model-checking search restriction, which can hide behaviors.
History variable
Auxiliary state recording past events to express or prove a property.
Prophecy variable
Auxiliary machinery that predicts a future choice when a simple refinement mapping cannot otherwise express the relationship.
Fencing token
An ordered authority token the protected resource checks to reject superseded writers.
A final exercise that connects the course
Explain a photo-sharing app’s “Upload complete” message. The phone may retry, the object store may contain the bytes before the metadata row exists, a thumbnail worker may run twice, and a stale CDN response may arrive after replacement. Mark each boundary in the diagram before choosing your variables.
One familiar app. Each red edge is a boundary from an earlier lesson: retries, separate stores, duplicate work, and a stale fill.
Retrieve five ideas without looking: a state versus an action; an invariant versus a progress claim; an atomic boundary versus a sequence of steps; a simulation versus an exhaustive finite check; and a refinement mapping versus a copied implementation detail. Then give one failure trace for each red edge.
Compare with a possible modeling answer
Use a stable upload ID, immutable content identity, durable object existence, metadata state, thumbnail effect count, and cached version. Require that “complete” implies the chosen durable evidence, a retry does not create another logical photo, and an old thumbnail cannot replace a newer one. Ask separately whether upload and processing eventually finish under recovery and delivery assumptions. A model can be safe while the phone waits forever.
For efficient review, alternate examples: apply the inventory guard idea to authorization, the request-identity idea to uploads, and the delayed-message idea to cache invalidation. If you can only repeat the original example, revisit its underlying state and transition rule before advancing.
Evidence to keep with every model
Write down the property, the abstraction boundary, the allowed failures, the constants and bounds, the invariants and temporal properties actually checked, the tool version, and whether the search completed. Preserve at least one known-bad mutation. A useful model is one another engineer can challenge and rerun.
To carry this into daily work, choose one small uncertainty in a real design: a retry boundary, a stale lease, or a race during failover. Model that uncertainty first. The next useful milestone is a counterexample that teaches your team something it did not already know.
Choose your next study
Learn TLA+ — an extended written course and topic reference.
Specifying Systems — language reference, composition, real time, and worked systems.
Final problem set: the whole course, one system at a time.
This is the course's comprehensive exam. Five problems, each a real design, together use every part of the course: states and actions, sets and records, two-phase commit and messages, quorums and Raft, temporal properties and fairness, refinement, PlusCal, inductive invariants and symmetry, idempotency and fencing, and layered contracts. The last problem asks for all of it at once. Use Review, reference, and next steps to find your way back to anything you have forgotten.
Every module is complete and was checked with TLC exactly as shown. Trace lengths come from TLC with one worker (-workers 1) and count the initial state. Before you run anything, write down what you expect: the point of an exam is to find out which predictions you can make without the tool.
Problem
Main ideas
Course parts
1. Write skew
PlusCal, interleaving, invariants as search goals
Lectures 1–5, Beyond I
2. Order saga
Messages, compensation versus two-phase commit, liveness
A hospital's on-call app keeps one row per doctor per shift in Postgres, at the REPEATABLE READ isolation level, which Postgres implements as snapshot isolation. The rule is that at least one doctor stays on call. To go off call, the app runs one transaction: count the doctors on call in the shift; if there are at least two, set your own row to off call; commit. Alice and Bob both feel unwell and press the button at the same moment. Both transactions commit, and nobody is on call. Kleppmann's Designing Data-Intensive Applications uses this example.
Under snapshot isolation each transaction reads from a snapshot taken when it starts, and two transactions conflict only if they write the same row. The PlusCal model has one process per doctor's transaction. snap is the transaction's snapshot and version counts commits per row. With Isolation = "Serializable", a transaction aborts at commit if any row it read has changed since its snapshot. Translate the algorithm with pcal.trans before running TLC; the translation is omitted below.
---------------- MODULE PSfinal_OnCall ----------------
EXTENDS Naturals, FiniteSets
CONSTANTS Doctors, Isolation
ASSUME Isolation \in {"Snapshot", "Serializable"}
(*--algorithm OnCall
variables onCall = [d \in Doctors |-> TRUE], \* committed rows
version = [d \in Doctors |-> 0]; \* committed row versions
define
AtLeastOneOnCall == \E d \in Doctors : onCall[d]
end define;
process Tx \in Doctors
variables snap = [d \in Doctors |-> TRUE], \* this transaction's snapshot
snapVersion = [d \in Doctors |-> 0];
begin
Begin:
snap := onCall;
snapVersion := version;
Check:
if Cardinality({d \in Doctors : snap[d]}) >= 2 then
Commit:
if Isolation = "Serializable" /\ version # snapVersion then
skip; \* abort: a row it read has changed since its snapshot
else
onCall[self] := FALSE;
version[self] := version[self] + 1;
end if;
end if;
end process;
end algorithm; *)
=======================================================
Each snapshot is frozen at Begin. Bob’s check runs after Alice’s commit and still counts her as on call.
Before running TLC: each transaction on its own preserves AtLeastOneOnCall. Which behaviors could break it? Answer in terms of states and steps.
Run Isolation = "Snapshot" and report TLC's trace.
Snapshot isolation does detect a write-write conflict, and the first transaction to commit wins. Why does that not stop this anomaly?
Run Isolation = "Serializable". Report the distinct states. Then explain how the model's rule relates to Postgres's SERIALIZABLE level, and what the application must do when a transaction is aborted.
Hint
Atomicity and the last ticket had the same structure: a check, then an action based on it, with another process changing the facts in between. Here the database itself keeps the check's facts frozen, inside the snapshot.
Solution
1. Only interleavings. Run alone, either transaction sees two doctors on call and leaves one. A bad behavior needs both checks to happen before either change becomes visible to the other.
2.AtLeastOneOnCall fails after 7 states: Begin(alice), Check(alice) (2 on call), Begin(bob), Commit(alice), Check(bob), Commit(bob). Bob checks after Alice has committed, but he reads his snapshot, which was taken before her commit. The diagram shows the two snapshots disagreeing with the database.
3. The writes go to different rows, Alice's and Bob's, so first-committer-wins never fires. What makes the outcome wrong is that each transaction's decision depended on a row the other one changed. That read-write dependency is not something snapshot isolation tracks.
4. No error, 21 distinct states. In every interleaving where both have read the other's row before either commits, the second commit sees a changed version and aborts. The model's rule, validating the read set at commit, is a simple optimistic scheme, not Postgres's algorithm. Postgres's SERIALIZABLE uses serializable snapshot isolation: it tracks read-write dependencies among concurrent transactions and aborts one when they could form a cycle. In this example the effect is the same, one of the two fails with a serialization error. The application must be ready to retry the transaction from the start, and the retry will see one doctor on call and refuse. Another fix keeps REPEATABLE READ and makes the conflict a write conflict, for example by locking the shift's row before counting. This model does not check that variant.
Note what the model left out: the number of doctors, other shifts, retries. Two processes and one invariant were enough to produce the bug, which is the reduction argument of State explosion and trustworthy reductions.
Problem 2●●○Microservices
An order saga that refunds a charge that hasn't happened yet
An order service runs a saga, a sequence of local transactions in different services, each with a compensating action that undoes it if a later step fails. Step 1 reserved the stock. Step 2 asks the payment service to charge the card. If the charge is declined, the compensation releases the stock and the order is cancelled. The payment service is sometimes slow, so after 30 seconds the order service gives up on the reply and compensates. Customers complain about being charged for cancelled orders.
The team tries three designs for the timeout. "ReleaseOnly" releases the stock and cancels. "Refund" also sends a refund request. "RefundTombstone" sends the refund too, and the payment service records a refund for a charge it has not seen yet. That record makes a late charge request for the same order fail. The network is a set of messages that can arrive in any order. Timeout has no fairness: it may or may not happen, which is the environment's choice.
---------------- MODULE PSfinal_Saga ----------------
CONSTANT Design
ASSUME Design \in {"ReleaseOnly", "Refund", "RefundTombstone"}
VARIABLES stock, \* inventory service: "reserved" or "released"
pay, \* payment service: "none", "charged", "declined",
\* "refunded" or "blocked" (a refund came first)
orch, \* orchestrator: "charge", "wait", "done", "cancelled"
msgs \* messages in flight
vars == <<stock, pay, orch, msgs>>
Init == /\ stock = "reserved" \* step 1 of the saga has completed
/\ pay = "none"
/\ orch = "charge"
/\ msgs = {}
\* Step 2: ask the payment service to charge the card.
SendCharge == /\ orch = "charge"
/\ orch' = "wait"
/\ msgs' = msgs \cup {"charge"}
/\ UNCHANGED <<stock, pay>>
\* The payment service handles the charge request.
Reply(m) == msgs' = (msgs \ {"charge"}) \cup {m}
Charge == /\ "charge" \in msgs
/\ \/ pay = "none" /\ pay' = "charged" /\ Reply("charged")
\/ pay = "none" /\ pay' = "declined" /\ Reply("declined")
\/ pay = "blocked" /\ UNCHANGED pay /\ Reply("declined")
/\ UNCHANGED <<stock, orch>>
\* The orchestrator gets the outcome.
Charged == /\ "charged" \in msgs
/\ msgs' = msgs \ {"charged"}
/\ orch' = IF orch = "wait" THEN "done" ELSE orch
/\ UNCHANGED <<stock, pay>>
Declined == /\ "declined" \in msgs
/\ msgs' = msgs \ {"declined"}
/\ IF orch = "wait"
THEN orch' = "cancelled" /\ stock' = "released"
ELSE UNCHANGED <<orch, stock>>
/\ UNCHANGED pay
\* No reply yet: the orchestrator gives up and compensates.
Timeout == /\ orch = "wait"
/\ orch' = "cancelled"
/\ stock' = "released"
/\ msgs' = IF Design = "ReleaseOnly" THEN msgs
ELSE msgs \cup {"refund"}
/\ UNCHANGED pay
\* The payment service handles a refund for this order.
Refund == /\ "refund" \in msgs
/\ msgs' = msgs \ {"refund"}
/\ pay' = CASE pay = "charged" -> "refunded"
[] pay = "none" /\ Design = "RefundTombstone" -> "blocked"
[] OTHER -> pay
/\ UNCHANGED <<stock, orch>>
Next == SendCharge \/ Charge \/ Charged \/ Declined \/ Timeout \/ Refund
Spec == Init /\ [][Next]_vars
FairSpec == /\ Spec
/\ WF_vars(SendCharge) /\ WF_vars(Charge) /\ WF_vars(Charged)
/\ WF_vars(Declined) /\ WF_vars(Refund)
\* What a finished order must look like.
Settled == \/ orch = "done" /\ stock = "reserved" /\ pay = "charged"
\/ orch = "cancelled" /\ stock = "released" /\ pay # "charged"
EventuallySettled == <>[]Settled
\* A search goal: a quiet system with a paid, cancelled order.
NoPaidCancelled == ~(orch = "cancelled" /\ pay = "charged" /\ msgs = {})
\* "Never charged while the stock is released" (true of 2PC's outcome).
NoChargedRelease == ~(pay = "charged" /\ stock = "released")
======================================================
A timeout is not a failure. The charge was still on its way, and a refund that arrives first has nothing to undo.
Run "ReleaseOnly" with PROPERTY EventuallySettled. Then use the Die Hard trick: check INVARIANT NoPaidCancelled under Spec. Compare the two runs.
Run "Refund". Why didn't the refund help?
Run "RefundTombstone" and report the distinct states.
Check INVARIANT NoChargedRelease on "RefundTombstone". It fails. Is that a bug? Compare with what two-phase commit, as in Two-phase commit and records, would guarantee, and say what it would cost here.
Hint
A timeout does not mean the request failed. It means the reply did not arrive in time. Ask what the request can still do after the timeout, and who can stop it.
Solution
1.EventuallySettled fails: SendCharge, Charge (succeeds), Timeout (the reply is in flight; stock released), Charged (ignored, since the order is cancelled), then stuttering forever in a state with a paid, cancelled order. The invariant NoPaidCancelled describes that end state as a safety goal. TLC finds it in 5 states with the same steps, under Spec, with no fairness. Turning "this must not happen eventually" into "this state is never reached" made the check simpler, which is the trick of Die Hard: make TLC solve it. It works when the bad outcome is a state the system cannot leave.
2."Refund" fails differently: SendCharge, Timeout (refund sent while the charge request is still on the network), Refund (nothing to refund yet), Charge (succeeds), Charged. The refund and the charge were reordered, as Messages, failures, and retries allows, and the refund of a charge that did not exist yet did nothing. The diagram draws this trace.
3. No error, 17 distinct states. The refund leaves a durable record, "blocked", so the late charge is declined. In a real payment service, the charge and the refund both carry the order's ID, and the service keeps the ID's state, which is the idempotency record of Architecture: durable idempotent worker.
4. It fails after 4 states: SendCharge, Charge, Timeout. The card is charged while the stock is released, and the refund is still on its way. That is not a bug in a saga: a saga gives up isolation, so other observers can see intermediate states, and promises only that compensations eventually bring it to a consistent end. EventuallySettled states that promise. Two-phase commit would rule the intermediate state out. Both services would prepare and hold their resources, and a coordinator would decide. The cost is what Two-phase commit and records and Paxos Commit: surviving the coordinator showed: every participant must support a prepared state, resources stay locked while the decision is pending, and a coordinator failure can block them. An external payment provider is usually not a participant you can enlist in your own two-phase commit, which is one reason payment flows are often built as sagas.
A social app runs active replicas in three regions, and each region accepts likes locally. Replicas periodically send their whole state to each other and merge what they receive. The first design keeps one integer per region and merges with max, "because max never loses the bigger number". The second merges by adding. The third is a G-counter, a grow-only counter from the literature on conflict-free replicated data types (CRDTs). Each replica keeps a vector with one entry per replica, increments only its own entry, merges by taking the maximum of each entry, and displays the sum.
---------------- MODULE PSfinal_NaiveCounter ----------------
EXTENDS Naturals
CONSTANTS Replicas, MaxLikes, MergeRule
ASSUME MergeRule \in {"Max", "Add"}
VARIABLES n, \* n[r]: the single number replica r stores
likes \* history: likes actually taken, anywhere
vars == <<n, likes>>
Init == n = [r \in Replicas |-> 0] /\ likes = 0
Like(r) == /\ likes < MaxLikes
/\ n' = [n EXCEPT ![r] = @ + 1]
/\ likes' = likes + 1
Merge(r, s) == /\ r # s
/\ n' = [n EXCEPT ![r] = IF MergeRule = "Max"
THEN (IF n[s] > n[r] THEN n[s] ELSE n[r])
ELSE n[r] + n[s]]
/\ UNCHANGED likes
Next == \E r, s \in Replicas : Like(r) \/ Merge(r, s)
Spec == Init /\ [][Next]_vars
FairSpec == Spec /\ \A r, s \in Replicas : WF_vars(Merge(r, s))
Bounded == \A r \in Replicas : n[r] <= MaxLikes + 1 \* a CONSTRAINT for "Add"
NeverOverCount == \A r \in Replicas : n[r] <= likes
Converges == <>[](\A r \in Replicas : n[r] = likes)
=============================================================
The G-counter is checked against a one-variable contract, a counter like the one in Your first spec through TLC, written as a module of its own. The mapping says the contract's count is the sum of each replica's own entry.
---------------- MODULE PSfinal_Counter ----------------
EXTENDS Naturals
VARIABLE count \* likes on one post: the contract
Init == count = 0
Next == count' = count + 1
Spec == Init /\ [][Next]_count
=========================================================
---------------- MODULE PSfinal_GCounter ----------------
EXTENDS Naturals
CONSTANTS Replicas, MaxLikes
VARIABLE c \* c[r][s]: what replica r knows of the likes taken at s
vars == c
RECURSIVE SumOver(_, _)
SumOver(f, S) == IF S = {} THEN 0
ELSE LET x == CHOOSE x \in S : TRUE
IN f[x] + SumOver(f, S \ {x})
Value(r) == SumOver(c[r], Replicas) \* what replica r displays
Total == SumOver([s \in Replicas |-> c[s][s]], Replicas)
Init == c = [r \in Replicas |-> [s \in Replicas |-> 0]]
\* A like arrives at replica r; it counts it in its own entry.
Like(r) == /\ Total < MaxLikes
/\ c' = [c EXCEPT ![r][r] = @ + 1]
\* Replica r receives s's state and takes the entrywise maximum.
Merge(r, s) == c' = [c EXCEPT ![r] = [x \in Replicas |->
IF c[s][x] > c[r][x] THEN c[s][x] ELSE c[r][x]]]
Next == \E r, s \in Replicas : Like(r) \/ Merge(r, s)
Spec == Init /\ [][Next]_vars
FairSpec == Spec /\ \A r, s \in Replicas : WF_vars(Merge(r, s))
NeverOverCount == \A r \in Replicas : Value(r) <= Total
OwnEntryLargest == \A r, s \in Replicas : c[s][r] <= c[r][r]
Converges == <>[](\A r \in Replicas : Value(r) = Total)
Contract == INSTANCE PSfinal_Counter WITH count <- Total
Refines == Contract!Spec
==========================================================
Only the owner raises its own entry, so merges never change Total: they are stuttering steps of the counter contract. The display catches up in jumps.
Run the naive counter with MergeRule = "Max". Read the counterexample. After two likes in different regions, what value do the replicas settle on?
Run MergeRule = "Add" with SPECIFICATION Spec, INVARIANT NeverOverCount and CONSTRAINT Bounded. Why must a merge be idempotent?
Run the G-counter configuration. Report the result, and explain why every Merge step is a stuttering step of the contract. Which invariant does that argument need?
A colleague maps the contract to what one replica displays: count <- Value(r) for a fixed replica r. Predict what TLC reports, then check it.
Hint
A merge function's input may include information the receiver already has. Ask what happens if the same state arrives twice, and whether the merge can tell two different likes from one like seen twice.
Solution
1.Converges fails: Like(r2), Like(r1), then stuttering, with n = (r1 :> 1 @@ r2 :> 1) and likes = 2. The replicas agree, on 1. Weak fairness forces every merge that is enabled, but a merge of 1 with 1 changes nothing, so it is a stuttering step and fairness asks for nothing more. Max cannot tell two different likes from one like seen twice. Convergence to the wrong value is not convergence.
2.NeverOverCount fails after 4 states: Like(r1), Merge(r2, r1), Merge(r2, r1), with r2 showing 2 after one like. Gossip delivers the same state many times, as messages in Messages, failures, and retries could be duplicated. So a merge must be idempotent, as well as commutative and associative, because states arrive in any order and grouping. Max on each entry has all three properties. Addition is not idempotent.
3. No error, 414 distinct states. NeverOverCount and OwnEntryLargest hold, Converges holds under the merge fairness, and so does Refines. A Like(r) adds 1 to c[r][r] and so to Total: an abstract Next step. A Merge(r, s) sets c[r][r] to the larger of c[r][r] and c[s][r], which is c[r][r] because of OwnEntryLargest: only r ever increments its own entry, so no one knows more about it than r. Every own entry is unchanged, so Total is unchanged and the step stutters, as in What it means to implement a spec. This is how refinement uses an invariant: the mapping is only correct in reachable states.
4. TLC reports the contract's action property violated after 4 states: Like(r2), Like(r2), then a Merge into the watched replica, whose display jumps from 0 to 2. The contract allows only steps of 1 (the replica TLC watches is CHOOSE r \in Replicas : TRUE, so your run may name a different one). The display is a lagging view of the counter, not the counter. A contract for it would be weaker: never more than Total, never decreasing, eventually equal.
---------------- MODULE PSfinal_GCounterMap ----------------
EXTENDS PSfinal_GCounter
\* A different mapping: the contract's count is what one replica displays.
Watched == CHOOSE r \in Replicas : TRUE
Displayed == INSTANCE PSfinal_Counter WITH count <- Value(Watched)
RefinesDisplayed == Displayed!Spec
=============================================================
A team is building a metadata service on a Raft-style replicated log. Each log entry records the term of the leader that created it. A leader sends a follower the entry at index i + 1 together with the index i and term of the entry before it, and the follower accepts only if its own entry i has that term. The Raft paper calls the resulting guarantee Log Matching: if two logs contain an entry with the same index and term, the logs are identical up to that index. A refactoring "optimizes" the follower by dropping the check.
The model abstracts elections: Elect(s, t) makes s leader of a newer term, and OneLeaderPerTerm says whether two servers can win the same term. Real Raft gets that from votes, as you saw in Problem set 7. AppendEntries is one atomic step from leader to follower. As a simplification, the follower always cuts its log after the new entry, where Raft deletes entries only on a conflict. That is harmless for Log Matching, but it would not be for a property about committed entries.
---------------- MODULE PSfinal_RaftLog ----------------
EXTENDS Naturals, Sequences
CONSTANTS Servers, MaxTerm, MaxLen, PrevCheck, OneLeaderPerTerm
ASSUME PrevCheck \in BOOLEAN /\ OneLeaderPerTerm \in BOOLEAN
Terms == 1..MaxTerm
VARIABLES term, \* term[s]: the latest term server s knows
leaders, \* leaders[t]: servers elected leader in term t
log \* log[s]: the term of each entry, in index order
vars == <<term, leaders, log>>
Init == /\ term = [s \in Servers |-> 0]
/\ leaders = [t \in Terms |-> {}]
/\ log = [s \in Servers |-> <<>>]
\* Elections are abstracted: s wins term t, a term newer than its own.
Elect(s, t) == /\ t > term[s]
/\ OneLeaderPerTerm => leaders[t] = {}
/\ leaders' = [leaders EXCEPT ![t] = @ \cup {s}]
/\ term' = [term EXCEPT ![s] = t]
/\ UNCHANGED log
IsLeader(s) == term[s] > 0 /\ s \in leaders[term[s]]
\* A leader appends a client command, tagged with its term, to its own log.
ClientRequest(s) == /\ IsLeader(s)
/\ Len(log[s]) < MaxLen
/\ log' = [log EXCEPT ![s] = Append(@, term[s])]
/\ UNCHANGED <<term, leaders>>
\* Leader l sends f entry i+1, with prevLogIndex i and prevLogTerm log[l][i].
\* f accepts if l's term is not older than f's and (with PrevCheck) f's
\* entry i has that term. f keeps entries 1..i, then takes entry i+1.
AppendEntries(l, f, i) ==
/\ l # f /\ IsLeader(l)
/\ term[l] >= term[f]
/\ i < Len(log[l]) /\ i <= Len(log[f])
/\ PrevCheck => IF i = 0 THEN TRUE ELSE log[f][i] = log[l][i]
/\ log' = [log EXCEPT ![f] = [j \in 1..(i + 1) |->
IF j <= i THEN log[f][j] ELSE log[l][i + 1]]]
/\ term' = [term EXCEPT ![f] = term[l]]
/\ UNCHANGED leaders
Next == \/ \E s \in Servers, t \in Terms : Elect(s, t)
\/ \E s \in Servers : ClientRequest(s)
\/ \E l, f \in Servers, i \in 0..(MaxLen - 1) : AppendEntries(l, f, i)
Spec == Init /\ [][Next]_vars
\* Log Matching: same index and term => identical logs up to that index.
LogMatching ==
\A s, u \in Servers : \A i \in 1..MaxLen :
(i <= Len(log[s]) /\ i <= Len(log[u]) /\ log[s][i] = log[u][i])
=> \A j \in 1..i : log[s][j] = log[u][j]
=========================================================
Both logs have term 2 at index 2 but different histories before it. The previous-entry check exists to refuse exactly the last step.
Run the configuration shown and report the distinct states.
Set PrevCheck = FALSE. Draw the logs in each state of TLC's trace and explain the violation.
Restore the check and set OneLeaderPerTerm = FALSE. Explain the trace. Which fact about quorums rules this out in real Raft?
The servers are interchangeable. Write a module that extends PSfinal_RaftLog and TLC and defines Perms == Permutations(Servers), add SYMMETRY Perms, and rerun task 1. Why is the reduction sound for this property, and why would you hesitate to use it for a liveness property?
Explain in a few sentences why the check makes Log Matching hold: argue by induction on the steps, as in Safety and inductive invariants.
Hint
Log Matching has two halves. An (index, term) pair must name a single entry, and the entries before it must agree. Each half is protected by a different mechanism; break one at a time.
Solution
1. No error, 793 distinct states.
2.LogMatching fails after 7 states: Elect(s1, 1), Elect(s2, 2), ClientRequest(s1) (s1's log is <<1>>), ClientRequest(s2) twice (s2's log is <<2, 2>>), then AppendEntries(s2, s1, 1). s2 sends its entry 2 with previous term 2, s1's entry 1 has term 1, and without the check s1 keeps it and appends: <<1, 2>>. Now s1 and s2 both have term 2 at index 2 but differ at index 1. The diagram shows the logs. Any later reasoning that "same index and term means same history", which Raft's commit rule depends on, is wrong for this pair.
3.LogMatching fails after 8 states: Elect(s1, 1), Elect(s2, 2), ClientRequest(s1), Elect(s1, 2) (a second leader of term 2), ClientRequest(s1) gives <<1, 2>>, and ClientRequest(s2) twice gives <<2, 2>>. No message was needed. In Raft a candidate needs votes from a majority, and each server votes at most once per term. Two majorities of the same servers intersect, as in Set operations and quorums, so two leaders of one term would need some server to vote twice.
4. With SYMMETRY Perms: no error, 148 distinct states instead of 793.
The reduction is sound here because no definition singles out a server: Init, Next and LogMatching treat every server alike, so a permuted state violates the invariant exactly when the original does. State explosion and trustworthy reductions warns against combining symmetry with liveness checks unless your tools and reasoning explicitly support it, so run liveness checks without it.
5. Suppose Log Matching holds before a step. ClientRequest appends an entry whose term is the leader's current term at a new index. No other log has an entry with that term at that index, because one leader creates all of a term's entries and it never overwrites its own. So the new entry matches nothing yet. AppendEntries(l, f, i) gives f the prefix up to i only if f's entry i has the same term as l's. By the hypothesis, f's prefix through i equals l's. The new entry i + 1 is l's, so f's new log is a prefix of l's, and every pair involving f reduces to a pair involving l. Making this into a checked inductive invariant needs extra facts, such as that each term's entries appear in that term's leader's log. Finding them is the work Safety and inductive invariants describes.
Problem 5●●●Infrastructure
Capstone: a job scheduler that sends each invoice exactly once
A billing platform runs one job per customer each month. The job computes the invoice, writes it to storage, and queues the invoice email. A scheduler leases each job to one worker at a time and issues an increasing fencing token per job with each lease. Workers can pause past their lease's expiry, and they can crash. The worker writes the output, then runs one storage transaction that marks the job done and inserts an outbox row for the email, as in the outbox problem of Problem set 13. The product requirement is that every customer eventually gets exactly one invoice, built from the output of the run that committed it.
Three designs differ only in storage's checks. "LeaseOnly" trusts the lease: storage checks nothing. "DedupOnly" refuses to commit a job already done. "Fenced" also refuses a write or a commit whose token is below the job's fence, and refuses writes to a finished job. Expiries and crashes are bounded to keep the model finite. Reap frees the lease of a worker that crashed, and has fairness, because a lease always runs out eventually. The contract, PSfinal_Jobs, sends each job's invoice once, eventually.
---------------- MODULE PSfinal_Jobs ----------------
EXTENDS Naturals
CONSTANT Jobs
VARIABLE invoiced \* invoiced[j]: invoices sent for job j
Init == invoiced = [j \in Jobs |-> 0]
\* The contract: each job's invoice goes out once, in one step.
Finish(j) == /\ invoiced[j] = 0
/\ invoiced' = [invoiced EXCEPT ![j] = 1]
Next == \E j \in Jobs : Finish(j)
Spec == Init /\ [][Next]_invoiced /\ WF_invoiced(Next)
======================================================
---------------- MODULE PSfinal_Scheduler ----------------
EXTENDS Naturals
CONSTANTS Workers, Jobs, Design, MaxExpiries, MaxCrashes
ASSUME Design \in {"LeaseOnly", "DedupOnly", "Fenced"}
VARIABLES lease, \* lease[j]: the worker holding j's lease, or "none"
issued, \* issued[j]: the last fencing token issued for j
wpc, \* wpc[w]: "idle", "run" or "wrote" (volatile)
wjob, \* wjob[w]: the job w is running
wtok, \* wtok[w]: the token w received with its lease
output, \* storage: output[j] = token of the run that wrote it
fence, \* storage: fence[j] = highest token accepted for j
done, \* storage: jobs committed as finished
doneTok, \* storage: doneTok[j] = token of the committing run
invoices, \* outbox rows: invoices[j] = invoices queued for j
expiries, \* lease expiries so far (the holder is still alive)
crashes \* worker crashes so far
vars == <<lease, issued, wpc, wjob, wtok, output, fence, done, doneTok,
invoices, expiries, crashes>>
MaxTok == 1 + MaxExpiries + MaxCrashes \* enough for every run allowed
Init == /\ lease = [j \in Jobs |-> "none"]
/\ issued = [j \in Jobs |-> 0]
/\ wpc = [w \in Workers |-> "idle"]
/\ wjob = [w \in Workers |-> CHOOSE j \in Jobs : TRUE]
/\ wtok = [w \in Workers |-> 0]
/\ output = [j \in Jobs |-> 0]
/\ fence = [j \in Jobs |-> 0]
/\ done = {}
/\ doneTok = [j \in Jobs |-> 0]
/\ invoices = [j \in Jobs |-> 0]
/\ expiries = 0
/\ crashes = 0
Storage == <<output, fence, done, doneTok, invoices>>
\* The scheduler leases an unfinished job to an idle worker, with a token.
Acquire(w, j) == /\ wpc[w] = "idle" /\ lease[j] = "none" /\ j \notin done
/\ issued[j] < MaxTok
/\ lease' = [lease EXCEPT ![j] = w]
/\ issued' = [issued EXCEPT ![j] = @ + 1]
/\ wpc' = [wpc EXCEPT ![w] = "run"]
/\ wjob' = [wjob EXCEPT ![w] = j]
/\ wtok' = [wtok EXCEPT ![w] = issued[j] + 1]
/\ UNCHANGED <<Storage, expiries, crashes>>
\* The worker stops; it gives the lease back if it still holds it.
Stop(w) == /\ wpc' = [wpc EXCEPT ![w] = "idle"]
/\ lease' = IF lease[wjob[w]] = w
THEN [lease EXCEPT ![wjob[w]] = "none"] ELSE lease
\* The worker writes the job's output to storage.
Write(w) == LET j == wjob[w] IN
/\ wpc[w] = "run"
/\ IF Design = "Fenced" /\ (j \in done \/ wtok[w] < fence[j])
THEN /\ Stop(w) \* storage refused
/\ UNCHANGED <<output, fence>>
ELSE /\ output' = [output EXCEPT ![j] = wtok[w]]
/\ fence' = [fence EXCEPT ![j] = IF wtok[w] > @ THEN wtok[w] ELSE @]
/\ wpc' = [wpc EXCEPT ![w] = "wrote"]
/\ UNCHANGED lease
/\ UNCHANGED <<issued, wjob, wtok, done, doneTok, invoices, expiries, crashes>>
\* One storage transaction marks the job done and queues the invoice.
Commit(w) == LET j == wjob[w] IN
/\ wpc[w] = "wrote"
/\ Stop(w)
/\ IF \/ Design # "LeaseOnly" /\ j \in done
\/ Design = "Fenced" /\ wtok[w] # fence[j]
THEN UNCHANGED <<done, doneTok, invoices>> \* refused
ELSE /\ done' = done \cup {j}
/\ doneTok' = [doneTok EXCEPT ![j] = wtok[w]]
/\ invoices' = [invoices EXCEPT ![j] = @ + 1]
/\ UNCHANGED <<issued, wjob, wtok, output, fence, expiries, crashes>>
\* The lease runs out while its holder is alive but paused.
Expire(j) == /\ lease[j] # "none" /\ expiries < MaxExpiries
/\ lease' = [lease EXCEPT ![j] = "none"]
/\ expiries' = expiries + 1
/\ UNCHANGED <<issued, wpc, wjob, wtok, Storage, crashes>>
\* A worker crashes; its lease stays until Reap.
Crash(w) == /\ wpc[w] # "idle" /\ crashes < MaxCrashes
/\ wpc' = [wpc EXCEPT ![w] = "idle"]
/\ crashes' = crashes + 1
/\ UNCHANGED <<lease, issued, wjob, wtok, Storage, expiries>>
\* The lease of a worker that is no longer running the job runs out.
Reap(j) == /\ lease[j] # "none"
/\ LET w == lease[j] IN wpc[w] = "idle" \/ wjob[w] # j
/\ lease' = [lease EXCEPT ![j] = "none"]
/\ UNCHANGED <<issued, wpc, wjob, wtok, Storage, expiries, crashes>>
Next == \/ \E w \in Workers, j \in Jobs : Acquire(w, j)
\/ \E w \in Workers : Write(w) \/ Commit(w) \/ Crash(w)
\/ \E j \in Jobs : Expire(j) \/ Reap(j)
Spec == Init /\ [][Next]_vars
FairSpec == /\ Spec
/\ \A j \in Jobs : WF_vars(\E w \in Workers : Acquire(w, j))
/\ WF_vars(Reap(j))
/\ \A w \in Workers : WF_vars(Write(w)) /\ WF_vars(Commit(w))
OneInvoice == \A j \in Jobs : invoices[j] <= 1
OutputOfCommitter == \A j \in done : output[j] = doneTok[j]
Contract == INSTANCE PSfinal_Jobs WITH invoiced <- invoices
Refines == Contract!Spec
===========================================================
For task 4, this module adds a type invariant, a first guess at an inductive invariant, and a stronger candidate. It also defines a specification with no fairness for Reap.
INIT Guess
NEXT Next
CONSTANTS Workers = {w1, w2}
Jobs = {j1}
Design = "Fenced"
MaxExpiries = 1
MaxCrashes = 1
INVARIANT Guess
CHECK_DEADLOCK FALSE
w1 committed after its lease ended, and w2, the rightful holder, then overwrote a finished job’s output. Deduplication saw nothing wrong. Fenced storage refuses the red write, because the job is already done.
Safety. Run "LeaseOnly" and "DedupOnly" with both invariants. For each, say which fails and tell the story of TLC's trace. Which earlier lesson's fix does each design lack?
Refinement and liveness. Run the configuration shown, then with Jobs = {j1, j2}. Then check Refines on "DedupOnly". It passes. What does that tell you about the contract?
Fairness. Check Refines under NoReapSpec on the fenced design. Explain the counterexample and name the real mechanism that WF_vars(Reap(j)) stands for.
Inductive invariant. Run the Guess configuration and explain the counterexample to induction. Then check Inv the same way. Finally, argue by hand that Inv implies both safety properties and that Init implies Inv.
Review. List the assumptions this model makes that a real deployment must provide, in the spirit of Capstone: multi-region payments's rubric.
Hint
For task 1, follow the worker whose lease expired: what can it still do, and what does storage know about it? For task 4, find a variable in the counterexample's first state that disagrees with another one in a way no behavior could produce, and write that relation down as a conjunct.
Solution
1."LeaseOnly" fails OneInvoice after 8 states. w1 acquires j1 with token 1 and writes the output. Its lease expires while it is paused. w2 acquires with token 2. w1 commits: done, one invoice. w2 writes and commits: a second invoice. Storage trusted a lease that had already ended. That is the fencing problem, and checking nothing also loses idempotency. "DedupOnly" passes OneInvoice but fails OutputOfCommitter after 7 states, the same steps up to w1's commit and then w2's write. The job is done with token 1, but the stored output now comes from run 2. The invoice email describes one computation and storage holds another. Deduplication from Architecture: durable idempotent worker stopped the second commit, but only fencing from Architecture: leases, fencing, and time stops the stale run's write. The diagram draws this trace. In "Fenced", w2's write is refused because the job is done; if w2 had written first, w1's commit would have been refused instead, since its token would be below the fence.
2. No error: 163 distinct states with one job, 2189 with two. Refines checks the contract's whole formula, including WF_invoiced(Next), so it checks that every invoice is eventually sent, not just that none is sent twice. "DedupOnly" also refines the contract (207 distinct states), although its invoice can describe the wrong output. The contract says nothing about which output; a passing refinement is only as strong as the contract. Either add the output to the contract or keep OutputOfCommitter as a separate checked property.
3.Refines fails. w1 acquires; its lease expires; w2 acquires, writes, and crashes, and w2's lease stays held. w1 resumes, its write is refused (token 1 is below fence 2), and then the system stutters forever: j1 is not done, no one can acquire it, and the invoice never goes out. WF_vars(Reap(j)) stands for lease expiry: a crashed holder's lease runs out because the lock service's clock keeps moving. That is the time assumption Architecture: leases, fencing, and time told you to make explicit. Safety never depended on it; liveness does.
4.Guess fails from an unreachable state: invoices[j1] = 1 while done = {} and w2 is about to commit, so Commit(w2) makes the count 2. The missing fact is that invoices and done move together, and similarly that the stored output always belongs to the fence's token. Inv says exactly that. Starting from every state that satisfies it, TLC finds no error (138,240 distinct states), so it is inductive for these constants. By hand: Init has every count, token and fence at 0 and nothing done, so it satisfies Inv. Inv gives invoices[j] <= 1 directly, and for a done job output[j] = fence[j] = doneTok[j], which is OutputOfCommitter. The step case is the one TLC checked. The fenced Write sets output and fence to the same token. Commit needs wtok[w] = fence[j], so doneTok becomes the fence. And nothing changes output or fence after the job is done. As Safety and inductive invariants says, this is a finite check, not a proof for all sizes; From model checking to proof shows how to make it one.
5. Tokens increase per job and are never reused, even after the scheduler restarts. Storage checks the token and applies the write, or the commit, in one atomic step, like a conditional update in one transaction. The outbox relay and the email consumer give at-least-once delivery with deduplication, as in Problem set 13. Crashes and pauses happen finitely often; the bounds here stand in for that. A crashed holder's lease eventually expires. And the contract is about invoices queued, not delivered: delivery is the next layer's contract. Every one of these is either checked in some model of this course or stated as an assumption. That is what a reviewable design looks like.