14-04

Chapter 14 · Specs meet code: trace validation and contracts

What traces cannot see

  • 42 min core
  • Core track
  • Skills: evidence, acceptance

00Recall

One card from 14-03 on where a replay diverges, one from chapter 12 on wording a claim after a simulation, and one from chapter 06 on what Next says about who runs next. All three are about the same gap today: the distance between "this happened" and "this is all that can happen".

14-03-a from Validate a small key-value store, find the first divergence

A replay diverges at a read. Is that the record where the bug happened?

Show answer

Rarely. It is the first record the spec cannot explain. The defect and the damage come at or before it; read backwards to the last record that touched the same data.

12-04-a from Simulation and honest claims

Simulation reports no violation after many thousands of states. What does that tell you?

Show answer

That none of the random behaviors it picked broke the invariant. It keeps no record of what it has seen, so it cannot say what fraction of the model it covered; read its coverage line.

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.

Skip recall Recall is never required.

01Commit

A teammate's TraceSpec, specs/KVTraceBlind.tla, is KVTrace with one line removed. Its MatchGet checks that a read is the next record, that the server is up and that the key is known. It does not compare the value the code returned with the spec's store. You replay the seed 3 log, the one from 14-03 in which kv.py lost the value of b.

Commit a

KVTraceBlind replays the seed 3 log. What does ./tla report?

  1. Rejected at the same record as in 14-03: the lost value is still in the log.
  2. Trace accepted.
  3. Rejected earlier, at the crash, now that reads are not checked.

Answer Trace accepted.

Now the seed 1 log, which KVTrace (the careful one) accepted in 14-01. Look at records 4 to 8:

output
4  {"op":"put","k":"a","v":2}
5  {"op":"flush","n":2}
6  {"op":"put","k":"a","v":2}
7  {"op":"crash"}
8  {"op":"recover"}

kv.py acknowledged the put in record 6, and the crash in record 7 emptied the buffer that held it. The same bug as seed 3, on the same code.

Commit b

KVTrace accepts the seed 1 log even though kv.py lost the put in record 6. How?

  1. KVTrace does not check puts, only reads.
  2. No later record can tell the two states apart: the lost put wrote the value the disk already held.
  3. The flush at record 5 made the put in record 6 durable, so nothing was lost.

Answer No later record can tell the two states apart: the lost put wrote the value the disk already held.

02Lab

shell
./tla check chapters/14-specs-meet-code/specs/KVTraceBlind.cfg
./tla check chapters/14-specs-meet-code/specs/KVTrace.cfg
Expected output 14-specs-meet-code/specs/KVTraceBlind
14-specs-meet-code/specs/KVTraceBlind  KVTraceBlind.cfg  (Keys={"a", "b"}, Vals={1, 2})
parse ok
model check: invariant TraceUnfinished violated; trace has 17 states (16 steps); 17 distinct states
trace validation: the spec matched all 16 log entries (trace-accepted)
expected outcome met: trace-accepted
trace (changed variables only; ./tla trace --full shows all):
   1  Init          store = [a |-> 0, b |-> 0], up = TRUE, l = 0
   2  MatchPut      store: [a |-> 0, b |-> 0] -> [a |-> 0, b |-> 1], l: 0 -> 1
   3  MatchGet      l: 1 -> 2
   4  MatchPut      l: 2 -> 3
   5  MatchCrash    up: TRUE -> FALSE, l: 3 -> 4
   6  MatchRecover  up: FALSE -> TRUE, l: 4 -> 5
   7  MatchGet      l: 5 -> 6
   8  MatchGet      l: 6 -> 7
   9  MatchPut      store: [a |-> 0, b |-> 1] -> [a |-> 0, b |-> 2], l: 7 -> 8
  10  MatchFlush    l: 8 -> 9
  11  MatchGet      l: 9 -> 10
  12  MatchFlush    l: 10 -> 11
  13  MatchGet      l: 11 -> 12
  14  MatchPut      store: [a |-> 0, b |-> 2] -> [a |-> 0, b |-> 1], l: 12 -> 13
  15  MatchCrash    up: TRUE -> FALSE, l: 13 -> 14
  16  MatchRecover  up: FALSE -> TRUE, l: 14 -> 15
  17  MatchFlush    l: 15 -> 16

Reveal for commit a

Accepted: the spec matched all 16 records. The trace shows only the variables each step changes. Row 2 sets the spec's b to 1, and no row changes it again before row 7, the blind MatchGet of record 6, the read in which the code returned 0. The replay walked straight past it.

Reveal for commit b

Accepted, with 18 states. In the replay, the put in record 6 changes only l: the spec's store already held a |-> 2. The flush at record 5 had written the same value to disk. Losing a put that changes nothing is a real bug that no log of this run can show.

03Reason

If you picked "rejected, the value is in the log", you trusted the log to speak for itself. It cannot. A log is evidence only through the TraceSpec that reads it, and only about the states the records reveal. This lesson is a tour of what that leaves out. There are four blind spots. Every trace validation can have all four; ask about each.

1. What you logged but did not check. KVTraceBlind drops one conjunct and accepts a run that lost data. Its acceptance is as green as KVTrace's. The habit from chapter 03 applies to TraceSpecs: break each matcher on purpose and confirm that some committed log turns red. The course's grader cfgs exist for that. Each trace exercise in this chapter runs at least one log your TraceSpec must accept and one it must not.

2. What you did not log. Suppose kv.py logged puts without their values. Then MatchPut cannot say which value was written. It has to admit every value the put could have written, and TLC follows every one of them:

3. Runs that did not happen. Commit b showed it: the same bug, on the same code, invisible in one run and visible in another. Seed 1 and seed 3 differ only in the choices sim.py made: which call, which key, which value, and when to crash. A replay checks the run you have. It says nothing about the run you would have got with a crash one step later. That is why sim.py takes a seed, why ./tla validate says "try other seeds" after every acceptance, and why a team's CI should replay many of them (lesson 14-06 shows the loop).

Write something before openingsim.py runs everything on one thread. Which interleavings can a replay of its logs ever check?

Only the ones the scheduler happened to produce, which for a single-threaded driver means one per seed. Exercise 14-04-ex2 makes the point with a counter: Monday's log has every read and write of an increment back to back, and is accepted. Tuesday's has two reads before either write, and the finished replay rejects it at record 4, the second write. The code is the same; the scheduler was not. A model check of a spec explores every interleaving the spec allows within the model's constants and bounds. A replay explores one.

4. Faults that were never injected. A workload with no crash never logs a recovery. Then the replay of every run is green, and recovery has not been tested once. sim.py injects crashes, duplicate requests and delays on purpose, at fixed probabilities, so that seeds exercise the paths a quiet day never does. Even so, nothing forces a given seed to hit a given path. The cheapest way to know which paths a log exercised is coverage. specs/KVTrace.allfire.cfg replays seed 1 as a passing run, and ./tla reports whether every matcher fired. A matcher that never fired on any committed log is a clause of the contract with no evidence behind it.

Put the four together and you get the honest sentence after an acceptance. Not "kv.py meets KVStore", but: "The seed 1 run of kv.py can be explained step by step by KVStore, through a TraceSpec that checks puts and reads, and every matcher fired." The second sentence is longer. Every word of it is true.

Write something before openingwhen would you rather have a model check of the spec, and when a replay of the code?

They answer different questions. A model check covers every behavior of a model, and never touches your code. A replay touches your code, and covers one run. Use the first to find out whether the design is right, and the second to find out whether this code, on this run, followed the design. Neither replaces the other, and neither replaces reading the code.

04In your editor

The blind TraceSpec is chapters/14-specs-meet-code/specs/KVTraceBlind.tla; diff it against KVTrace.tla to see the one changed line. Check this lesson's exercises and specs with:

shell
./tla check 14-04

The seed 1 replay with KVTrace:

Output 14-specs-meet-code/specs/KVTrace
14-specs-meet-code/specs/KVTrace  KVTrace.cfg  (Keys={"a", "b"}, Vals={1, 2})
parse ok
model check: invariant TraceUnfinished violated; trace has 18 states (17 steps); 18 distinct states
trace validation: the spec matched all 17 log entries (trace-accepted)
expected outcome met: trace-accepted
trace (changed variables only; ./tla trace --full shows all):
   1  Init          store = [a |-> 0, b |-> 0], up = TRUE, l = 0
   2  MatchPut      store: [a |-> 0, b |-> 0] -> [a |-> 0, b |-> 2], l: 0 -> 1
   3  MatchGet      l: 1 -> 2
   4  MatchGet      l: 2 -> 3
   5  MatchPut      store: [a |-> 0, b |-> 2] -> [a |-> 2, b |-> 2], l: 3 -> 4
   6  MatchFlush    l: 4 -> 5
   7  MatchPut      l: 5 -> 6
   8  MatchCrash    up: TRUE -> FALSE, l: 6 -> 7
   9  MatchRecover  up: FALSE -> TRUE, l: 7 -> 8
  10  MatchCrash    up: TRUE -> FALSE, l: 8 -> 9
  11  MatchRecover  up: FALSE -> TRUE, l: 9 -> 10
  12  MatchPut      l: 10 -> 11
  13  MatchPut      store: [a |-> 2, b |-> 2] -> [a |-> 1, b |-> 2], l: 11 -> 12
  14  MatchPut      l: 12 -> 13
  15  MatchPut      l: 13 -> 14
  16  MatchPut      l: 14 -> 15
  17  MatchPut      l: 15 -> 16
  18  MatchPut      l: 16 -> 17

For your own system, write the four blind spots at the top of your logging plan as questions: which fields do my matchers ignore, which values do I not log, which interleavings can my test driver produce, which faults does it inject?

05Practice

Warm-up. The seed 1 run, logged without the values of puts. Write a MatchPut that still accepts it, and check that it cannot explain two reads that disagree.

Core. A page-view counter, logged as a read and a write per increment. Write a TraceSpec that accepts Monday's log and rejects Tuesday's, and say what Monday's acceptance did not show.

14-04-ex1Warm-up5 min

14-04-ex1 · Unlogged values

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

kv-seed1-novalues.ndjson is the seed 1 run from lesson 14-01, logged by an older build of kv.py that wrote puts as {"op":"put","k":"a"}, without the value. Gets still carry the value they returned. The TraceSpec in this folder is the lesson's KVTrace, and its MatchPut still reads Entry.v.

  1. Run ./tla check 14-04-ex1. TLC stops with an error, not a verdict. In your terminal, open the file on the raw log: line and find the sentence that names a record. What did MatchPut ask of it?
  2. Fill gap g1: match a put whose value was not logged. The spec allows any value in Vals; the TraceSpec cannot know which one the code wrote.
  3. Run the check again. Compare the distinct-state count with the replay of the full seed 1 log in lesson 14-01, and explain the difference.

Four short hand-written logs test your matcher. A missing value widens what a put may have written, and nothing else:

cfglogmust be rejected at
KVTrace.grader.cfgkv-two-reads.ndjson: two reads of one key disagree, with no put between themthe second read
KVTrace.keys.cfgkv-other-key.ndjson: a put to a, then a read of b that sees a value nobody wrote therethe read
KVTrace.lost.cfgkv-put-lost.ndjson: a read right after a put sees 0, a value no put writesthe read
KVTrace.down.cfgkv-put-while-down.ndjson: a put acknowledged while the server is downthe put

Leave the four cfgs and their logs as they are.

Hints: HINTS.md, under "14-04-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/04-ex1-unlogged-values/; open it after you have a passing answer of your own.

You are done when all five cfgs meet their goals: "goal met: trace-accepted" for KVTrace.cfg, "goal met: trace-rejected at=3" for KVTrace.grader.cfg, and "goal met: trace-rejected at=2" for the other three.

Done when: ./tla check 14-04-ex1 prints "goal met: trace-accepted".

./tla check 14-04-ex1

Repo chapters/14-specs-meet-code/exercises/04-ex1-unlogged-values/

Hints

Hint 1

The raw log says TLC tried to select a field that the record does not have. A put record in this log has op and k. What does MatchPut need that the record cannot give?

Hint 2

When a log leaves a value out, the TraceSpec has to admit every value the spec could have used, and let TLC follow each one. TLA+ says "some value in a set" with \E.

Hint 3 (nearly the answer)

Keep Is("put"), the test on Entry.k and the step on l. Replace Entry.v with a bound variable, and wrap the KV!Put in \E over Vals. Keep the key from the record.

14-04-ex2Core10 min

14-04-ex2 · One interleaving

Tier: core. Time: about 10 minutes.

A page-view counter. Its contract, Counter.tla, has one step per increment. The service implements an increment as a read of the counter followed by a write of the value read plus one, with no lock, and logs both halves, as the top of CounterTrace.tla describes. monday.ndjson and tuesday.ndjson are two days of the same service.

This time the TraceSpec is nearly blank. CounterTrace.tla gives you its variables, the instance C of Counter, Entry, Next, Spec and the acceptance check; you write the rest, from the shape every TraceSpec in this chapter has had.

  1. Run ./tla check 14-04-ex2. The first block stops before TLC has checked anything; the other two stop for a different reason. Read both messages.
  2. Fill gap g1 in CounterTrace.tla: TypeOK, and Init, the counter's initial state with no line matched yet.
  3. Fill gaps g2 and g3: MatchRead and MatchWrite. Each checks that its line is next and names a known worker. A read is a stuttering step of Counter: it changes nothing, and the value read must be the counter's value. A write is the increment: it is Counter's step, and the value written must be what the increment produces.
  4. Fill gap g4, the whole of CounterTrace.cfg: the spec, the constant (the workers are "w1" and "w2"), the invariants to check, and deadlock checking off, with the reason in a comment.
  5. Run the check until Monday is accepted and Tuesday is rejected.

CounterTrace.grader.cfg replays Tuesday's log. Before you look at its verdict, read Tuesday's log and say which line the contract cannot explain. CounterTrace.stale.cfg replays Wednesday's, from the day a cache in front of the counter served an old value; a read matcher that does not compare the value lets it through to a later line. CounterTrace.stranger.cfg replays Thursday's, from a worker the contract does not list; Counter's step ignores the worker, so only your test on the worker's name can refuse it. Leave the three files as they are.

Then write two sentences in NOTES.md: what Monday's acceptance showed about the service, and what it did not. Lesson 14-04's third blind spot is the one to name.

Hints: HINTS.md, under "14-04-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/04-ex2-one-interleaving/; open it after you have a passing answer of your own.

You are done when all four cfgs meet their goals: "goal met: trace-accepted" for CounterTrace.cfg, "goal met: trace-rejected at=4" for CounterTrace.grader.cfg, and "goal met: trace-rejected at=3" for each of CounterTrace.stale.cfg and CounterTrace.stranger.cfg.

Done when: ./tla check 14-04-ex2 prints "goal met: trace-accepted".

./tla check 14-04-ex2

Repo chapters/14-specs-meet-code/exercises/04-ex2-one-interleaving/

Hints

Hint 1

Tuesday's log has two reads before either write. In Counter, every increment adds one to the current value. What value does the second write log, and what would an increment have produced?

Hint 2

Copy the shape of KVTrace.tla: Init is the contract's Init plus a value for l, and TypeOK the contract's plus a range for l. A read is like MatchGet: it changes nothing and compares a logged value with the spec's. A write is Counter's step for the worker in the record, and the value logged must be the value after the step. The cfg needs the constant as well as the checks.

Hint 3 (nearly the answer)

Each matcher starts with l < Len(Trace), a test on Entry.op and one on Entry.w. MatchRead then needs an equation between Entry.x and x, and UNCHANGED x. MatchWrite needs C!Inc applied to the record's worker and an equation between x' and Entry.x. Both end with the step on l. The cfg is SPECIFICATION, CONSTANT Workers, TypeOK, TraceUnfinished, and the deadlock switch with its reason.

14-mxMixed20 min · mastery path

14-mx · Staged commit

Tier: mixed. Time: about 20 minutes. Off the core clock: this is on the mastery path.

A replicated store writes in two phases: a value is first prepared (staged, invisible to readers), then committed (made visible). Its contract, AtomicKV.tla, knows nothing of phases: a write takes effect in one step. The store logs three kinds of line, described at the top of StagedKVTrace.tla. A commit line names the key but not the value.

  1. Run ./tla check 14-mx and read why every replay stops at the first record.
  2. Decide what the TraceSpec needs to check a commit, given what a commit line carries and what AtomicKV's state can hold. Gaps g1 and g2 in StagedKVTrace.tla are where the TraceSpec's own state goes: its variables, vars, TypeOK and Init. Change them if your answer needs it, and delete their \* GAP markers either way.
  3. Fill gaps g3 to g5. A prepare changes nothing that AtomicKV can see. A commit is AtomicKV's write, of the value that was prepared for that key. A read changes nothing and sees the committed value.
  4. Run the check until replica-ok.ndjson is accepted and the other two logs are rejected.

StagedKVTrace.grader.cfg replays replica-stale.ndjson, from a build in which a commit made the older value visible. Before you look at its verdict, say which record first shows the bug, and which record contains it. StagedKVTrace.dup.cfg replays replica-dup.ndjson, from a day the network delivered one commit message twice and the replica applied and logged both. Before you run it, decide whether the replay should accept that log, and at which record it should stop if not. Leave both cfgs as they are.

For the notes: which steps of the replica are stuttering steps of AtomicKV, what would go wrong if the commit matcher guessed the value, and which earlier chapter's tool is the thing you decided on for gaps g1 and g2?

Hints: HINTS.md, under "14-mx hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/mx-staged-commit/; 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 StagedKVTrace.cfg, "goal met: trace-rejected at=3" for StagedKVTrace.dup.cfg, and "goal met: trace-rejected at=6" for StagedKVTrace.grader.cfg.

Done when: ./tla check 14-mx prints "goal met: trace-accepted".

./tla check 14-mx

Repo chapters/14-specs-meet-code/exercises/mx-staged-commit/

Hints

Hint 1

Every replay stops at record 1 because every matcher is FALSE. Now look at a commit line: which value does it make visible, and where in the log, or in AtomicKV's state, could the matcher find it?

Hint 2

Neither the commit line nor AtomicKV's store holds the prepared value, so the TraceSpec has to remember it itself: a variable of its own, written by a prepare and read by a commit. Chapter 11 had a name for such a variable. A prepare is then a stuttering step of AtomicKV.

Hint 3 (nearly the answer)

Add a function from keys to values (0 for nothing prepared) to the variables, vars, TypeOK and Init. MatchPrepare updates it at the record's key and leaves store unchanged. MatchCommit needs something remembered for the key, A!Write of the record's key and that value, and forgets it again, which is what the duplicated commit tests. MatchGet compares store at the key with Entry.v and changes nothing.

06Explain it

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

After you writeCheck your explanation

Good: "Reads are stuttering steps that compare the value with x; writes are Counter's increment, with the logged value compared. Monday is accepted because each read and write happened back to back; Tuesday is rejected at the second write, because two reads of 0 produced two writes of 1. Monday's acceptance showed only that one interleaving fits the contract: the code has no lock, and a replay checks the interleaving the scheduler happened to produce, not the others."

Weak: "Monday passed, so the counter is correct on Mondays."

The weak answer treats a day as a cause. The code was the same both days; the explanation should name the scheduling, which is exactly what a replay of one run cannot cover.

Done?