14-06

Chapter 14 · Specs meet code: trace validation and contracts

Three implementations, one contract

  • 45 min core
  • Essentials track
  • Milestone 7
  • Skills: acceptance, evidence

00Recall

One card from 14-05 on the three files of a contract, one from 14-03 on the three suspects when a replay diverges, and one from chapter 11 on an AI summary that claimed more than its check covered. That last kind of claim is the subject of this chapter's AI item, and of the workflow this lesson ends with.

14-05-a from What a contract contains

Name the three files of a contract in this course, and who owns the first two.

Show answer

The spec (what the system may do), the properties (what must always hold, over the spec's variables), and CONTRACT.md (scope, logging plan, acceptance, owners). The owner of the service owns the spec and the properties; implementers change implementation files only.

11-05-b from When no mapping exists

An AI summary says "TLC confirms AlternatingBit refines ReliableChannel, so every message is eventually delivered." The cfg checked ChanInit and ChanStep on Spec. Is the summary accurate?

Show answer

No. Those properties are the safety half. The protocol's Spec has no fairness and allows it to stop, so delivery was not checked; checking Chan!Liveness on Spec fails. It passes only on a spec that adds enough of the protocol's own fairness, and the summary should say which.

Skip recall Recall is never required.

01Commit

Imagine handing the contract from 14-05 to an agent and getting back three implementations of the lease server: impl/lease_a.py, lease_b.py and lease_c.py. All three are short, tidy and plausible, and their docstrings say they follow CONTRACT.md. They carry provenance curated: the course wrote them in the style of agent output, to show two failure classes beside a correct version, and makes no claim about how often any model produces them.

diff makes the three short to compare. Each differs from A in one line of code, and in what its docstring claims:

The change from AWhat it implements
Anonethe formulas in LeaseKV.tla
Brenew checks holder == client, not that the lease is validits own idea: "renewal keeps the lease with its holder"
Cwrite checks holder == client, not that the lease is validthe comment above Write in LeaseKV.tla: "The holder writes the register."

The contract's acceptance test is the owner's TraceSpec, specs/LeaseKVTrace.tla, which matches every record with LeaseKV's own actions and guards and checks LeaseKVProps during the replay. sim.py drives each implementation with seed 8: two clients acquiring, writing, renewing and releasing, with some requests delayed or duplicated. In the seed 8 run, a delayed renewal reaches the server after the lease it renews has run out, while its client is still the holder. No client asks to write after its lease has run out.

Commit a

Each implementation's seed 8 log is replayed through the owner's TraceSpec. Which logs are accepted?

  1. All three: the agent wrote each one from the same contract.
  2. A and C.
  3. Only A.
  4. A and B.

Answer A and C.

In the same scenario, the agent also hands you a TraceSpec for the service, exercises/06-ex2-same-source/AgentLeaseTrace.tla (curated too). Its matchers restate the rules as the agent understood them. Its cfg checks TypeOK and acceptance, and none of the owner's properties.

Commit b

The agent's own TraceSpec replays B's seed 8 log. What does it report?

  1. Rejected at the same record as the owner's TraceSpec: a log is a log.
  2. Trace accepted.
  3. Rejected at the late renewal: the agent's matchers check the record's tick against the spec's clock.

Answer Trace accepted.

02Lab

The owner's TraceSpec on seed 8 for A, B and C, then C on seed 4:

shell
./tla check chapters/14-specs-meet-code/specs/LeaseKVTrace.cfg
./tla check chapters/14-specs-meet-code/specs/LeaseKVTrace.b8.cfg
./tla check chapters/14-specs-meet-code/specs/LeaseKVTrace.c8.cfg
./tla check chapters/14-specs-meet-code/specs/LeaseKVTrace.c4.cfg

The agent's TraceSpec on B's seed 8 log is the starter of exercise 14-06-ex2:

shell
./tla check 14-06-ex2
Expected output 14-specs-meet-code/specs/LeaseKVTrace.b8
14-specs-meet-code/specs/LeaseKVTrace.b8  LeaseKVTrace.b8.cfg  (Clients={"c1", "c2"}, Dur=3, MaxTime=12, Vals={1, 2})
parse ok
model check: no violation found in 7 distinct states (8 generated, depth 7)
trace validation: the spec followed entries 1 to 6; entry 7 of 21 is the first it cannot match (trace-rejected at=7)
expected outcome met: trace-rejected at=7

Reveal for commit a

A and C are accepted on seed 8. B is rejected: the first divergence is record 7, a renewal at tick 4 of a lease that ran out at tick 3. C, accepted on seed 8, is rejected on seed 4 at record 9: a write at tick 6 by a client whose lease ran out at tick 6.

Reveal for commit b

Accepted: the agent's TraceSpec matched all 21 records of the log the owner's TraceSpec rejects. Add the owner's three properties to the agent's TraceSpec (the exercise) and the same replay stops with NoRenewAfterExpiry violated, at the same renewal.

03Reason

If you picked "all three", you took "written from the contract" as "meets the contract". If you picked "A and B", you checked that the renewal did the right thing and forgot to ask whether it was allowed. Now read the code, with the verdicts in hand.

C is the interesting one. It did what the spec's comment says. The formula says Valid(c), which also needs now < expires, and CONTRACT.md says that when a comment and a formula disagree, the formula is the contract. C implemented the comment instead of the formula. It passed seed 8 because, in that run, no client wrote after its lease had run out. Seed 4 has one.

Seed 8 catches B and misses C. Seed 4 catches C and misses B: specs/LeaseKVTrace.b4.cfg accepts B's seed 4 log. Run one seed, and you ship one of the two bugs.

Write something before openingB's seed 8 log is accepted by the agent's TraceSpec and rejected by the owner's. Who wrote each, and from what?

The owner wrote LeaseKVTrace from LeaseKV.tla: its MatchRenew is LK!Renew(Entry.c), guard included. In the scenario, the agent wrote AgentLeaseTrace and B from one reading of the contract, in which a renewal needs only the holder. The two artefacts agree because they share a source, not because either is right.

That is same-source failure: an implementation and the check that accepts it, both derived from the same understanding, so that a misunderstanding passes straight through. It is not special to agents. A developer who writes the code and its tests in one sitting does it too. Agents make it cheap, fast and confident. The defence is not to distrust the agent harder. It is to make sure the check comes from somewhere else:

  • the spec and the properties come from the owner (14-05);
  • the TraceSpec that runs in CI is the owner's, and matches records with the spec's own actions, never restated rules;
  • the owner's properties run during every replay, as a net under the matchers;
  • an implementation's pull request does not touch any of the above.
Write something before openingthe agent's TraceSpec has a single matcher for every refusal, which checks only that nothing changed. What can it never catch?

A refusal the spec would have granted. An implementation that refuses every acquire, renew and write would be accepted: each record says "ok": false, nothing changes, and the matcher is satisfied. None of LeaseKVProps catches it either: a refusal leaves the spec's variables unchanged, and every property in that file allows such steps. Catching it needs a step-level rule that the spec could not have granted the request, which is what the owner's RefuseAcquire, RefuseRenew, RefuseWrite and RefuseRelease say. Exercise 14-06-ex2 asks you to notice this.

Here is the workflow the chapter has been building, as a team would run it:

  1. The owner writes the spec, the properties, the TraceSpec and CONTRACT.md, and checks the properties on the spec with witnesses and full coverage.
  2. An implementer, a person or an agent, gets the contract and writes code that logs per the logging plan. The implementer may run the acceptance test locally as often as they like.
  3. CI runs ./tla validate <impl> --seed k for a list of seeds, plus every committed fixture, with networking disabled. Any rejection fails the build; the log and the divergence are attached to the run.
  4. A pull request that changes the spec, the properties, the TraceSpec or their cfgs goes to the owner, separately. An agent that makes CI pass by editing a check has failed the task, however green the result.
  5. When a rejection turns out to be the contract's fault (14-03-ex2), the owner changes the contract, in its own pull request, and says why.

In a repository, the fourth step is a CODEOWNERS entry and a branch rule. The CI step can be as plain as a loop, with impl set to the implementation under review:

shell
for seed in 1 2 3 4 5 6 7 8; do ./tla validate "$impl" --seed "$seed" || exit 1; done

04In your editor

The implementations are in chapters/14-specs-meet-code/impl/; their committed logs are in impl/fixtures/. Check this lesson's exercises and specs with:

shell
./tla check 14-06

B's seed 8 log through the owner's TraceSpec:

Output 14-specs-meet-code/specs/LeaseKVTrace.b8
14-specs-meet-code/specs/LeaseKVTrace.b8  LeaseKVTrace.b8.cfg  (Clients={"c1", "c2"}, Dur=3, MaxTime=12, Vals={1, 2})
parse ok
model check: no violation found in 7 distinct states (8 generated, depth 7)
trace validation: the spec followed entries 1 to 6; entry 7 of 21 is the first it cannot match (trace-rejected at=7)
expected outcome met: trace-rejected at=7

With Python 3.10 or newer, run more seeds yourself: ./tla validate lease_c --seed 5. Before it runs anything, the engine scans impl/ for obvious imports of networking, process, thread and file modules, for os beyond os.path, and for open, eval, exec and run-time name lookups. It is a lint, not a sandbox: code written to get past it can. Read delegated or AI-written code before you run it, and run it inside the dev container (lesson 00-04 says what that does not isolate).

05Practice

Warm-up. The owner's TraceSpec, missing MatchWrite. Write it from the contract's own action, and check that it rejects C's seed 4 log at the right record.

Core. The agent's TraceSpec accepts B. Bring the owner's properties into it, without touching its matchers, and watch the same replay fail. Then explain what its refusal matcher can never catch.

14-06-ex1Warm-up5 min

14-06-ex1 · Match the write

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

LeaseKVTrace.tla in this folder is the owner's TraceSpec from the lesson, missing one matcher: MatchWrite == FALSE. Read the comment at the top of the module first. Its rule for every matcher is the point of this exercise.

  1. Run ./tla check 14-06-ex1. Implementation A's seed 8 log is rejected. At which record, and why there?
  2. Fill gap g1: a granted write is a Write step of the contract's spec, LK!Write, with the client and the value the log names. Look at RefuseWrite, directly below the gap, for how a request is recognised.
  3. Run the check again.

LeaseKVTrace.cfg replays A's seed 8 log, which must be accepted. Three cfgs are the course's tests of your matcher, and each replay must be rejected at the write. LeaseKVTrace.grader.cfg replays C's seed 4 log, where C granted a write after the lease had run out; a matcher that restates the rule as "the holder writes" accepts it. LeaseKVTrace.refused.cfg replays write-refused.ndjson, a write refused while the client's lease was valid, and LeaseKVTrace.tick.cfg replays write-stale-tick.ndjson, a granted write stamped with a tick the clock had passed. Leave the three 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-06-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/14-specs-meet-code/exercises/06-ex1-match-the-write/; 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 LeaseKVTrace.cfg, "goal met: trace-rejected at=9" for LeaseKVTrace.grader.cfg, "goal met: trace-rejected at=2" for LeaseKVTrace.refused.cfg, and "goal met: trace-rejected at=3" for LeaseKVTrace.tick.cfg.

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

./tla check 14-06-ex1

Repo chapters/14-specs-meet-code/exercises/06-ex1-match-the-write/

Hints

Hint 1

A's seed 8 log stops at its first granted write. Look at how MatchAcquire and MatchRenew are written in the same module: what do they use for the step itself?

Hint 2

The module's comment says every matcher uses LeaseKV's own action. LK is the instance. A granted write record has ok true, a client c and a value v.

Hint 3 (nearly the answer)

Request("write"), Entry.ok, Entry.v \in Vals, the contract's Write through LK with the record's client and value, and the step on l. No hand-written guard.

14-06-ex2Core8 min

14-06-ex2 · Same source

Tier: core. Time: about 8 minutes.

AgentLeaseTrace.tla is the TraceSpec from lesson 14-06's scenario, written from the same reading of the contract as implementation B. Its matchers restate the rules as that reading has them. Provenance: curated. Its cfgs check TypeOK and acceptance, and none of the owner's properties.

  1. Run ./tla check 14-06-ex2. The agent's TraceSpec accepts B's seed 8 log, which the owner's TraceSpec rejects. Do not touch the matchers.
  2. Fill gap g1 in AgentLeaseTrace.tla: bring the owner's three properties from LeaseKVProps into this module, through the instance LK that the module already has. Name them ContractLeaseNeverTooLong, ContractNoWriteWithoutLease and ContractNoRenewAfterExpiry.
  3. Fill gap g2 in all three cfgs: check the three properties during the replay. One is a state predicate; two are action properties. Each kind has its own cfg keyword.
  4. Run the check again. B's replay must now fail on the owner's renewal property, and A's must still be accepted.

AgentLeaseTrace.cfg replays B's seed 8 log, which must now fail on the renewal property. AgentLeaseTrace.a.cfg replays A's, so that a definition that rejects good runs does not pass. AgentLeaseTrace.long.cfg replays lease-long-grant.ndjson, a hand-written log from a server that grants a five-tick lease; the agent's acquire matcher copies the expiry from the log, so only LeaseNeverTooLong can catch it. The agent's write matcher already requires a valid lease, so no log can make NoWriteWithoutLease fail through these matchers; check it anyway.

Then answer in NOTES.md: the agent's MatchRefused checks only that nothing changed. What kind of wrong implementation would it accept, and why would none of the owner's properties catch it?

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

You are done when all three cfgs meet their goals: "goal met: property LK!NoRenewAfterExpiry" for AgentLeaseTrace.cfg, "goal met: trace-accepted" for AgentLeaseTrace.a.cfg, and "goal met: violation ContractLeaseNeverTooLong" for AgentLeaseTrace.long.cfg.

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

./tla check 14-06-ex2

Repo chapters/14-specs-meet-code/exercises/06-ex2-same-source/

Hints

Hint 1

LK is an instance of LeaseKVProps, so LK!LeaseNeverTooLong already means the owner's property over this module's variables. You only need to give the three properties the names the cfgs use.

Hint 2

Two of the owner's properties have the form [][...]_vars. A cfg checks those with PROPERTY, and state predicates with INVARIANT. Naming an action property as an invariant is an error, not a check.

Hint 3 (nearly the answer)

Three definitions in the module, each one name defined as the matching LK! property. In each cfg, one INVARIANT line for the state predicate and two PROPERTY lines.

06Explain it

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

After you writeCheck your explanation

Good: "I defined the owner's three properties through LK and checked them during the agent's replay; B's seed 8 log then fails NoRenewAfterExpiry at the late renewal, while A's log still passes. The fix assumes the owner's properties are right; if the owner had written them over Renew, they would pass B too. The agent's refusal matcher still accepts a server that refuses requests the spec would grant, and no property over the variables can object to a step that changes nothing."

Weak: "Adding the properties made the agent's TraceSpec catch B, so it is now as good as the owner's."

The weak answer misses the second half of the exercise. The matchers are unchanged and still restate the agent's reading; the properties are a net, and the refusal matcher has a hole that none of them covers (the lesson's fold on refusals says why).

07Your system

Milestone 7: a logging plan, a CONTRACT.md and a Props.tla for your system.

Work in my-system/ (run ./tla my-system init if you have not), in a private repository. Strip identifiers from anything you share, and do not paste proprietary designs, customer data or credentials into a third-party AI tool without your organisation's approval.

  1. Take the spec from your earlier milestones. List every action, including the environment's: crashes, timeouts, messages lost.
  2. Write the logging plan as a table: for each action, the code location that performs it, the record it writes, the fields, and the moment it is written (when the effect becomes visible). Add a row for every internal event your code logs that the spec has no action for, and say how the TraceSpec will treat it. Log only the fields the spec needs. Never log credentials, tokens or personal data; use opaque ids instead. Keep real logs in my-system/ (private), and never commit them as fixtures or paste them into a third-party tool.
  3. Write <YourModule>Props.tla: at least one invariant and one action property, stated over variables, never over action names. Break your spec on purpose once per property and see it fail.
  4. Write CONTRACT.md with the sections of specs/CONTRACT.md: what the service does, files and owners, interface, properties, logging plan, acceptance, out of scope. Name the owner of the spec and the properties.
  5. Check the properties on the spec with ./tla check, with a witness and full coverage.

Tick milestone 7 in my-system/MILESTONES.md when the properties pass on the spec and each has failed once on a broken copy.

Done?