11-03
Chapter 11 · Refinement is implication
Refinement mappings
00Recall
One card from 11-02 on which steps must match the abstract spec, one from chapter 08 on the alternating bit protocol, and one from chapter 05 on counting the functions in [S -> T]: each gives a value to every element of S, and the Warm-up's mapping must too. Chapter 08's protocol is back, and this time you get to say what it is for.
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.
08-04-a from Alternating bit
Why is one bit enough for stop-and-wait over a channel that keeps order, but not over one that reorders?
Show answer
When both the data and the ack channels keep order, only copies of the current and the previous message, and acks for them, can arrive, and the bit tells those two apart. With reordering, a copy of any older message or ack can arrive, and a bit cannot tell it from a new one.
05-02-a from Functions are total maps
How many functions does [S -> T] contain, for finite sets S and T?
Show answer
|T| to the power |S|: one independent choice of value from T for each element of S.
Skip recall Recall is never required.
01Commit
Chapter 08's alternating bit protocol sends messages over channels that lose them. Its promise was always "the receiver gets every message once, in order". specs/ReliableChannel.tla states that promise as an intent with three variables: sent, the messages handed over; q, those not yet delivered; out, those delivered. specs/AlternatingBit.tla has sent and out too, but no queue. It has a sender that is busy waiting for an ack, the sender's bit sbit, the receiver's expected bit rbit, and two lossy channels.
Commit a
To check that AlternatingBit implements ReliableChannel, the mapping must give q a value in every state of the protocol. Which works?
- q <- << >>: the protocol keeps no queue, so the abstract queue is empty.
- q <- the messages in the data channel: that is what is in transit.
- q <- the sender's current message while the sender waits and the receiver still expects its bit; otherwise << >>.
- None: ReliableChannel has a variable the protocol lacks, so no refinement check is possible.
Answer q <- the sender's current message while the sender waits and the receiver still expects its bit; otherwise << >>.
- If you picked A
- Then the sender takes a message, sent grows, and the abstract queue stays empty. ReliableChannel's Send grows sent and q together, so that step has no abstract explanation.
- If you picked B
- Follow the first step, Accept. sent grows, but nothing has been sent on the data channel yet, so the shadow q stays empty, and ReliableChannel's Send grows sent and q together. specs/InFlightABP.cfg runs this mapping.
- If you picked D
- A mapping is any expression over the protocol's variables, not a variable with the same name. The protocol has no variable called q, but its state still determines which message is in transit.
Commit b
The refinement check MCAlternatingBit.cfg explores the protocol and checks ReliableChannel's spec as a property. Compared with AlternatingBit.cfg alone, how many distinct states does it report?
- More: TLC also has to explore ReliableChannel's states.
- The same number.
- Fewer: the abstract spec rules some protocol states out.
Answer The same number.
- If you picked A
- ReliableChannel contributes no variables of its own here. Every one of its variables is replaced by an expression over the protocol's state, so there is nothing extra to explore.
- If you picked C
- A property does not prune the search; it is checked on what the search finds. If the abstract spec ruled a reachable state out, you would see a violation, not a smaller count.
02Lab
./tla check chapters/11-refinement/specs/AlternatingBit.cfg
./tla check chapters/11-refinement/specs/MCAlternatingBit.cfg11-refinement/specs/MCAlternatingBit11-refinement/specs/MCAlternatingBit MCAlternatingBit.cfg (Input<-ThreeMessages, Cap=2)
parse ok
model check: no violation found in 107 distinct states (365 generated, depth 19)
TLC warning: The formula ChanInit is a state-level formula, but it was used as a PROPERTY (or PROPERTIES), where a temporal formula is typically expected. State-level formulas used as PROPERTY or PROPERTIES are only checked in the initial state. To verify that the formula ChanInit holds in all states of every behavior, use INVARIANT ChanInit instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ChanInit changes it into a temporal formula, asserting that ChanInit holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.
expected outcome met: pass
coverage: all 7 actions fired
witness ShadowDone reached (trace of 12 states)Reveal for commit a
The working mapping is z. It is Pending in specs/MCAlternatingBit.tla, and TLC finds no violation of ChanInit or ChanStep, with the witness ShadowDone reached. Mapping y fails at once: specs/InFlightABP.cfg reports ChanStep violated after a trace of 2 states.
Reveal for commit b
The same: 107 distinct states alone, 107 in the refinement check.
03Reason
If you picked "none", you read refinement as renaming: look for the abstract spec's variables inside the implementation and match them up. That works for AtomicKV, whose store happens to live in one variable of ReplicatedKV. In general, a mapping gives each abstract variable an expression over the implementation's variables, whatever the implementation stores and however it stores it. Here is the one that works:
Pending is defined as IF busy and rbit = sbit THEN tuple of Input[sent] end tuple ELSE tuple of end tuple
Chan is defined as INSTANCE ReliableChannel WITH q <- Pendingsent and out are not mentioned, because AlternatingBit has variables with those names, and INSTANCE substitutes same-named variables for you. Only q needs a formula. How do you find one? Ask, for each kind of protocol state, which messages a perfect channel would be holding.
Write something before openingthe sender is not busy. Which messages are in transit?
None. The sender is idle only before the first message or after an ack for the last one it took, and an ack means the receiver already delivered it. So q is empty.
Write something before openingthe sender is busy and rbit = sbit. Has the receiver delivered the current message?
No. The receiver flips rbit when it delivers. While its expected bit still equals the bit the sender attaches, the current message, Input[sent], has been handed over and not delivered: exactly one message in transit. Once the receiver delivers and flips, rbit # sbit, and q is empty again, although the sender still waits for its ack.
As a table, the cases are:
| Protocol state | Has the receiver delivered Input[sent]? | q |
|---|---|---|
| sender idle | yes, or nothing taken yet | << >> |
sender busy, rbit = sbit | no | << Input[sent] >> |
sender busy, rbit # sbit | yes | << >> |
Each row is one branch of the IF. If two rows had needed different values while looking the same in the protocol's variables, there would be no IF to write. Those cases give Pending. Now check the steps against the intent. Accept takes the next message: sent grows and Pending becomes that message, which is ReliableChannel's Send. A delivering RcvData appends to out and flips rbit, so Pending empties, which is Deliver. Every resend, every loss, every stale ack leaves sent, q and out unchanged: stuttering steps of the channel. The protocol's whole machinery is invisible from above, which is what "reliable channel" means.
One convenience deserves a warning. INSTANCE fills in every abstract variable you do not mention with the implementation's variable of the same name. Here sent means the same thing in both modules, so that is right. If the protocol had used out for "messages handed to the network", the default would have mapped the wrong thing without a word, and the check might still pass. Read the abstract module's variable list and say, for each one, where its value comes from. "Same name" is a mapping too, and it deserves the same scrutiny as the one you wrote.
Notice also which way the check runs. It says every behavior of the protocol, seen through Pending, is a behavior of a perfect channel. It does not say every behavior of a perfect channel can happen in the protocol. A protocol that delivered nothing at all would pass the safety part too. That is the job of the shadow witness, and, in lesson 11-05, of liveness.
./tla check chapters/11-refinement/specs/MCLoggedRelay.cfgWrite something before openingwhat does the protocol's out mean, and what does ReliableChannel's out mean?
Read the protocol's variable list. Its out is the relay's log of what it forwarded; what the receiver delivered is got. INSTANCE matched the names and never asked what they mean, so the check judged the relay and never looked at the receiver. specs/MCLoggedRelay.got.cfg writes the mapping the intent means, out <- got, with q read off the relay's log and the outbox, and TLC reports GotStep violated after a trace of 7 states: the receiver puts each new message in front of the old ones. The default read the wrong variable, and TLC prints no warning for it.
The second COMMIT has a quieter surprise: the refinement check reports exactly as many distinct states as the protocol alone, although you added a second specification. TLC is not skipping ReliableChannel. In this check ReliableChannel has no state of its own: each of its variables is an expression over the protocol's state. TLC explores the protocol exactly as before, and at each step it evaluates Chan!Next on the old and new shadow. Checking a refinement costs time per step, not extra states. The abstract spec is a judge that sits beside the search, not a second search.
Write something before openingwhy does mapping y, "the messages in the data channel", fail at the very first step?
The first step is Accept: the sender takes message a, so sent becomes 1 in both views. Nothing has been sent yet, so the data channel is empty and the shadow q stays empty. ReliableChannel's Send adds to sent and to q in the same step, and no other abstract step changes sent alone. The data channel is the wrong variable: it holds copies of packets, while q holds messages.
04In your editor
The protocol, the intent and the check are in chapters/11-refinement/specs/. Check this lesson's exercises with:
./tla check 11-03The refinement check, with its shadow witness:
11-refinement/specs/MCAlternatingBit11-refinement/specs/MCAlternatingBit MCAlternatingBit.cfg (Input<-ThreeMessages, Cap=2)
parse ok
model check: no violation found in 107 distinct states (365 generated, depth 19)
TLC warning: The formula ChanInit is a state-level formula, but it was used as a PROPERTY (or PROPERTIES), where a temporal formula is typically expected. State-level formulas used as PROPERTY or PROPERTIES are only checked in the initial state. To verify that the formula ChanInit holds in all states of every behavior, use INVARIANT ChanInit instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ChanInit changes it into a temporal formula, asserting that ChanInit holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.
expected outcome met: pass
coverage: all 7 actions fired
witness ShadowDone reached (trace of 12 states)To find a mapping for your own system, make a table. One row per kind of implementation state, one column per abstract variable, and in each cell the abstract value a perfect implementation would show. Then write the cells as one IF ... THEN ... ELSE or CASE expression. If two rows that look identical in the implementation need different abstract values, no expression exists, and you have met lesson 11-05.
Keep the table, as a comment above the mapping. The next person to read the check needs it more than you did, and a reviewer can argue with a table far more easily than with a nested IF.
05Practice
Warm-up. Two shard servers each hold half the keys. Glue them into one AtomicKV.
Core. A channel built from two one-slot hops. Write Pending, the abstract queue, in the right order.
Stretch. The TaskBoard has a status per task and a log, but no queue. Write the queue's intent, the mapping and the cfg yourself.
11-03-ex1Warm-up5 min
11-03-ex1 · Glue the shards
Tier: warm-up. Time: about 5 minutes.
ShardedKV.tla splits the store across two shard servers. Shard A's map a covers only the keys in KeysA; shard B's map b covers only KeysB. Neither is the store. Together they should be.
- Run
./tla check 11-03-ex1. TLC reports that the very first state is not an initial state ofAtomicKV. The starter mapping reads the whole store off shard A. Why is that wrong before any step happens? - Fill gap g1 in
MCShardedKV.tla: one map over all ofKeys, each key's value taken from the shard that owns it.Keysis defined inShardedKVasKeysA \cup KeysB. - Run the check until it passes with the shadow witness
ShadowFullreached.
Hints: HINTS.md, under "11-03-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/11-refinement/exercises/03-ex1-glue-the-shards/; 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.
Done when: ./tla check 11-03-ex1 prints "goal met: pass".
./tla check 11-03-ex1
Repo chapters/11-refinement/exercises/03-ex1-glue-the-shards/
Hints
Hint 1
AtomicKV's store is a function over all of Keys. Shard A's map is a function over KeysA only. A function's domain is part of its value.
Hint 2
Build a new function with [k \in Keys |-> …]. For each key, the value comes from a or from b, depending on which set the key is in.
Hint 3 (nearly the answer)
Inside the function, the value for k depends on whether k is in KeysA. In each case, which shard's map do you read, and at which key? The whole function is what you substitute for store.
11-03-ex2Core8 min
11-03-ex2 · Two hops
Tier: core. Time: about 8 minutes.
TwoHopChannel.tla builds a channel out of two one-slot hops: the sender's outbox, then a relay, then the receiver. A message moves one hop per step. Two messages can be in flight at once, one in each slot. Check that it implements ReliableChannel, which has a queue q that this protocol does not.
- Run
./tla check 11-03-ex2.ChanStepfails on the first step. Compute the shadow by hand: what doesReliableChannel'sSenddo toq, and what does the starter'sPendingdo? - Fill gap g1 in
MCTwoHopChannel.tla:Pending, the messages handed over and not yet delivered, oldest first.Opt(slot)turns a slot into a sequence of zero or one messages, and\ojoins two sequences. - Run the check until it passes with the shadow witness
ShadowDonereached. - Swap the two halves of your
Pendingand run again. Read the trace: which step breaks, and why that one?
Hints: HINTS.md, under "11-03-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/11-refinement/exercises/03-ex2-two-hops/; 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.
Done when: ./tla check 11-03-ex2 prints "goal met: pass".
./tla check 11-03-ex2
Repo chapters/11-refinement/exercises/03-ex2-two-hops/
Hints
Hint 1
Ask, for each slot, whether a message in it has been handed over and not yet delivered. Both slots hold such messages.
Hint 2
The queue's head is the next message to be delivered. Which slot is nearer to the receiver?
Hint 3 (nearly the answer)
Opt turns one slot into a sequence of zero or one messages, and \o joins two sequences. Pending needs one Opt per slot. Which slot holds the older message, and so goes first?
11-03-ex3Stretch40 min · mastery path
11-03-ex3 · The board is a queue
Tier: stretch. Time: about 40 minutes. Off the core clock: this is on the mastery path.
The TaskBoard from chapters 06, 08 and 10 is back, in TaskBoard.tla. Each task has a status, log records the posting order, and each worker's holder entry names the task it holds. The team says "it's a work queue". Nothing on the board is a queue. Write the queue's intent, the mapping and the cfg, and find out.
- Run
./tla check 11-03-ex3. Three cfgs run. YourMCTaskBoard.cfgnames a spec and nothing else, so TLC stops: no value forTasks. The course'sMCTaskBoard.grader.cfgstops too: yourQueue'sInitis stillFALSE.MCQueue.cfgstops before it looks atInit: yourTypeOKis stillTRUE, and that cfg checks that it rules out a state of the wrong type. - In
Queue.tla, fill gaps g1 to g5:TypeOK,Init, and the three actions. A task joins the back if it is neither waiting nor held; a free worker takes the front; a worker finishes the task it holds. Two variables:qandholding. - In
MCTaskBoard.tla, fill gap g1: mapqto the tasks that are waiting, in the order they were posted, andholdingto what each worker holds. Look upSelectSeqin the standard moduleSequences. - In
MCTaskBoard.cfg, fill gap g1: the board's spec, three tasks, two workers, the board's own invariants, and both halves ofQ!Specas properties. Leave the header lines as they are. - Run the check until all three cfgs pass.
MCTaskBoard.grader.cfgchecks both halves ofQ!Specwith three witnesses:AllDoneon the board, and two on the shadow,ShadowTwoWaitingandShadowTwoHeld, so a mapping that never moves cannot pass. That is one direction, the board refines yourQueue, and an intent looser than a queue passes it too.MCQueue.cfgchecks the other side: yourQueuealone, with no board, must let only the front leave, add only at the back, and never have a task waiting twice or waiting while held; yourTypeOKmust rejectNonewaiting in the queue and a worker holding a worker. Leave both course cfgs,MCQueue.tlaand the witness definitions as they are. Your own cfg passes without itsPROPERTYlines; the grader checks those properties for you. - Break your mapping once on purpose: order
qby something other than the posting order. Which action of the board does TLC catch?
Leave TaskBoard.tla as it is: the exercise is to describe it, not to change it.
Hints: HINTS.md, under "11-03-ex3 hint 1" to "hint 3". The solution is in solutions/chapters/11-refinement/exercises/03-ex3-board-as-queue/; 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.
All three cfgs must meet their goal, "goal met: pass". You are done when every cfg prints its "goal met" line and none prints "goal not met" or "starter state". The run's last line, "3 of 3 checks met their expected outcome", is no sign of that: the untouched starter prints it too.
Done when: ./tla check 11-03-ex3 prints "goal met: pass".
./tla check 11-03-ex3
Repo chapters/11-refinement/exercises/03-ex3-board-as-queue/
Hints
Hint 1
Write the queue's intent first, with no thought of the board: what a queue of tasks and a set of holders do. Then ask what on the board says "waiting, in order".
Hint 2
A task is waiting exactly when its status is "open", and log keeps the order of posting. SelectSeq(s, Test) keeps the elements of s for which Test is true, in order. In the cfg, check QInit and QStep as properties, and the board's TypeOK and OneHolder as invariants.
Hint 3 (nearly the answer)
Map q to SelectSeq of log with a LAMBDA testing the task's status, and holding to holder. In Queue, Dequeue(w) sets holding[w] to Head(q) and q to Tail(q); Enqueue(t) needs t neither in q nor held.
06Explain it
Open NOTES.md and answer the three prompts under 11-03, about the Core exercise.
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:Compare your answers with "11-03 check your explanation" in HINTS.md.
After you writeCheck your explanation
A good answer: "Pending is the relay's message, then the outbox's, because the relay holds the older one. Forward moves a message between slots without changing its place in the queue, so it is a stutter of ReliableChannel. It relies on each slot holding one message and moving in order; a relay that could hold two, or overtake, would need a different expression. TLC checked three messages with no loss, and only safety: it did not check that a message is ever delivered."
A weak answer: "I wrote the queue as the two slots and TLC passed." It does not say why the order matters, and the swapped order, which fails, is also "the two slots".
Done?