07-04

Chapter 07 · PlusCal: labels are atomicity

Move a label, change the bugs

  • 45 min core
  • Core track
  • Lab: Interleaving Explorer
  • Skills: abstraction, counterexamples

00Recall

One card from 07-03 on what await becomes, one from 07-02 on why a loop needs a label, and one from chapter 03 on how ./tla checks a witness. Today's question is the chapter's hook, so commit before you read the specs closely.

07-03-a from Processes, await, either, with

What does await P become in the translation, and what does a process at a false await do?

Show answer

A conjunct P of the label's action. While P is false the action is not enabled, so the process takes no step at all; it does not spin.

07-02-b from Labels are steps

Why does the PlusCal translator insist on a label in front of every while loop?

Show answer

The loop jumps back to its test, and pc needs a value that means "at the test". The label provides it. Leaving the loop is one more step of that label.

03-03-b from Break it on purpose

How does ./tla check that the witness W is reachable?

Show answer

It checks ~W as an invariant in a wrapper module and expects a violation; the trace shows how W is reached.

Skip recall Recall is never required.

01Commit

A box office has one seat left (Seats = 1) and two ticket sellers, s1 and s2. Each seller runs the same statements: if a seat is free, record the sale and print the ticket.

TLA+
  Check: if sold < Seats then
           sold := sold + 1;
           printed := printed + 1;
         end if;

That is version A, specs/BoxOfficeOneLabel.tla: one label, so the whole thing is one step. Versions B and C have the same statements and one more label each.

  • B, specs/BoxOfficeCheckThenSell.tla: a label Sell: in front of sold := sold + 1. Checking for a free seat is one step; recording and printing is the next.
  • C, specs/BoxOfficeSellThenPrint.tla: a label Print: in front of printed := printed + 1. Checking and recording are one step; printing is the next.

The requirement is NoOversell: never more tickets printed than seats.

Commit a

Same statements, labels in three places. Which versions can print more tickets than there are seats?

  1. B and C: each splits a seller's work into two steps, so each has a race.
  2. Only B.
  3. None: one seller's check and sale are never interleaved with the other's, since each statement is atomic.

Answer Only B.

Version C passes NoOversell. A teammate adds a second invariant, Matched == sold = printed, because every run of C ends with the two equal.

Commit b

TLC checks Matched (sold = printed) on version C, where every run ends with the two equal. What does it report?

  1. No violation: every run ends with sold equal to printed.
  2. A violation, as soon as one seller has recorded a sale.
  3. An error: an invariant cannot relate variables that change in different steps.

Answer A violation, as soon as one seller has recorded a sale.

02Lab

Lab · Interleaving ExplorerWhat you’re looking at: every run of version B, two sellers and one seat, as a tree. TLC marked the leaves with more tickets printed than seats. A and C are not drawn; run them in the terminal below.

TLC found no violation

TLC evaluated Oversold in every state: it holds in state 10, marked ✗.

123456789✗ 10

This is a teaching view. Real checking happens with TLC on your machine.

Text view: every state and step
States and their successors
StatesoldprintedpcSteps (action → state)
initial 100(s1 :> "Check" @@ s2 :> "Check")Check(s1) → 2; Check(s2) → 3
200(s1 :> "Sell" @@ s2 :> "Check")Sell(s1) → 4; Check(s2) → 5
300(s1 :> "Check" @@ s2 :> "Sell")Check(s1) → 5; Sell(s2) → 6
411(s1 :> "Done" @@ s2 :> "Check")Check(s2) → 7
500(s1 :> "Sell" @@ s2 :> "Sell")Sell(s1) → 8; Sell(s2) → 9
611(s1 :> "Check" @@ s2 :> "Done")Check(s1) → 7
711(s1 :> "Done" @@ s2 :> "Done")Terminating → self
811(s1 :> "Done" @@ s2 :> "Sell")Sell(s2) → 10
911(s1 :> "Sell" @@ s2 :> "Done")Sell(s1) → 10
✗ bad: Oversold 1022(s1 :> "Done" @@ s2 :> "Done")Terminating → self

Before you open the tree, sketch version A's on paper. It has one step per seller, so it is small: how many runs are there, and what does each leaf hold? Then open B's tree, which has one more step per seller, and find a marked leaf. Read the path to it: who checked when? Then run all three versions, A first:

shell
./tla check chapters/07-pluscal/specs/BoxOfficeOneLabel.cfg
./tla check chapters/07-pluscal/specs/BoxOfficeCheckThenSell.cfg
./tla check chapters/07-pluscal/specs/BoxOfficeSellThenPrint.cfg
./tla check chapters/07-pluscal/specs/BoxOfficeSellThenPrint.matched.cfg
Expected output 07-pluscal/specs/BoxOfficeOneLabel
07-pluscal/specs/BoxOfficeOneLabel  BoxOfficeOneLabel.cfg  (Sellers={s1, s2}, Seats=1)
PlusCal translated (translation up to date)
parse ok
model check: no violation found in 4 distinct states (6 generated, depth 3)
expected outcome met: pass
coverage: all 2 actions fired
witness SoldOut reached (trace of 2 states)
witness AllDone reached (trace of 3 states)
Expected output 07-pluscal/specs/BoxOfficeCheckThenSell
07-pluscal/specs/BoxOfficeCheckThenSell  BoxOfficeCheckThenSell.cfg  (Sellers={s1, s2}, Seats=1)
PlusCal translated (translation up to date)
parse ok
model check: invariant NoOversell violated; trace has 5 states (4 steps); 10 distinct states
expected outcome met: violation NoOversell
trace (changed variables only; ./tla trace --full shows all):
  1  Init   pc = (s1 :> "Check" @@ s2 :> "Check"), sold = 0, printed = 0
  2  Check  pc: (s1 :> "Check" @@ s2 :> "Check") -> (s1 :> "Sell" @@ s2 :> "Check")
  3  Check  pc: (s1 :> "Sell" @@ s2 :> "Check") -> (s1 :> "Sell" @@ s2 :> "Sell")
  4  Sell   pc: (s1 :> "Sell" @@ s2 :> "Sell") -> (s1 :> "Done" @@ s2 :> "Sell"), sold: 0 -> 1, printed: 0 -> 1
  5  Sell   pc: (s1 :> "Done" @@ s2 :> "Sell") -> (s1 :> "Done" @@ s2 :> "Done"), sold: 1 -> 2, printed: 1 -> 2
Expected output 07-pluscal/specs/BoxOfficeSellThenPrint
07-pluscal/specs/BoxOfficeSellThenPrint  BoxOfficeSellThenPrint.cfg  (Sellers={s1, s2}, Seats=1)
PlusCal translated (translation up to date)
parse ok
model check: no violation found in 8 distinct states (12 generated, depth 4)
expected outcome met: pass
coverage: all 3 actions fired
witness SoldOut reached (trace of 2 states)
witness AllDone reached (trace of 4 states)
Expected output 07-pluscal/specs/BoxOfficeSellThenPrint.matched
07-pluscal/specs/BoxOfficeSellThenPrint.matched  BoxOfficeSellThenPrint.matched.cfg  (Sellers={s1, s2}, Seats=1)
PlusCal translated (translation up to date)
parse ok
model check: invariant Matched violated; trace has 2 states (1 steps); 2 distinct states
expected outcome met: violation Matched
trace (changed variables only; ./tla trace --full shows all):
  1  Init   pc = (s1 :> "Check" @@ s2 :> "Check"), sold = 0, printed = 0
  2  Check  pc: (s1 :> "Check" @@ s2 :> "Check") -> (s1 :> "Print" @@ s2 :> "Check"), sold: 0 -> 1

Reveal for commit a

Only B. TLC finds no violation in A (4 distinct states) or in C (8). In B, NoOversell fails after a trace of 5 states: both sellers pass the check before either records the sale.

Reveal for commit b

A violation, in a trace of 2 states: one seller's Check step records the sale, and the state right after it has sold = 1 and printed = 0.

03Reason

If you picked "B and C", you counted labels. A label marks where another process may run, and that is necessary for a race but not enough. The question to ask at every label is: what can the other process see here, and will it act on it?

Take B. Here is its Check action:

TLA+
Check(self) is defined as and pc[self] = "Check"
               and IF sold < Seats
                     THEN and pcprime = [pc EXCEPT ![self] = "Sell"]
                     ELSE and pcprime = [pc EXCEPT ![self] = "Done"]
               and UNCHANGED tuple of sold, printed end tuple

The step decides, and changes nothing but pc. Between Check and Sell, the seat is promised to this seller, but sold does not say so. The other seller reads sold, sees a free seat, and decides the same way. Both sell. That is check-then-act: a decision made on a value that can change before the action it justifies.

Now C. Its Check step records the sale in the same step as the decision. Between Check and Print, the other seller sees sold = Seats and correctly goes home. The gap only delays the printing of a ticket that is already accounted for. Moving the label from before the sale to after it moved the gap from a place where it matters to a place where it does not.

There are two ways to fix B, and they are the same fix. You can move the label, which gives you C. Or you can keep the label and make the database do the check and the sale in one call, a conditional update that says "add one to sold, but only if sold < Seats". In the model, that call is one step, so the check and the sale share a label again. Either way the rule is the same: the decision and the record of the decision happen in one atomic step.

Write something before openingversion A passes, and it has the fewest steps. Is it the right model of the box office?

Only if the real box office checks, sells and prints in one transaction. A has one label, so it claims that nothing can happen between the check and the print. If the real system makes three calls with no transaction around them, A's pass is a pass for a system you do not have. A pass is evidence about the model you wrote. Whether the model is the system is a question about labels, and TLC cannot answer it.

Write something before openingB oversells with one seat. Does it still oversell with two seats and two sellers?

No. BoxOfficeCheckThenSell.twoseats.cfg finds no violation in 9 distinct states: two sellers can sell at most two tickets, and there are two seats. The race is still in the algorithm; this model is too small to show it. Before you trust a pass, ask whether the constants leave room for the bug: here, more sellers than seats left.

The second question is about invariants. An invariant is checked in every reachable state, and with labels, the reachable states include the ones in the middle of a process's work. Matched describes a seller at rest. In C, a seller between Check and Print is not at rest, and TLC finds that state at once.

So labels do two jobs at once, and moving one changes both. They decide which interleavings exist, and therefore which races TLC can find. And they decide which intermediate states exist, and therefore which invariants hold. Too few labels, and the model hides races the code has. Too many, and you claim the code can be interrupted where it cannot, and chase bugs it does not have.

A recipe, for your own models. Start with one label per call to something shared: the database, a queue, another process's memory. If you cannot name the real operation a label stands for, it is probably in the wrong place. Let purely local computation join the step it belongs to. Then walk the labels one at a time and ask this lesson's question at each: what can the other process see here, and will it act on it? Where the answer is "a decision that is not recorded yet", you have a check-then-act race, and TLC will find it for you, provided your constants leave room for it.

Write something before openingan assistant hands you a PlusCal model of your service. Which question do you ask at each of its labels?

First, one that matters more when someone else placed the labels: which real call does this label stand for, and does the service make it in one atomic step? Then the recipe's question. A model with too few labels passes for a system you do not have, and nothing in TLC's output says so. The AI item, 07-ai1, is exactly that case.

04In your editor

The three versions are in chapters/07-pluscal/specs/. Check this lesson's exercises with:

shell
./tla check 07-04

The racy version, B:

Output 07-pluscal/specs/BoxOfficeCheckThenSell
07-pluscal/specs/BoxOfficeCheckThenSell  BoxOfficeCheckThenSell.cfg  (Sellers={s1, s2}, Seats=1)
PlusCal translated (translation up to date)
parse ok
model check: invariant NoOversell violated; trace has 5 states (4 steps); 10 distinct states
expected outcome met: violation NoOversell
trace (changed variables only; ./tla trace --full shows all):
  1  Init   pc = (s1 :> "Check" @@ s2 :> "Check"), sold = 0, printed = 0
  2  Check  pc: (s1 :> "Check" @@ s2 :> "Check") -> (s1 :> "Sell" @@ s2 :> "Check")
  3  Check  pc: (s1 :> "Sell" @@ s2 :> "Check") -> (s1 :> "Sell" @@ s2 :> "Sell")
  4  Sell   pc: (s1 :> "Sell" @@ s2 :> "Sell") -> (s1 :> "Done" @@ s2 :> "Sell"), sold: 0 -> 1, printed: 0 -> 1
  5  Sell   pc: (s1 :> "Done" @@ s2 :> "Sell") -> (s1 :> "Done" @@ s2 :> "Done"), sold: 1 -> 2, printed: 1 -> 2

After you move a label, rerun every invariant, not only the one you were thinking about: moving a label can break a claim about states that did not exist before.

05Practice

Warm-up. A parking office whose clerks check and issue a permit in one step. Add one label so that two clerks can both issue the last permit, and watch TLC find it.

Core. Two top-ups from a gift card race and lose money. The card service can subtract an amount in one call. Rewrite the steps so that there are exactly two, and none of them loses money.

07-04-ex1Warm-up5 min

07-04-ex1 · Break it with a label

Tier: warm-up. Time: about 5 minutes.

A parking office has one space left (Spaces = 1) and two clerks. In ParkingPermits.tla, a clerk checks the register, records the issue, and hands a permit over the counter, all in one step. TLC finds nothing wrong, and the model claims something the office's software does not do: there, the check and the record are separate.

Break it on purpose, as in 03-03: make TLC show you the double issue.

  1. Run ./tla check 07-04-ex1. It passes.
  2. Fill gap g1: add one label, named Issue, so that two clerks can both hand out a permit for the last space. Delete the \* GAP marker. Change nothing but labels.
  3. Run the check and read the trace: at which step did the second clerk decide, and what did it see?

Before you run it, predict where the label must go. There is a place for one more label that does not break anything; if you find it first, TLC will tell you.

Hints: HINTS.md, under "07-04-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/07-pluscal/exercises/04-ex1-break-it-with-a-label/; open it after you have a passing answer of your own.

Done when: ./tla check 07-04-ex1 prints "goal met: violation NoOverIssue".

./tla check 07-04-ex1

Repo chapters/07-pluscal/exercises/04-ex1-break-it-with-a-label/

Hints

Hint 1

Ask, for each place a label could go, what the other clerk can see while this clerk is between its two steps.

Hint 2

A race needs a decision that is not yet recorded. In Check, which line is the decision, and which line records it?

Hint 3 (nearly the answer)

Put Issue: in front of the assignment to issued, so that the if and the record are in different steps.

07-04-ex2Core8 min

07-04-ex2 · Two calls, no race

Tier: core. Time: about 8 minutes.

Two top-ups move money from a gift card to an app wallet at once. WalletTopUp.tla models each top-up in three steps: read the card balance, write it back minus the amount, credit the wallet. That loses money, the way the lesson's transfers did.

The card service has a call that subtracts an amount in one go; nobody needs to read the balance first. The wallet is a different service, so the credit stays a separate call.

  1. Run ./tla check 07-04-ex2. Two cfgs run: read the counterexample from WalletTopUp.cfg. WalletTopUp.twosteps.cfg is the course's check of the task's shape, and fails on the starter because a top-up still has a Read step.
  2. Fill gap g1: rewrite the debit so that a top-up takes exactly two steps, labelled Debit and Credit, and no money is made or lost. Delete the \* GAP markers. The Credit label below the gap stays as it is.
  3. Run the check again. Then answer in one sentence: what can the other top-up see between your Debit and Credit, and why does it not matter?

Both cfgs' @coverage lines name Debit and Credit, so both labels must exist and fire, and TwoSteps in the second cfg says they are the only two. Leave the cfgs and TwoSteps as they are.

Hints: HINTS.md, under "07-04-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/07-pluscal/exercises/04-ex2-two-calls-no-race/; open it after you have a passing answer of your own.

If TLC finds no violation but Debit or Credit never fires or the witness BothDone is not reached, ./tla prints "goal not met" and exits with code 1.

Done when: ./tla check 07-04-ex2 prints "2 of 2 checks met their expected outcome".

./tla check 07-04-ex2

Repo chapters/07-pluscal/exercises/04-ex2-two-calls-no-race/

Hints

Hint 1

In the counterexample, find the step where one top-up writes the card balance from a value the other top-up has since changed.

Hint 2

A race needs a value read in one step and used in a later one. The card service can do the read and the write in one call, so the model can too.

Hint 3 (nearly the answer)

Delete the Read line, and write the Debit step so that it computes the new card balance from card itself instead of from seen.

06Explain it

Open NOTES.md and answer the three prompts under 07-04, about the Core exercise.

output
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:

Compare your answers with "07-04 check your explanation" in HINTS.md.

After you writeCheck your explanation

A good answer: "A top-up now has two steps: Debit, which subtracts Amount from card in one step, and Credit. No step reads a value that another top-up can change before it is used, so nothing is lost, and MoneyConserved holds once both are done. Between the steps the money is in flight, which is why the invariant is stated only at the end. It relies on the card service's subtract being atomic. TLC checked two top-ups of 5 from a card of 20, and nothing about a credit that fails after the debit."

A weak answer: "I removed the read, so there is no race." It does not say why removing the read is allowed (the service subtracts in one call), and does not mention what happens between the two steps.

Done?