10-05
Chapter 10 · Fairness, derived
Where fairness comes from
00Recall
One card from 08-02 on why loss is free for invariants, one from 07-02 on what one PlusCal step is, and one from 10-04 on reading a liveness pass that rests on strong fairness. Chapter 08 left you a warning: when you add fairness, check that you have not quietly made your network reliable. Today you check.
On the essentials track? This lesson puts fairness on PlusCal processes and reads their translation; PlusCal is chapter 07, which that track skips. Read the recaps of 07-01 and 07-02 in chapters/07-pluscal/CONCEPTS.md first.
08-02-b from Loss and duplication for free
Why does adding an explicit Lose action never make an invariant about the sender and receiver fail?
Show answer
Any behavior with a lost message matches one where the message stays in the set and is never taken, with the same endpoint states. Loss matters for a property that mentions the network, and once fairness says messages must arrive.
07-02-a from Labels are steps
In PlusCal, what is one step?
Show answer
Everything from one label to the next. The translator turns it into one action, so no other process can run in the middle of it.
10-04-b from Fairness hides liveness bugs, never safety bugs
An AI summary says "with strong fairness on every action, TLC finds no violation of NoStarvation, so the design is starvation-free." What should you check before accepting it?
Show answer
What each fairness conjunct promises and who keeps that promise. SF on a lock or on a user's action is an assumption the real system may not meet; under the fairness a real scheduler gives, the same design may starve.
Skip recall Recall is never required.
01Commit
The task board is back, cut down to one open task and two workers. specs/SilentLossBoard.tla uses chapter 08's network: net is the set of claims ever sent, and receiving a claim leaves it there. A claim nobody ever reads has, in effect, been lost. Without fairness, SilentLossBoard.live.cfg shows exactly that: both workers ask, and nothing happens for ever. Now add weak fairness on receiving:
WFSpec is defined as Spec and for all w in Workers : WF_vars(Receive(w))Commit a
SilentLossBoard.wf.live.cfg checks EventuallyClaimed (once anyone asks, the task eventually has an owner) against WFSpec. What does TLC report?
- A violation: the network can still lose both claims.
- No violation.
- A violation: Receive is only enabled now and then, so weak fairness cannot force it.
Answer No violation.
- If you picked A
- In this spec, loss is not an action; it is a claim that stays in net and is never read. Ask whether weak fairness still allows "never read" for a claim that stays readable.
- If you picked C
- Nothing ever leaves net, and owner stays NoOne until someone receives. So from the first Request on, Receive stays enabled in every state until it happens.
specs/TaskBoard.tla makes loss an action instead. Lose(w) takes a claim out of the network; Retry(w) is a worker's timeout firing, which sends the claim again while the task is still open. WFSpec there puts weak fairness on Receive and on Retry, and none on Lose or Request.
Commit b
TaskBoard.wf.live.cfg checks EventuallyClaimed against that WFSpec. What does TLC report?
- No violation: retries keep putting the claim back, and weak fairness on Receive then delivers it.
- A violation: a lasso in which every claim sent is lost, and the workers keep resending.
- A violation: a lasso in which the workers give up and stop resending.
Answer A violation: a lasso in which every claim sent is lost, and the workers keep resending.
- If you picked A
- After each Retry, Receive is enabled. After each Lose, it is not. Weak fairness asks for an action that is enabled continuously.
- If you picked C
- Weak fairness on Retry rules that out: while a worker's claim is out of the network and the task is open, Retry stays enabled until it happens or the task is claimed.
02Lab
No browser lab today. Run the two checks from the repository root:
./tla check chapters/10-fairness/specs/SilentLossBoard.wf.live.cfg
./tla check chapters/10-fairness/specs/TaskBoard.wf.live.cfg10-fairness/specs/TaskBoard.wf.live10-fairness/specs/TaskBoard.wf.live TaskBoard.wf.live.cfg (W1=W1, W2=W2, NoOne=NoOne)
parse ok
model check: temporal property EventuallyClaimed violated; lasso of 6 states, looping back to state 3; 15 distinct states
expected outcome met: property EventuallyClaimed
trace (changed variables only; ./tla trace --full shows all):
1 Init ask = (W1 :> "idle" @@ W2 :> "idle"), net = {}, owner = NoOne
2 Request ask: (W1 :> "idle" @@ W2 :> "idle") -> (W1 :> "asking" @@ W2 :> "idle"), net: {} -> {W1}
3 Request ask: (W1 :> "asking" @@ W2 :> "idle") -> (W1 :> "asking" @@ W2 :> "asking"), net: {W1} -> {W1, W2}
4 Lose net: {W1, W2} -> {W1}
5 Lose net: {W1} -> {}
6 Retry net: {} -> {W1}
Retry(W2) back to state 3Reveal for commit a
No violation of EventuallyClaimed, in 8 distinct states, with every action firing and the witness BothInFlight reached. The task is always claimed, on a network that was supposed to lose claims.
Reveal for commit b
A violation: a lasso of 6 states. In the loop the network drops every claim, the workers resend, and the board never reads one. TaskBoard.live.cfg uses LiveSpec, with strong fairness on Receive, and finds no violation in 15 distinct states.
03Reason
If you picked a violation for the first question, you remembered chapter 08 correctly and missed what fairness did to it. In SilentLossBoard a lost claim is a claim that sits in net unread for ever. While the task is open, every claim in net stays readable, so its Receive stays enabled, and weak fairness forces some claim to be read. The one thing loss could do here, keep the task open for ever, is gone. The pass is honest about the formula and dishonest about the network. You asked "is the task claimed on a lossy network?" and checked "is it claimed on a network that delivers everything?"
With Lose in the spec, the flicker from 10-03 returns in a new costume. Every Retry enables Receive; every Lose disables it. Weak fairness asks for continuous enabling and gets none, so the scheduler, now playing the network, wins:
- State 1 Initial state ask = (W1 :> "idle" @@ W2 :> "idle") net = {} owner = NoOne
- State 2 Request ask (W1 :> "idle" @@ W2 :> "idle") becomes (W1 :> "asking" @@ W2 :> "idle") net {} becomes {W1}
- State 3 Request ask (W1 :> "asking" @@ W2 :> "idle") becomes (W1 :> "asking" @@ W2 :> "asking") net {W1} becomes {W1, W2}
- State 4 Lose net {W1, W2} becomes {W1}
- State 5 Lose net {W1} becomes {}
- State 6 Retry net {} becomes {W1}
- Loop Retry(W2) back to state 3
Strong fairness on Receive closes the gap: a claim that keeps being sent is eventually received. That is LiveSpec, and it passes. But every fairness conjunct is a promise about the world, so ask the question this lesson is named for. What in a real system makes it true?
Write something before openingname a real situation in which "a claim that is sent again and again is eventually received" is false.
A network partition that never heals: the worker's side of the network can reach nothing, however often it resends. A firewall rule that drops every packet to the board. A board that is down for good. In each case the strong fairness is false, the liveness property is false, and that is the right answer. The model's claim is "if the network drops copies only now and then, and the worker keeps resending, the task is claimed". The if is the fairness, and it belongs in the design document, not only in the spec.
Every fairness conjunct in this chapter can be traced to a mechanism, or to nothing:
| Conjunct | Mechanism that keeps the promise | What breaks it |
|---|---|---|
WF on a thread's own step | A preemptive scheduler that gives every runnable thread a time slice | A crashed or paused process; a thread kept off the CPU by higher priorities |
WF on Retry | A timer that keeps firing while the task is open | A worker that crashes, or a retry budget that runs out |
SF on Receive, with retries | A network that drops copies at random, not all of them for ever (random loss makes this true with probability 1; SF is how the spec records it) | A partition that never heals |
SF on Acquire | Nothing in a plain spin lock; a lock that queues its waiters | Real hardware: a spinning thread can lose every race |
Any fairness on Request or GetHungry | Nobody: these are the environment's choices | Every user who stops asking |
The fourth row is the one to remember. Strong fairness on Acquire is a promise no ordinary lock makes. The fix is a design, not a conjunct: make waiting processes queue, so that once the lock is free the head of the queue stays able to enter until it does. Then weak fairness is enough, and the first row of the table is its mechanism: still an assumption to write down, but a far smaller one. The AI item 10-ai3 claims exactly that for a queue lock, and the Stretch asks you to build a ticket lock with the same property.
PlusCal writes fairness on the process line. In specs/TaskBoardPlusCal.tla, the workers are a fair process, the courier that carries claims to the board is a fair+ process, and the network that drops them is a plain process. fair is weak fairness on the whole process, all its labels together; fair+ is strong fairness; no keyword means no fairness. A label written with a minus, as in the workers' Claim:-, is left out of its process's fairness: nobody has to ask. The translator turns those words into conjuncts of Spec.
Write something before openingwrite the Spec the translator produces for those three process lines. Where does the quantifier over workers go?
Spec is defined as and Init and always[Next]_vars
and for all self in Workers : WF_vars((pc[self] not equal to "Claim") and Worker(self))
and SF_vars(Courier)One weak fairness condition per worker, with the quantifier outside WF, as 10-02 recommended; pc[self] # "Claim" is what Claim:- produced, so the condition covers the resends and not the first claim. One strong fairness condition for the courier. Nothing at all for the network: a plain process adds no conjunct. Worker(self) and Courier are the translator's names for "any step of that process", the disjunction of its labels.
04In your editor
Check this lesson's exercises and the specs it uses with:
./tla check 10-05The PlusCal board:
10-fairness/specs/TaskBoardPlusCal.live10-fairness/specs/TaskBoardPlusCal.live TaskBoardPlusCal.live.cfg (Workers={w1, w2}, NoOne=NoOne)
PlusCal translated (translation up to date)
parse ok
model check: no violation found in 29 distinct states (63 generated, depth 7)
expected outcome met: pass
coverage: all 4 actions fired
witness LostAndOpen reached (trace of 3 states)When you write fair or fair+ in PlusCal, add a comment on the same line naming the mechanism: fair process Worker \in Workers \* the worker's timer keeps firing. A process line with no comment and no keyword should be part of the environment.
05Practice
Warm-up. The PlusCal courier is weakly fair, and the network can still starve the board. Change one keyword.
Core. A shop's server sends a webhook over a network that loses requests. Write Lose, the retry, and the least fairness that gets the order confirmed.
Stretch. A ticket lock from a skeleton, cfg included, live under weak fairness alone.
10-05-ex1Warm-up5 min
10-05-ex1 · Fair plus
Tier: warm-up. Time: about 5 minutes.
The PlusCal task board from lesson 10-05, with one keyword changed. The courier that carries claims to the board is a fair process, which is weak fairness. The network that drops claims has no fairness at all.
- Run
./tla check 10-05-ex1. The engine translates the algorithm, and TLC reportsEventuallyClaimedviolated. Read the loop: in which of its states could the courier deliver, and in which could it not? - In gap g1, change the fairness keyword on the courier's process line. Do not touch the workers or the network.
- Run the check again. The engine retranslates the algorithm. It must pass, with every action firing and the witness
LostAndOpenreached.
TaskBoardPlusCal.ceiling.cfg checks that Spec assumes no more than CeilingSpec: in particular, no fairness on a worker's first claim. A keyword on the network would not fail it, because on this board it changes no behavior; it would still be a promise about the environment. Leave the cfg and CeilingSpec as they are.
Then open the translation between \* BEGIN TRANSLATION and \* END TRANSLATION and find the conjunct your keyword produced in Spec. Never edit that block: the engine writes it.
Hints: HINTS.md, under "10-05-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/10-fairness/exercises/05-ex1-fair-plus/; open it after you have a passing answer of your own.
Done when: ./tla check 10-05-ex1 prints "2 of 2 checks met their expected outcome".
./tla check 10-05-ex1
Repo chapters/10-fairness/exercises/05-ex1-fair-plus/
Hints
Hint 1
In the loop, the courier's Deliver is enabled while net holds a claim, and disabled when the network has dropped every claim. Which kind of fairness asks something of an action like that?
Hint 2
In PlusCal, fair is weak fairness on the whole process, and fair+ is strong fairness. The keyword goes in front of process.
Hint 3 (nearly the answer)
You need the strongly fair keyword from lesson 10-05, on the courier and nowhere else. Delete the \* GAP marker and run the check so the engine retranslates; then find the courier's conjunct at the end of Spec in the translation and check which kind it is.
10-05-ex2Core8 min
10-05-ex2 · Retry the webhook
Tier: core. Time: about 8 minutes.
A shop's server tells a partner's server about each order by sending a webhook, an HTTP request, over a network that can lose it. The partner confirms the first request it receives. When the shop's retry timer fires with no confirmation, it sends the request again. The requirement, Confirmed: once the order event happens, the partner eventually confirms it.
Webhook.tla has three gaps: the loss, the retry, and the fairness.
- Run
./tla check 10-05-ex2.Webhook.cfgreportsConfirmedviolated by a stutter.MCWebhook.cfgreports a coverage gap:Losenever fires, because the starter'sLoseisFALSE. - Fill gap g1,
Lose: the network loses the request in flight. Fill gap g2,Retry: the timer fires and the shop sends the request again. Each gap's comment says when its action may happen. - Fill gap g3,
LiveSpec. Start with weak fairness onDeliverandRetry, run it, and read the loop. Then strengthen only what the loop shows you need. - Run the check. Both cfgs must pass, with every action firing and the witness
LostRequestreached.
MCWebhook.cfg is the course's check of your work. It allows strong fairness on delivering and on retrying, and nothing on Lose or Fire: you may not assume the network stops losing requests, or that orders keep coming. It also checks that a request is in flight only after the order event and never once the partner has confirmed (SendDiscipline), that only a delivered request confirms (OnlyDeliveryConfirms), and that a retry sends a request (RetrySends). Leave MCWebhook.tla and its cfg as they are.
Next to each fairness conjunct, write the mechanism that keeps the promise and what would break it, in the style of the table in lesson 10-05. Then name one real situation in which your LiveSpec is false, and the order is never confirmed.
Hints: HINTS.md, under "10-05-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/10-fairness/exercises/05-ex2-retry-the-webhook/; open it after you have a passing answer of your own.
Done when: ./tla check 10-05-ex2 prints "2 of 2 checks met their expected outcome".
./tla check 10-05-ex2
Repo chapters/10-fairness/exercises/05-ex2-retry-the-webhook/
Hints
Hint 1
Lose and Retry each change one variable, inflight, and leave the others alone. Lose happens while a request is in flight; Retry happens while none is, the order event has happened, and nothing is confirmed yet. MCWebhook.cfg's SendDiscipline fails if a guard is missing.
Hint 2
With weak fairness on both, the loop is send, lose, send, lose. In that loop, is Deliver enabled in every state, in some, or in none? Ask the same of Retry.
Hint 3 (nearly the answer)
The action that the loop shows enabled after every send and disabled after every loss needs the kind of fairness whose hypothesis is "infinitely often". The other one stays as it is. Nothing on Lose or Fire.
10-05-ex3Stretch40 min · mastery path
10-05-ex3 · Take a ticket
Tier: stretch. Time: about 40 minutes. Off the core clock: this is on the mastery path.
Lesson 10-05 said that strong fairness on Acquire is a promise no ordinary lock makes, and that the fix is a design: make waiting processes queue. A ticket lock is that design in two counters, like the numbered tickets at a deli counter.
TicketLock.tla names the variables and the actions and supplies one witness. Every body is a placeholder, and so is the cfg. You write the rest.
The lock:
- An idle process takes a ticket: it gets the dispenser's number, and the dispenser moves on to the next one.
- A waiting process enters the critical section when the lock is serving its number.
- The process in the critical section leaves, and the lock moves on to serve the next number.
- Numbers wrap round: after
Size - 1comes 0. - Safety,
Mutex: never two processes in the critical section. - Liveness,
NoStarvation: every waiting process eventually enters. LiveSpecuses weak fairness only, and none on taking a ticket: nobody has to want the lock.
Steps:
- Run
./tla check 10-05-ex3. All five cfgs stop with the same TLC error. What does TLC say about anInitthat isFALSE? - Fill gaps g1 to g7 in
TicketLock.tla. - Fill gap g1 in
TicketLock.cfg, withSize = 3: the behavior spec with its fairness, and the checks worth running. - Run the check until all five cfgs meet their goals. Your
TicketLock.cfg,MCTicketLock.cfgandMCTicketLock.ceiling.cfgmust pass, with every action firing andOneWaitsreached.MCTicketLock.cfgchecks the types and the requirements in the course's own words, so your lock cannot pass by being checked against weaker properties.MCTicketLock.ceiling.cfgchecks that yourLiveSpecassumes no more than weak fairness onEnterandLeave. The other two test your own properties on broken locks:MCTicketLock.loose.cfglets a process enter without its number being served, so yourMutexmust be violated there, andMCTicketLock.noleave.cfgdrops the fairness on leaving, so yourNoStarvationmust be violated there. No cfg grades yourTypeOK, or which checks your own cfg names: compare those with the solution's. LeaveMCTicketLock.tlaand its four cfgs as they are. - Before you finish, explain why weak fairness is enough here when lesson 10-03 needed strong fairness for
FairLock. Look at when yourEnter(p)is enabled, and ask whether anything can disable it before it happens. - Change
Sizeto 2 in your cfg for a moment, predict whether anything breaks, and run it. Then try 1. Explain both results from how many tickets can be out at once, and changeSizeback to 3.
Hints: HINTS.md, under "10-05-ex3 hint 1" to "hint 3". The solution is in solutions/chapters/10-fairness/exercises/05-ex3-take-a-ticket/; open it after you have a passing answer of your own.
The goals differ: "goal met: violation Mutex" for MCTicketLock.loose.cfg, "goal met: property NoStarvation" for MCTicketLock.noleave.cfg, and "goal met: pass" for the other three.
Done when: ./tla check 10-05-ex3 prints "5 of 5 checks met their expected outcome".
./tla check 10-05-ex3
Repo chapters/10-fairness/exercises/05-ex3-take-a-ticket/
Hints
Hint 1
Write TypeOK, Init and the cfg first, with INVARIANT TypeOK only, and run it. Then the three actions, one at a time. All ticket arithmetic wraps: use % Size.
Hint 2
TakeTicket(p) gives p the dispenser's current number and moves the dispenser on. Enter(p) needs p waiting and its ticket equal to serving. Leave(p) moves serving on. Each action changes only the variables it must and keeps the rest UNCHANGED.
Hint 3 (nearly the answer)
Which action is a process deciding to ask, and which are the lock's job? Only the lock's actions get fairness, and the ticket lock's point is that the weaker kind is enough: a waiting process whose number is being served stays able to enter until it does, because nothing else changes serving while nobody is inside. The cfg names LiveSpec, the constants, TypeOK, Mutex and NoStarvation.
10-mxMixed20 min · mastery path
10-mx · Two flags and a turn
Tier: mixed. Time: about 20 minutes. Off the core clock: this is on the mastery path.
Two processes guard a critical section with no lock at all: two flags and a shared turn variable. Each step writes at most one shared variable, and the wait reads both flag and turn in one step, a simplification of the textbook loop, which reads them one at a time. A process that wants in raises its flag, writes turn, and then waits until the other process does not want in, or turn says it may go.
- Run
./tla check 10-mx. Both cfgs fail.Peterson.cfgreportsMutexviolated.Peterson.live.cfgreportsNoStarvationviolated. - Read the safety trace first. Write down, in the order the trace shows, the two writes to
turnand the two entries. Who wroteturnlast, and who did that write let in? - Read gap g1. When both processes want in, the write to
turndecides who goes first. Is the starter's write polite or greedy? - Fix the one placeholder line.
- Run the check. Both cfgs must pass, with every action firing and the witness
OneWaitsreached.
Then look at LiveSpec. It has weak fairness on every step after SetFlag, and nothing stronger. Why is weak fairness enough here, when a plain lock needed strong fairness? Find the moment in the protocol after which the waiting process's Enter stays enabled until it happens.
Two flags and a turn is Gary L. Peterson's 1981 mutual-exclusion algorithm (Myths About the Mutual Exclusion Problem); this model and its names are the course's own.
Hints: HINTS.md, under "10-mx hint 1" to "hint 3". The solution is in solutions/chapters/10-fairness/exercises/mx-two-flags-and-a-turn/; open it after you have a passing answer of your own.
Done when: ./tla check 10-mx prints "2 of 2 checks met their expected outcome".
./tla check 10-mx
Repo chapters/10-fairness/exercises/mx-two-flags-and-a-turn/
Hints
Hint 1
In the safety trace, the second process to write turn writes its own name, and that lets it in while the first process is already inside. What should a process write to turn when both want the critical section?
Hint 2
The point of turn is politeness: when both want in, the last one to write turn should be the one that waits. The module already defines an operator for "the other process".
Hint 3 (nearly the answer)
The value SetTurn(p) writes is the one thing to change: a polite process hands the turn away rather than taking it. When the other process next writes turn, it hands the turn to the waiter, and from then on the waiter's Enter stays enabled until it happens, which is why weak fairness is enough.
06Explain it
Open NOTES.md and answer the three prompts under 10-05, about the Core exercise.
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:Compare your answers with "10-05 check your explanation" in HINTS.md.
After you writeCheck your explanation
A good answer: "Lose takes the request out of flight, and Retry sends it again when the timer fires. Confirmed needs weak fairness on Retry, kept by a retry timer that keeps firing while the order is unconfirmed, and strong fairness on Deliver, kept by a network that drops requests now and then rather than every copy for ever. Weak fairness on Deliver fails because every loss disables it. A partner that is down for good breaks the strong fairness, and then the order is never confirmed, which is the right answer. A retry budget that runs out breaks the weak fairness. TLC checked one order, with no time: a confirmation that arrives after an hour still counts."
A weak answer: "I added SF_vars(Deliver) because WF failed." It names the conjunct but not the mechanism behind it, or a real situation in which it is false.
For the gate and its twin. Grade your Spec comments the same way: each conjunct names a mechanism and what breaks it. Then run the self-check from the gate README. Replace each SF_ with WF_ in turn, and delete any fairness on the desks or cars and on going offline or cutting power; if Liveness still passes after a change, keep the change, because the conjunct you removed was an assumption you did not need. A conjunct with no mechanism you can name is one to delete and rerun without. A disjunction inside one condition, such as SF_vars(Grant \/ Skip), is acceptable only if you can argue for each part.
07Your system
Milestone 4: one liveness property, the fairness it needs, and the real mechanism behind that fairness.
Keep this work in my-system/, which Git ignores, and in a private repository. Strip names and identifiers before you share any of it, and do not paste proprietary designs or customer data into third-party AI tools without your organisation's approval.
- Write one liveness property of your system in a sentence: something that must eventually happen, such as "every accepted order is eventually shipped or refunded". Then write it with
~>or<>. - Put it in a
.live.cfgand check it with no fairness. Read the stuttering counterexample: it is the system doing nothing. - Add fairness one conjunct at a time. Sort each action into the three groups from 10-04 first. After each conjunct, run the check and read the new counterexample.
- For every conjunct in the passing version, write one line in
my-system/DECISIONS.md: the sentence it stands for, the component that makes it true (scheduler, timer, retry loop, queue), and what would break it. If you usedSF, say whyWFwas not enough.
Tick milestone 4 in my-system/MILESTONES.md when the check passes with a witness reached and every conjunct has its line.
Done?