06-03

Chapter 06 · Concurrency is interleaving

Atomicity is a choice

  • 42 min core
  • Essentials track
  • Skills: abstraction, hostile-env

00Recall

One card from 06-02 on which local variables belong in the state, one from 06-01 on check-then-act, and one from chapter 00 on what must happen for a lost update.

06-02-a from Program counters by hand

When you model concurrent code by hand, which local variables must become part of the state?

Show answer

Every local variable whose value is set in one step and used in a later one. It carries a view of shared data across a gap where other processes can act.

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.

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

Two accounts, "a" and "b", start with Start = 10 each. Two transfers run at once in opposite directions: Amt1 = 3 from "a" to "b", and Amt2 = 4 from "b" to "a". The bank's code changes a balance like this:

output
def debit(account, amount):
    balance = db.get(account)              # one call
    db.put(account, balance - amount)      # another call

and credit is the same with a plus. specs/BankTransfer.tla models it faithfully: four steps per transfer, read and write for the debit, read and write for the credit, with the value read kept in tmp[t]. Its invariant Conserved says that the two balances plus the money in flight always add up to what the bank started with.

Commit a

TLC checks Conserved on BankTransfer, with both transfers running at once. What does it report?

  1. No violation: each transfer is correct on its own, and the money only moves.
  2. A violation: one transfer writes back a stale copy of a balance and erases the other's change.
  3. A violation, but only if both transfers touch the same account at the same instant.

Answer A violation: one transfer writes back a stale copy of a balance and erases the other's change.

A teammate writes specs/CoarseBankTransfer.tla: the same two transfers, but each debit and each credit is one step, read and write together. It passes, with full coverage and both witnesses, including one in which both transfers are in flight at once.

Commit b

CoarseBankTransfer passes. The bank's real code is the two-call debit above. What does the coarse pass tell you about that code?

  1. That it is correct: TLC checked every interleaving of the transfers.
  2. Nothing: it checked a different program, one whose balance updates are indivisible.
  3. That it is correct as long as transfers are rare enough not to overlap.

Answer Nothing: it checked a different program, one whose balance updates are indivisible.

02Lab

Run both models:

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

Read the failing trace, watching tmp and acct. It prints only the values that changed, so a read that copies the number already in tmp shows no tmp at all; ./tla trace --full shows every value. Find the write that uses a tmp value which no longer matches the balance it was copied from. That write is the lost update. Then ask which step, by the other transfer, made the copy stale.

Expected output 06-concurrency-is-interleaving/specs/BankTransfer
06-concurrency-is-interleaving/specs/BankTransfer  BankTransfer.cfg  (Start=10, Amt1=3, Amt2=4)
parse ok
model check: invariant Conserved violated; trace has 7 states (6 steps); 25 distinct states
expected outcome met: violation Conserved
trace (changed variables only; ./tla trace --full shows all):
  1  Init       acct = [a |-> 10, b |-> 10], tmp = <<0, 0>>, pc = <<"readFrom", "readFrom">>
  2  ReadFrom   tmp: <<0, 0>> -> <<10, 0>>, pc: <<"readFrom", "readFrom">> -> <<"writeFrom", "readFrom">>
  3  WriteFrom  acct: [a |-> 10, b |-> 10] -> [a |-> 7, b |-> 10], pc: <<"writeFrom", "readFrom">> -> <<"readTo", "readFrom">>
  4  ReadTo     pc: <<"readTo", "readFrom">> -> <<"writeTo", "readFrom">>
  5  ReadFrom   tmp: <<10, 0>> -> <<10, 10>>, pc: <<"writeTo", "readFrom">> -> <<"writeTo", "writeFrom">>
  6  WriteTo    acct: [a |-> 7, b |-> 10] -> [a |-> 7, b |-> 13], pc: <<"writeTo", "writeFrom">> -> <<"done", "writeFrom">>
  7  WriteFrom  acct: [a |-> 7, b |-> 13] -> [a |-> 7, b |-> 6], pc: <<"done", "writeFrom">> -> <<"done", "readTo">>

Reveal for commit a

Conserved is violated after 7 states. In every shortest run, a debit and a credit of the same account overlap: one transfer reads the balance, the other writes it, and the first writes back its old copy. Whether money vanishes or appears depends on which of the two writes is lost; the trace in your terminal shows one case.

Reveal for commit b

Nothing about the two-call code. The coarse model passes in 9 distinct states, and every word of that is true about a bank whose database changes a balance indivisibly. Your bank's code is not that bank.

03Reason

If you picked "it is correct", you trusted the run and forgot to ask what was run. TLC did its job perfectly, on a model of a program you do not have.

Look at the coarse debit:

TLA+chapters/06-concurrency-is-interleaving/specs/CoarseBankTransfer.tla
Debit(t) is defined as
    and pc[t] = "debit"
    and acctprime = [acct EXCEPT ![From[t]] = acct[From[t]] - Amount[t]]
    and pcprime = [pc EXCEPT ![t] = "credit"]

and the faithful one, in two pieces:

TLA+chapters/06-concurrency-is-interleaving/specs/BankTransfer.tla
ReadFrom(t) is defined as
    and pc[t] = "readFrom"
    and tmpprime = [tmp EXCEPT ![t] = acct[From[t]]]
    and pcprime = [pc EXCEPT ![t] = "writeFrom"]
    and UNCHANGED acct
TLA+chapters/06-concurrency-is-interleaving/specs/BankTransfer.tla
WriteFrom(t) is defined as
    and pc[t] = "writeFrom"
    and acctprime = [acct EXCEPT ![From[t]] = tmp[t] - Amount[t]]
    and pcprime = [pc EXCEPT ![t] = "readTo"]
    and UNCHANGED tmp

Same arithmetic. The only difference is where the step boundary falls.

Write something before openingwhat does the fine model have that the coarse one has no room for?

States in the middle of an update. After ReadFrom and before WriteFrom, a transfer holds a copy of a balance in tmp that may already be out of date. The coarse model has no such state: its debit goes from before to after in one step. Every cut you add creates states like that, and each one is a place where the other transfer's steps can land.

So every action you write is a promise about the implementation, and the promise is easy to make by accident, because balance - amount looks like one thing. That gives you the rule: make each step exactly as big as the implementation's real indivisible operation. Not bigger, or you hide interleavings the code has. Not smaller either: split a single database statement into a read and a write, and TLC will report races the database rules out, over more states.

What counts as indivisible depends on where the code runs, not on how it looks:

LineWhere it runsSteps
sold = sold + 1a Python threada read and a write
UPDATE flights SET sold = sold + 1one SQL statementone
queue.pop_head()a thread-safe library callone
cache.set(k, cache.get(k) + 1)two network callstwo
Write something before openingthe coarse model passes and the fine one fails. Can it ever be the other way round, the coarse one failing while the fine one passes?

No, as long as each coarse step is an honest summary of its pieces, and the question is an invariant. Every coarse behavior has a fine counterpart: replace each coarse step by its pieces, run back to back with nothing in between. So every state the coarse model reaches has a counterpart the fine model reaches, with the same shared variables, and an invariant violation on the shared variables carries over to the finer code. This is about invariants only: deadlock and liveness results do not transfer this way. And a pass in a coarse model is evidence only about the coarse program.

Write something before openingin lesson 06-01's SeatReserve, Book is one step. The airline's code is Python. What could a faithful Book do that the lesson's model cannot?

Work it out on paper. Split Book into a read of sold and a write of the copy plus one. Now both clients can read 0 and both write 1. sold says one seat is sold; two people hold tickets. NoOverbooking is sold <= Seats, and in that run it holds. Other orders still push sold past Seats, but this one slips by: the invariant counted with the very variable the race corrupted. A faithful model needs both the right steps and an invariant about what the airline cares about, the passengers, rather than about a counter that can lie.

Real code hides these splits well. account.balance -= amount followed by account.save() in an ORM reads like one line of intent and runs as a read, a computation and a write. So does counter[key] += 1 on a shared dictionary, or a "get, change, put" against a key-value store. Each one is a read and a write with a gap between them. Whether anything can land in the gap depends on the mechanism underneath, not on how short the line is.

None of this makes coarse models bad. A coarse model of a system whose operations really are indivisible is the right model, and smaller. The mistake is choosing the grain to make the model pass, or never choosing it at all.

04In your editor

The models are in chapters/06-concurrency-is-interleaving/specs/. Check this lesson's exercises with:

shell
./tla check 06-03

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

Output 06-concurrency-is-interleaving/specs/CoarseBankTransfer
06-concurrency-is-interleaving/specs/CoarseBankTransfer  CoarseBankTransfer.cfg  (Start=10, Amt1=3, Amt2=4)
parse ok
model check: no violation found in 9 distinct states (14 generated, depth 5)
expected outcome met: pass
coverage: all 3 actions fired
witness AllDone reached (trace of 5 states)
witness BothInFlight reached (trace of 3 states)

Before you trust any concurrent model, write next to each action the shared variables it reads and the ones it writes. An action that does both claims that nothing can come between them; put the mechanism that backs the claim in the action's comment, or split the action. Try the same audit on one get-modify-put in your own code, or in a diff an assistant gave you.

05Practice

Warm-up. Write the coarse model's one-step debit, and see the pass for yourself.

Core. A teammate modelled a like counter's two network calls as one step. Split the step and find out what the pass was hiding.

06-03-ex1Warm-up5 min

06-03-ex1 · One-step debit

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

CoarseBankTransfer.tla is the lesson's coarse model, with the debit missing. Here the database changes a balance in one indivisible operation, so a debit is one step.

  1. Run ./tla check 06-03-ex1. Read the starter's deadlock: which state is it in, and why can nothing happen?
  2. Fill gap g1: in one step, Debit(t) takes Amount[t] out of the payer's account, From[t], and moves the transfer on to "credit". Credit(t), right below it, is the mirror image.
  3. Before you run it, write down one trace of lesson 06-03's BankTransfer that this model cannot produce, and why not.
  4. Run the check. It should pass, with both witnesses reached. The cfg also checks RightBalances: at the end, each account holds what it should.

The witness BothInFlight matters: it shows that both transfers really are in the middle at the same moment. A model that ran them one after the other would pass for a much less interesting reason.

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

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

./tla check 06-03-ex1

Repo chapters/06-concurrency-is-interleaving/exercises/03-ex1-one-step-debit/

Hints

Hint 1

The starter's deadlock is in the initial state: both transfers are at "debit", and Debit can never happen. Look at Credit right below it.

Hint 2

In one step: the payer's balance, acct[From[t]], goes down by Amount[t], and the transfer moves on to "credit". Both are EXCEPT updates.

Hint 3 (nearly the answer)

Copy Credit, change the account it touches to From[t], the sign to a minus, and the label it moves to to "credit". Keep its guard on "debit".

06-03-ex2Core8 min

06-03-ex2 · Split the step

Tier: core. Time: about 8 minutes.

Two web servers each record a like on the same post. The code that runs on each:

output
def record_like():
    n = cache.get("likes")       # one network call
    cache.set("likes", n + 1)    # another network call

A teammate modelled it with a Read step that does the whole increment and a Write step that does nothing, "because count = count + 1 is one line". Their model passes. Your job is to make the model match the code.

  1. Run ./tla check 06-03-ex2. The teammate's own cfg passes. Ask yourself whether that is evidence about the code above. The course's MCLikeCounter.cfg already objects: it sees the counter move before any server has written.
  2. Fill gap g1: Read(s) copies the counter into seen[s] and changes nothing shared.
  3. Fill gap g2: Write(s) writes back what this server read, plus one.
  4. Before you run it, write down the trace you expect. Then run the check and compare.

The check also runs MCLikeCounter.cfg, the course's own test of your two steps: one increment at a time, where every like must be counted and the counter moves only on a write. A split that loses likes even there is not computing "plus one", and a Read that changes the counter is not a read. Leave the two MC files as they are.

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

Both cfgs must meet their goals: "goal met: violation NoLostLike" for LikeCounter.cfg, and "goal met: pass" for MCLikeCounter.cfg.

Done when: ./tla check 06-03-ex2 prints "goal met: violation NoLostLike".

./tla check 06-03-ex2

Repo chapters/06-concurrency-is-interleaving/exercises/03-ex2-split-the-step/

Hints

Hint 1

The teammate's Read does all the work and Write does none. In the code, the first call only fetches a value. Where does the fetched value live until the second call?

Hint 2

Read copies count into this server's entry of seen, and changes nothing shared. Write sets count from what this server saw, not from what count is now.

Hint 3 (nearly the answer)

g1: seen' is seen with server s's entry set to count, and count is unchanged. g2: count' is this server's entry of seen plus one, and seen is unchanged. If your Write mentions count on the right-hand side, it is reading the counter again.

06Explain it

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

After you writeCheck your explanation

A good answer. "I split the increment into Read, which copies the counter into seen[s], and Write, which writes seen[s] + 1, matching the code's two network calls. TLC then finds a lost like: both servers read 0 and both write 1. The teammate's pass rested on the assumption that the increment is one indivisible step, which two network calls are not. TLC did not check more servers, the cache's own atomic operations, or retries."

A weak answer. "The split version fails because of a race condition. The coarse version was wrong."

Why it is weak. The coarse version was not "wrong"; it was a correct model of a different program. The answer never says which assumption separated the two.

Done?