14-05

Chapter 14 · Specs meet code: trace validation and contracts

What a contract contains

  • 43 min core
  • Essentials track
  • Skills: acceptance, intent

00Recall

One card from 14-04 on fields a TraceSpec ignores, one from chapter 13 on leases without wall clocks, and one from chapter 09 on what makes a property a safety property. Today's spec is a lease, its properties are safety properties, and the question is who gets to change them.

On the essentials track? This lesson and 14-06 build on 14-01 to 14-04: a TraceSpec replays a log, matchers compare fields, and ./tla validate reports the first divergence. Read their recaps in this chapter's CONCEPTS.md first.

The chapter 13 card said to count down rather than keep a growing now. LeaseKV keeps a growing now anyway, for a reason that belongs to this chapter: the servers log absolute ticks, "t": 5, and a spec clock that counts the same way lets every matcher compare Entry.t with now directly. A countdown spec would need the TraceSpec to keep a clock of its own and map the logged ticks onto it. MaxTime stops the spec's clock, so the model stays finite; a run that outlasted it would need a bigger bound.

14-04-a from What traces cannot see

A TraceSpec's MatchGet does not compare the value the code returned. What happens to a log in which the code read a lost value?

Show answer

It is accepted. A field the TraceSpec ignores is as good as unlogged; the replay can only catch what a matcher compares.

13-04-b from Leases without wall clocks

Why does LeaseLock count time down to zero instead of keeping a variable now that grows on every tick?

Show answer

A growing now takes infinitely many values, so the reachable states never run out. A countdown keeps only the time a decision depends on, relative to the grant, and bounded.

09-01-a from The prefix judge

What makes a property a safety property, and what makes it a liveness property?

Show answer

Safety: every violating behavior has a finite prefix that already violates it, whatever comes next. Liveness: every finite prefix can still be continued into a behavior that satisfies it.

Skip recall Recall is never required.

01Commit

Lessons 14-05 and 14-06 use a new service: one register guarded by a time-limited lease. Its contract is three files in specs/:

  • LeaseKV.tla, the spec: acquire, renew, write, release, and a clock that ticks.
  • LeaseKVProps.tla, the properties: what the owner requires, stated over the spec's variables.
  • CONTRACT.md, the prose: scope, interface, logging plan, acceptance, and who may change what.

LeaseKVProps.tla is the finished contract, and two of its properties are this lesson's exercises. Do the exercises before you open it.

A contributor sends a small change to LeaseKV.tla. Renew(c) used to need Valid(c): c holds the lease and it has not run out. Now it needs only holder = c, "so that a client that renews a little late is not punished". They do not touch LeaseKVProps.tla. CI runs the owner's three properties on the changed spec (specs/MCLeaseKVLateRenew.cfg).

Commit a

The owner's properties run, unchanged, on the contributor's spec. What does TLC report?

  1. No violation: the spec defines what is allowed, and it changed consistently.
  2. NoRenewAfterExpiry is violated.
  3. LeaseNeverTooLong is violated: a late renewal makes the lease too long.

Answer NoRenewAfterExpiry is violated.

In an earlier draft, the owner had written the renewal rule over the action instead of over the variables (specs/MCLeaseKVLateRenew.tla):

TLA+chapters/14-specs-meet-code/specs/MCLeaseKVLateRenew.tla
DraftRenewOnlyWhenValid is defined as
    always[for all c in Clients : Owner!Renew(c) implies Owner!Valid(c)]_vars

Owner!Renew is the contract's Renew, from LeaseKV.tla. The cfg specs/MCLeaseKVLateRenew.draft.cfg checks this draft alone on the contributor's spec.

Commit b

The draft property runs on the contributor's spec, which lets a client renew after its lease ran out. What does TLC report?

  1. The draft property is violated, at the late renewal.
  2. No violation.
  3. An error: a property cannot name an action.

Answer No violation.

02Lab

shell
./tla check chapters/14-specs-meet-code/specs/MCLeaseKVLateRenew.cfg
./tla check chapters/14-specs-meet-code/specs/MCLeaseKVLateRenew.draft.cfg
Expected output 14-specs-meet-code/specs/MCLeaseKVLateRenew
14-specs-meet-code/specs/MCLeaseKVLateRenew  MCLeaseKVLateRenew.cfg  (Clients={"c1", "c2"}, Dur=3, MaxTime=5, Vals={1, 2})
parse ok
model check: action property Owner!NoRenewAfterExpiry violated; trace has 6 states (5 steps); 90 distinct states
expected outcome met: property Owner!NoRenewAfterExpiry
trace (changed variables only; ./tla trace --full shows all):
  1  Init     now = 0, holder = "nobody", expires = 0, granted = 0, val = 0
  2  Acquire  holder: "nobody" -> "c1", expires: 0 -> 3
  3  Tick     now: 0 -> 1
  4  Tick     now: 1 -> 2
  5  Tick     now: 2 -> 3
  6  Renew    expires: 3 -> 6

Reveal for commit a

NoRenewAfterExpiry is violated with a trace of 6 states: a client acquires the lease, three ticks pass, it has run out, and the client renews it anyway. TLC reports the property as Owner!NoRenewAfterExpiry, through the instance the wrapper uses.

Reveal for commit b

No violation, in 510 distinct states, with every action firing and both witnesses reached. Every sign of a healthy check is there, and the property checks nothing. The pass is the bug.

03Reason

If you picked "no violation, the spec changed consistently", you treated the spec as the contract's last word. It is the contract's description of the system, and it is the file most likely to change: someone always has a reason. The properties are the owner's requirements, in a file that changes rarely and only by the owner's hand. A contract has both so that each can check the other.

So what goes in a contract? Three files, each answering one question.

FileQuestion it answersHere
Spec.tlaWhat may the system do?LeaseKV.tla
Props.tlaWhat must always be true of it?LeaseKVProps.tla
CONTRACT.mdWhat is in scope, how is it logged, how is it accepted, who changes what?CONTRACT.md

The course names them <Module>.tla and <Module>Props.tla, as everywhere else; Spec.tla and Props.tla are the roles. A fourth piece, the TraceSpec with its cfgs, is the acceptance test, and belongs to the contract too: an implementer who writes their own acceptance test is grading their own homework. Lesson 14-06 shows what that costs.

Read CONTRACT.md now. It is short. Notice four things in it.

The owner owns the spec and the properties. An implementation's pull request changes implementation files only. Anyone may propose a change to the spec, as the contributor did, and the owner reviews it against the properties. That is what commit a was: the properties caught a spec change that would have weakened the service.

Properties are stated over variables, not actions. Here is the shape, in the one property no exercise asks you to write:

TLA+chapters/14-specs-meet-code/specs/LeaseKVProps.tla
NoWriteWithoutLease is defined as always[valprime not equal to val implies holder not equal to Nobody and now < expires]_vars

It never mentions Write. It describes a change in the state, the register taking a new value, and what must hold before that change, so it applies to any step that makes the change, whatever the action is called and however it is written. NoRenewAfterExpiry works the same way: it names the change a renewal makes to the lease's variables (same holder, same grant, a new expiry) and what must hold in the state before it (the lease has not run out). Writing it is exercise 14-05-ex2. The draft in commit b did the opposite. It named Renew, and Renew carries its own guard, so the draft said "a step that satisfies the guard satisfies the guard".

Write something before openingwhy did the draft pass even though the contributor's spec renews late? Which steps did it actually constrain?

None. Owner!Renew(c) is the contract's renewal, guard included. A late renewal in the contributor's spec is not an Owner!Renew step: it fails the guard. So the implication's left side is false for it, and the implication is true. For a step that is an Owner!Renew step, Owner!Valid(c) is part of the left side. The draft is true of every step of every spec. A property that restates an action checks the action's definition against itself.

The interface table quotes the formulas, and the formula wins. LeaseKV.tla has comments, and comments drift. CONTRACT.md says that where a comment and a formula disagree, the formula is the contract. Keep that sentence in mind for 14-06.

Acceptance is a procedure, not a feeling. The properties hold on the spec (LeaseKVProps.cfg, with witnesses and full coverage). Every implementation, every seed CI lists, replays as accepted through the owner's TraceSpec, which also checks the properties during the replay. And the last line says what acceptance does not cover.

Write something before openingCONTRACT.md ends with a list of what is out of scope. Why write down what the contract does not cover?

Because an acceptance is only as wide as the contract. Clock skew, retries and the network are not in LeaseKV, so a replay that passes says nothing about them, and a reader who assumes otherwise is reading coverage into a green line. The list also tells an implementer where a change stops being an implementation detail: a server that starts retrying on its own has changed something the contract never described, and that goes to the owner first.

Write something before openingthe contract's TraceSpec checks LeaseKVProps during every replay, even though its matchers already use LeaseKV's actions. Why check both?

Because each can be wrong. A matcher can be written loosely, as a teammate or an agent might. Then the property is the net under it: a replay that the loose matcher accepts still violates NoRenewAfterExpiry at the step where the code renewed late. Exercise 14-06-ex2 is exactly that. The net has holes of its own. NoWriteWithoutLease looks only at steps that change val, so a write after the lease ran out that stores the value already in the register changes nothing and passes it; only MatchWrite, which uses Write's guard, rejects that record.

04In your editor

The contract is in chapters/14-specs-meet-code/specs/: LeaseKV.tla, LeaseKVProps.tla, CONTRACT.md. Check this lesson's exercises and specs with:

shell
./tla check 14-05

The contract check on the spec itself:

Output 14-specs-meet-code/specs/LeaseKVProps
14-specs-meet-code/specs/LeaseKVProps  LeaseKVProps.cfg  (Clients={"c1", "c2"}, Dur=3, MaxTime=5, Vals={1, 2})
parse ok
model check: no violation found in 510 distinct states (1965 generated, depth 12)
expected outcome met: pass
coverage: all 5 actions fired
witness Renewed reached (trace of 4 states)
witness LapsedWriter reached (trace of 6 states)

When you write a property, test it on a spec that is wrong in the way the property should catch. The exercises give you one per property: LeaseKVLong, which stacks renewals, and LeaseKVLateRenew, the contributor's change.

05Practice

Warm-up. LeaseNeverTooLong: a lease never reaches more than Dur ticks into the future. The course checks it on a spec that stacks renewals.

Core. NoRenewAfterExpiry, stated over the variables, and named in the contract's cfg. The course checks it on the contributor's late-renewal spec.

Stretch. A token-bucket rate limiter, from a skeleton: the property, the TraceSpec and the cfgs that check them.

14-05-ex1Warm-up5 min

14-05-ex1 · Never too long

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

The first of the owner's three properties, in words: a lease never reaches more than Dur ticks into the future. LeaseKVProps.tla in this folder holds it as TRUE.

  1. Run ./tla check 14-05-ex1. All three cfgs pass. Read the TLC warning about the property: what does TLC think of a claim that is nothing but TRUE?
  2. Fill gap g1 in LeaseKVProps.tla: state the property over the spec's variables, holder, expires and now. Decide whether it should say anything when nobody holds the lease.
  3. Run the check again.

LeaseKVProps.cfg checks your property on the contract's own spec, where it must hold, with every action firing and both witnesses reached. Two specs test it, each the contract with one change marked in the file. MCLeaseKVLong.cfg runs it on LeaseKVLong.tla, which lets an early renewal stack time on top of the old expiry. MCLeaseKVPlusOne.cfg runs it on LeaseKVPlusOne.tla, which grants a renewal one tick more than Dur. Your property must catch both, so a bound that is merely generous will not do. Leave the four MCLeaseKV… and LeaseKV… test 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-05-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/05-ex1-never-too-long/; open it after you have a passing answer of your own.

If TLC finds no violation but an action never fires or a witness is not reached, ./tla prints "goal not met" and exits with code 1.

You are done when all three cfgs meet their goals: "goal met: pass" for LeaseKVProps.cfg, "goal met: violation LongCheck" for MCLeaseKVLong.cfg, and "goal met: violation PlusOneCheck" for MCLeaseKVPlusOne.cfg.

Done when: ./tla check 14-05-ex1 prints "goal met: violation PlusOneCheck".

./tla check 14-05-ex1

Repo chapters/14-specs-meet-code/exercises/05-ex1-never-too-long/

Hints

Hint 1

The property is about one state, so it is an invariant. Which variables say how far into the future the lease reaches?

Hint 2

"Reaches into the future" is the distance from now to expires. "No more than Dur ticks" is a <=. Decide whether the claim needs to hold when holder = Nobody.

Hint 3 (nearly the answer)

The property mentions expires, now and Dur, and optionally holder. The bound is exact: the course's second test spec renews one tick too far. Replace the TRUE and delete the \* GAP marker.

14-05-ex2Core8 min

14-05-ex2 · Renew in time

Tier: core. Time: about 8 minutes.

The owner's third property, in words: the same lease is extended only before it runs out. "The same lease" means the holder and the grant time stay as they were. The lesson's contributor wants Renew to need only holder = c. The property is how the owner says no without reading every future pull request by hand.

  1. Run ./tla check 14-05-ex2. Every cfg passes, which is the problem.
  2. Fill gap g1 in LeaseKVProps.tla: state NoRenewAfterExpiry as an action property, over the variables holder, granted, expires and now and their primed versions. Do not mention Renew: lesson 14-05 showed what a property that restates an action checks.
  3. Fill gap g2 in LeaseKVProps.cfg: name the property, so that CI checks it on the spec. An action property is not an invariant; use the cfg keyword for temporal properties.
  4. Run the check again.

LeaseKVProps.cfg checks your property on the contract's spec, where it must hold with every action firing and both witnesses reached. MCLeaseKVContract.cfg checks it there too, whatever your cfg names, so a property that the contract itself breaks fails even if g2 is left out. Two specs test it, and it must fail on both. MCLeaseKVLateRenew.cfg runs it on the contributor's LeaseKVLateRenew.tla; a property written over Renew passes there. MCLeaseKVEdgeRenew.cfg runs it on LeaseKVEdgeRenew.tla, which lets the holder renew in the very tick its lease runs out. The contract counts a lease as run out when now >= expires, so that renewal is late too. Leave the six MCLeaseKV… and LeaseKV… test files as they are.

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

You are done when all four cfgs meet their goals: "goal met: pass" for each of LeaseKVProps.cfg and MCLeaseKVContract.cfg, and "goal met: property Learner!NoRenewAfterExpiry" for each of MCLeaseKVEdgeRenew.cfg and MCLeaseKVLateRenew.cfg.

Done when: ./tla check 14-05-ex2 prints "goal met: property Learner!NoRenewAfterExpiry".

./tla check 14-05-ex2

Repo chapters/14-specs-meet-code/exercises/05-ex2-renew-in-time/

Hints

Hint 1

An action property describes a step: unprimed variables are the state before, primed ones the state after. Which change in the variables does a renewal make, and which variables does it leave alone?

Hint 2

"The same lease" is holder and granted unchanged. "Is extended" is expires changing. "Before it runs out" is about the state before the step. The whole thing goes inside [][...]_vars.

Hint 3 (nearly the answer)

An implication inside [][...]_vars: on the left, three conjuncts about holder', granted' and expires'; on the right, one comparison between now and expires. In the cfg, one PROPERTY line.

14-05-ex3Stretch40 min · mastery path

14-05-ex3 · A token bucket

Tier: stretch. Time: about 40 minutes. Off the core clock: this is on the mastery path.

A rate limiter for one API key, as a contract you finish yourself. TokenBucket.tla is the spec, complete: the bucket starts full with Burst tokens, each admitted request spends one, each tick adds one back up to Burst. The owner's requirement, in words: over the whole run, no more requests are admitted than a full bucket plus one token per tick. The limiter logs one line per tick and per request, as the top of TokenBucketTrace.tla describes. quiet.ndjson is a quiet minute; burst.ndjson is from a build with a refill bug.

You write the property, the TraceSpec and every cfg line that matters:

  1. TokenBucketProps.tla, gap g1: RateLimit, a state predicate over the spec's variables.
  2. TokenBucketProps.cfg, gap g5: the constants (Burst = 2, MaxTime = 4) and the invariants. The deadlock switch and its reason are given.
  3. TokenBucketTrace.tla, gap g2: TypeOK and Init for the TraceSpec. Gap g3: three matchers, for a tick, an admitted request and a refused one. Check the clock the limiter logged, and the tokens it says are left.
  4. TokenBucketTrace.cfg and TokenBucketTrace.burst.cfg, gap g4 in each: the constants (Burst = 2, MaxTime = 8), the invariants, including the owner's property during the replay, and deadlock checking with its reason.

Run ./tla check 14-05-ex3 after each step and read every block.

MCTokenBucketLeaky.cfg and MCTokenBucketExtra.cfg are the course's tests of your property: TokenBucketLeaky.tla is a limiter whose tick adds two tokens, and TokenBucketExtra.tla one whose bucket starts with a token more than Burst. Your RateLimit must catch both, so a bound that is merely generous will not do. Three more cfgs are the course's tests of your matchers, each on a two-line hand-written log, and each replay must be rejected at its second line: TokenBucketTrace.left.cfg (wrong-left.ndjson, the limiter claims a token it does not have), TokenBucketTrace.clock.cfg (clock-skip.ndjson, its clock jumps a tick) and TokenBucketTrace.refuse.cfg (early-refusal.ndjson, it turns a request away with a token left). Leave the test files and their logs as they are.

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

You are done when all eight cfgs meet their goals: "goal met: pass" for TokenBucketProps.cfg, "goal met: violation LeakCheck" for MCTokenBucketLeaky.cfg, "goal met: violation ExtraCheck" for MCTokenBucketExtra.cfg, "goal met: trace-accepted" for TokenBucketTrace.cfg, "goal met: trace-rejected at=6" for TokenBucketTrace.burst.cfg, and "goal met: trace-rejected at=2" for each of the left, clock and refuse cfgs.

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

./tla check 14-05-ex3

Repo chapters/14-specs-meet-code/exercises/05-ex3-token-bucket/

Hints

Hint 1

Do the property first and check it alone, with TokenBucketProps.cfg and the leaky limiter. Then do the TraceSpec. The starter traces stop with "Init is false" until you write Init.

Hint 2

How many requests can be admitted by tick now? The bucket starts with Burst, and each tick adds at most one. For the TraceSpec, follow KVTrace: Init is the spec's Init plus l = 0, and each matcher is the spec's action with the logged fields compared.

Hint 3 (nearly the answer)

RateLimit compares admitted with a sum of Burst and now. MatchTick adds an equation between Entry.t and now + 1 to TB!Tick. MatchAdmit adds an equation between tokens' and Entry.left to TB!Admit. MatchRefuse needs an empty bucket and an unchanged state. The trace cfgs check TypeOK, ContractRateLimit and TraceUnfinished.

06Explain it

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

After you writeCheck your explanation

Good: "NoRenewAfterExpiry says that any step keeping the holder and the grant while moving the expiry starts before the lease runs out. It is stated over variables, so it applies to every action that makes that change, including ones added later. It assumes granted changes on every acquire; if a future spec reused the old grant time on a re-acquire, the property would treat that acquire as a renewal. TLC checked it on two small models, not on any code, and not with more than two clients."

Weak: "It says that Renew only happens when the lease is valid."

The weak answer restates the action, which is the draft property from the lesson: true by Renew's own guard and useless against a spec that changes the guard.

Done?