07-03

Chapter 07 · PlusCal: labels are atomicity

Processes, await, either, with

  • 45 min core
  • Core track
  • Skills: abstraction, counterexamples

00Recall

One card from 07-02 on what a step is in PlusCal, one from 07-01 on what Terminating changes, and one from chapter 02 on what \/ does inside an action. That last one is today's either, in different clothes.

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.

07-01-b from Read the translation first

Does the Terminating disjunct change which behaviors the spec allows?

Show answer

No. [Next]_vars already allows steps that change nothing. It changes only what TLC's deadlock check sees, and only in states where every process is done.

02-03-a from Or means "may"

What does \/ do inside an action?

Show answer

It lists the ways a step may go. A pair of states satisfies the action if it satisfies any disjunct, so when several are true the spec allows each, and TLC explores every one. Nothing is chosen.

Skip recall Recall is never required.

01Commit

specs/PetersonPlusCal.tla is Peterson's mutual exclusion, which you wrote by hand in chapter 06, now as two PlusCal processes, 0 and 1:

TLA+
process proc in {0, 1}
begin
  Want:  while TRUE do
           flag[self] := TRUE;
  Yield:   turn := 1 - self;
  Wait:    await flag[1 - self] = FALSE or turn = self;
  CS:      skip;
  Leave:   flag[self] := FALSE;
         end while;
end process;

await P is read "wait until P". With processes named 0 and 1, the expression 1 - self is the other process: it turns 0 into 1 and 1 into 0. Process 0 has reached Wait, and P is false: process 1 wants in, and the turn is 1's.

Commit a

Process 0 is at Wait and its await condition is false. What can process 0 do in the next step?

  1. It takes a Wait step that changes nothing and tries again: it spins.
  2. Nothing. Its Wait step is not enabled, so only process 1 can move.
  3. Nothing, and TLC reports a deadlock, because a process is blocked.

Answer Nothing. Its Wait step is not enabled, so only process 1 can move.

specs/Courier.tla has couriers who take any waiting parcel and then either deliver it or bring it back:

TLA+
  Take:    with p in waiting do
             parcel := p;
             waiting := waiting set minus {p};
           end with;
  Deliver: either
             delivered := delivered union {parcel};
           or
             returned := returned union {parcel};
           end either;
           parcel := NoParcel;

specs/CourierDeadBranch.tla has one bug: the or branch also says await parcel \in waiting, which is never true once the courier holds the parcel. Its cfg has \* @coverage: all.

Commit b

In CourierDeadBranch the second branch of Deliver can never run. Its cfg asks for full coverage. What does the coverage line say?

  1. A coverage gap: TLC sees that one branch of Deliver never runs.
  2. Every action fired.
  3. No coverage line: the run stops with a deadlock, because one branch of Deliver can never run.

Answer Every action fired.

02Lab

shell
./tla check chapters/07-pluscal/specs/PetersonPlusCal.cfg
./tla check chapters/07-pluscal/specs/CourierDeadBranch.cfg

For the first run, read the witness lines: they say which situations TLC actually reached. A witness reported as not reached means the model never got there, and ./tla does not count such a run as met. For the second, compare its distinct count with the working courier's in the reveal below. Then open the raw log, the file named on the second run's raw log: line, and search for CourierDeadBranch: 0. Each line you find is an expression of the translation that TLC never evaluated: look its line number up in CourierDeadBranch.tla.

Expected output 07-pluscal/specs/PetersonPlusCal
07-pluscal/specs/PetersonPlusCal  PetersonPlusCal.cfg
PlusCal translated (translation up to date)
parse ok
model check: no violation found in 26 distinct states (45 generated, depth 8)
expected outcome met: pass
coverage: all 5 actions fired
witness ZeroInCS reached (trace of 4 states)
witness OneInCS reached (trace of 4 states)
witness BothWaiting reached (trace of 5 states)
Expected output 07-pluscal/specs/CourierDeadBranch
07-pluscal/specs/CourierDeadBranch  CourierDeadBranch.cfg  (Couriers={c1, c2}, Parcels={p1, p2}, NoParcel=NoParcel)
PlusCal translated (translation up to date)
parse ok
model check: no violation found in 16 distinct states (26 generated, depth 5)
expected outcome met: pass
coverage: all 3 actions fired
witness SomeDelivered reached (trace of 3 states)

Reveal for commit a

Process 0 can do nothing; process 1 moves. TLC finds no violation of MutualExclusion in 26 distinct states, and the witness BothWaiting is reached: both processes at Wait at once, and neither deadlocks, because exactly one of them has its condition true.

Reveal for commit b

coverage: all 3 actions fired, and a pass. The run is smaller than the working courier's (16 distinct states against 27), and the terminal output does not say why. The raw log does, in small print: the lines that end in : 0 are the second branch of Deliver, the update to returned among them. Nothing turns that 0 into a failure.

03Reason

If you picked "it spins", you were picturing the code: while (!condition) {}. The model is not the code. Read the translation of Wait:

TLA+
Wait(self) is defined as and pc[self] = "Wait"
              and flag[1 - self] = FALSE or turn = self
              and pcprime = [pc EXCEPT ![self] = "CS"]
              and UNCHANGED tuple of flag, turn end tuple

The await is a guard, one more conjunct. When it is false, the whole action is false, and no Wait step exists for that process. A busy loop would add steps that change nothing; the model leaves them out, and TLC still explores everything the other process does in the meantime.

Look at the step right after it, too. CS: skip; becomes an action whose only change is pc. The critical section is not an action that does something; it is a place a process can be. MutualExclusion says that no two processes are at that place in the same state. CS gets a label of its own so that being inside has its own pc value for the property to name; without it, a process that had passed Wait would be at "Leave", and the property would have to say that instead.

Write something before openingPeterson writes flag[self] and then turn, in two labelled steps. Why would merging them under one label make the check weaker, not stronger?

One label is one atomic step. A real processor does two separate writes, and the other process can run between them. Merging the two removes exactly the interleavings between the writes. For an invariant such as MutualExclusion, a pass on the merged model then covers fewer runs than the hardware has. (For deadlock the direction can flip: an await merged into one label with the writes before it holds those writes back too, as in 07-01's Core exercise.) The labels give TLC the hard case, the writes split, and in that case it finds no violation of MutualExclusion.

Every PlusCal construct translates into something you already know:

PlusCalTranslationRead it as
process p \in Sone copy per element of S, named by self\E self \in S : p(self) in Next
process p = "name"a single process with that namep in Next
await Pa conjunct P, evaluated after any earlier assignments in the same label, so it may mention primed valuesthe step is possible only when P holds
either A or B end either\/ between the branches, inside one actionthe step may do A or B
with x \in S do ... end with\E x \in S : around the bodythe step picks any x in S

The two forms of process differ only in how many copies there are. process transfer \in Transfers makes one copy per element and gives each its name as self. process producer = "producer" makes exactly one, whose name is the string, so its entry in pc is pc["producer"], and its local variables stay plain variables, with no index, because there is only one copy. You will meet both in 07-05.

Here are Take and Deliver, translated:

TLA+
Take(self) is defined as and pc[self] = "Take"
              and there exists p in waiting:
                   and parcelprime = [parcel EXCEPT ![self] = p]
                   and waitingprime = waiting set minus {p}
              and pcprime = [pc EXCEPT ![self] = "Deliver"]
              and UNCHANGED tuple of delivered, returned end tuple

with is "there exists": TLC tries every waiting parcel, one successor state each. When waiting is empty there is no p, and the step is not enabled, exactly like a false await.

either and with both make one label produce several successors, and they differ in what is chosen. with chooses a value, from a set the current state defines. either chooses a branch, from a list you wrote down. Neither chooses at random, and neither picks the likely option: TLC follows every choice, as it followed every order of steps in the previous lesson.

Now read Deliver in the broken courier. Its second branch translates to parcel[self] \in waiting followed by the update to returned, all inside one \/ of the action. That conjunct is false in every state where a courier holds a parcel, so the second disjunct is false. The first disjunct is still true. The action as a whole stays enabled, and fires on every delivery. An await inside a branch switches off that branch, not the label.

Write something before openingDeliver contains an either. How many actions does TLC's coverage report count for Deliver, one or two?

One. The translation of Deliver is a single operator whose body contains \/ ... \/ ... for the two branches, followed by the assignment both branches share. ./tla's coverage line reports per operator. So it said "fired" as soon as one delivery succeeded, and the dead branch hid inside a green line; only the raw log's per-expression counts show its zeros.

So how do you catch a dead branch? With the witness rule from 03-03: claim the thing you expect to happen never happens, and demand that TLC refute you. NeverReturned claims that no parcel ever comes back.

shell
./tla check chapters/07-pluscal/specs/Courier.returned.cfg
./tla check chapters/07-pluscal/specs/CourierDeadBranch.returned.cfg

On the working courier, TLC refutes it with a trace of 3 states, and the last step is the or branch. On the broken one, TLC finds no violation: the claim survives, and that pass is the bug report. In a cfg's header, the same predicate is \* @witness: SomeReturned, and ./tla runs that check for you on every pass.

04In your editor

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

shell
./tla check 07-03

The working courier, with both witnesses reached:

Output 07-pluscal/specs/Courier
07-pluscal/specs/Courier  Courier.cfg  (Couriers={c1, c2}, Parcels={p1, p2}, NoParcel=NoParcel)
PlusCal translated (translation up to date)
parse ok
model check: no violation found in 27 distinct states (53 generated, depth 5)
expected outcome met: pass
coverage: all 3 actions fired
witness SomeDelivered reached (trace of 3 states)
witness SomeReturned reached (trace of 3 states)

Read every await you write as a question: which process makes this true, and in which step? If you cannot name one, you have found a deadlock, or a dead branch, before TLC has. When you add an either or a with to a model, add a witness for each branch you care about in the same edit. Coverage will not notice a branch that never runs; only a witness that needs that branch will.

05Practice

Warm-up. Two packers share a label printer. Write the await that makes them take turns.

Core. Restaurant hosts seat parties at any table, even a taken one. Change the with so that a host picks only among free tables.

07-03-ex1Warm-up5 min

07-03-ex1 · Wait for the printer

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

Two warehouse packers share one label printer. A packer claims it by writing its own name into holder, prints, and releases it. In LabelPrinter.tla, the claim waits for nothing: its await says TRUE.

  1. Run ./tla check 07-03-ex1 and read the trace: how do both packers end up printing?
  2. Fill gap g1: replace the TRUE so that a packer may claim the printer only while nobody holds it. Delete the \* GAP marker.
  3. Run the check again. Then read the translation of Claim: where did your condition go?

Before you run it: once one packer holds the printer, what can the other packer do?

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

If TLC finds no violation but an action never fires or the witness BothFinished is not reached, ./tla prints "goal not met" and exits with code 1. A condition that is never true makes the packers wait for ever, and TLC reports a deadlock.

Done when: ./tla check 07-03-ex1 prints "goal met: pass".

./tla check 07-03-ex1

Repo chapters/07-pluscal/exercises/03-ex1-wait-for-the-printer/

Hints

Hint 1

In the trace, look at holder in the state right before the second Claim. What should the second packer have done there?

Hint 2

await P turns into a conjunct P of the label's action. A packer at a false await takes no step at all.

Hint 3 (nearly the answer)

Replace the TRUE with a comparison of holder and one of the module's constants.

07-03-ex2Core8 min

07-03-ex2 · Any free table

Tier: core. Time: about 8 minutes.

Restaurant hosts seat arriving parties. In HostStand.tla, a host picks a table with with t \in Tables: any table, including one where a party already sits. The second party then replaces the first in the table plan.

  1. Run ./tla check 07-03-ex2 and read the trace. Which invariant fails, and in what state?
  2. Fill gap g1: change the with so that a host chooses only among tables where nobody sits. Keep the label Seat and the assignment below the gap. Delete the \* GAP marker.
  3. Run the check again. Then read the translation of Seat. What does with become, and what happens to a host if the set it chooses from is empty?

There is more than one correct answer: a smaller set to choose from, or an await inside the with. Try to say why both work.

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

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

Done when: ./tla check 07-03-ex2 prints "goal met: pass".

./tla check 07-03-ex2

Repo chapters/07-pluscal/exercises/03-ex2-any-free-table/

Hints

Hint 1

Read the trace's last step: which table did the second host choose, and who was sitting there?

Hint 2

with t \in S becomes "there exists t in S". If S holds only the tables you are willing to use, TLC never tries the others.

Hint 3 (nearly the answer)

Replace Tables in the with by a set comprehension {x \in Tables : ...} that keeps the tables where seated says nobody sits.

06Explain it

Open NOTES.md and answer the three prompts under 07-03, 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-03 check your explanation" in HINTS.md.

After you writeCheck your explanation

A good answer: "The host now chooses only among free tables, with t \in {x \in Tables : seated[x] = Nobody}, which translates to 'there exists a free table'. If no table is free the step is not enabled, and the host waits. It relies on the choice and the seating being one step; if hosts looked at the plan and sat down in two steps, two could pick the same table. TLC checked two hosts and two tables, and coverage only says the Seat label ran, which is why the witness AllTablesTaken matters."

A weak answer: "I filtered the tables so hosts cannot double-book." It says what was typed, not why one step is enough, and nothing about what the model leaves out.

Done?