00-01
Chapter 00 · The bug your tests won't find
Predict the balance
00Recall
This is the first lesson, so there is nothing to recall yet. Later lessons open with up to three short review cards from earlier lessons. You can always skip them.
No earlier cards yet.
Skip recall Recall is never required.
01Commit
Here is a function from a payments service. It moves money between accounts kept in memory.
def transfer(ledger, src, dst, amount):
... # rejects amount <= 0 and src == dst
balance = ledger.balance(src) # Read
if balance < amount:
raise InsufficientFunds(...)
ledger.set_balance(src, balance - amount) # Debit
ledger.set_balance(dst, ledger.balance(dst) + amount) # CreditAccount a holds 100. Two requests arrive at the same moment. One sends 30 from a to b. The other sends 50 from a to c. The server runs each request on its own thread, so both calls to transfer() are in flight at once. The test suite has 200 tests, and every one of them passes. They are in impl/py/test_transfer.py: four checks (the source loses the amount, the destination gains it, the total stays the same, and two transfers in a row add up), each run over ten opening balances and five amounts.
Commit a
Account a holds 100. Two calls to transfer() run at once: one sends 30 from a to b, the other sends 50 from a to c. Both finish without raising an error. Which final balances of a are possible?
- 20, 50 or 70.
- Only 20. Each transfer takes its amount out, 100 - 30 - 50 = 20, and 200 passing tests would have caught anything else.
- 20 or 70, but never 50.
- 20, 50, 70, or even less than 20: working from a stale balance, the funds checks can let the account be overdrawn.
Answer 20, 50 or 70.
- If you picked A
- Right. Two of those three balances are wrong, and both come from the same gap in the code.
- If you picked B
- The arithmetic is right, but it treats each transfer as one event that runs from its first line to its last with nothing in between. And tests only report on the situations they create. Look for a gap between the line that reads the balance and the line that writes it.
- If you picked C
- You saw that the 50 can go missing when the other transfer writes last. Now swap the roles. Which transfer writes last is up to the scheduler, so either debit can be the one that disappears.
- If you picked D
- Both funds checks do pass on the same stale balance. But each write is that transfer's own copy minus its own amount, and its check made sure the copy covered the amount, so no write goes below zero. Here the stale read loses a debit. With amounts that add up to more than 100, the same stale read would let both checks pass and pay out more than the account held, still without a negative balance.
Commit b
How many of the 200 tests ever have two calls to transfer() in flight at the same time?
- None of them.
- A quarter of them: the "two transfers in a row" tests make two transfers from the same account.
- Most of them: the suite is large.
Answer None of them.
- If you picked A
- Right. Every test calls transfer() and waits for it to return before doing anything else.
- If you picked B
- Those tests make two transfers, but one after the other: the second call starts after the first has returned. Two calls in a row are not two calls at once.
- If you picked C
- Size is not the same as reach. A thousand tests that each call transfer() once explore the same single situation a thousand times, with different numbers.
02Lab
TLC found no violation
This is a teaching view. Real checking happens with TLC on your machine.
Text view: every state and step
| State | seen | balance | paid | pc | Steps (action → state) |
|---|---|---|---|---|---|
| initial 1 | <<0, 0>> | 100 | 0 | <<"read", "read">> | Read(1) → 2; Read(2) → 3 |
| 2 | <<100, 0>> | 100 | 0 | <<"debit", "read">> | Debit(1) → 4; Read(2) → 5 |
| 3 | <<0, 100>> | 100 | 0 | <<"read", "debit">> | Read(1) → 5; Debit(2) → 6 |
| 4 | <<100, 0>> | 70 | 0 | <<"credit", "read">> | Credit(1) → 7; Read(2) → 8 |
| 5 | <<100, 100>> | 100 | 0 | <<"debit", "debit">> | Debit(1) → 9; Debit(2) → 10 |
| 6 | <<0, 100>> | 50 | 0 | <<"read", "credit">> | Read(1) → 11; Credit(2) → 12 |
| 7 | <<100, 0>> | 70 | 30 | <<"done", "read">> | Read(2) → 13 |
| 8 | <<100, 70>> | 70 | 0 | <<"credit", "debit">> | Credit(1) → 13; Debit(2) → 14 |
| 9 | <<100, 100>> | 70 | 0 | <<"credit", "debit">> | Credit(1) → 15; Debit(2) → 16 |
| 10 | <<100, 100>> | 50 | 0 | <<"debit", "credit">> | Debit(1) → 17; Credit(2) → 18 |
| 11 | <<50, 100>> | 50 | 0 | <<"debit", "credit">> | Debit(1) → 19; Credit(2) → 20 |
| 12 | <<0, 100>> | 50 | 50 | <<"read", "done">> | Read(1) → 20 |
| 13 | <<100, 70>> | 70 | 30 | <<"done", "debit">> | Debit(2) → 21 |
| 14 | <<100, 70>> | 20 | 0 | <<"credit", "credit">> | Credit(1) → 21; Credit(2) → 22 |
| 15 | <<100, 100>> | 70 | 30 | <<"done", "debit">> | Debit(2) → 23 |
| 16 | <<100, 100>> | 50 | 0 | <<"credit", "credit">> | Credit(1) → 23; Credit(2) → 24 |
| 17 | <<100, 100>> | 70 | 0 | <<"credit", "credit">> | Credit(1) → 25; Credit(2) → 26 |
| 18 | <<100, 100>> | 50 | 50 | <<"debit", "done">> | Debit(1) → 26 |
| 19 | <<50, 100>> | 20 | 0 | <<"credit", "credit">> | Credit(1) → 27; Credit(2) → 28 |
| 20 | <<50, 100>> | 50 | 50 | <<"debit", "done">> | Debit(1) → 28 |
| 21 | <<100, 70>> | 20 | 30 | <<"done", "credit">> | Credit(2) → 29 |
| 22 | <<100, 70>> | 20 | 50 | <<"credit", "done">> | Credit(1) → 29 |
| 23 | <<100, 100>> | 50 | 30 | <<"done", "credit">> | Credit(2) → 30 |
| 24 | <<100, 100>> | 50 | 50 | <<"credit", "done">> | Credit(1) → 30 |
| 25 | <<100, 100>> | 70 | 30 | <<"done", "credit">> | Credit(2) → 31 |
| 26 | <<100, 100>> | 70 | 50 | <<"credit", "done">> | Credit(1) → 31 |
| 27 | <<50, 100>> | 20 | 30 | <<"done", "credit">> | Credit(2) → 32 |
| 28 | <<50, 100>> | 20 | 50 | <<"credit", "done">> | Credit(1) → 32 |
| 29 | <<100, 70>> | 20 | 80 | <<"done", "done">> | |
| 30 | <<100, 100>> | 50 | 80 | <<"done", "done">> | |
| 31 | <<100, 100>> | 70 | 80 | <<"done", "done">> | |
| 32 | <<50, 100>> | 20 | 80 | <<"done", "done">> |
The tree starts with both transfers about to read. Each branch is a choice of which transfer takes its next step. Open a few leaves and look at balance in each. Then answer this for yourself before you read on: is every leaf at the same balance?
Reveal for commit a
The leaves show three different final balances. The expected one is 20, which is Start - Amt1 - Amt2 with Start = 100, Amt1 = 30 and Amt2 = 50. Some leaves end at 70, which is Start - Amt1: the 50 was never taken out. Others end at 50, which is Start - Amt2: the 30 was never taken out. In every one of those runs both payees were still paid. The bank paid out 80 and kept more than 20, so money appeared from nowhere.
Reveal for commit b
None. Open impl/py/test_transfer.py and look at the four checks. Each one builds a fresh ledger, calls transfer(), waits for it to return, and then checks the result. The two-in-a-row check calls it two times, one after the other. No test ever has two calls running at once, so no test can see what happens when they overlap.
03Reason
If you picked "only 20", you did the arithmetic correctly on a picture of the program that is not true. In that picture, a transfer is one event. It happens all at once, and the other transfer happens before it or after it. Two events in some order give 100 − 30 − 50 either way.
The program is not one event. Read it as the computer runs it, one line at a time.
Write something before openingbetween which two lines can the other transfer change the account, and why does that matter?
Between the Read line and the Debit line. The Read line copies the balance into a local variable, balance. The Debit line writes back balance - amount, computed from that copy. If the other transfer changes the account in between, the copy is out of date, and the Debit line writes an answer based on old information.
Picture two clerks who share one ledger book. Each copies the balance onto a sticky note, subtracts their amount on the note, and writes the result into the book without looking at the book again.
Now walk through it with real numbers. Call the first transfer T1 (30 to b) and the second T2 (50 to c).
| Who acts | What happens | Account a |
|---|---|---|
T1 reads | T1's note says 100 | 100 |
T2 reads | T2's note says 100 | 100 |
T2 debits | writes 100 − 50 | 50 |
T1 debits | writes 100 − 30 | 70 |
| both credit | b gets 30, c gets 50 | 70 |
T2's debit happened, and then T1 wrote over it. Nothing raised an error. The funds check passed both times, because both clerks saw 100 on their notes. The payees received 80, and the account still holds 70. Swap who debits last and the account ends at 50 instead.
Write something before openingwhat has to be true about the order of steps for the balance to come out wrong?
Both reads must happen before either debit. Then both transfers compute from the same starting balance, and the second write erases the first. If one transfer's debit lands before the other transfer reads, the second reader sees the updated balance and everything adds up.
So why does a suite of 200 passing tests say nothing about this? Because a test only reports on the situations it creates. Every test here runs one call to transfer() to completion before the next starts. Of all the ways the two transfers' steps can be ordered, the tests only ever produce the two where one transfer runs from start to finish before the other begins. The bad orders need a second transfer to start while the first is still between its Read and its Debit. No sequential test can make that happen.
Be honest about the other side too. Stress tests do catch some races. If you started thousands of threads that all called transfer() and checked the total afterwards, you might see a wrong balance. You might also not. The window is narrow: the other transfer has to read after this one reads and before this one writes, and that gap lasts a tiny fraction of the time each request takes. Whether a stress run lands in it depends on the machine, the interpreter and the load. A test that fails once in a while looks flaky, and a rerun that passes says nothing about the race.
A test samples the possible orders. The model checker you will meet in this course, TLC, covers all of them, within the model's bounds. It does not list the orders one by one. It visits every state the model can reach and checks a claim you give it, such as "the account plus what was paid out never exceeds 100", in each one. A claim about single states that holds in every reachable state holds along every order, because every order passes only through reachable states. The tree in the lab was not drawn by hand. It is TLC's state graph of specs/Transfer.tla, a short description of the same three steps, unfolded so that each path appears on its own.
04In your editor
The code and its tests are in chapters/00-the-bug-your-tests-wont-find/impl/py/. If you have Python 3.10 or newer, run the tests from that folder:
python3 -m unittestThe last lines say that 200 tests ran and the result is OK. Python is optional in this course. If you do not have it, read the test file instead.
The lab's data comes from this command, run from the repository root. Lesson 00-03 sets up the tools and walks you through it, so you can wait until then.
./tla check 00-01It runs the configuration behind the lab and prints:
00-the-bug-your-tests-wont-find/specs/Transfer.explore00-the-bug-your-tests-wont-find/specs/Transfer.explore Transfer.explore.cfg (Start=100, Amt1=30, Amt2=50)
parse ok
model check: no violation found in 32 distinct states (43 generated, depth 7)
expected outcome met: pass
coverage: all 3 actions fired
witness LostUpdate reached (trace of 7 states)05Practice
Warm-up: a worked example, then your turn. Here is one order, worked out: T1 reads 100, T1 debits to 70, T2 reads 70, T1 credits 30, T2 debits to 20, T2 credits 50. The steps of the two transfers mix, but T2 read after T1 had written, so the balance ends at 20 and nothing is lost.
Now fill in the two blanks for this order: T2 reads, T1 reads, T1 debits, T1 credits, T2 debits, T2 credits. T2's note says ____. The final balance is ____.
Write something before openingyour two numbers.
T2's note says 100, because it read before anyone wrote. T1 then writes 70, and T2 writes over it with 100 − 50 = 50. The final balance is 50, and T1's 30 was lost. Both reads came before both debits, which is the pattern from the second fold above.
Core. Find, in the lab, a leaf that ends at 70 and a leaf that ends at 20 whose paths both start with T1 reading. Write down each path as a list of steps. Then say in one sentence what the two paths do differently.
Write something before openingwhat separates the two paths?
In the path to 70, T2 reads before T1 debits, so both transfers work from 100 and T2 debits first, then T1 writes over it. In the path to 20, T1 debits before T2 reads. Whether the balance goes wrong depends only on whether T2's read lands inside T1's window between Read and Debit. Which wrong value you get depends on which debit lands last.
06Explain it
Open NOTES.md in this chapter's folder and answer the three prompts under 00-01. If the file is missing, ./tla notes 00 writes it. Then compare your answers with "00-01 check your explanation" in HINTS.md. You grade yourself here: the point is to put the idea in your own words.
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:In this lesson you built nothing yet, so for the first prompt explain why the balance can end at 70.
After you writeCheck your explanation
A good answer: "The balance can end at 70 because both transfers read 100 before either wrote. T2 wrote 50, then T1 wrote 70, computed from its old copy, and T2's debit vanished. This depends on the two threads really overlapping; if every call ran to completion first, it could not happen. TLC explored a model of the code, not the Python itself: the lab's tree comes from Transfer.tla, and matching its three steps to the code is my claim."
A weak answer: "Because of a race condition." It names the category without saying which two steps race, what value is lost, or what has to be true for it to happen.
Done?