07-05

Chapter 07 · PlusCal: labels are atomicity

Producer and consumer

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

00Recall

One card from 07-04 on when a label creates a race, one from 07-03 on what coverage cannot see, and one from chapter 00 on the lost update you met first. The buffer below has no lost updates. It has a different way to go wrong.

07-04-a from Move a label, change the bugs

Two processes, and one more label in each. When does that label create a race?

Show answer

When the other process can see, between the two steps, a value that it then acts on, such as a check whose result is not yet recorded. A label after the decision is recorded only delays the rest.

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

A branch of an either can never run, and coverage says every action fired. Why, and what catches it?

Show answer

./tla's coverage line counts actions, and the whole either is inside one label's action. A witness that needs the branch catches it: ./tla reports the witness NOT reached.

00-01-a from Predict the balance

In transfer(), what must happen for the final balance to be wrong?

Show answer

Both transfers read the balance before either one writes it back. Then both compute from the same old value, and the second write erases the first.

Skip recall Recall is never required.

01Commit

specs/BoundedBuffer.tla is a bounded buffer: a producer hands items to a consumer through a buffer with Capacity = 2 slots. The producer makes Items = 3 numbered items; the consumer takes them in order and records them in out.

TLA+
process producer = "producer"
variables next = 1;
begin
  Put:  while next less than or equal to Items do
          await Len(buf) < Capacity;
          buf := Append(buf, next);
          next := next + 1;
        end while;
end process;

Picture the pass-through window between a kitchen and a dining room, with room for two plates. The cook puts a plate in only when there is a free spot; the waiter takes one only when there is a plate to take. Nobody hands a plate across directly, and nobody needs to know how fast the other is.

The consumer mirrors the producer: await Len(buf) > 0, then move the head of buf to the end of out. It passes Bounded (never more than Capacity items in the buffer) and InOrder (out is 1, 2, 3, ... with nothing skipped or doubled).

A real consumer is a service that runs forever. specs/BoundedBufferForever.tla says so: its consumer loops while TRUE instead of stopping after Items items. Nothing else changes, and deadlock checking stays on.

Commit a

The consumer now loops forever; the producer still stops after Items items. What does TLC report for BoundedBufferForever?

  1. No violation: PlusCal's Terminating step covers the end.
  2. A deadlock, once every item has been consumed.
  3. An error: once the buffer is empty, the looping consumer evaluates the head of an empty sequence.

Answer A deadlock, once every item has been consumed.

specs/BoundedBufferNoWait.tla goes the other way: the consumer keeps its loop but loses its await. It takes Head(buf) whether or not there is one.

Commit b

The consumer's await Len(buf) > 0 is deleted. What does TLC report?

  1. A violation of InOrder: the consumer records a garbage item.
  2. An error: TLC cannot compute the head of an empty buffer.
  3. A deadlock: with nothing in the buffer, the consumer's step cannot happen.

Answer An error: TLC cannot compute the head of an empty buffer.

02Lab

shell
./tla check chapters/07-pluscal/specs/BoundedBuffer.cfg
./tla check chapters/07-pluscal/specs/BoundedBufferForever.cfg
./tla check chapters/07-pluscal/specs/BoundedBufferNoWait.cfg
Expected output 07-pluscal/specs/BoundedBufferForever
07-pluscal/specs/BoundedBufferForever  BoundedBufferForever.cfg  (Capacity=2, Items=3)
PlusCal translated (translation up to date)
parse ok
model check: deadlock reached; trace has 8 states (7 steps); 12 distinct states
expected outcome met: deadlock
trace (changed variables only; ./tla trace --full shows all):
  1  Init  pc = [producer |-> "Put", consumer |-> "Take"], buf = <<>>, out = <<>>, next = 1
  2  Put   buf: <<>> -> <<1>>, next: 1 -> 2
  3  Put   buf: <<1>> -> <<1, 2>>, next: 2 -> 3
  4  Take  buf: <<1, 2>> -> <<2>>, out: <<>> -> <<1>>
  5  Put   buf: <<2>> -> <<2, 3>>, next: 3 -> 4
  6  Put   pc: [producer |-> "Put", consumer |-> "Take"] -> [producer |-> "Done", consumer |-> "Take"]
  7  Take  buf: <<2, 3>> -> <<3>>, out: <<1>> -> <<1, 2>>
  8  Take  buf: <<3>> -> <<>>, out: <<1, 2>> -> <<1, 2, 3>>
Expected output 07-pluscal/specs/BoundedBufferNoWait
07-pluscal/specs/BoundedBufferNoWait  BoundedBufferNoWait.cfg  (Capacity=2, Items=3)
PlusCal translated (translation up to date)
parse ok
model check: TLC error: Attempted to apply Head to the empty sequence.
  chapters/07-pluscal/specs/BoundedBufferNoWait.tla:62:9: Attempted to apply Head to the empty sequence.
expected outcome met: error Head to the empty sequence
trace (changed variables only; ./tla trace --full shows all):
  1  Init  out = <<>>, next = 1, buf = <<>>, pc = [producer |-> "Put", consumer |-> "Take"]

Reveal for commit a

A deadlock, after a trace of 8 states. The last state is the same in every such trace: the producer is done, all items are in out, the buffer is empty, and the consumer waits at an await that can never become true.

Reveal for commit b

An error, in the initial state: "Attempted to apply Head to the empty sequence." TLC stops while it is computing the initial state's successors, and prints that state.

03Reason

If you picked "no violation", you expected Terminating to cover the end. It cannot. Read the last lines of the translation of BoundedBufferForever:

TLA+
consumer is defined as Take

Next is defined as producer or consumer

No Terminating. Terminating is one disjunct for the whole algorithm, not one per process. The translator leaves it out when a process's whole body is a while TRUE loop, as the consumer's is: that process can never be "Done". Even if it were there, it would be enabled only when every pc is "Done". So the end of this model is a state where no process has an enabled step and not everyone has finished: a deadlock, honestly reported.

Is it a bug? In the system, a consumer idling on an empty queue after the last item is fine. In the model, it is a sign that the model's story ends before the system's does. You have three honest options, and one dishonest one:

  • make the consumer stop after the last item, as BoundedBuffer does (while Len(out) < Items);
  • let the producer run forever too, and bound the model another way;
  • turn deadlock checking off, with a comment that names the one stuck state you expect;
  • turn it off with a comment that explains the stuck state away, as the teammates in the 03 and 06 reviews did.

The first option is usually the best one for a model. It makes the end of the story explicit, keeps the deadlock check fully armed, and costs one loop condition. The third is honest but blunt: from then on TLC is silent about every stuck state, including a consumer stuck with items still in the buffer, which is the stuck state you would most want to hear about. The Core exercise asks you to choose.

Write something before openingBoundedBuffer passes with deadlock checking on. Where does its run end, and why is that not a deadlock?

Both processes leave their loops: the producer after the last Put, the consumer after out holds every item. Both pcs become "Done", Terminating is enabled, and the final state has a successor: itself. Every action fired, including Terminating, and both witnesses were reached: BufferFull and AllDelivered.

Now the missing await. Here is the consumer's step in BoundedBuffer:

TLA+
Take is defined as and pc["consumer"] = "Take"
        and IF Len(out) < Items
              THEN and Len(buf) > 0
                   and outprime = Append(out, Head(buf))
                   and bufprime = Tail(buf)
                   and pcprime = [pc EXCEPT !["consumer"] = "Take"]
              ELSE and pcprime = [pc EXCEPT !["consumer"] = "Done"]
                   and UNCHANGED tuple of buf, out end tuple
        and nextprime = next

The conjunct Len(buf) > 0 is the await. TLC evaluates conjuncts in order, so it reaches Head(buf) only when the buffer has something in it. Delete the await and nothing protects Head: TLC evaluates it in the very first state, where buf is empty, and stops.

The two awaits are the whole protocol. The producer's says "only into a slot that is free", and Bounded checks it. Delete the producer's await and you get the opposite failure to the one above: the step stays enabled and runs, and nothing stops an item from going into a full buffer. The Warm-up is exactly that mistake in a bakery: its starter's oven has await TRUE, and TLC reports FitsOnTray violated. The consumer's says "only from a buffer that has something", and without it TLC stops with an error at the first state. InOrder checks what is left: that the items come out as they went in, with none skipped, doubled or reordered. A lost last item leaves no gap for InOrder to see; it shows up as the consumer's deadlock, or as AllDelivered not reached.

Write something before openingis first-in, first-out order something the model enforces or something it checks?

Both, in different places. The model enforces it by construction: the producer uses Append, which adds at the end, and the consumer uses Head and Tail, which take from the front. InOrder checks the result from the outside, end to end. If a teammate later replaced the sequence with a set to "simplify" the model, the construction would no longer promise anything, and InOrder is the line that would notice. A property that restates the code catches nothing; one that states what the user sees catches changes to the code.

The gate builds on this pattern: a job pool is a bounded buffer with two consumers, and a pass needs every one of the checks above.

04In your editor

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

shell
./tla check 07-05

The working buffer, with every action and both witnesses:

Output 07-pluscal/specs/BoundedBuffer
07-pluscal/specs/BoundedBuffer  BoundedBuffer.cfg  (Capacity=2, Items=3)
PlusCal translated (translation up to date)
parse ok
model check: no violation found in 14 distinct states (20 generated, depth 9)
expected outcome met: pass
coverage: all 3 actions fired
witness BufferFull reached (trace of 3 states)
witness AllDelivered reached (trace of 7 states)

When TLC reports a deadlock in a PlusCal model, look at the pc of every process in the last state. A trace prints pc as a function, such as [producer |-> "Put", consumer |-> "Take"], one entry per process. Whoever is not "Done" is waiting for something: find its label in the algorithm and read its await or with. That condition, false forever, is the story of the deadlock.

05Practice

Warm-up. An oven and a cooling tray. Write the oven's await so that it never puts a loaf on a full tray.

Core. A coffee bar's runner serves forever, and TLC reports a deadlock at the end of the rush. Make the runner stop when the rush is over, without hiding real deadlocks.

Stretch. Readers and writers, from a skeleton: both processes, the exclusion property and the whole cfg.

07-05-ex1Warm-up5 min

07-05-ex1 · Wait for room

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

An oven bakes Loaves = 3 numbered loaves onto a cooling tray with Slots = 2 places, and a shop assistant sells them, oldest first. In BakeryTray.tla, the oven's await says TRUE.

  1. Run ./tla check 07-05-ex1 and read the trace: how many loaves are on the tray in its last state?
  2. Fill gap g1: the oven may put a loaf on the tray only while the tray has a free place. Delete the \* GAP marker.
  3. Run the check again.

The witness TrayFull must be reached: a condition that keeps the tray from ever filling up is too strict, and ./tla says so.

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

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

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

./tla check 07-05-ex1

Repo chapters/07-pluscal/exercises/05-ex1-wait-for-room/

Hints

Hint 1

Read FitsOnTray. The oven's await has to make that true after every Bake step.

Hint 2

The oven adds one loaf per step. Before the step, how many loaves can the tray hold at most, so that it still fits after?

Hint 3 (nearly the answer)

Compare Len(tray) with Slots, strictly. The shop assistant's await, in the assistant process of the same file, has the same shape.

07-05-ex2Core8 min

07-05-ex2 · Know when to stop

Tier: core. Time: about 8 minutes.

A barista puts the Orders = 3 cups of one rush on the pass, a counter with room for Room = 2, and a runner takes them to the tables. In CoffeePass.tla, the runner loops while TRUE, like a real service. TLC reports a deadlock at the end of the rush.

  1. Run ./tla check 07-05-ex2. Read the last state of the trace: where is each process, and what is the runner waiting for?
  2. Fill gap g1: make the runner stop once every order of the rush has been served. Keep deadlock checking on and leave the cfg as it is. Delete the \* GAP marker.
  3. Run the check again. Then look at the end of the translation: what is there now that was not there before, and why?

The cfg asks for the witness RushOver: a state in which both processes are "Done". A fix that keeps the runner looping, for example by giving it a step that does nothing while the pass is empty, ends the deadlock report but never lets the runner finish, so ./tla reports RushOver not reached. Coverage alone would not catch it: while the runner's body is a while TRUE loop, the translator writes no Terminating for coverage to miss.

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

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

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

./tla check 07-05-ex2

Repo chapters/07-pluscal/exercises/05-ex2-know-when-to-stop/

Hints

Hint 1

In the last state of the trace, the barista is done and the pass is empty. What is the runner waiting for, and will it ever come?

Hint 2

Terminating is one disjunct for the whole algorithm, possible only when every process is "Done". A process whose whole body is a while TRUE loop is never "Done", and the translator leaves Terminating out.

Hint 3 (nearly the answer)

Replace TRUE in the while with a condition that is true until served holds every order of the rush. The shop assistant process in 05-ex1 (assistant, in BakeryTray.tla) stops the same way.

07-05-ex3Stretch30 min · mastery path

07-05-ex3 · Readers and writers

Tier: stretch. Time: about 30 minutes. Off the core clock: this is on the mastery path.

A shared document. Any number of readers may be inside at once. A writer needs the document to itself: no reader inside, and no other writer. Each reader and each writer goes in once, does its work, and comes out. You do not have to be fair to writers.

The skeleton ReadersWriters.tla gives you the two global variables, reading and writing (the sets of readers and writers inside now), TypeOK, and the witnesses TwoReading and SomeoneWriting. Everything else is yours.

  1. Run ./tla check 07-05-ex3. TLC stops before it computes a state: your cfg has to give the constants first.
  2. Fill gap g1 of ReadersWriters.tla: Exclusive, in the define block, over reading and writing.
  3. Fill gap g2: the reader and writer processes. Choose the labels yourself; they must be unique across the whole algorithm. Think about where each label goes before you write it: what must a writer check, and in the same step as what?
  4. Fill gap g1 of ReadersWriters.cfg: the whole cfg. Two readers and two writers, as model values, are enough. Name TypeOK and Exclusive as invariants.
  5. Run the check. Then break your own spec once on purpose: move one label so that a writer checks in one step and enters in the next, and read TLC's trace. Move it back.

ReadersWritersProps.tla is the course's check of your Exclusive: it asks your definition about five sample situations (a reader with a writer, two writers, all readers, one writer, nobody) by putting chosen values in place of the variables. An Exclusive that is TRUE everywhere, or that forbids two readers, fails there. Its cfg also checks TypeOK and your Exclusive on your algorithm. Leave that file and its cfg as they are.

Hints: HINTS.md, under "07-05-ex3 hint 1" to "hint 3". The solution is in solutions/chapters/07-pluscal/exercises/05-ex3-readers-and-writers/; open it after you have a passing answer of your own.

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

./tla check 07-05-ex3

Repo chapters/07-pluscal/exercises/05-ex3-readers-and-writers/

Hints

Hint 1

Start with the cfg: SPECIFICATION, the two constants as sets of model values, and the two invariants. Run it with Exclusive still TRUE and the processes still skip, so that you know the cfg works before you write anything else.

Hint 2

Exclusive is an implication: if somebody is writing, then two things hold. A writer must check for readers and writers in the same step as it adds itself to writing, and a reader must check for writers in the same step as it adds itself to reading.

Hint 3 (nearly the answer)

Each process needs two labels: one that awaits its condition and adds self to its set, and one that removes self again. Name them so that no label repeats across the two processes. Exclusive uses writing # {}, reading = {} and Cardinality(writing).

07-mxMixed15 min · mastery path

07-mx · Type the translation

Tier: mixed. Time: about 15 minutes. Off the core clock: this is on the mastery path.

A car-rental desk keeps keys in a cabinet; two clerks each hand a key out and put it back. KeyCabinet.tla is complete and passes. Its author never wrote a TypeOK.

  1. Run ./tla check 07-mx. Five cfgs run. KeyCabinet.cfg checks the desk itself. The four MCKeyCabinet cfgs check your TypeOK, which so far is TRUE: TLC warns that it mentions no variables.
  2. Read the translation in KeyCabinet.tla. List every variable it declares, including the ones the translator added, and say what kind of value each one holds: a set, a function from what to what, a string from which list?
  3. Fill gap g1 in MCKeyCabinet.tla: TypeOK, one conjunct per variable. Delete the \* GAP marker.
  4. Run the check again.

The same file defines three sloppy versions of the desk, which the course uses to test your TypeOK: one writes the string "none" for an empty hand instead of the model value NoKey, one jumps to a label "done" that does not exist, and one puts an empty hand back into the cabinet. Each bug shows up in a different variable. Your TypeOK must hold on the real desk and be violated on all three sloppy ones. Without it, the label bug only shows up later, as a deadlock. Leave everything below the gap as it is.

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

All five cfgs must meet their goals: "goal met: pass" for MCKeyCabinet.cfg (and KeyCabinet.cfg stays as it was), and "goal met: violation TypeOK" for MCKeyCabinet.nonestring.cfg, MCKeyCabinet.lowercase.cfg and MCKeyCabinet.emptyhand.cfg.

Done when: ./tla check 07-mx prints "5 of 5 checks met their expected outcome".

./tla check 07-mx

Repo chapters/07-pluscal/exercises/mx-type-the-translation/

Hints

Hint 1

Start from the translation, not the algorithm. The VARIABLES line lists every variable, including pc.

Hint 2

A local variable of a process set (process p \in S) becomes a function from the processes to values. pc is a function too, and its values are label names, plus one label nobody wrote.

Hint 3 (nearly the answer)

Write three conjuncts. cabinet is a subset of Keys. key and pc are functions from Clerks: write each set of possible values out, with NoKey for an empty hand and the three label strings for pc.

06Explain it

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

After you writeCheck your explanation

A good answer: "The runner now loops while Len(served) < Orders, so once every order is served it finishes, the translator writes Terminating, and TLC finds no deadlock with deadlock checking on. A runner stuck with cups on the pass, or a barista stuck at a full pass, would not be "Done", so those deadlocks would still be reported. It relies on the runner knowing how many orders the rush has. TLC checked one rush of three orders and a pass of two cups, and nothing about the runner eventually serving every cup, which needs fairness."

A weak answer: "I turned deadlock checking off because the runner is supposed to run forever." That hides every deadlock, including the real ones, and the exercise said to leave the cfg alone.

Done?