14-02

Chapter 14 · Specs meet code: trace validation and contracts

TraceSpec

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

00Recall

One card from 14-01 on records the spec has no action for, one from chapter 03 on how ./tla checks a witness by expecting ~W to fail, and one from chapter 05 on records. Today the log becomes a sequence of records, and acceptance becomes an invariant you want to fail.

14-01-a from What to log

The code logs an internal event, such as a buffer flush, that the spec has no action for. What should the TraceSpec do with that record?

Show answer

Match it with a step that changes none of the spec's variables and still advances l. A record with no matcher stops the replay there.

03-03-b from Break it on purpose

How does ./tla check that the witness W is reachable?

Show answer

It checks ~W as an invariant in a wrapper module and expects a violation; the trace shows how W is reached.

05-03-b from Records, sequences, SUBSET

What is the difference between [a |-> S] and [a : S]?

Show answer

[a |-> S] is one record whose field a holds S. [a : S] is the set of every record whose field a holds an element of S.

Skip recall Recall is never required.

01Commit

In 14-01 you ran KVTrace and read ./tla's verdict. Now look under it. ./tla turns the log into a TLA+ module, TraceLog, whose one definition is the log as a sequence:

output
Trace == <<
    [op |-> "put", k |-> "b", v |-> 2],
    [op |-> "get", k |-> "a", v |-> 0],
    ...

KVTrace keeps a counter l, the number of records matched so far, which starts at 0. Every matcher ends with l' = l + 1. The cfg names one invariant besides TypeOK:

TLA+chapters/14-specs-meet-code/specs/KVTrace.tla
TraceUnfinished is defined as l < Len(Trace)

Commit a

The seed 1 log can be matched to its last record. What does TLC itself report on KVTrace.cfg, before ./tla interprets it?

  1. No violation found: every record matched.
  2. TraceUnfinished is violated, in the state after the last record.
  3. A deadlock after the last record: no matcher is enabled.

Answer TraceUnfinished is violated, in the state after the last record.

A teammate's first cfg for the same replay, specs/KVTrace.deadlock.cfg, names INVARIANT TypeOK and nothing else, and leaves deadlock checking on.

Commit b

With TypeOK only and deadlock checking on, what does the seed 1 replay report?

  1. No violation found: nothing went wrong.
  2. A deadlock, in the state after the last record.
  3. Trace accepted, as with the full cfg.

Answer A deadlock, in the state after the last record.

02Lab

shell
./tla check chapters/14-specs-meet-code/specs/KVTrace.cfg
./tla check chapters/14-specs-meet-code/specs/KVTrace.deadlock.cfg
./tla validate --log chapters/14-specs-meet-code/impl/fixtures/kv-seed1.ndjson --emit

The third command prints the TraceLog module that ./tla generates from the log, so you can read exactly what TLC reads.

Expected output 14-specs-meet-code/specs/KVTrace.deadlock
14-specs-meet-code/specs/KVTrace.deadlock  KVTrace.deadlock.cfg  (Keys={"a", "b"}, Vals={1, 2})
parse ok
model check: deadlock reached; trace has 18 states (17 steps); 18 distinct states
trace validation: the spec stopped after matching 17 entries of 17, and with deadlock checking on, TLC reports that dead end as a deadlock
expected outcome met: deadlock
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

Reveal for commit a

TLC reports invariant TraceUnfinished violated with a trace of 18 states, and the next line, from ./tla, says the spec matched all the log's entries: trace-accepted. The violation is the acceptance.

Reveal for commit b

A deadlock, with a trace of 18 states: the same states as the accepted run. The teammate's run reached the end of the log and then had nothing to say about it. The facts are right and the verdict is in the wrong words.

03Reason

If you picked "no violation found", you expected success to look like silence. In most of this course it does. A TraceSpec turns that around, for a reason worth deriving rather than memorising.

What question are you asking TLC? "Is there a behavior of the spec whose steps line up with every record of this log?" That is a question about the existence of one path. TLC answers existence questions the usual way: you claim the thing is impossible, and it shows you a counterexample if it is not. You used the same trick for witnesses in chapter 03. So you claim "no behavior gets to the end of the log", which is TraceUnfinished, and hope to be wrong.

Here is the whole shape, from specs/KVTrace.tla:

TLA+chapters/14-specs-meet-code/specs/KVTrace.tla
Entry is defined as Trace[l + 1]

Is(op) is defined as
    and l < Len(Trace)
    and Entry.op = op
TLA+chapters/14-specs-meet-code/specs/KVTrace.tla
MatchPut is defined as
    and Is("put")
    and Entry.k in Keys
    and Entry.v in Vals
    and KV!Put(Entry.k, Entry.v)
    and lprime = l + 1

Four pieces, every time:

  1. The spec's variables plus l. Init is the spec's Init with l = 0.
  2. Entry, the next record. Trace[l + 1] is a function application, and Trace has no element past its end.
  3. One matcher per record type: "this record is next" (Is), "its fields are values the spec knows" (Entry.k \in Keys), "the spec takes this step" (KV!Put(...)), and "one more record matched" (l' = l + 1).
  4. TraceUnfinished, the acceptance check.

Seen from chapter 11, an accepted replay says that this one run, read through the logging plan, is a behavior of the spec: a refinement check of a single behavior.

Write something before openingMatchPut checks Entry.k \in Keys before it calls KV!Put. What would the matcher say, without that line, about a put of key "c", which the model does not know?

It would explain the record with a step that does not do what the record says. In TLA+, [store EXCEPT !["c"] = 2] is defined over the domain of store, which has no "c", so it equals store itself. KV!Put("c", 2) becomes a step that changes nothing, and the replay walks past a write that the spec never allowed and never performed. The membership test turns that strange record into what it should be: a rejection at that record, with a depth that points at it. Every field a matcher hands to the spec deserves the same question: is it a value the spec can say something about?

Now the other outcome. Suppose record 6 cannot be matched. What does TLC report?

Write something before openingif the log cannot be matched past some record, where is the deepest state TLC finds, and what is l there?

Every step adds one to l, and Init sets it to 0, so a state at level j of the search (level 1 is the initial state) has l = j - 1. If records 1 to 5 can be matched and record 6 cannot, the deepest states have l = 5 and sit at level 6. TLC finds no violation, because TraceUnfinished never fails, and reports a depth of 6. The depth is the number of the first record no behavior can match.

That derivation is the whole of ./tla's rejection logic: no violation, so read the depth. It holds because of two choices in the shape: l starts at 0, and every step adds exactly one. Change either, and the depth points at the wrong record.

Why is deadlock checking off? Every path TLC explores reaches a state with no successor under Next: at the end of the log, or at the first record nothing can match. Both dead ends are verdicts. With deadlock checking on and no acceptance check, an accepted log shows up as a deadlock, as in commit b. With TraceUnfinished in the cfg, an accepted log is still reported as its violation, since invariants come first, but a rejected log is reported as a deadlock at the divergence. A TraceSpec has no other way to get stuck, so the switch hides nothing else, and every cfg in this chapter says so in a comment. A trace of k states always means k - 1 records matched.

Write something before openingKVTrace.allfire.cfg checks the same log with the witness Matched == l = Len(Trace) instead of TraceUnfinished. What does that buy?

A passing run, so ./tla can report coverage: which matchers fired. "Accepted" says the whole log was explained. Coverage says which kinds of record were in it. A log with no crash in it says nothing about recovery, however green the verdict. Lesson 14-04 builds on that.

./tla validate puts it together for code. It runs sim.py for an implementation and a seed (or takes a committed log with --log), writes TraceLog.tla under .tla-out/validate/, finds the trace cfg that declares @validates: for that implementation, adds TraceUnfinished and a separate module for reading the depth, and prints "trace accepted", or "trace rejected: first divergence at entry k" with the spec's state immediately before it. When the cfg also checks a property and the replay breaks it, it prints "while following the log, the spec reached a state that violates" and the property's name.

04In your editor

The TraceSpec is chapters/14-specs-meet-code/specs/KVTrace.tla. Check this lesson's exercises and specs with:

shell
./tla check 14-02

The seed 1 replay again, as a passing run with coverage:

Output 14-specs-meet-code/specs/KVTrace.allfire
14-specs-meet-code/specs/KVTrace.allfire  KVTrace.allfire.cfg  (Keys={"a", "b"}, Vals={1, 2})
parse ok
model check: no violation found in 18 distinct states (18 generated, depth 18)
trace validation: the spec followed all 17 log entries
expected outcome met: pass
coverage: all 5 actions fired
witness Matched reached (trace of 18 states)

To replay a log with whichever trace cfg declares @validates: for its implementation, use ./tla validate --log <file>. With Python 3.10 or newer, ./tla validate kv --seed 7 runs sim.py and replays the run it prints; run delegated or AI-written code inside the dev container.

05Practice

Warm-up. MatchGet with its value check missing. Write the comparison, and watch the course's grader log change its verdict.

Core. A turnstile at a ferry pier, and its controller's log. Write the three matchers and the rest of the cfg, so that the morning log is accepted and the evening one is not.

14-02-ex1Warm-up5 min

14-02-ex1 · Check the read

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

KVTrace.tla in this folder has a MatchGet with its value check missing: gap g1 holds TRUE. Every other line is the lesson's TraceSpec.

  1. Run ./tla check 14-02-ex1. Both logs are accepted: seed 1, and seed 3, the run in which kv.py lost an acknowledged put and a later read returned the old value. One of those acceptances is wrong. Which one, and what is the starter's MatchGet failing to look at?
  2. Fill gap g1: the value the code returned must be the value the spec holds for that key. Keep it to one conjunct.
  3. Run the check again and watch the grader's verdict change.

KVTrace.cfg replays seed 1, which must stay accepted. KVTrace.grader.cfg and KVTrace.invented.cfg are the course's tests of your comparison. On seed 3, the replay must be rejected at the read that returned the lost value. On kv-invented-value.ndjson, a hand-written log in which a read returns more than was ever written to its key, it must be rejected at that read. Leave both files as they are.

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

Hints: HINTS.md, under "14-02-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/02-ex1-check-the-read/; 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=6" for KVTrace.grader.cfg, and "goal met: trace-rejected at=2" for KVTrace.invented.cfg.

Done when: ./tla check 14-02-ex1 prints "goal met: trace-rejected at=6".

./tla check 14-02-ex1

Repo chapters/14-specs-meet-code/exercises/02-ex1-check-the-read/

Hints

Hint 1

Seed 3 is the run that lost data, and the starter accepts it. Which record shows the loss, and what does the starter's MatchGet do with that record's v field?

Hint 2

The spec's value for key k is store[k]. The record's key is Entry.k and its value is Entry.v.

Hint 3 (nearly the answer)

One equation between the spec's store at the record's key and the record's value. Replace the TRUE and delete the \* GAP marker.

14-02-ex2Core8 min

14-02-ex2 · The turnstile's log

Tier: core. Time: about 8 minutes.

A coin-operated turnstile at a ferry pier. Turnstile.tla is its contract: a coin unlocks the arm, one person pushes through and the arm locks again. A push against a locked arm moves nothing, so in the spec it is a stuttering step, not a Next step. The controller logs three kinds of line, described at the top of TurnstileTrace.tla. morning.ndjson is a normal shift. evening.ndjson is from the day the arm's latch stuck.

  1. Run ./tla check 14-02-ex2. With every matcher FALSE, what do you expect each log's replay to report? Compare with the output.
  2. Fill gaps g1 to g3 in TurnstileTrace.tla: one matcher for a coin, one for a push that went through, one for a push that did not. Use the spec's own actions where the spec has a step. Check every field the controller logged that the spec can say something about.
  3. Fill gap g4 in TurnstileTrace.cfg: the invariants to check, and deadlock checking off, with the reason in a comment.
  4. Run the check until the morning log is accepted and the evening log is rejected.

TurnstileTrace.grader.cfg replays the evening log. Before you look at its verdict, find the line yourself where the evening log stops making sense, and write down why. Two more cfgs test the fields a loose matcher would skip, each on a short hand-written log: TurnstileTrace.miscount.cfg, from a controller whose count skips a number, and TurnstileTrace.jammed.cfg, from an arm that stayed shut after a coin had unlocked it. Leave all three files as they are.

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

All four cfgs must meet their goals: "goal met: trace-accepted" for TurnstileTrace.cfg, "goal met: trace-rejected at=6" for TurnstileTrace.grader.cfg, "goal met: trace-rejected at=4" for TurnstileTrace.miscount.cfg, and "goal met: trace-rejected at=2" for TurnstileTrace.jammed.cfg.

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

./tla check 14-02-ex2

Repo chapters/14-specs-meet-code/exercises/02-ex2-turnstile-trace/

Hints

Hint 1

Copy the shape of the matchers in KVTrace.tla: Is(...), then what must hold of the record, then the spec's step (or UNCHANGED), then l' = l + 1. A push line needs one more test, on its through field, to tell the two push matchers apart.

Hint 2

A blocked push is a stuttering step of Turnstile, which the spec allows anywhere, so it changes nothing. The record also claims the arm was locked: say so, because that claim is what the log line means. A push that went through is T!Pass, and the controller's count must agree with what Pass makes of passed.

Hint 3 (nearly the answer)

MatchThrough needs Entry.through, T!Pass and an equation between passed' and Entry.count. MatchBlocked needs ~Entry.through, locked, and an UNCHANGED over both spec variables. The cfg needs TypeOK, TraceUnfinished and the deadlock switch with its reason.

06Explain it

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

After you writeCheck your explanation

Good: "Coins are T!Coin, a push through is T!Pass with the logged count compared, and a blocked push changes nothing and requires the arm to be locked; acceptance is TraceUnfinished, with deadlock checking off because every path TLC explores ends at the end of the log or at a divergence, and both are verdicts. It breaks if the controller logs a push before the arm has turned, because then a crash between the two would put a pass in the log that never happened. TLC checked two logs, not the controller between log lines and not days nobody logged."

Weak: "The morning log passes and the evening log fails, so the TraceSpec is correct."

The weak answer takes the two grader verdicts as the whole story. A matcher that skips the count would get the same two verdicts; the explanation should say what each matcher compares and why.

Done?