06-01

Chapter 06 · Concurrency is interleaving

Productive failure

  • 40 min core
  • Essentials track
  • Lab: Interleaving Explorer
  • Skills: hostile-env, counterexamples

00Recall

One card from chapter 00 on what has to happen for a transfer's balance to go wrong, one on the difference between a state and an interleaving, and one from chapter 03 on why an invariant's trace stops at the bad state.

On the essentials track? This chapter's specs use model values, Cardinality, function sets and |-> from chapter 05, which that track skips. Read the recaps of 05-01, 05-02 and 05-05 in chapters/05-just-enough-set-theory/CONCEPTS.md before you go on.

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.

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.

03-02-a from Your first counterexample

Why does a TLC trace for an invariant violation stop at the bad state instead of showing a whole infinite behavior?

Show answer

Once a state breaks an invariant, nothing later can repair it, so the path to that state is all the evidence needed.

Skip recall Recall is never required.

01Commit

An airline's booking service has one function that matters:

output
def reserve(client):
    if sold < SEATS:      # check: is a seat free?
        sold = sold + 1   # book it

The if guards the write. Nobody books unless a seat is free. The service runs on many threads, and tonight's flight has one seat left. Two clients press "Book" at the same moment.

Before you read on, take two minutes and write, on paper or in NOTES.md, a three-sentence argument that this code never sells more seats than the plane has. Make it the argument you would give in a design review. You will need it later in this lesson.

specs/SeatReserve.tla models the code: two clients, Seats = 1, and one step per line of reserve(). Its cfg checks NoOverbooking == sold <= Seats in every reachable state.

Commit a

TLC checks NoOverbooking on SeatReserve with two clients and one seat. What does it report?

  1. No violation: the if makes sure nobody books without a free seat.
  2. A violation: both clients book, and two seats are sold.
  3. A violation, but only because sold = sold + 1 is itself a read and a write that can collide.

Answer A violation: both clients book, and two seats are sold.

Commit b

If TLC finds an overbooking, its trace orders four steps, a check and a booking per client. Which order must it be?

  1. Client 1 checks and books, then client 2 checks and books.
  2. Both clients check before either one books.
  3. Any order of the four steps overbooks, as long as both clients run.
  4. The two bookings must happen at the same instant.

Answer Both clients check before either one books.

02Lab

Lab · Interleaving ExplorerWhat you’re looking at: every run of the two clients, unfolded as a tree. A state several orders reach repeats here; TLC visits it once. TLC marked the leaves where more seats are sold than exist; read one's path.

TLC found no violation

TLC evaluated Overbooked 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
StatesoldpcSteps (action → state)
initial 10(c1 :> "check" @@ c2 :> "check")Check(c1) → 2; Check(c2) → 3
20(c1 :> "book" @@ c2 :> "check")Book(c1) → 4; Check(c2) → 5
30(c1 :> "check" @@ c2 :> "book")Check(c1) → 5; Book(c2) → 6
41(c1 :> "done" @@ c2 :> "check")Check(c2) → 7
50(c1 :> "book" @@ c2 :> "book")Book(c1) → 8; Book(c2) → 9
61(c1 :> "check" @@ c2 :> "done")Check(c1) → 7
71(c1 :> "done" @@ c2 :> "done")Finished → self
81(c1 :> "done" @@ c2 :> "book")Book(c2) → 10
91(c1 :> "book" @@ c2 :> "done")Book(c1) → 10
✗ bad: Overbooked 102(c1 :> "done" @@ c2 :> "done")Finished → self

Expand the tree until every branch ends. Pick a marked leaf and read its path from the top: which steps came before the first booking? Then pick an unmarked leaf and find the step where its path left the bad ones behind. Count the leaves, then the marked ones. Is the bug rarer or more common than you expected?

Or in the terminal:

shell
./tla check chapters/06-concurrency-is-interleaving/specs/SeatReserve.cfg
Expected output 06-concurrency-is-interleaving/specs/SeatReserve
06-concurrency-is-interleaving/specs/SeatReserve  SeatReserve.cfg  (Clients={c1, c2}, Seats=1)
parse ok
model check: invariant NoOverbooking violated; trace has 5 states (4 steps); 10 distinct states
expected outcome met: violation NoOverbooking
trace (changed variables only; ./tla trace --full shows all):
  1  Init   sold = 0, pc = (c1 :> "check" @@ c2 :> "check")
  2  Check  pc: (c1 :> "check" @@ c2 :> "check") -> (c1 :> "book" @@ c2 :> "check")
  3  Check  pc: (c1 :> "book" @@ c2 :> "check") -> (c1 :> "book" @@ c2 :> "book")
  4  Book   sold: 0 -> 1, pc: (c1 :> "book" @@ c2 :> "book") -> (c1 :> "done" @@ c2 :> "book")
  5  Book   sold: 1 -> 2, pc: (c1 :> "done" @@ c2 :> "book") -> (c1 :> "done" @@ c2 :> "done")

Reveal for commit a

TLC reports that NoOverbooking is violated, with a trace of 5 states. At the end, sold is 2 on a plane with one seat: both clients booked.

Reveal for commit b

Both checks come first. Every overbooking run has that shape, not only the one TLC printed: a client books only after a check that saw a free seat, and once anyone has booked, no check sees one. So both checks must happen while sold is still 0.

03Reason

If you picked "no violation", look at the argument you wrote. It probably says something like "the if ensures a seat is free before the booking". That sentence is true of one client running alone. It quietly assumes nothing happens between the if and the line under it. With two clients, something can.

Here is TLC's trace again, changed variables only:

  1. State 1 Initial state sold = 0 pc = (c1 :> "check" @@ c2 :> "check")
  2. State 2 Check pc (c1 :> "check" @@ c2 :> "check") becomes (c1 :> "book" @@ c2 :> "check")
  3. State 3 Check pc (c1 :> "book" @@ c2 :> "check") becomes (c1 :> "book" @@ c2 :> "book")
  4. State 4 Book sold 0 becomes 1 pc (c1 :> "book" @@ c2 :> "book") becomes (c1 :> "done" @@ c2 :> "book")
  5. State 5 Book sold 1 becomes 2 pc (c1 :> "done" @@ c2 :> "book") becomes (c1 :> "done" @@ c2 :> "done")

Read the pc column. pc[c] is client c's program counter: the line it will run next. TLC prints a function from clients to values as (c1 :> "book" @@ c2 :> "check"), read "c1 maps to book, and c2 maps to check". The trace says: one client checks and sees a free seat. Then the other client checks, and also sees a free seat, because nobody has booked yet. Then both book.

Write something before openingat the moment a client books, what does its check tell it?

Nothing about now. The check found that sold < Seats was true at the moment of the check. By the time the client books, that fact is old news. A check is a statement about the past, and the booking acts as if it were about the present.

That is the whole bug, and it has a name: check-then-act. A process tests a condition on shared data, then acts on the result in a separate step, and another process changes the data in between. You have seen its cousin. Chapter 00's transfers read a balance and wrote it back later, so a write could erase another write. Here no write is erased. Each booking adds exactly one. The damage comes from a decision made on stale information.

Why did your argument miss it? Because arguments about code are written one thread at a time. Concurrency means the steps of different processes can be interleaved: between any two steps of one client, the other client may take none, one, or all of its steps. A spec says this directly:

TLA+chapters/06-concurrency-is-interleaving/specs/SeatReserve.tla
Next is defined as
    or there exists c in Clients :
        or Check(c)
        or Book(c)
    or Finished

\E c \in Clients is read "there is some client c such that". A step of the system is one step of some client, any client. Nothing says whose turn it is.

Finished is the step that says every client is done and nothing changes. Lesson 06-05 is about why it is there.

Write something before openinga stress test runs reserve() from two threads a million times. Does it find this bug?

Sometimes. The bad orders need the second check to land between the first check and the first booking, a window of a few instructions. On one core, the scheduler rarely switches between two adjacent lines; on many cores, the two threads must reach those lines within nanoseconds of each other. A million runs may hit it, or none may, and a pass tells you only that this machine, today, did not hit it. TLC does not sample orders. It visits every state reachable by any interleaving, which is enough to check an invariant on all of them.

Now put that fold next to the lab. If you counted the tree's leaves, the marked ones were not a rare few. So how can a stress test miss a bug that many branches of the tree reach?

Write something before openingthe tree says bad orders are common, the stress test says they are rare. Which one is wrong?

Neither. The tree counts orders. It gives every branch the same weight, because it asks only whether an order is possible. A real machine is not fair to orders. In a two-thread stress test, "check, then book, with nothing in between" is what you get almost every time: one core rarely switches threads between two adjacent lines, and many cores rarely line two threads up that closely. Under real load, with many requests overlapping, the window is hit more often. TLC answers "can this happen?", never "how often?". For a booking system the first question is the one that matters: a bug that happens once a month still sells a seat twice.

So your written argument was not useless. It was an argument about the wrong system: one client at a time. The model is the system you actually have, and TLC read every order of it. The rest of this chapter is about building such models on purpose, and about the ways they can mislead you.

04In your editor

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

shell
./tla check 06-01

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

Output 06-concurrency-is-interleaving/specs/SeatReserve
06-concurrency-is-interleaving/specs/SeatReserve  SeatReserve.cfg  (Clients={c1, c2}, Seats=1)
parse ok
model check: invariant NoOverbooking violated; trace has 5 states (4 steps); 10 distinct states
expected outcome met: violation NoOverbooking
trace (changed variables only; ./tla trace --full shows all):
  1  Init   sold = 0, pc = (c1 :> "check" @@ c2 :> "check")
  2  Check  pc: (c1 :> "check" @@ c2 :> "check") -> (c1 :> "book" @@ c2 :> "check")
  3  Check  pc: (c1 :> "book" @@ c2 :> "check") -> (c1 :> "book" @@ c2 :> "book")
  4  Book   sold: 0 -> 1, pc: (c1 :> "book" @@ c2 :> "book") -> (c1 :> "done" @@ c2 :> "book")
  5  Book   sold: 1 -> 2, pc: (c1 :> "done" @@ c2 :> "book") -> (c1 :> "done" @@ c2 :> "done")

When a trace has a pc variable, read it column by column. Follow one process's entry down the trace and you have that process's view: the lines it ran, in order. Then look at what the other process did between two of those lines. The bug is almost always in that gap.

05Practice

Warm-up. Three clients, two seats. Write the booking step yourself and predict the trace before you run it.

Core. A teammate's fix: check again, right before booking. Model the second check, and find out what it buys.

06-01-ex1Warm-up5 min

06-01-ex1 · Three clients

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

The lesson raced two clients for one seat. Here three clients race for two seats. You write the booking step yourself.

  1. Run ./tla check 06-01-ex1. The starter's Book can never happen. Read what TLC reports, and where each client is in the last state of the trace.
  2. Fill gap g1 in SeatReserve.tla: one more seat is sold, and the client is done. Copy the shape of Check.
  3. Before you run it, write down how many states the overbooking trace will have, and which steps it must contain. Then run the check and compare.

The check also runs SeatReserve.grader.cfg, the course's own test of your Book: a flight with a seat for every client, where nobody can be overbooked and the flight must sell out. Leave that file as it is.

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

Both cfgs must meet their goals: "goal met: violation NoOverbooking" for SeatReserve.cfg, and "goal met: pass" for SeatReserve.grader.cfg.

Done when: ./tla check 06-01-ex1 prints "goal met: violation NoOverbooking".

./tla check 06-01-ex1

Repo chapters/06-concurrency-is-interleaving/exercises/01-ex1-three-clients/

Hints

Hint 1

Read the starter's last state: every client that passed its check is sitting at "book", and the starter's Book can never happen, so nobody can move. Your action must take a client out of "book".

Hint 2

Book changes two things: the number of seats sold, and the client's own program counter. Check shows how to change one entry of pc with EXCEPT.

Hint 3 (nearly the answer)

Keep the guard on pc[c]. Replace both \* GAP lines with two conjuncts: one gives sold' as one more than sold, the other gives pc' as pc with client c moved to "done".

06-01-ex2Core8 min

06-01-ex2 · Check twice

Tier: core. Time: about 8 minutes.

A teammate saw the overbooking trace and proposed a fix:

output
def reserve(client):
    if sold < SEATS:          # check
        if sold < SEATS:      # check again, just to be sure
            sold = sold + 1   # book
        else:
            turn_away(client) # turned away late

"The second check catches anyone who sneaked in after the first." SeatReserve.tla models the new code, one step per line. The second check is missing.

  1. Run ./tla check 06-01-ex2. Read the starter's deadlock: where are the clients stuck?
  2. Fill gap g1: Recheck(c) sends the client on to "book" if a seat is still free, and to "late" if not. Nothing else changes.
  3. Before you run it, decide: does the second check fix the overbooking? Then run the check and read the trace.
  4. Write one sentence for the teammate: what the second check does not do.

The check also runs MCSeatReserve.cfg, the course's own test of your Recheck. It glues the second check to the booking, so that no other client can recheck or book between a client's second check and its booking, and it sells more than one seat. With that glue your Recheck must never overbook, and must turn a late client away. Leave the two MC files as they are.

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

Both cfgs must meet their goals: "goal met: violation NoOverbooking" for SeatReserve.cfg, and "goal met: pass" for MCSeatReserve.cfg.

Done when: ./tla check 06-01-ex2 prints "goal met: violation NoOverbooking".

./tla check 06-01-ex2

Repo chapters/06-concurrency-is-interleaving/exercises/01-ex2-check-twice/

Hints

Hint 1

The second check is the same question as the first, asked one line later. Look at Check and ask what changes: only the two labels it can send the client to.

Hint 2

Recheck changes only the client's pc, and leaves sold alone. A free seat leads to "book"; a full flight leads to "late".

Hint 3 (nearly the answer)

Write pc' as pc with client c moved to an IF … THEN "book" ELSE "late", testing the same condition Check tests, and say that sold is unchanged. Then read the trace: where do both rechecks fall, relative to the two bookings?

06Explain it

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

After you writeCheck your explanation

A good answer. "I modelled the teammate's second check as its own step, Recheck, which sends a client to "book" or "late". It is not correct as a fix: TLC still finds overbooking, with both clients passing both checks before either books. It would be correct only if nothing that writes sold could come between the second check and the booking, which is what the exercise's MCSeatReserve.cfg models: no other client may recheck or book in between. TLC did not check more clients or seats, or whether sold = sold + 1 is itself indivisible."

A weak answer. "I added the recheck and TLC found a violation, so the fix doesn't work. It breaks if there are more clients."

Why it is weak. It reports the verdict without the mechanism (the check and the act are still separate steps), and the assumption it names is not the one that matters.

Done?