14-01

Chapter 14 · Specs meet code: trace validation and contracts

What to log

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

00Recall

One card from chapter 04 on what makes a step a stuttering step, one from chapter 11 on which implementation steps must match an abstract action and which may stutter, and one from chapter 06 on how big a step should be. All three come back today. A log is the code describing its own steps, and you have to decide which of them the spec has a name for.

04-02-a from Stuttering steps

A step of the minute clock takes min from 7 to 8 and leaves hr unchanged. Is it a stuttering step?

Show answer

For the hour clock's spec, subscript hr, yes: hr is unchanged. For the minute clock's spec, subscript << hr, min >>, no: min changed. Stuttering is always relative to a subscript.

11-02-a from The one-line intent

In a refinement check, which implementation steps must match an action of the abstract spec?

Show answer

Only the steps that change the shadow, the abstract state read off through the mapping. Every other step is a stuttering step of the abstract spec, which [Next]_vars allows.

06-03-b from Atomicity is a choice

How big should each step of a concurrency model be?

Show answer

As big as the implementation's real indivisible operation: one atomic hardware instruction (such as compare-and-swap), one single-row SQL update or a transaction run at SERIALIZABLE isolation, one thread-safe call. Bigger hides interleavings; smaller reports races the system rules out.

Skip recall Recall is never required.

01Commit

This chapter checks code against its spec one run at a time: the code writes a log, and the spec must explain every line of it.

The code is impl/kv.py, a small key-value store. Its contract is specs/KVStore.tla: a put is acknowledged and durable in one step, a crash takes the server down, and recovery brings it back with every acknowledged value in place. The store logs one JSON record per event, through five calls: put, get, flush, crash and recover. KVStore has three actions: Put, Crash and Recover.

A teammate writes the first TraceSpec, specs/KVTraceNoFlush.tla. Every step must match the next log record with a KVStore action. There are matchers for put, get (a read, checked against the store), crash and recover. There is none for flush, because KVStore has no flush.

Commit a

KVTraceNoFlush replays the seed 1 log, whose fifth record is a flush. What does ./tla report?

  1. Trace accepted: the flush records are internal, so the replay skips them.
  2. Trace rejected at the first flush: no step can match it.
  3. An error: the log holds a record type the module never mentions.

Answer Trace rejected at the first flush: no step can match it.

The full TraceSpec, specs/KVTrace.tla, adds a matcher for flush. It replays all 17 records of the same log.

Commit b

KVTrace accepts the seed 1 log. How many distinct states will TLC report?

  1. One per log record.
  2. One per log record, plus the initial state.
  3. Many more: every state KVStore can reach in that many steps.

Answer One per log record, plus the initial state.

02Lab

Run the teammate's TraceSpec, then the full one:

shell
./tla check chapters/14-specs-meet-code/specs/KVTraceNoFlush.cfg
./tla check chapters/14-specs-meet-code/specs/KVTrace.cfg
Expected output 14-specs-meet-code/specs/KVTraceNoFlush
14-specs-meet-code/specs/KVTraceNoFlush  KVTraceNoFlush.cfg  (Keys={"a", "b"}, Vals={1, 2})
parse ok
model check: no violation found in 5 distinct states (5 generated, depth 5)
trace validation: the spec followed entries 1 to 4; entry 5 of 17 is the first it cannot match (trace-rejected at=5)
expected outcome met: trace-rejected at=5

Reveal for commit a

The replay stops at the first flush. TLC finds no violation in 5 distinct states, and ./tla reads TLC's depth, 5, as the first record no behavior can match. That record is the flush. Lesson 14-02 shows why the depth is the record number; for now, read the line that starts trace validation:.

Reveal for commit b

18 distinct states for 17 records. The trace below the verdict has one row per state, and every row after the first names the matcher that explained that record.

03Reason

If you picked "the replay skips the flush", you read the log the way a person does: skim the lines you recognise, ignore the rest. TLC reads it the way a contract lawyer does. Every line is a claim the code makes about its own behavior, and every claim must be explained by a step of the spec, in order. A line with no explanation ends the story.

So the first question of trace validation is not about TLA+ at all. It is: what should the code write down?

Write something before openinga get changes nothing in the store. Why log it at all?

Because a read is the only moment the code shows you its state. A put says "I was told to store 2". A get says "this is what I actually hold". If the store quietly lost a value, no put record would show it. The next read of that key would. Lesson 14-03 finds a real bug exactly there.

Here is the logging plan behind kv.py, one row per call. Read it as a table of promises.

CallRecordWhat the spec does with itLogged when
put(k, v){"op":"put","k":"a","v":2}Put(k, v)the client is told "ok"
get(k){"op":"get","k":"a","v":2}a stuttering step that checks store[k] = vthe value is returned
flush(){"op":"flush","n":2}a stuttering stepthe buffer is on disk
crash(){"op":"crash"}Crashthe process stops
recover(){"op":"recover"}Recoverthe process answers again

Three rules produced that table.

Log every step the spec has a name for, including the environment's. Crash is not something kv.py decides to do; the world does it to kv.py. It is still an action of KVStore, so the log must record it, or the replay will meet a recovery with the server already up. In a real system the crash record is written by whatever notices the crash: the supervisor that restarts the process, or the process itself on its way up. sim.py, the course's seeded scheduler, injects crashes and writes the record for you.

Log at the moment the effect becomes visible to someone else. For a put, that is the moment the client hears "ok", after the value is durable, because "ok" is the promise the contract is about. Log earlier, and a crash between the log line and the effect makes the log claim a put that never happened. Log later, and a crash in between hides a put the client was told had succeeded. A record written at "ok" sits inside the operation's interval, from the call to the reply, and its position in the log orders it against every other record. Herlihy and Wing's linearizability asks each operation to appear to take effect at one instant between its call and its reply; that instant is usually called its linearization point. For a single-threaded store like kv.py, the "ok" is a safe stand-in for it.

Log what the step needs, and the outputs you want checked. Put(k, v) has two parameters, so the record carries k and v. A get has an output, the value returned, so the record carries v, and the matcher compares it with the spec. A thread id or a timestamp adds nothing here, because KVStore mentions neither. A field the spec never reads is free to log and does nothing for the check.

Write something before openingwhat should a TraceSpec do with a flush, which KVStore cannot express?

Match it with a step that changes none of KVStore's variables, and still count it. Chapter 11 called such a step a stuttering step of the abstract spec: the implementation did real work, and the abstract state did not move. Refusing the record stops the replay, as you saw. Deleting flush records from the log would work too, and it would be a lie of omission that you would forget about by next quarter.

Here is the matcher the full TraceSpec uses. Is("flush") checks that the next record is a flush and that there is a next record at all:

TLA+chapters/14-specs-meet-code/specs/KVTrace.tla
MatchFlush is defined as
    and Is("flush")
    and UNCHANGED tuple of store, up end tuple
    and lprime = l + 1

l is the number of records matched so far. Every matcher ends with l' = l + 1, so a behavior of KVTrace is a walk through the log, one record per step.

Now commit b. Why exactly one state per record? Because every record removes all the choices. In KVStore, a state has a successor for every key and value a put could write, and one for a crash. In KVTrace, the record says which key, which value, or which event, so each state has one successor or none. TLC's distinct count for such a replay is the number of states on the one path it walked: records matched plus one.

04In your editor

The specs are in chapters/14-specs-meet-code/specs/, the store in chapters/14-specs-meet-code/impl/kv.py, and the seed 1 log in impl/fixtures/kv-seed1.ndjson. Check this lesson's exercises and specs with:

shell
./tla check 14-01

The full replay of the seed 1 log:

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

Open impl/kv.py next to the trace. For each row, find the line that wrote the record, and check it against the table above: is the record written at the moment the effect becomes visible? If you have Python 3.10 or newer, python3 chapters/14-specs-meet-code/impl/sim.py --impl kv --seed 1 prints the same log.

05Practice

Warm-up. The starter KVStore has no recovery: Recover == FALSE. The seed 1 log has two. Write the step that explains them, without explaining too much.

Core. KVTrace without a flush matcher, and a cfg with no acceptance check. Match the internal event, then finish the cfg so that a fully matched log is reported as accepted.

14-01-ex1Warm-up5 min

14-01-ex1 · Explain the recovery

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

kv.py logs {"op":"recover"} when the server answers again after a crash. The starter KVStore.tla in this folder has no recovery at all: Recover == FALSE. The seed 1 log has two recoveries.

  1. Run ./tla check 14-01-ex1. Before you do, write down the record at which you expect the replay of seed 1 to stop, and why that one.
  2. Fill gap g1 in KVStore.tla: the step that explains a recovery. Ask what a recovery needs, what it changes, and what it must leave alone.
  3. Run the check again.

The check also runs two of the course's tests of your Recover; leave both files as they are. KVTrace.grader.cfg replays the seed 3 log, in which kv.py really did lose an acknowledged put: the replay must be rejected at the read that shows the loss. KVTrace.crash.cfg replays a short hand-written log, kv-unlogged-crash.ndjson, whose second crash was never logged: the replay must be rejected at the second recovery. Before you write Recover, ask which mistakes in it would let each log through.

If you change only the module and the result does not change, check that you deleted the \* GAP marker.

Hints: HINTS.md, under "14-01-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/01-ex1-explain-the-recovery/; 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-01-ex1 prints "goal met: trace-accepted".

./tla check 14-01-ex1

Repo chapters/14-specs-meet-code/exercises/01-ex1-explain-the-recovery/

Hints

Hint 1

The replay stops at the first recover record, because FALSE describes no step at all. Read Crash in the same file: your action is its mirror image.

Hint 2

An action has three parts: when it may happen (a guard on the current state), what it changes (primed variables), and what it leaves alone. A recovery only makes sense while the server is down.

Hint 3 (nearly the answer)

Your action touches up twice, once in the state before and once after, and says one thing about store. What it says about store is the contract's promise about crashes; it is what makes the grader's seed 3 replay fail at the read. Both mentions of up are what the short hand-written log tests.

14-01-ex2Core8 min

14-01-ex2 · Internal events

Tier: core. Time: about 8 minutes.

KVTrace.tla in this folder is the full TraceSpec from the lesson with one matcher missing: MatchFlush == FALSE. kv.py logs {"op":"flush","n":2} whenever it copies its write buffer to disk, and KVStore has no action for that. The cfg is unfinished too: it checks TypeOK and nothing else, and leaves deadlock checking on.

  1. Run ./tla check 14-01-ex2 and read the outcome. The replay does stop somewhere. Why does TLC call it a deadlock rather than a verdict about the log?
  2. Fill gap g1 in KVTrace.tla: match a flush record. Decide what a step that KVStore cannot see is allowed to change.
  3. Fill gap g2 in KVTrace.cfg: add the acceptance check from lesson 14-02, and turn deadlock checking off, with a comment that says why the switch hides nothing else in a TraceSpec. Gap g3 in KVTrace.grader.cfg needs the same switch: that log must be rejected, and without the switch a rejection is reported as a deadlock.
  4. Run the check until the seed 1 log is accepted.

The check also runs KVTrace.grader.cfg, on kv-reorder.ndjson, a hand-written log from a build whose flush also rewrote memory from the buffer, in the wrong order, so that a read after it returns an older value. A flush matcher that may change the store explains that, and the grader would accept it. There, the replay must be rejected at the read. Apart from gap g3, leave that file as it is.

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

Both cfgs must meet their goals: "goal met: trace-accepted" for KVTrace.cfg, and "goal met: trace-rejected at=4" for KVTrace.grader.cfg.

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

./tla check 14-01-ex2

Repo chapters/14-specs-meet-code/exercises/01-ex2-internal-events/

Hints

Hint 1

The deadlock is real: after the replay stops, no step is possible. TLC reports it as a deadlock because nothing in the cfg says that stopping at the end of the log is the goal.

Hint 2

A flush is invisible to KVStore. Which of KVStore's variables may a step that KVStore cannot see change? Look at how MatchGet handles a record that changes nothing.

Hint 3 (nearly the answer)

MatchFlush is Is("flush"), an UNCHANGED over both of KVStore's variables, and the step on l. In the cfg, add INVARIANT with the module's acceptance check, then CHECK_DEADLOCK FALSE with a comment naming the two ways a TraceSpec can stop; the grader's gap g3 takes the same switch.

06Explain it

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

After you writeCheck your explanation

Good: "My MatchFlush matches a flush with a step that changes neither store nor up and moves l on, because KVStore cannot see a flush; the cfg reports a full match as accepted through TraceUnfinished. It assumes the contract cannot see a flush; under a contract that tracks durability, such as BufferedKV in 14-03, a flush is a real step, and a matcher that changes nothing would be wrong. TLC did not check other seeds, or whether kv.py writes its records at the moment the effect becomes visible."

Weak: "I added MatchFlush and the trace was accepted, so flush works."

The weak answer reports the verdict and calls it a property of the code. It names no assumption, and "flush works" is a claim about every run that one replay cannot carry.

Done?