05-04

Chapter 05 · Just enough set theory

CHOOSE is deterministic

  • 45 min core
  • Core track
  • Skills: abstraction, intent

00Recall

One card from 05-03 on the subsets of a set, one from 05-02 on EXCEPT, and one from 03-03 on how ./tla checks a witness. Today a model passes every check you know, including the witness, and is still wrong.

05-03-a from Records, sequences, SUBSET

List the elements of SUBSET {"read", "write"}.

Show answer

{}, {"read"}, {"write"} and {"read", "write"}. SUBSET includes the empty set and each element on its own.

05-02-b from Functions are total maps

Why does an action update a function with [f EXCEPT ![x] = v] and not with f'[x] = v?

Show answer

f'[x] = v only says what the new function is at x; it says nothing about the other points. EXCEPT names the whole new function: f everywhere, except v at x.

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.

Skip recall Recall is never required.

01Commit

A storeroom with two bins, left and right, each holding up to Cap = 3 units. A delivery brings between 1 and MaxDelivery = 2 units at once. A teammate wrote specs/ChosenDelivery.tla, and wrote "some delivery arrives" like this:

TLA+
\* "Some delivery arrives." The teammate wrote the size with CHOOSE.
Deliver(b) is defined as
    LET n is defined as CHOOSE k in 1..MaxDelivery : TRUE
    IN  and qty[b] < Cap
        and qtyprime = [qty EXCEPT ![b] = @ + n]

LET n == ... IN ... is read "let n be ..., in ...": it names a value for use in the formula after IN. CHOOSE k \in S : P is read "choose a k in S such that P". 1..MaxDelivery is the set of integers from 1 to MaxDelivery. Look at the guard too: it checks that the bin has room for one more unit, not for the whole delivery. The requirement is WithinCapacity: no bin ever holds more than Cap.

Commit a

TLC checks WithinCapacity on ChosenDelivery. What will it report?

  1. A violation: a delivery of 2 into a bin holding 2 overflows it.
  2. No violation, with every action firing and the witness reached.
  3. An error: CHOOSE needs exactly one k that satisfies its condition, and TRUE has two.

Answer No violation, with every action firing and the witness reached.

02Lab

The teammate's storeroom, then the same storeroom with the size written with \E:

shell
./tla check chapters/05-just-enough-set-theory/specs/ChosenDelivery.cfg
./tla check chapters/05-just-enough-set-theory/specs/AnyDelivery.cfg
Expected output 05-just-enough-set-theory/specs/ChosenDelivery
05-just-enough-set-theory/specs/ChosenDelivery  ChosenDelivery.cfg  (Bins={left, right}, Cap=3, MaxDelivery=2)
parse ok
model check: no violation found in 16 distinct states (49 generated, depth 7)
expected outcome met: pass
coverage: all 2 actions fired
witness BinFull reached (trace of 4 states)

Reveal for commit a

No violation, in 16 distinct states, with both actions firing and BinFull reached. AnyDelivery.tla changes one line, \E n \in 1..MaxDelivery : in place of the LET, and TLC finds the overflow after a trace of 3 states.

03Reason

If you picked "a violation", you read CHOOSE as "pick any". That is what the teammate meant, and it is not what the formula says.

So every delivery in the teammate's model has the same size.

Write something before openingwhich size did TLC's CHOOSE pick here? Work it out from the verdict, without opening any file.

One unit. If it had picked 2, the first delivery to a bin would bring it to 2, which is below Cap = 3, so the guard would allow a second delivery and the bin would hold 4. TLC found no violation, so that never happened, so the size was not 2. The only other choice is 1. The math does not say which element CHOOSE denotes; TLC picks one, the same one every time, and this model happens to make the choice visible.

Now look at what the passing run checked. WithinCapacity held. Both actions fired. The witness BinFull was reached: a bin did fill up, one unit at a time. Every check from chapter 03 came back green, and a delivery of two units into a nearly full bin, the one case that breaks the guard, was never even tried. Coverage counts actions, not values of n. A witness asks whether a state is reachable, and a full bin is reachable without the big delivery.

Write something before openinga state cannot remember how it was reached. So how could a check from chapter 03 have caught the missing delivery?

Give the state a memory. Add a variable that records the size of the most recent delivery, and the question "did a big delivery ever happen?" becomes a question about one state. Then break it on purpose, as in 03-03: claim that no delivery is ever MaxDelivery units, and demand a violation. With CHOOSE the claim holds, and that pass is the alarm. The Core exercise ships with exactly that variable and that claim, in a cfg of its own.

Here is what the one-line change finds:

  1. State 1 Initial state qty = (left :> 0 @@ right :> 0)
  2. State 2 Deliver qty (left :> 0 @@ right :> 0) becomes (left :> 2 @@ right :> 0)
  3. State 3 Deliver qty (left :> 2 @@ right :> 0) becomes (left :> 4 @@ right :> 0)

\E n \in 1..MaxDelivery : ... says "for some size n, this step happens". It allows one step per size, so TLC explores them all. That is how you model a choice the world makes: the supplier, the network, the user, the scheduler. CHOOSE is how you name a value the spec fixes.

Write something before openingthe teammate's run reached every combination of bin levels. So what did CHOOSE take away?

Steps, not states. One unit at a time still reaches every level from 0 to Cap = 3 in each bin, so the run found 16 distinct states, 4 × 4, every combination there is. What never happened is the step from a bin holding 2 straight to a bin holding 4. A distinct count can look complete while a whole kind of step is missing.

So is CHOOSE a mistake? No. It is the right tool when every possible choice gives the same answer. specs/InventoryLedger.tla keeps a ledger, a running total, and its requirement is that the ledger matches the shelves. Adding up the shelves needs a sum over a set of bins, and Naturals has no such operator, so the spec defines one:

TLA+
RECURSIVE Total(_)
Total(S) is defined as
    IF S = {} THEN 0
    ELSE LET b is defined as CHOOSE x in S : TRUE
         IN  qty[b] + Total(S set minus {b})

RECURSIVE Total(_) announces that Total, with one argument, refers to itself. Without it, SANY stops at the recursive call with "Unknown operator: Total'." (specs/UndeclaredTotal.tla). S \ {b}is read "S minus b". Each call takes one bin out withCHOOSE, counts it, and adds the total of the rest, until no bins are left. Here CHOOSEmay pick any bin it likes: addition does not care about order, so every choice gives the same sum. WithBins = {left, right}andCap = 2, TLC finds no violation of LedgerMatchesin {{fact 05-just-enough-set-theory/specs/InventoryLedger distinct}} distinct states, every action firing and the witnessAllFull` reached.

Write something before openingis the b in LET b == ... a variable that each call of Total sets?

No. LET makes a local definition, not an assignment. Within one call, b means one value everywhere it appears, and nothing can change it. The next call of Total has a different S, so its CHOOSE may name a different bin, but that is a new definition in a new expression. TLA+ has no assignment anywhere: not in actions, not in LET. TLC's messages do talk about assigning x': while it computes successors, TLC treats a first x' = e as fixing x'. That is how the tool evaluates the formula, not a feature of TLA+.

A recursive definition must also stop. Total stops because each call removes one bin, so the set shrinks to {}, where the THEN branch answers without recursing. A recursion whose argument never shrinks is not a definition TLC can evaluate: specs/RunawayTotal.tla calls Total(S) on the same set, and TLC stops with "This was a Java StackOverflowError." instead of a verdict.

The rule fits in one line: use CHOOSE to name a value whose choice cannot matter; use \E for a choice the system or its environment makes.

04In your editor

The specs are in chapters/05-just-enough-set-theory/specs/. Check this lesson's exercises with:

shell
./tla check 05-04

The ledger, with its recursive total:

Output 05-just-enough-set-theory/specs/InventoryLedger
05-just-enough-set-theory/specs/InventoryLedger  InventoryLedger.cfg  (Bins={left, right}, Cap=2)
parse ok
model check: no violation found in 9 distinct states (25 generated, depth 5)
expected outcome met: pass
coverage: all 2 actions fired
witness AllFull reached (trace of 5 states)

Two more specs in the folder show recursion going wrong, one at each stage: UndeclaredTotal.cfg is rejected by SANY, and RunawayTotal.cfg gets past SANY and stops TLC with an error.

shell
./tla check chapters/05-just-enough-set-theory/specs/UndeclaredTotal.cfg
./tla check chapters/05-just-enough-set-theory/specs/RunawayTotal.cfg

When you review someone else's spec, search it for CHOOSE. For each one, ask: if this picked a different element, could anything the spec checks come out differently? If yes, ask who makes the choice: if the system or its environment does, use \E; if the cfg should fix it, make it a constant. The same audit applies to an AI-written spec, and most of all when its summary cites green coverage and reached witnesses as evidence: this lesson's model had both.

LET is useful well beyond CHOOSE. Whenever a guard and an update both need the same expression, name it once: LET free == {s \in Seats : seat[s] = Free} IN ... reads better than the filter written out twice, and a reviewer can check the definition in one place. A LET name is visible only in the formula after IN. It must still be a new name: SANY rejects a LET that reuses a name already defined or declared in the module, with "Operator qty already defined or declared." for a LET qty == ... in a module whose variable is qty (specs/ReusedLetName.tla). It costs nothing in states: it is shorthand, not a variable. If you notice that the same LET appears in several actions, promote it to an ordinary definition at the top level, the way SeatsOf is in 05-02.

Recursion works the same way for any set you can take apart. A count of the empty bins or a sum of what the bins hold has the shape of Total: an answer for {}, and a step that removes one element. Before you write one, ask whether its CHOOSE can matter. For a sum it cannot. For "the first bin with room", it can, and you are back at the top of this lesson.

05Practice

Warm-up. Finish the recursive Total, so that TLC can check that the ledger matches the shelves.

Core. The teammate's storeroom, with a ledger and a record of the last delivery. Make every delivery size possible, and when a delivery does not fit, keep what fits and send the rest back.

05-04-ex1Warm-up5 min

05-04-ex1 · Count the shelves

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

The storeroom ledger from the lesson, with the recursive Total unfinished: for a nonempty set of bins it returns 0.

  1. Run ./tla check 05-04-ex1. TLC refutes LedgerMatches after the first delivery. Which side of the equation is wrong?
  2. Fill gap g1: for a nonempty S, pick any bin b of S with CHOOSE, and add qty[b] to the Total of the other bins of S. Name the bin with LET.
  3. Run the check.

If you forget to take b out of S before the recursive call, Total calls itself on the same set forever, and TLC stops with an error instead of a verdict.

The check also runs MCInventoryLedger.cfg, the course's test of your Total: a clerk who never writes in the ledger, so the ledger stays at 0 while the shelves fill. There LedgerMatches must fail. A Total that passes there is not counting the shelves. Leave the two MC files as they are.

Hints: HINTS.md, under "05-04-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/05-just-enough-set-theory/exercises/04-ex1-count-the-shelves/; 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.

Both cfgs must meet their goals, each in its own block of output: "goal met: pass" for InventoryLedger.cfg and "goal met: violation LedgerMatches" for MCInventoryLedger.cfg. Read each block's goal line, not only the last line.

Done when: ./tla check 05-04-ex1 prints "goal met: pass".

./tla check 05-04-ex1

Repo chapters/05-just-enough-set-theory/exercises/04-ex1-count-the-shelves/

Hints

Hint 1

The THEN branch handles the empty set. The ELSE branch must do some real counting.

Hint 2

Name one bin of S with LET and CHOOSE. Then the total is that bin's units plus the total of the rest.

Hint 3 (nearly the answer)

Use LET to name a bin b chosen from S with the condition TRUE. After IN, add qty[b] to a recursive call of Total on the set S with b removed, written with \.

05-04-ex2Core8 min

05-04-ex2 · Any delivery

Tier: core. Time: about 8 minutes.

The teammate's storeroom from the lesson, now with the ledger and two variables that remember the most recent delivery: last, the size the driver offered, and back, the units the driver carried back. Deliver still picks its size with CHOOSE, and still guards on room for one unit.

The storeroom has a new rule, which the lesson's AnyDelivery does not follow: a driver may offer any size from 1 to MaxDelivery, and when an offer does not all fit, the bin takes what fits and the driver carries the rest back. A full bin is not offered anything: Deliver is not enabled there. The cfg checks that with NeverAllBack: no delivery sends the whole offer back. NoEmptyOffer checks that no offer is of zero units.

  1. Run ./tla check 05-04-ex2. All three cfgs pass, and nothing is over capacity. That is the trap from the lesson.
  2. Change Deliver (gap g1) so that every offer size can arrive. Run the check and read the trace.
  3. Then make the bin take only what fits: the shelves and the ledger gain that many units, last records the offer, and back records what went back. Delete the \* GAP marker on the first line of Deliver when you are done.
  4. Run the check until InventoryLedger.cfg passes with every action firing and the witness reached: an offer of one unit.

The check also runs two course cfgs, each a claim that a correct storeroom must break. InventoryLedger.fulldelivery.cfg claims that no offer is ever MaxDelivery units; InventoryLedger.carryback.cfg claims that the driver never carries anything back. Leave both files as they are.

Hints: HINTS.md, under "05-04-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/05-just-enough-set-theory/exercises/04-ex2-any-delivery/; 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 goals, each in its own block of output: "goal met: pass" for InventoryLedger.cfg, "goal met: violation NoFullDelivery" for InventoryLedger.fulldelivery.cfg and "goal met: violation NothingCarriedBack" for InventoryLedger.carryback.cfg. Read each block's goal line, not only the last line.

Done when: ./tla check 05-04-ex2 prints "goal met: pass".

./tla check 05-04-ex2

Repo chapters/05-just-enough-set-theory/exercises/04-ex2-any-delivery/

Hints

Hint 1

The starter passes because CHOOSE always picks the same size. Which offer sizes did TLC explore? Lesson 05-04 shows how to let every size happen.

Hint 2

Put \E n \in 1..MaxDelivery : over the action, then use LET to name the number of units the bin takes. It is all n when they fit, otherwise the room left, Cap - qty[b].

Hint 3 (nearly the answer)

Under \E n, name fits with LET and an IF ... THEN ... ELSE. Keep the guard that the bin has room for at least one unit. Add fits to the bin and to the ledger, set last to n, and set back to the difference between the offer and what fit.

06Explain it

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

After you writeCheck your explanation

A good answer: "Deliver now uses \E n \in 1..MaxDelivery, so TLC tries every offer size, and the bin takes fits, all n or the room left, with the rest recorded in back. With CHOOSE, every offer had the same size and the overflow was never tried, though coverage was green. It assumes the driver always takes back what does not fit; a storeroom that could put overflow in another bin would need a different action. TLC checked two bins with Cap = 3 and MaxDelivery = 2."

A weak answer: "CHOOSE was wrong, so I used \E." It does not say what CHOOSE hid, why the passing checks missed it, or what the fix assumes.

Done?