14-03
Chapter 14 · Specs meet code: trace validation and contracts
Validate a small key-value store, find the first divergence
00Recall
One card from 14-02 on why acceptance is an invariant that fails, one from 14-01 on when code should write its record, and one from chapter 03 on why an invariant's trace stops at the bad state. Today the trace stops somewhere else: at the first record the spec cannot explain, which is rarely where the bug is.
14-02-a from TraceSpec
Why is a TraceSpec's acceptance check an invariant that fails, TraceUnfinished == l < Len(Trace)?
Show answer
Acceptance asks whether some behavior reaches the end of the log, an existence question. TLC answers those through a counterexample: claim no behavior gets there, and a violation means one does.
14-01-b from What to log
When should code write the log record for an operation, and what should the record carry?
Show answer
At the moment the effect becomes visible to others (for a put, when the client is told "ok"), carrying the parameters the spec's action needs and the outputs you want checked.
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
sim.py drives kv.py with seed 3 and injects a crash. Here are the first eight records of the log, numbered as the replay counts them (impl/fixtures/kv-seed3.ndjson has the rest):
1 {"op":"put","k":"b","v":1}
2 {"op":"get","k":"a","v":0}
3 {"op":"put","k":"b","v":1}
4 {"op":"crash"}
5 {"op":"recover"}
6 {"op":"get","k":"b","v":0}
7 {"op":"get","k":"b","v":0}
8 {"op":"put","k":"b","v":2}Record 3 repeats the put in record 1.
Commit a
KVTrace replays the seed 3 log. At which record will ./tla report the first divergence?
Your answer is a whole number.
Answer 6
- Exactly right
- Right. The loss happened earlier; this is the first record that shows it.
- Within 10 %
- For an answer this small, within 10 % is the answer itself.
- Under by more than half
- Under by more than half. The first records are ordinary puts and reads that KVStore allows; nothing had gone wrong yet.
- More than double
- More than double. Something visible goes wrong much earlier than that. Look for the first record whose content contradicts what the spec would hold.
- Anything else
- If you said 4 or 5, you pointed at the crash or the recovery, where the value was lost. KVStore allows a crash and a recovery at that point, so both records match. The replay can only diverge at a record that says something the spec cannot. If you said 7, count again from the top: the replay numbers records from 1, skipping the comment line.
Commit b
The replay diverges. What does the divergence establish by itself?
- kv.py has a bug.
- That this log and the TraceSpec disagree at that record. The cause may be the code, the contract, the matchers or the logging.
- That KVStore is too strict for a real store and should allow the loss.
Answer That this log and the TraceSpec disagree at that record. The cause may be the code, the contract, the matchers or the logging.
- If you picked A
- Probably, here. But the divergence says only that no behavior of KVTrace explains that record. A matcher that is wrong, or a record written at the wrong moment, produces a divergence too. Exercise 14-03-ex1 has one that is the TraceSpec's fault.
- If you picked C
- That is a decision about requirements, and it belongs to whoever owns the contract, not to whoever is trying to make a check pass. It may even be the right decision (exercise 14-03-ex2). The divergence alone cannot make it for you.
02Lab
./tla check chapters/14-specs-meet-code/specs/KVTrace.seed3.cfg
./tla validate --log chapters/14-specs-meet-code/impl/fixtures/kv-seed3.ndjsonThe second command replays the same log through ./tla validate. After the verdict it prints the record it could not match and the spec's state immediately before it.
14-specs-meet-code/specs/KVTrace.seed314-specs-meet-code/specs/KVTrace.seed3 KVTrace.seed3.cfg (Keys={"a", "b"}, Vals={1, 2})
parse ok
model check: no violation found in 6 distinct states (6 generated, depth 6)
trace validation: the spec followed entries 1 to 5; entry 6 of 16 is the first it cannot match (trace-rejected at=6)
expected outcome met: trace-rejected at=6Reveal for commit a
Record 6: the first read of b after the recovery. TLC finds no violation in 6 distinct states, and the depth names the record. ./tla validate shows where the spec stood after the record before it, the recovery: store = [a |-> 0, b |-> 1], server up. The code answered 0.
Reveal for commit b
The divergence is a disagreement, not a verdict about blame. Here the blame is easy to place, once you read the code with the record in hand. The REASON beat does that.
StillFollowing violated
This is a teaching view. Real checking happens with TLC on your machine.
Trace
- State 1 Initial state store = [a |-> 0, b |-> 0] l = 0 up = TRUE
- State 2 MatchPut store [a |-> 0, b |-> 0] becomes [a |-> 0, b |-> 1] l 0 becomes 1
- State 3 MatchGet l 1 becomes 2
- State 4 MatchPut l 2 becomes 3
- State 5 MatchCrash l 3 becomes 4 up TRUE becomes FALSE
- State 6 MatchRecover l 4 becomes 5 up FALSE becomes TRUE
Text view: every state and step
| State | l | store | up | Steps (action → state) |
|---|---|---|---|---|
| initial 1 | 0 | [a |-> 0, b |-> 0] | TRUE | MatchPut → 2 |
| 2 | 1 | [a |-> 0, b |-> 1] | TRUE | MatchGet → 3 |
| 3 | 2 | [a |-> 0, b |-> 1] | TRUE | MatchPut → 4 |
| 4 | 3 | [a |-> 0, b |-> 1] | TRUE | MatchCrash → 5 |
| 5 | 4 | [a |-> 0, b |-> 1] | FALSE | MatchRecover → 6 |
| 6 | 5 | [a |-> 0, b |-> 1] | TRUE |
03Reason
If you said 4, you found the bug and misread the report. The value of b was lost at the crash, record 4. But KVStore allows a crash there: Crash needs only the server to be up. It allows the recovery at record 5 too. Neither record says anything about b. The spec, which never loses an acknowledged put, still holds b = 1; the code, which did lose it, holds 0; and nothing in the log has mentioned b since record 3. The two have parted ways, and nobody has noticed yet.
Record 6 notices. It is a read, and a read is the code showing its state. MatchGet compares the value returned with the spec's:
MatchGet is defined as
and Is("get")
and up
and Entry.k in Keys
and store[Entry.k] = Entry.v
and UNCHANGED tuple of store, up end tuple
and lprime = l + 1store["b"] = 0 is false, so no step matches that read, and the deepest state TLC reaches is the one right after the recovery.
Write something before openingrecord 3 repeats record 1. Had it been a retried delivery, which sim.py also injects (record 13 of seed 1 is one), why could KVTrace still match it with the ordinary put matcher, with no special case?
Because writing a key's current value into it is a Put step that leaves store as it was. KVStore allows it, so the repeat fits the contract, and the replay does not need to know whether it was a retry. That is what makes a put idempotent: doing it twice in a row is indistinguishable from doing it once. An increment is not. A duplicated increment is matched as a second, legitimate increment, and the double count looks correct to the replay, because the log cannot say that the second record was a retry. Catching it needs a request id in the record and in the spec. Even a put is safe to repeat only if no other write to the key comes in between: a retry delivered after a newer put brings the old value back, and the replay accepts it as a fresh put for the same reason. That lost update also needs a request id or a version to catch.
So a first divergence is the first record that the spec cannot explain. The bug is somewhere at or before it, and you find it by reading backwards. Three moments are worth naming separately, because they are three different questions:
| Moment | Record | Question |
|---|---|---|
| The defect is exercised | 1 and 3: puts acknowledged before they are durable | What did the code do wrong? |
| The damage happens | 4: the crash empties the buffer | When did the state go bad? |
| The damage shows | 6: a read returns the old value | When could anyone tell? |
A replay reports the third. A unit test that asserted the store's contents right after the crash would have caught the second. A replay catches the third without anyone thinking of that test, but only because a later record reads the key.
Write something before openingwhich three things could be wrong when a replay diverges, and how would you rule each one out here?
The code, the contract, or the bridge between them (the matchers and the logging). The bridge: get logs the value it returns at the moment it returns it, and MatchGet compares exactly that, so the record and its reading are honest. The contract: KVStore says an acknowledged put survives a crash, and kv.py's docstring names KVStore as its contract. That leaves the code: put answers "ok" once the value is in memory and the write buffer, and crash empties the buffer. The fix is a decision. Flush before acknowledging, or change the contract and tell the clients.
Now read the divergence a second way, inside ./tla check and the Trace Theater. specs/MCKVTraceProbe.tla adds one invariant to KVTrace:
StillFollowing is defined as l < Len(Trace) implies ENABLED Next"While there are records left, some step is possible." It fails in the state where the replay is stuck before the end, and its counterexample is the path that got there: the longest prefix of the log the spec can follow. That is exact here because every KVTrace step is forced by its record. From each state at most one matcher is enabled, so there is one path and one dead end.
Write something before openingthe probe's trace ends with the recovery. Why does it not show the read that failed?
Because no step matches that read. A trace is a sequence of states joined by steps the spec allows, and the failed read is exactly the step that does not exist. The record is in the log; the step is not in the spec.
04In your editor
The log is chapters/14-specs-meet-code/impl/fixtures/kv-seed3.ndjson; the probe is specs/MCKVTraceProbe.tla. Check this lesson's exercises and specs with:
./tla check 14-03The probe's trace, the replay up to the state before the divergence:
14-specs-meet-code/specs/MCKVTraceProbe14-specs-meet-code/specs/MCKVTraceProbe MCKVTraceProbe.cfg (Keys={"a", "b"}, Vals={1, 2})
parse ok
model check: invariant StillFollowing violated; trace has 6 states (5 steps); 6 distinct states
trace validation: after matching 5 entries of 16, the spec reached a state that violates StillFollowing
expected outcome met: violation StillFollowing
trace (changed variables only; ./tla trace --full shows all):
1 Init l = 0, store = [a |-> 0, b |-> 0], up = TRUE
2 MatchPut l: 0 -> 1, store: [a |-> 0, b |-> 0] -> [a |-> 0, b |-> 1]
3 MatchGet l: 1 -> 2
4 MatchPut l: 2 -> 3
5 MatchCrash l: 3 -> 4, up: TRUE -> FALSE
6 MatchRecover l: 4 -> 5, up: FALSE -> TRUEWhen a replay of your own system diverges, read in this order: the record that failed, the spec's state before it (from ./tla validate), then backwards through the log to the last record that touched the same data. Only then open the code.
05Practice
Warm-up. A teammate's MatchRecover and a replay that diverges at the read right after a recovery. Decide whether the code, the contract or the matcher is wrong, and fix that one.
Core. Suppose the owner decides that a store which loses unflushed puts is acceptable, if it says so. Write that weaker contract, BufferedKV, so that the seed 3 log is accepted and a store that loses flushed data is still rejected.
14-03-ex1Warm-up5 min
14-03-ex1 · Whose divergence?
Tier: warm-up. Time: about 5 minutes.
A teammate replayed the seed 39 run of kv.py and got a rejection at the read right after a recovery, record 10. Their message: "kv.py loses data on restart, opening a bug." The TraceSpec in this folder is the lesson's KVTrace, except for MatchRecover, which the teammate wrote by hand instead of using KVStore's action.
- Run
./tla check 14-03-ex1and read the divergence. Then openchapters/14-specs-meet-code/impl/fixtures/kv-seed39.ndjsonand read the records around it. - Lesson 14-03 named three suspects: the code, the contract, and the bridge (the matchers and the logging). Rule each one in or out. Compare the teammate's
MatchRecoverwithRecoverinKVStore.tla, and compare both with what the log says the code did. - Fix whichever side is wrong, inside gap g1 only.
KVStore.tlais the contract; you may not change it to make a replay pass. - Run the check again.
KVTrace.grader.cfg is the course's test of your fix, on the seed 3 log, in which kv.py really did lose an acknowledged put: there, the replay must still be rejected, at the read that shows the loss. A fix that accepts everything fails it. KVTrace.crash.cfg replays the hand-written log from exercise 14-01-ex1, whose second crash was never logged: a recovery matcher that may fire while the server is up explains it away, so the replay must be rejected at the second recovery. Leave both files as they are.
Write one sentence in NOTES.md for the teammate: whose divergence it was, and how you could tell.
Hints: HINTS.md, under "14-03-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/03-ex1-whose-divergence/; open it after you have a passing answer of your own.
You are done when all three cfgs meet their goals: "goal met: trace-accepted" for KVTrace.cfg, "goal met: trace-rejected at=3" for KVTrace.crash.cfg, and "goal met: trace-rejected at=6" for KVTrace.grader.cfg.
Done when: ./tla check 14-03-ex1 prints "goal met: trace-accepted".
./tla check 14-03-ex1
Repo chapters/14-specs-meet-code/exercises/03-ex1-whose-divergence/
Hints
Hint 1
Read records 7 to 10 of the seed 39 log. Was the value of a flushed before the crash? What does the code read after the recovery, and what does the teammate's matcher say the store holds?
Hint 2
Compare the teammate's MatchRecover with Recover in KVStore.tla line by line. The code and the contract agree with each other here. Which one disagrees with both?
Hint 3 (nearly the answer)
Replace the hand-written body with the contract's own action, the way MatchCrash uses KV!Crash: Is("recover"), the recovery step of KV, and the step on l.
14-03-ex2Core8 min
14-03-ex2 · Weaken the contract, on purpose
Tier: core. Time: about 8 minutes.
The owner of the store reads the seed 3 divergence from the lesson and decides: flushing on every put is too slow, so the contract will say what kv.py does. A put is acknowledged once it is in memory. A flush makes every acknowledged put durable. A crash loses whatever was not flushed. Recovery brings the server back. The owner writes it as a new spec, BufferedKV.tla, with two variables where KVStore had one: mem, what reads see, and disk, what survives a crash. The TraceSpec, BufferedKVTrace.tla, is written for you.
- Run
./tla check 14-03-ex2. Every action ofBufferedKVisFALSE, so what can the replay match? - Fill gaps g1 to g4 in
BufferedKV.tla:Put,Flush,CrashandRecover, from the four sentences above. Each sentence says what changes; the frame (what does not) is your job. - Fill gap g5 in
BufferedKVTrace.cfg: the invariants to check, and deadlock checking off, with the reason in a comment. - Run the check until the seed 3 log is accepted.
A weaker contract must still forbid something. Six short hand-written logs check that yours does, each from a store that breaks the owner's promise in one way, and each replay must be rejected at the record that shows it:
| cfg | log | the store |
|---|---|---|
BufferedKVTrace.grader.cfg | kv-flushed-then-lost.ndjson | loses a flushed put at its second crash |
BufferedKVTrace.put.cfg | kv-put-loses-flushed.ndjson | loses a flushed value when another key is written |
BufferedKVTrace.flush.cfg | kv-flush-changes-reads.ndjson | changes what a read returns when it flushes |
BufferedKVTrace.down.cfg | kv-put-while-down.ndjson | acknowledges a put while it is down |
BufferedKVTrace.flushdown.cfg | kv-flush-while-down.ndjson | logs a flush while it is down |
BufferedKVTrace.recover.cfg | ../01-ex1-explain-the-recovery/kv-unlogged-crash.ndjson | recovers while it is up, after a crash it never logged |
A sentence above says what each action changes. The rest of the frame, and the guards, are what these logs test: an action that may change a variable its sentence does not mention, or may happen when the server is in the wrong state, lets one of these stores through. Leave the six cfgs and their logs as they are.
Changing a contract is the owner's decision, made in its own pull request, never a way to turn a red replay green. Lesson 14-06 comes back to this.
Hints: HINTS.md, under "14-03-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/03-ex2-weaken-the-contract/; open it after you have a passing answer of your own.
You are done when all seven cfgs meet their goals: "goal met: trace-accepted" for BufferedKVTrace.cfg, and "goal met: trace-rejected at=7", "at=6", "at=3", "at=2", "at=2" and "at=3" for the grader, put, flush, down, flushdown and recover cfgs.
Done when: ./tla check 14-03-ex2 prints "goal met: trace-accepted".
./tla check 14-03-ex2
Repo chapters/14-specs-meet-code/exercises/03-ex2-weaken-the-contract/
Hints
Hint 1
Start from the four sentences in the README, one per action. Each says what changes. Then ask, for each of mem, disk and up, whether the sentence lets it change; if not, it goes in the frame.
Hint 2
Reads see mem, crashes keep disk. So a put touches only memory, a flush copies memory to disk, and a crash puts back in memory what is on disk. Which actions need the server to be up?
Hint 3 (nearly the answer)
Put changes mem only. Flush changes disk only. Crash changes up and mem. Recover changes up only, as in KVStore. Every variable an action does not change goes in its frame. Three of the four need the server to be up, and the fourth needs it down. The cfg is the same as every other TraceSpec cfg in this chapter.
06Explain it
Open NOTES.md and answer the three prompts under 14-03, about the Core exercise.
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:Compare your answers with "14-03 check your explanation" in HINTS.md.
After you writeCheck your explanation
Good: "BufferedKV keeps mem for reads and disk for what survives a crash; a put writes memory, a flush copies memory to disk, and a crash restores memory from disk. It assumes the buffer is flushed whole, in order: a store that flushes half a buffer would be rejected for a behavior its owner might accept. TLC did not check that clients were told about the weaker promise, and it did not check runs that crash during a flush, because sim.py never logged one."
Weak: "I weakened the contract until the seed 3 log passed."
The weak answer describes changing a check to make a run pass, which is the one thing a contract change must never be. It names neither the owner's decision nor what the weaker contract still forbids.
Done?