06-02

Chapter 06 · Concurrency is interleaving

Program counters by hand

  • 44 min core
  • Essentials track
  • Skills: abstraction, counterexamples

00Recall

Two cards from 06-01, on why a check is a fact about the past and on what \E c says about who runs next, and one from chapter 00 on states versus interleavings.

06-01-a from Productive failure

Why is "the if checks for a free seat before booking" not an argument that check-then-act code is safe?

Show answer

The check is true when it runs. Another process can change the data before the act, so the act relies on a fact that may be stale.

06-01-b from Productive failure

In a spec, what does Next == \E c \in Clients : Check(c) \/ Book(c) say about who runs next?

Show answer

Nothing fixed: every step is a step of some client, any client. So the behaviors include every interleaving of the clients' steps, and TLC visits every state any of them reaches.

00-02-a from Every interleaving

What is the difference between a state and an interleaving?

Show answer

A state is a snapshot of every variable's value. An interleaving is one order of all the steps of a run; running it passes through a sequence of states. Many interleavings can pass through the same state.

Skip recall Recall is never required.

01Commit

Meet TaskBoard, the system that comes back in chapters 08, 10, 11, 12 and 16. A team keeps a shared board of tasks. Workers take tasks from it with this loop:

output
def worker(me):
    while True:
        free = [t for t in TASKS if board[t] is None]   # pick: read the board
        if not free:
            return                                      # nothing left: go home
        t = choose(free)
        board[t] = me                                   # claim: write my name
        work(t)                                         # work, then come back

Two workers run it at once, on two operating-system threads, on a board with two tasks.

Commit a

While worker w1 runs this loop, where can worker w2 take a step?

  1. Only between iterations of w1's loop, when w1 is back at the top.
  2. Between any two of w1's steps, including between w1's pick and w1's claim.
  3. Only while w1 is blocked on something slow, such as the work itself.

Answer Between any two of w1's steps, including between w1's pick and w1's claim.

specs/TaskBoard.tla models the loop with three variables: owner, the board; mine, the task each worker picked; and pc, each worker's next line. The cfg checks ClaimsHold: a worker busy with a task is the one whose name is on it.

Commit b

A teammate says only owner is real state; mine and pc are bookkeeping and could be deleted. What could the spec then no longer express?

  1. Nothing that matters: TLC would find the same double claim from owner alone.
  2. A worker that has picked a task but not yet claimed it, and which task it picked.
  3. Which worker is running at this moment.

Answer A worker that has picked a task but not yet claimed it, and which task it picked.

02Lab

Run the board with ClaimsHold:

shell
./tla check chapters/06-concurrency-is-interleaving/specs/TaskBoard.cfg

Read the trace before you open the reveals. Find the first state from which the double claim can no longer be avoided. Is the board already wrong in that state?

Expected output 06-concurrency-is-interleaving/specs/TaskBoard
06-concurrency-is-interleaving/specs/TaskBoard  TaskBoard.cfg  (Workers={w1, w2}, Tasks={t1, t2}, None=None)
parse ok
model check: invariant ClaimsHold violated; trace has 5 states (4 steps); 30 distinct states
expected outcome met: violation ClaimsHold
trace (changed variables only; ./tla trace --full shows all):
  1  Init   owner = (t1 :> None @@ t2 :> None), mine = (w1 :> None @@ w2 :> None), pc = (w1 :> "pick" @@ w2 :> "pick")
  2  Pick   mine: (w1 :> None @@ w2 :> None) -> (w1 :> t1 @@ w2 :> None), pc: (w1 :> "pick" @@ w2 :> "pick") -> (w1 :> "claim" @@ w2 :> "pick")
  3  Pick   mine: (w1 :> t1 @@ w2 :> None) -> (w1 :> t1 @@ w2 :> t1), pc: (w1 :> "claim" @@ w2 :> "pick") -> (w1 :> "claim" @@ w2 :> "claim")
  4  Claim  owner: (t1 :> None @@ t2 :> None) -> (t1 :> w1 @@ t2 :> None), pc: (w1 :> "claim" @@ w2 :> "claim") -> (w1 :> "work" @@ w2 :> "claim")
  5  Claim  owner: (t1 :> w1 @@ t2 :> None) -> (t1 :> w2 @@ t2 :> None), pc: (w1 :> "work" @@ w2 :> "claim") -> (w1 :> "work" @@ w2 :> "work")

Reveal for commit a

Between any two. In TLC's trace, both workers pick the same task before either one claims it: the second pick falls between the first worker's pick and its claim. Then both claim, and the second name overwrites the first. ClaimsHold breaks after 5 states.

Reveal for commit b

The third state of the trace is the one to look at. owner is still empty on both tasks, exactly as in the initial state. What has changed is pc, both workers at "claim", and mine, both holding the same task. Delete those two variables and TLC cannot tell this state from the start, so it cannot represent the double claim that is about to happen.

03Reason

If you picked "only owner is real", you were thinking of the state as the data a program stores. A state in a spec is more than that. It is everything that decides what can happen next. Chapter 01 called a state a snapshot of every variable, with nothing special about a program counter. This lesson cashes that in.

Here is the trace again:

  1. State 1 Initial state owner = (t1 :> None @@ t2 :> None) mine = (w1 :> None @@ w2 :> None) pc = (w1 :> "pick" @@ w2 :> "pick")
  2. State 2 Pick mine (w1 :> None @@ w2 :> None) becomes (w1 :> t1 @@ w2 :> None) pc (w1 :> "pick" @@ w2 :> "pick") becomes (w1 :> "claim" @@ w2 :> "pick")
  3. State 3 Pick mine (w1 :> t1 @@ w2 :> None) becomes (w1 :> t1 @@ w2 :> t1) pc (w1 :> "claim" @@ w2 :> "pick") becomes (w1 :> "claim" @@ w2 :> "claim")
  4. State 4 Claim owner (t1 :> None @@ t2 :> None) becomes (t1 :> w1 @@ t2 :> None) pc (w1 :> "claim" @@ w2 :> "claim") becomes (w1 :> "work" @@ w2 :> "claim")
  5. State 5 Claim owner (t1 :> w1 @@ t2 :> None) becomes (t1 :> w2 @@ t2 :> None) pc (w1 :> "work" @@ w2 :> "claim") becomes (w1 :> "work" @@ w2 :> "work")

The board changes only at the claims. Everything before them happens in mine and pc, the variables the teammate wanted to delete. That is where concurrency bugs live: in what a process remembers between two of its steps.

Follow one worker's column down the trace and its story is sensible: it looked, saw a free task, wrote its name, started work. Follow the other worker's column and its story is just as sensible. Neither worker did anything wrong by its own lights. The bug exists only in the merge of the two stories, which is why reading one function at a time, as code review usually does, misses it.

Turning code into a spec like this is a recipe, and you can follow it by hand.

  1. List the shared variables. Here, the board: owner.
  2. Cut the code into steps. A step is something that happens indivisibly. Put a cut wherever another process could act, at the least before every read or write of shared data. pick reads the board; claim writes it; work is done by the worker alone.
  3. Name each cut. Those names are the labels: "pick", "claim", "work", plus "done" for a worker that went home.
  4. Give every process a program counter. pc is a function from workers to labels.
  5. Keep local variables that live across a cut. t is chosen at pick and used at claim, so it must be in the state: mine[w].
  6. Write one action per step. Each is guarded by pc[w] and moves pc[w] on:
TLA+chapters/06-concurrency-is-interleaving/specs/TaskBoard.tla
Claim(w) is defined as
    and pc[w] = "claim"
    and ownerprime = [owner EXCEPT ![mine[w]] = w]
    and pcprime = [pc EXCEPT ![w] = "work"]
    and UNCHANGED mine

[owner EXCEPT ![mine[w]] = w] is read "owner, except that task mine[w] now maps to w". Notice that Claim never looks at the board before writing. It writes whatever Pick told it, however long ago.

  1. Join the actions with \E. Next is "some worker takes one of its steps".

One line of the Python has no counterpart yet: t = choose(free). The code picks some free task by a rule you may not know, or that may change next release. The spec does not guess the rule. It lets the worker pick any free task, and TLC follows every choice. That is nondeterminism used on purpose: when you do not know what the code will choose, the model allows all of it. You will write that pick yourself in the Warm-up.

Write something before openingrun the recipe on 06-01's SeatReserve. The check's result crosses a cut, yet SeatReserve has no local variable for it. Where did it go?

Into the program counter. A client that saw a free seat moves to "book"; one that saw a full flight moves to "done". The label it lands on is the remembered answer. When a local value has only a few possible outcomes and each leads to different code, the pc can carry it. When the value is data that a later step uses, like the task t that the claim writes, it needs its own variable.

Write something before openingpick has two outcomes, a task or nothing. Why are they two actions, Pick and GiveUp, with the same label?

Because they are two different steps from the same place in the code. Both start at "pick"; one leads to "claim", the other to "done". Giving each outcome its own named action lets coverage tell you whether both really happen, and lets the trace say which one did.

Write something before openingthe recipe put the whole board scan into one step. Is that honest?

It is a choice, and it is generous to the code. A real scan reads one task at a time, so another worker could write between two reads. Treating the scan as one step allows fewer interleavings than the code has. Here the coarse model still finds the bug, and that is good news: if fewer interleavings already break the claim, more will too. A pass on a coarse model would say much less. Lesson 06-03 is about exactly this.

The recipe is mechanical, and that is its value. A local variable that crosses a cut is a stale copy waiting to happen, so every one of them is worth a second look.

04In your editor

The model is chapters/06-concurrency-is-interleaving/specs/TaskBoard.tla. Check this lesson's exercises with:

shell
./tla check 06-02

The board's run, as ./tla prints it:

Output 06-concurrency-is-interleaving/specs/TaskBoard
06-concurrency-is-interleaving/specs/TaskBoard  TaskBoard.cfg  (Workers={w1, w2}, Tasks={t1, t2}, None=None)
parse ok
model check: invariant ClaimsHold violated; trace has 5 states (4 steps); 30 distinct states
expected outcome met: violation ClaimsHold
trace (changed variables only; ./tla trace --full shows all):
  1  Init   owner = (t1 :> None @@ t2 :> None), mine = (w1 :> None @@ w2 :> None), pc = (w1 :> "pick" @@ w2 :> "pick")
  2  Pick   mine: (w1 :> None @@ w2 :> None) -> (w1 :> t1 @@ w2 :> None), pc: (w1 :> "pick" @@ w2 :> "pick") -> (w1 :> "claim" @@ w2 :> "pick")
  3  Pick   mine: (w1 :> t1 @@ w2 :> None) -> (w1 :> t1 @@ w2 :> t1), pc: (w1 :> "claim" @@ w2 :> "pick") -> (w1 :> "claim" @@ w2 :> "claim")
  4  Claim  owner: (t1 :> None @@ t2 :> None) -> (t1 :> w1 @@ t2 :> None), pc: (w1 :> "claim" @@ w2 :> "claim") -> (w1 :> "work" @@ w2 :> "claim")
  5  Claim  owner: (t1 :> w1 @@ t2 :> None) -> (t1 :> w2 @@ t2 :> None), pc: (w1 :> "work" @@ w2 :> "claim") -> (w1 :> "work" @@ w2 :> "work")

When you translate code yourself, write the labels into the code as comments first, one per cut, before you write any TLA+. If two labels sit with nothing shared between them, merge them. If one label covers a read and a later write of shared data, split it.

05Practice

Warm-up. The first step of the worker's loop is missing. Write Pick.

Core. The board moves into a database, whose conditional update tests and writes in one step. Change the claim to match.

Stretch. A job queue, from a blank page: translate a worker loop into a spec with a hand-written program counter, including the cfg.

06-02-ex1Warm-up5 min

06-02-ex1 · Pick a free task

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

TaskBoard.tla is the lesson's board, with the first step of the worker's loop missing: the line that scans the board and remembers a free task.

  1. Run ./tla check 06-02-ex1. TLC reports a deadlock in the initial state. Why can no worker take even one step?
  2. Fill gap g1: Pick(w) chooses any task nobody owns, stores it in mine[w], and moves the worker on to "claim". The board itself is only read. \E t \in Tasks : … is read "there is some task t such that …", and TLC tries every such task.
  3. Run the check. The goal is the lesson's counterexample: two workers who both believe they own the same task.

The check also runs MCTaskBoard.cfg, the course's own test of your Pick: one pick at a time, so nobody can claim a task behind someone's back. There, ClaimsHold must hold, the board must be cleared, and either task must be possible as the first pick: a Pick that follows a fixed rule, such as CHOOSE, fails. Leave the two MC files as they are.

Hints: HINTS.md, under "06-02-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/06-concurrency-is-interleaving/exercises/02-ex1-pick-a-free-task/; open it after you have an answer of your own.

Both cfgs must meet their goals: "goal met: violation ClaimsHold" for TaskBoard.cfg, and "goal met: pass" for MCTaskBoard.cfg.

Done when: ./tla check 06-02-ex1 prints "goal met: violation ClaimsHold".

./tla check 06-02-ex1

Repo chapters/06-concurrency-is-interleaving/exercises/02-ex1-pick-a-free-task/

Hints

Hint 1

The starter's deadlock is in the initial state: both workers are at "pick", Pick never happens, and GiveUp needs a full board. Your Pick gives every worker a first step.

Hint 2

Pick reads the board and writes only the worker's own variables: mine[w] gets a task, and pc[w] moves to "claim". Which task? Any task whose owner is None: use \E t \in Tasks.

Hint 3 (nearly the answer)

Inside \E t \in Tasks :, put two conjuncts: the task has no owner, and mine' is mine with worker w's entry set to t. Outside it, move pc[w] to "claim" and leave owner unchanged.

06-02-ex2Core8 min

06-02-ex2 · Claim if free

Tier: core. Time: about 8 minutes.

The board is moving into a database. The claim becomes one conditional update:

output
UPDATE board SET owner = :me WHERE task = :t AND owner IS NULL

The database runs the test and the write as one indivisible operation, and reports whether a row changed. The worker's code becomes:

output
def worker(me):
    while True:
        free = [t for t in TASKS if board[t] is None]   # pick
        if not free:
            return                                      # give up
        t = choose(free)
        if claim_if_free(t, me):                        # claim: test and write, one step
            work(t)                                     # work
        # else: someone beat us to it; go back to the board

TaskBoard.tla already has a second action at label "claim", BackOff(w), for the "someone beat us to it" branch. You change two things.

  1. Run ./tla check 06-02-ex2. The starter is the lesson's board, and it fails the same way.
  2. Fill gap g1: Claim(w) may happen only if nobody's name is on the picked task.
  3. Fill gap g2: BackOff(w) happens when someone's name is already there. It writes nothing on the board, forgets the task, and sends the worker back to "pick".
  4. Run the check until it passes, with every action firing and both witnesses reached. The cfg also checks BackOffOnlyWhenTaken: a worker backs off only when the database really turned it away, and then returns to "pick" with its task forgotten.

The witness Bumped is a worker standing at "claim" in front of a task someone else already owns. It shows that the race really happens in this model, so your test in Claim is doing work.

Hints: HINTS.md, under "06-02-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/06-concurrency-is-interleaving/exercises/02-ex2-claim-if-free/; open it after you have an answer of your own.

Done when: ./tla check 06-02-ex2 prints "goal met: pass".

./tla check 06-02-ex2

Repo chapters/06-concurrency-is-interleaving/exercises/02-ex2-claim-if-free/

Hints

Hint 1

The database's test is part of the same step as its write. So the test belongs in Claim's guard, next to pc[w] = "claim", not in a step of its own.

Hint 2

Claim may happen only when the picked task, mine[w], has no owner. BackOff is the other case: the picked task already has one. Between them, a worker at "claim" always has exactly one way forward.

Hint 3 (nearly the answer)

g1 is one conjunct about owner[mine[w]]. g2 is four: the opposite test, mine' with worker w's entry set back to None, pc' with w back at "pick", and the board unchanged.

06-02-ex3Stretch40 min · mastery path

06-02-ex3 · Job queue

Tier: stretch. Time: about 40 minutes.

A blank page, almost. JobQueue.tla names the variables, the actions and two witnesses; every body is a placeholder. You translate this code into a spec with a hand-written program counter, and write the cfg.

output
def worker(me):
    while True:
        job = queue.pop_head()   # thread-safe: removes the head, or returns None if empty
        if job is None:
            return
        run(job)

pop_head() is one indivisible call. Two workers run this loop over the same queue, which starts with jobs 1 to NumJobs. The requirements:

  • NoJobTwice: no job ever runs twice.
  • NoJobLost: once every worker has gone home, every job has run.

Steps:

  1. Run ./tla check 06-02-ex3. Read the starter error.
  2. Decide where the labels go before you write any action. One label per point in the loop where another worker could step in. The skeleton already commits you to three: "take", "run" and "done". Say to yourself why pop_head() and the if share a label.
  3. Fill gaps g1 to g8 in JobQueue.tla, then gap g1 in JobQueue.cfg: the spec, two workers, three jobs, and every invariant worth checking. Head(s) and Tail(s) from the standard module Sequences give the first element of a sequence and the rest.
  4. Run the check until it passes with full coverage and both witnesses.
  5. Read the trace of MCJobQueueSplit.cfg: which job runs twice, and what happens to the job behind it?

The check also runs course-written cfgs that test your requirements. MCJobQueueReqs.cfg runs your Spec with NoJobTwice and NoJobLost whatever your own cfg checks, and checks that a worker holds a job only at "run". MCJobQueueSplit.cfg runs your workers against an older library whose pop_head() read the head and then removed it in two calls; your NoJobTwice must report a violation there, so TRUE cannot pass. MCJobQueueDrop.cfg runs them against a queue that can lose its first job; your NoJobLost must report a violation there. Leave the MC files as they are.

Hints: HINTS.md, under "06-02-ex3 hint 1" to "hint 3". The solution is in solutions/chapters/06-concurrency-is-interleaving/exercises/02-ex3-job-queue/; open it after you have a passing answer of your own.

All four cfgs must meet their goals: "goal met: pass" for JobQueue.cfg and MCJobQueueReqs.cfg, "goal met: violation NoJobTwice" for MCJobQueueSplit.cfg, and "goal met: violation NoJobLost" for MCJobQueueDrop.cfg.

Done when: ./tla check 06-02-ex3 prints "goal met: pass".

./tla check 06-02-ex3

Repo chapters/06-concurrency-is-interleaving/exercises/02-ex3-job-queue/

Hints

Hint 1

Start from the labels. A worker can be interrupted before pop_head() and before run(job), and nowhere else that matters, so there are two working labels plus "done". Take and Quit both start at "take"; they are the two outcomes of one indivisible call.

Hint 2

Take needs a non-empty queue, puts Head(queue) into job[w] and leaves Tail(queue) behind, in one step. Run adds one to runs at the job the worker holds, and sets job[w] back to 0. The cfg needs SPECIFICATION, the constants, and three INVARIANT lines.

Hint 3 (nearly the answer)

NoJobTwice says every job's run count is at most one. NoJobLost is an implication: if every worker is at "done", then every job's count is exactly one. TypeOK gives each variable its set; Seq(S) is the set of sequences of elements of S.

06Explain it

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

After you writeCheck your explanation

A good answer. "Claim now tests that the picked task has no owner in the same step as it writes, and BackOff sends a worker whose task was taken back to "pick". With two workers and two tasks, TLC found no violation of ClaimsHold, every action fires, and Bumped shows the race still happens and is handled. It rests on the database running the test and the write as one operation; if the conditional update were a read then a write, the model would need two steps and the race would return. TLC did not check more workers, failures, or tasks added later."

A weak answer. "I made the claim atomic, so two workers can't claim the same task. It breaks if the database is slow."

Why it is weak. "Slow" is not the assumption: speed never matters in an interleaving model. Indivisibility of the conditional update does.

Done?