Ran Wei/ Formal methods/Module 13
中文
Formal Methods with Isabelle · Part IV · Verification

Module 13Modelling systems: state machines and invariants

Describe a system as a state machine and prove in Isabelle that nothing bad ever happens in it. You will model states, events, guards and effects, define the reachable states, prove safety properties with invariants, strengthen an invariant that is not inductive, turn a counterexample into a trace, and carry what you proved about an abstract model over to a more concrete one.

⏱ 230 minYou need: Modules 1–12

In this module you will

  • Model a system as a state machine with states, an initial state, and events that have guards and effects
  • Define the transitions and the reachable states of a model with inductive, and relate reachability to r⇧*
  • Prove a safety property by rule induction with an invariant, and strengthen an invariant that is not inductive
  • Find a run that breaks a faulty design with Quickcheck or Nitpick, read it as a trace, and fix the design
  • Prove that a concrete model refines an abstract one, so that the abstract invariants hold in the concrete model
  • Tell safety from liveness, and name the tools that check liveness
1

Systems that react

The programs you verified in Module 12 compute a result: they take a list and return it sorted, or take a tree and a key and return a new tree. Their specification relates the output to the input. Many systems do not work like that. A traffic light controller, a lift, a network protocol, a bank and an operating system are often intended to run indefinitely. They keep a state, and react to events: a button is pressed, a timer runs out, a message arrives. One central question is: “Can the system ever get into a bad state?” Two trains on the same piece of track, a lift that moves with its door open, a lock held by two processes at once: these are bad states, and the system must never reach one, however its enabled events are chosen and however long it runs.

This module describes such systems as state machines and proves in Isabelle that no reachable state is bad. The method is the invariant of Module 5, now on systems with many events, together with the inductive definitions and rule induction of Module 11.

Start with a small system, the door of a lift. The door is open, closing or closed, and the lift is moving or not. Five events can happen. Each has a guard, a condition on the current state that says when the event can happen, and an effect, which says how the event changes the state.

Example 13.1The lift door

The state has two parts: the door (Open, Closing or Closed) and whether the lift moves. Initially the door is closed and the lift stands still.

Event Guard: it can happen when Effect
open the lift does not move the door becomes Open
close the door is Open the door becomes Closing
shut the door is Closing the door becomes Closed
start the door is Closed the lift moves
stop always the lift stops

The event shut is the door mechanism reporting that the door has finished closing. The guard of open allows the door to reopen while it is closing, as real lift doors do when someone steps in.

Module 4 introduced state machines, with a door and its lock as the example, and found their reachable states with the closure r⇧*. This module uses the same definition and describes the steps by events.

Definition 13.1State machine

A state machine, or transition system, consists of a set of states, a set of initial states, and a transition relation: s→ts \to t means that the machine can go from state ss to state tt in one step. In this module the steps are described by events. An event can happen in state ss when its guard holds in ss⁠, and it leads to the state given by its effect.

Definition 13.2Run, trace and reachable state

A run is a sequence of states s0→s1→s2→…s_0 \to s_1 \to s_2 \to \dots⁠, finite or infinite, that starts in an initial state and follows the transition relation. An event trace records its events: a finite list for a finite run, or an infinite sequence for an infinite run. Given an initial state and deterministic event effects, the events determine the states; this need not hold for a nondeterministic machine. A state is reachable if a finite run leads to it.

Here is a run of the lift, from the initial state, with the events written over the arrows:

(Closed,still)→ open (Open,still)→ close (Closing,still)→ shut (Closed,still)→ start (Closed,moving)(\mathit{Closed}, \text{still}) \xrightarrow{\ \mathit{open}\ } (\mathit{Open}, \text{still}) \xrightarrow{\ \mathit{close}\ } (\mathit{Closing}, \text{still}) \xrightarrow{\ \mathit{shut}\ } (\mathit{Closed}, \text{still}) \xrightarrow{\ \mathit{start}\ } (\mathit{Closed}, \text{moving})

Its trace is open, close, shut, start. The machine has 3×2=63 \times 2 = 6 states, and four of them are reachable. The other two are the dangerous ones:

Door Lift Reachable?
Closed still yes, it is the initial state
Open still yes, by open
Closing still yes, by open, close
Closed moving yes, by start
Open moving no
Closing moving no

Why can the lift never move with its door open or closing? With six states you can check every state and every event by hand. A real controller has many more states, and a model with a counter or a queue can have infinitely many. A finite-state model checker analyses reachable states explicitly or in symbolic groups (Module 1). Induction applies to finite and infinite state spaces; finding a suitable invariant is the work this module teaches.

Good to know

A model is a decision about what to leave out. The lift model has no floors, no passengers, no motor and no time. A proof about the model says nothing about what the model leaves out; as Module 1 put it, a proof shows that the model meets its specification, and only validation shows that the model and the specification describe the real lift. Choose what goes into a model by the property you want to prove: here, the door and the motion.

2

State machines in Isabelle

In Isabelle, describe the states with types you know, the transitions with an inductive definition (Module 11), and the reachable states with another one. A state of the lift is a pair: the door, and a Boolean that is True when the lift moves.

Isabelle
datatype door = Open | Closing | Closed

inductive lstep :: "door × bool ⇒ door × bool ⇒ bool" where
  open_door:  "¬ m ⟹ lstep (d, m) (Open, m)"
| close_door: "d = Open ⟹ lstep (d, m) (Closing, m)"
| shut_door:  "d = Closing ⟹ lstep (d, m) (Closed, m)"
| start_lift: "d = Closed ⟹ lstep (d, m) (d, True)"
| stop_lift:  "lstep (d, m) (d, False)"

lstep s t says that one step leads from state s to state t: it is the transition relation. Each rule is one event of Example 13.1. The premise of a rule is the guard of its event, and the conclusion relates the state before the event to the state after it; the effect is the difference between the two. Rule start_lift reads: if the door is closed, one step leads from (d, m) to (d, True), the same door with the lift moving. Rule stop_lift has no premise, because stopping is always possible.

The reachable states are those you get from the initial state by any number of steps:

Isabelle
inductive lreach :: "door × bool ⇒ bool" where
  init: "lreach (Closed, False)"
| step: "lreach s ⟹ lstep s t ⟹ lreach t"

Rule init makes the initial state reachable. Rule step says that one step from a reachable state leads to a reachable state. Nothing else is reachable, because an inductive definition defines the smallest predicate closed under its rules (Module 11). Each finite run gives a derivation of its final state’s reachability. An infinite run has such a derivation for every finite prefix. Here is the run to (Closing, False), step by step, in Isar (Module 10):

Isabelle
lemma "lreach (Closing, False)"
proof -
  have "lreach (Closed, False)" by (rule lreach.init)
  moreover have "lstep (Closed, False) (Open, False)" by (rule open_door) simp
  ultimately have "lreach (Open, False)" by (rule lreach.step)
  moreover have "lstep (Open, False) (Closing, False)" by (rule close_door) simp
  ultimately show "lreach (Closing, False)" by (rule lreach.step)
qed

Each lstep fact is one event of the run, proved with its rule: rule open_door leaves the guard ¬ False to prove, which simp does. Each ultimately adds the step to the run with rule lreach.step.

To prove something about every reachable state, you need the induction rule of lreach:

Isabelle
thm lreach.induct
Output
⟦lreach ?x; ?P (Closed, False); ⋀s t. ⟦lreach s; ?P s; lstep s t⟧ ⟹ ?P t⟧
⟹ ?P ?x

Read it as the invariant method of Module 5. To prove that a property ?P holds in every reachable state ?x, prove that it holds in the initial state, and that one step from a reachable state with ?P leads to a state with ?P. Section 13.3 uses this rule.

Reachability is a closure

In Module 4 you met the reflexive–transitive closure r⇧* of a relation r: the pairs (a, b) such that b can be reached from a in zero or more steps of r. The reachable states of the lift are the states s with ((Closed, False), s) in the closure of the step relation. Isabelle proves that the two definitions agree:

Isabelle
lemma lreach_rtrancl: "lreach s ⟷ ((Closed, False), s) ∈ {(s, t). lstep s t}*"
proof
  assume "lreach s"
  then show "((Closed, False), s) ∈ {(s, t). lstep s t}*"
    by induction (auto intro: rtrancl_into_rtrancl)
next
  assume "((Closed, False), s) ∈ {(s, t). lstep s t}*"
  then show "lreach s"
    by induction (auto intro: lreach.intros)
qed

{(s, t). lstep s t} is the step relation as a set of pairs, and ⇧* (type ^*) is the closure. In each half, then passes the assumption to the induction method, which then needs no arguments: it inducts on that fact with the fact’s own induction rule. The first half is a rule induction on lreach s. The second is an induction on the closure, with the library’s rule rtrancl_induct. The library rule rtrancl_into_rtrancl adds one step at the end of a path, as lreach.step does.

You could work with r⇧* directly. A definition of your own, such as lreach, gives its induction rule exactly the two cases of the invariant method, with names you choose, and builds the initial state into the definition. Module 11 defined reachability with the step at the front instead (steps). For invariants, the step at the end is more convenient: the induction hypothesis is then about the state before the last step, exactly as in the invariant method, and the initial state stays fixed. With the step at the front, a rule induction about the runs from one initial state meets the problem that Module 11 met with steps move Done s: the induction rule replaces the start of the run by a variable.

3

Safety properties and invariants

The property you want for the lift is that it never moves unless its door is closed. Properties of this kind have a name.

Definition 13.3Safety property

A safety property says that something bad never happens. In this module the bad thing is a bad state, so a safety property is a property of states that must hold in every reachable state. A run that reaches a state where it fails is a counterexample to it.

Definition 13.4Invariant and inductive invariant

A property II of states is an invariant of a state machine if it holds in every reachable state. It is inductive if it holds in every initial state and every step from a state that satisfies II leads to a state that satisfies II⁠.

Module 5 called a property an invariant when it holds initially and every step preserves it, which is the second notion. From now on the difference matters: every inductive property is an invariant, but Section 13.5 shows an invariant that is not inductive.

Fact 13.1Inductive invariants hold in every reachable state

If II is inductive, then II holds in every reachable state.

The proof is a rule induction over reachability: II holds in the initial state, and the rule for a step passes II from a reachable state to the next one. In Isabelle, write the safety property of the lift as a function of the state, and start the rule induction:

Isabelle
fun lift_ok :: "door × bool ⇒ bool" where
  "lift_ok (d, m) = (m ⟶ d = Closed)"

lemma lift_safe: "lreach s ⟹ lift_ok s"
  apply (induction rule: lreach.induct)
Output
proof (prove)
goal (2 subgoals):
 1. lift_ok (Closed, False)
 2. ⋀s t. ⟦lreach s; lift_ok s; lstep s t⟧ ⟹ lift_ok t

Subgoal 1 is the base case: the initial state is safe. Subgoal 2 is the induction step: for a reachable state s that is safe and a step from s to t, the state t is safe. Both follow from the rules of lstep:

Isabelle
  apply (auto elim: lstep.cases)
  done

lstep.cases is rule inversion (Module 11): from lstep s t it produces one case for each rule, with s and t replaced by the states in that rule and the guard as an assumption. In four of the five cases the new state is safe whatever the old state was: open needs a lift that stands still and keeps it still, start needs a closed door, and shut and stop lead to a closed door or a still lift. In the case close, the induction hypothesis matters. The door was open, so by lift_ok s the lift did not move, and the new state (Closing, False) is safe. That is why an invariant proof needs the induction hypothesis: an event that leaves part of the state alone relies on that part being safe already.

The theorem answers the question of Section 13.1:

Isabelle
corollary "¬ lreach (Open, True)"
  using lift_safe by force

Isabelle treats corollary and theorem exactly as it treats lemma. The words tell the reader what role a result plays: a theorem is a main result, and a corollary follows directly from one.

Watch out

State the property for a state variable, not for a pattern. This version looks the same, but fails:

Isabellefails on purpose
lemma "lreach (d, m) ⟹ m ⟶ d = Closed"
  by (induction rule: lreach.induct) (auto elim: lstep.cases)
Output
Failed to finish proof⌂:
goal (1 subgoal):
 1. m ⟹ d = Closed

The goal left over is false: it claims that for the d and m of the lemma, a moving lift has a closed door. The argument of lreach is the pair (d, m), not a variable, and the induction rule is about a variable state ?x. Given a pattern, the method does not replace d and m by the states of the rules; they stay as they are, so the base case asks for the claim about d and m instead of about (Closed, False). Module 11 met the same problem with a constant. Write the property as a function of the whole state, as lift_ok does, and the induction works.

4

Modelling a pedestrian crossing

The rest of the module works with one larger system: a pedestrian crossing with a push button. Cars see a traffic light (green, amber, red); pedestrians see a signal (walk or don’t walk). The controller should meet these requirements:

  • R1. Pedestrians may walk only when the cars have red.
  • R2. After someone presses the button, the pedestrians eventually get to walk.

R1 is a safety property, and Sections 13.5 to 13.7 prove it. R2 is of another kind, which Section 13.8 discusses.

States as records

The state has three parts: the car light, the pedestrian signal, and whether a request is pending (the button was pressed and the pedestrians have not walked yet). A pair would do for two parts. For three or more, give the parts names with a record: a tuple whose components, its fields, have names.

Isabelle
datatype light = Green | Amber | Red
datatype signal = Walk | DontWalk

record crossing =
  cars :: light
  peds :: signal
  req  :: bool

The record command defines the type crossing and, for each field, a function that selects it: if s is a crossing, cars s is its car light. A record value lists its fields in brackets, as in ⦇cars = Green, peds = DontWalk, req = False⦈; type ⦇ as (| and ⦈ as |). The notation s⦇cars := Amber⦈ is the update of a field: the crossing s with its car light changed to amber and the other fields unchanged. The simplifier knows how selectors and updates interact, so that it rewrites cars (s⦇req := True⦈) to cars s by itself.

Isabelle
definition start :: crossing where
  "start = ⦇cars = Green, peds = DontWalk, req = False⦈"

value "start⦇cars := Amber⦈"
Output
"⦇cars = Amber, peds = DontWalk, req = False⦈"
  :: "crossing"
If something went wrong

An update needs :=. With =, Isabelle reads ⦇cars = Amber⦈ as a record value, which must list every field of the record, in the order of the record command:

Isabellefails on purpose
value "start⦇cars = Amber⦈"
Output
exception TERM raised⌂:
  Error in record input: expecting more fields
  ??.cars = Amber::<position>

The message says that the record value lacks fields; ??.cars = Amber is the field that Isabelle read, in its internal form. Write start⦇cars := Amber⦈.

Events with guards and effects

The controller reacts to six events. The button press comes from outside; the other five are the controller’s own decisions.

Event Guard Effect
Press always the request is set
ToAmber cars have green and a request is pending cars get amber
ToRed cars have amber cars get red
StartWalk cars have red, pedestrians don’t walk, a request is pending pedestrians walk
EndWalk pedestrians walk pedestrians stop; the request is cleared
ToGreen cars have red and no request is pending cars get green

Notice how the design uses the request. It stays set until the walk has ended, and the cars get green only when no request is pending. For the lift, each event was a rule of an inductive definition. This time, write the guards and the effects as two functions. Functions can be computed with value, so you can run the model, which will matter when you look for bugs in Section 13.6.

Isabelle
datatype event = Press | ToAmber | ToRed | StartWalk | EndWalk | ToGreen

fun guard :: "event ⇒ crossing ⇒ bool" where
  "guard Press s = True"
| "guard ToAmber s = (cars s = Green ∧ req s)"
| "guard ToRed s = (cars s = Amber)"
| "guard StartWalk s = (cars s = Red ∧ peds s = DontWalk ∧ req s)"
| "guard EndWalk s = (peds s = Walk)"
| "guard ToGreen s = (cars s = Red ∧ ¬ req s)"

fun effect :: "event ⇒ crossing ⇒ crossing" where
  "effect Press s = s⦇req := True⦈"
| "effect ToAmber s = s⦇cars := Amber⦈"
| "effect ToRed s = s⦇cars := Red⦈"
| "effect StartWalk s = s⦇peds := Walk⦈"
| "effect EndWalk s = s⦇peds := DontWalk, req := False⦈"
| "effect ToGreen s = s⦇cars := Green⦈"

The transition relation of the crossing is: s→ts \to t when tt = effect e s for some event e whose guard holds in ss⁠. The function run takes a list of attempted events. An event whose guard is false cannot happen, so run skips that attempt. Removing the skipped attempts gives an actual event trace from the chosen starting state:

Isabelle
fun run :: "event list ⇒ crossing ⇒ crossing" where
  "run [] s = s"
| "run (e # es) s = run es (if guard e s then effect e s else s)"

value "run [Press, ToAmber, ToRed, StartWalk] start"
Output
"⦇cars = Red, peds = Walk, req = True⦈"
  :: "crossing"

A pedestrian pressed the button, the car light went through amber to red, and the pedestrians walk. Now the same events without the press:

Isabelle
value "run [ToAmber, ToRed, StartWalk] start"
Output
"⦇cars = Green, peds = DontWalk, req = False⦈"
  :: "crossing"

Nothing happened. Without a request the guard of ToAmber is false, and while the car light is green, the guards of ToRed and StartWalk are false too, so run skips all three events. Figure 13.1 shows every state that runs can reach.

The pedestrian crossing as a state machinecars = Greenpeds = DontWalkreq = Falsecars = Greenpeds = DontWalkreq = Truecars = Amberpeds = DontWalkreq = Truecars = Redpeds = DontWalkreq = Falsecars = Redpeds = Walkreq = Truecars = Redpeds = DontWalkreq = TruestartPressToAmberToRedStartWalkEndWalkToGreenPressIn a state where req is already True,Press changes nothing.
Figure 13.1

The reachable states of the crossing and the events between them. In each box, the small light shows the car light. The thick box is the initial state start.

The reachable states are defined as for the lift, with a rule for the initial state and a rule for one event:

Isabelle
inductive reach :: "crossing ⇒ bool" where
  init: "reach start"
| step: "reach s ⟹ guard e s ⟹ reach (effect e s)"

thm reach.induct
Output
⟦reach ?x; ?P start; ⋀s e. ⟦reach s; ?P s; guard e s⟧ ⟹ ?P (effect e s)⟧
⟹ ?P ?x

The induction rule has the same two cases as before. In the induction step, the event e is arbitrary: a proof must deal with every event whose guard holds in a reachable state.

5

When an invariant is not inductive

Requirement R1 says: if the pedestrians walk, the cars have red.

Isabelle
definition safe :: "crossing ⇒ bool" where
  "safe s ⟷ (peds s = Walk ⟶ cars s = Red)"

The proof that fails

Try the proof of the lift. In Isar, with one case for the initial state and one for an event, and cases e to consider every event in turn:

Isabellefails on purpose
theorem "reach s ⟹ safe s"
proof (induction rule: reach.induct)
  case init
  show ?case by (simp add: safe_def start_def)
next
  case (step s e)
  then show ?case by (cases e) (auto simp: safe_def)
qed
Output
Failed to finish proof⌂:
goal (1 subgoal):
 1. ⟦reach s; e = ToGreen; cars s = Red; ¬ req s; peds s = Walk⟧ ⟹ False

The base case went through, and so did five of the six events. The goal that is left belongs to ToGreen. Read it as a state: the cars have red, no request is pending, and the pedestrians walk. The state is safe, because the cars have red. The guard of ToGreen holds in it, because the cars have red and no request is pending. After ToGreen the cars have green while the pedestrians walk, which is not safe. So safe is not inductive: a step from a safe state can lead to an unsafe one.

You can ask Isabelle for such a step directly. The lemma below says that every event preserves safe, from any state, reachable or not. Quickcheck tests it:

Isabelle
lemma "safe s ⟹ guard e s ⟹ safe (effect e s)"
  quickcheck
  oops
Output
Testing conjecture with Quickcheck-exhaustive...

Quickcheck found a counterexample:
  s = ⦇cars = Red, peds = Walk, req = False⦈
  e = ToGreen

A state and an event that break the induction step in this way are a counterexample to induction. Isabelle does not know whether this state can occur. There are two possibilities, and they call for different actions:

  1. The state is reachable. Then some run leads to it, the next ToGreen makes it unsafe, and the design is wrong. Section 13.6 shows this case.
  2. The state is not reachable. Then the design may well be safe, but safe is too weak to carry the induction: it allows states that never occur, and the induction step fails on one of them.

Quickcheck cannot execute this inductive reach predicate as currently defined: it has no code equations (Module 11). A separate executable reachability procedure or a search over event lists can help, but the direct call fails:

Isabellefails on purpose
lemma "reach s ⟹ safe s"
  quickcheck
  oops
Output
No code equations for reach,
requested by dependencies

Nitpick (Module 9) works differently: it searches for a model of the definitions, and it handles inductive definitions. Let it search the reachable states for an unsafe one:

Isabelle
lemma "reach s ⟹ safe s"
  nitpick
  oops
Output
Nitpicking formula...

Nitpick found no counterexample

Nitpick reports no counterexample within its search bounds. That does not establish unreachability. Find out on paper why the state of the goal cannot be reached. The pedestrians start to walk only through StartWalk, whose guard needs a request. While they walk, the request stays set, since only EndWalk clears it, and EndWalk also ends the walk. So in every reachable state: if the pedestrians walk, a request is pending. The state in the goal violates exactly this.

Strengthen the invariant

Add the missing fact to the property you prove. The new invariant says that pedestrians walk only when the cars have red and a request is pending:

Isabelle
definition invar :: "crossing ⇒ bool" where
  "invar s ⟷ (peds s = Walk ⟶ cars s = Red ∧ req s)"

lemma reach_invar: "reach s ⟹ invar s"
proof (induction rule: reach.induct)
  case init
  show ?case by (simp add: invar_def start_def)
next
  case (step s e)
  then show ?case by (cases e) (auto simp: invar_def)
qed

The proof is the same as before, and this time it goes through. Check the critical event on paper: in a state that satisfies invar, the guard of ToGreen says that no request is pending, so by invar the pedestrians do not walk, and turning the cars green is safe. The other events keep invar too: Press only sets the request; StartWalk needs red and a request, and keeps both; EndWalk ends the walk; ToAmber and ToRed happen only when the cars do not have red, so by invar the pedestrians do not walk. Safety follows at once, because invar says more than safe:

Isabelle
theorem crossing_safe: "reach s ⟹ safe s"
  using reach_invar by (simp add: invar_def safe_def)

The crossing has 3×2×2=123 \times 2 \times 2 = 12 states, few enough to draw them all. Figure 13.2 shows how the three sets of states fit together.

Reachable states, an inductive invariant and the safety propertyall 12 statessafe: 8 statesinvar: 7 states, inductivereachable: 6 statesnot safeGreenDontWalk¬ reqGreenDontWalkreqAmberDontWalkreqRedDontWalk¬ reqRedWalkreqRedDontWalkreqAmberDontWalk¬ reqRedWalk¬ reqGreenWalkreqAmberWalkreqGreenWalk¬ reqAmberWalk¬ reqToGreen
Figure 13.2

The 12 states of the crossing. The 6 reachable states (the thick box is start) lie inside the 7 states that satisfy invar, which lie inside the 8 states that satisfy safe. No step leads out of invar. From the one state that satisfies safe but not invar (cars red, pedestrians walking, no request), the event ToGreen leads out of safe.

Key idea

To prove that every reachable state is safe, find an inductive invariant in between: a set of states that contains the initial state, that no step leaves, and that contains only safe states. The reachable states themselves form such a set, but you rarely have a description of them. The safety property itself is often too large, because it contains unreachable states from which a step leads out. Strengthening the invariant shrinks it, by adding facts that hold in every reachable state, until no step leads out.

When a preservation check has a counterexample, it can suggest what to add. If the design is safe, a state satisfying the candidate property with an unsafe successor must be unreachable. Find a fact about reachable states that excludes it, add that fact with ∧, and try again. A larger system may need several rounds. A failed proof method alone does not produce a counterexample; it may instead need another lemma or more suitable automation.

Watch out
  • Adding a fact that is false. A fact that fails in some reachable state cannot be part of an invariant: the base case or the induction step fails, however many rounds you add. Test a candidate first: nitpick on reach s ⟹ invar s should find no counterexample. A fact that is true but not preserved together with the rest makes the induction step fail too; then you need another round.
  • Trying a stronger proof method. No method can prove the failed induction step for safe from safe s and the guard alone: that claim is false, as Quickcheck showed. The induction step also has the premise reach s, but using it needs a fact about all reachable states, which is the invariant you are looking for. A different method or an existing reachability lemma might solve that full goal; what no sound method can prove is the false preservation claim with reach s omitted.
6

Counterexample traces

Not every failed proof is a weak invariant. Sometimes the design is wrong, and then you want to see how.

Suppose a colleague proposes a change: the request has been served as soon as the pedestrians start to walk, so StartWalk should clear it, and EndWalk need not. Only two effects change:

Isabelle
fun effect_early :: "event ⇒ crossing ⇒ crossing" where
  "effect_early StartWalk s = s⦇peds := Walk, req := False⦈"
| "effect_early EndWalk s = s⦇peds := DontWalk⦈"
| "effect_early e s = effect e s"

fun reads overlapping equations in order, so the last equation covers the four other events: for them, effect_early does what effect does. Define the reachable states of the new design as before:

Isabelle
inductive reach_early :: "crossing ⇒ bool" where
  "reach_early start"
| "reach_early s ⟹ guard e s ⟹ reach_early (effect_early e s)"

The failed proof of Section 13.5, run on reach_early, stops at the same goal for ToGreen. This time Nitpick finds a reachable state that is not safe:

Isabelle
lemma "reach_early s ⟹ safe s"
  nitpick [card = 6]
  oops
Output
Nitpicking formula...

Nitpick found a counterexample:
  Free variable:
    s = ⦇cars = Green, peds = Walk, req = False⦈

The cars have green while the pedestrians walk. The option card = 6 selects a single default finite scope for types whose scopes Nitpick must approximate or choose. It does not make crossing a six-state type: its fields still determine 12 states. Nitpick also respects fixed datatype structure and type-specific scope settings. Fixing a scope restricts the search; it does not generally select a unique counterexample or guarantee identical output. Without it Nitpick tries a range of scopes.

Nitpick shows the bad state but not how to get there. To see the run, search for a list of events instead. Define run_early as run was defined, with the new effects, and ask whether every run of the new design ends in a safe state:

Isabelle
fun run_early :: "event list ⇒ crossing ⇒ crossing" where
  "run_early [] s = s"
| "run_early (e # es) s =
     run_early es (if guard e s then effect_early e s else s)"

lemma "safe (run_early es start)"
  nitpick [card = 6]
  oops
Output
Nitpicking formula...

Nitpick found a counterexample:
  Free variable:
    es = [Press, ToAmber, ToRed, StartWalk, ToGreen]

That is a counterexample trace: five events from start to an unsafe state. Replay it with value to see every state on the way. take n es is the first n events of es, so the list below holds the state after 0, 1, …, 5 events:

Isabelle
value "map (λn. run_early (take n [Press, ToAmber, ToRed, StartWalk, ToGreen]) start)
         [0..<6]"
Output
"[⦇cars = Green, peds = DontWalk, req = False⦈,
  ⦇cars = Green, peds = DontWalk, req = True⦈,
  ⦇cars = Amber, peds = DontWalk, req = True⦈,
  ⦇cars = Red, peds = DontWalk, req = True⦈,
  ⦇cars = Red, peds = Walk, req = False⦈,
  ⦇cars = Green, peds = Walk, req = False⦈]"
  :: "crossing list"

As a story: someone presses the button; the car light turns amber, then red; the pedestrian signal shows walk and, in the new design, the request is cleared; the controller sees no request and turns the car light green, while the pedestrians are still on the road.

After Event cars peds req
0 events Green DontWalk False
1 Press Green DontWalk True
2 ToAmber Amber DontWalk True
3 ToRed Red DontWalk True
4 StartWalk Red Walk False
5 ToGreen Green Walk False

Compare the state after 4 events with the goal of the failed proof in Section 13.5: cars red, pedestrians walking, no request. In the design of Section 13.4 that state is unreachable, and the remedy was a stronger invariant. In the new design it is reachable, and the remedy is to fix the design. Keep the request until the walk ends, as the design of Section 13.4 does; or add peds s = DontWalk to the guard of ToGreen, so that the controller checks the pedestrian signal itself (Exercise 13.6 asks you to prove that this fix works).

Key idea

Given a genuine counterexample to preservation, find out whether its starting state is reachable. If it is, its successor is reachable too and violates the candidate property. When that property is the safety requirement, the design is wrong: search for a trace and fix it. If the starting state is unreachable, strengthen the candidate to exclude it. A failed proof attempt by itself does not settle either question.

Tip

Quickcheck and Nitpick search in different ways. Quickcheck runs the definitions on many small values, so it needs functions it can execute, such as guard, effect_early and run_early. Nitpick translates the problem into a SAT problem, which also covers inductive definitions such as reach. Quickcheck’s exhaustive search tries small values first, with a default size bound of 5. This is a generator bound, not a promise to test every event list of length 5. In the checked run of safe (run_early es start), the default invocation found no counterexample, although a five-event trace exists. Fix the length with one variable for each event, and the smaller search finds it:

Isabelle
lemma "safe (run_early [e1, e2, e3, e4, e5] start)"
  quickcheck
  oops
Output
Testing conjecture with Quickcheck-exhaustive...

Quickcheck found a counterexample:
  e1 = Press
  e2 = ToAmber
  e3 = ToRed
  e4 = StartWalk
  e5 = ToGreen

With default settings, Isabelle/jEdit tries Quickcheck on new goals, but not Nitpick. These background checks are configurable; the explicit commands work independently of them.

7

Refinement: from abstract to concrete

The crossing of Section 13.4 has no time. A real controller keeps the amber light on for a few seconds, gives the pedestrians a minimum time to cross, and gives the cars a minimum green time before it serves the next request. You could add a timer to the model and prove safety again, with a new invariant. There is a better way: show that the timed controller refines the crossing, and let the safety theorem carry over.

Two models of one system

The timed controller has the lights of the crossing and a timer, which counts down the ticks that the current phase still lasts. A light may change only when the timer has run out, and a change sets the timer to the length of the new phase. The button can be pressed at any time.

Isabelle
record timed =
  lights :: crossing
  timer :: nat

fun delay :: "event ⇒ nat" where
  "delay ToAmber = 3"
| "delay ToRed = 2"
| "delay StartWalk = 6"
| "delay EndWalk = 2"
| "delay ToGreen = 10"
| "delay Press = 0"

inductive tstep :: "timed ⇒ timed ⇒ bool" where
  tick:   "timer c > 0 ⟹ tstep c (c⦇timer := timer c - 1⦈)"
| press:  "tstep c (c⦇lights := effect Press (lights c)⦈)"
| switch: "e ≠ Press ⟹ timer c = 0 ⟹ guard e (lights c) ⟹
             tstep c ⦇lights = effect e (lights c), timer = delay e⦈"

inductive treach :: "timed ⇒ bool" where
  init: "treach ⦇lights = start, timer = 0⦈"
| step: "treach c ⟹ tstep c c' ⟹ treach c'"

After ToAmber, at least 3 ticks are needed before another phase change; after StartWalk, at least 6; after ToGreen, at least 10. The initial green phase has timer 0 and no such minimum. These are minimum counts of tick events, not upper bounds on waiting or a connection to physical seconds. Presses can interleave and scheduling may postpone progress. A press does not start a phase, so delay Press is never used. The new event tick changes only the timer. Phase changes retain the abstract guards and additionally require timer 0; Press remains possible at any time.

The two models describe the same crossing at two levels of detail. The crossing is the abstract model, the timed controller the concrete one. They are related by an abstraction function: the field selector lights maps a concrete state to the abstract state it represents, by forgetting the timer. In Module 12, an abstraction function mapped a data structure to the value it represents. Here it maps the states of one machine to the states of another.

Definition 13.5Refinement

Let α\alpha map the states of a concrete machine CC to the states of an abstract machine AA⁠. Then CC refines AA (with abstraction function α\alpha⁠) if

  1. α\alpha maps every initial state of CC to an initial state of AA⁠, and
  2. for every step c→c′c \to c' of CC⁠, either α c→α c′\alpha\ c \to \alpha\ c' is a step of AA⁠, or α c′=α c\alpha\ c' = \alpha\ c⁠. A step of the second kind is a stutter step: the abstract state does not change.

Stutter steps are what allow the concrete model to take more steps than the abstract one. Every tick of the timed controller is a stutter step: the timer changes, the lights do not. Figure 13.3 shows a run of the timed controller and the run of the crossing that it represents.

The timed controller refines the crossingcrossing: reachtimed controller: treachGreen¬ reqtimer 0Greenreqtimer 0Amberreqtimer 3Amberreqtimer 2Amberreqtimer 1Amberreqtimer 0Redreqtimer 2PressToAmbertickticktickToRedGreen¬ reqGreenreqAmberreqRedreqPressToAmberToRedlightsthree ticks: stutter steps
Figure 13.3

A run of the timed controller (below) and its image under lights (above). All shown states have peds = DontWalk, omitted from the boxes. The three ticks change only the timer, so they are stutter steps; every other step is a step of the crossing.

The proof

The initial states match: lights ⦇lights = start, timer = 0⦈ is start. For the steps, prove that each concrete step is a stutter step or a step of the crossing. In Isar, proof cases takes the step apart by rule inversion, one case for each rule of tstep:

Isabelle
lemma sim:
  assumes "tstep c c'"
  shows "lights c' = lights c ∨
         (∃e. guard e (lights c) ∧ lights c' = effect e (lights c))"
  using assms
proof cases
  case tick
  then show ?thesis by simp
next
  case press
  then have "guard Press (lights c) ∧ lights c' = effect Press (lights c)" by simp
  then show ?thesis by blast
next
  case (switch e)
  then show ?thesis by auto
qed

Case tick is a stutter step. Case press is the abstract event Press: the have states the step with Press in place of e, and blast then proves the disjunction with Press as the witness for ∃e. Case switch is the abstract event e, and its abstract guard holds because it is part of the concrete guard.

Now the general argument: every reachable concrete state represents a reachable abstract state. It is a rule induction over treach, and it uses only the two conditions of the definition: the initial states match, and sim.

Isabelle
lemma treach_reach: "treach c ⟹ reach (lights c)"
proof (induction rule: treach.induct)
  case init
  show ?case by (simp add: reach.init)
next
  case (step c c')
  from ‹tstep c c'› have "lights c' = lights c ∨
      (∃e. guard e (lights c) ∧ lights c' = effect e (lights c))"
    by (rule sim)
  with step.IH show ?case by (auto intro: reach.step)
qed

In the induction step, a stutter step leads to the same abstract state, which is reachable by the induction hypothesis; any other step is a step of the crossing from a reachable state, which reach.step covers. And now the safety of the timed controller costs one line:

Isabelle
theorem timed_safe: "treach c ⟹ safe (lights c)"
  using treach_reach crossing_safe by blast

No new safety invariant was needed. The timed state type is infinite because its timer is a natural number, though this controller’s reachable timers are bounded by 10. The proof checks the initial state and the step correspondence without enumerating the timer values.

Fact 13.2Refinement preserves invariants

If CC refines AA with abstraction function α\alpha⁠, then α\alpha maps every reachable state of CC to a reachable state of AA⁠. So for every invariant II of AA⁠, the property “I(α c)I(\alpha\ c)” is an invariant of CC⁠.

This is the idea behind refinement-based development, used for example in the B method, with which the software of Paris Métro line 14 was developed (Module 1), and in its successor Event-B. You start with an abstract model in which the important properties are simple to state and prove. Then you add detail in small steps, timers, buttons, messages, data structures, and prove that each step is a refinement. The abstract state invariants proved at the top hold through the composed abstraction functions all the way down. Properties about newly introduced details need their own proofs.

Good to know

An abstraction function is a special case. In general, a concrete state may correspond to several abstract states. Then a simulation relation RR between concrete and abstract states takes the place of α\alpha⁠: every initial concrete state is related to some initial abstract state, and whenever R c aR\ c\ a and c→c′c \to c'⁠, there is an a′a' with R c′ a′R\ c'\ a' that aa reaches in zero steps or one. The proof has the same shape.

Watch out

The direction matters. The definition says that every concrete step is allowed by the abstract model; that is why safety properties carry over from the abstract model to the concrete one. It does not say that the concrete model can do everything the abstract one can. A concrete model may do less: the timed controller never changes a light while its timer runs, which the crossing would allow. Section 13.8 shows what refinement therefore does not preserve.

8

Beyond safety, and where to go next

Liveness

Requirement R2 says that after a press, the pedestrians eventually walk. It is not about bad states.

Definition 13.6Liveness property

A liveness property says that something good eventually happens: a request is eventually served, a message is eventually delivered, a program eventually terminates.

Under the usual infinite-run interpretation, no finite prefix alone refutes a liveness property: the good thing might still happen later. Termination and deadlock need a convention; one is to extend a stopped run by repeating its final state forever. A counterexample is then an infinite run in which the promised event never happens. In a finite-state model such a run can often be displayed as a finite prefix followed by a loop. The crossing has one: press the button again and again, forever, and nothing else ever happens. Every state of this run is reachable and safe, and the pedestrians never walk. A scheduling or fairness assumption can exclude this starvation, for example “an event whose guard stays true is eventually taken” (weak fairness). One proof technique combines a measure that decreases on progress steps with an argument that those steps occur, as in termination reasoning (Module 5). Leslie Lamport used the words safety and liveness for these two kinds of properties in 1977.

An ordinary state invariant alone does not establish eventual progress. The refinement criterion in Section 13.7 does not preserve liveness: a controller that never changes its lights, whatever happens, refines the crossing, since all its steps are presses and stutter steps (Exercise 13.9). It is perfectly safe and perfectly useless. Some refinement methods add proof obligations against divergence. Event-B, for example, can require a new event to be convergent: it must strictly decrease a suitable variant, such as a natural-number measure. Here the timer rules out an infinite sequence consisting only of tick steps. It does not forbid infinitely many ticks interleaved with abstract phase changes that reset the timer, and it does not force a phase change to occur. R2 still needs its own progress argument and scheduling assumptions.

Liveness is the home ground of temporal logic, which Amir Pnueli proposed for programs in 1977. Its operators speak about runs: □ P (“always P”) and ◇ P (“eventually P”). Requirement R2 becomes □(req ⟶ ◇ Walk): at every point of a run, if a request is pending, the pedestrians walk then or at some later point. Here req and Walk are the state predicates req s and peds s = Walk. The Boolean request flag coalesces repeated presses; this state-based reading allows a request during an existing walk to be served immediately. It does not specify a waiting-time bound or track a separate obligation for each pedestrian. Model checkers can check such formulas on finite models and return a counterexample run when a property is refuted: SPIN for models in its language Promela, nuXmv for models in the SMV language, and TLC for specifications in Lamport’s TLA+, the language that Amazon’s engineers used (Module 1). Isabelle can prove liveness too, but that needs more machinery than this series covers.

Where to go next

  • Isabelle for model verification. The applied project uses these ideas in a small model of a lid: a record of state, a guard that admits an operation, a lemma that the operation preserves the state invariant, and a proof that a translation between two representations preserves meaning. Its guard and update form an event in the sense of Section 13.4, and its lemma is the induction step of an invariant proof (Section 13.3); the translation theorem is of the kind that Module 14 proves for a compiler. The guide was written for Isabelle2025-2.
  • The Archive of Formal Proofs is a large online library of checked Isabelle developments, among them models of protocols, algorithms and systems with their invariants and refinements.
  • Event-B and its tool, the Rodin platform, are built around refinement: abstract machines, events with guards and actions, invariants, and refinement proofs, discharged mostly by automatic provers.
  • Model checkers such as TLC, SPIN and nuXmv analyse finite models and handle liveness. They can find counterexample traces and establish properties of those finite models. Deductive proofs can also handle infinite state spaces or whole families of models, when suitable arguments are available.

Module 14 ends the series with a different kind of system: a compiler, proved correct.

9

What you learned

  • A state machine has states, initial states and a transition relation. Its steps are events, each with a guard (when it can happen) and an effect (how it changes the state). A run follows the steps from an initial state; a trace lists its events; a state is reachable if a run leads to it.
  • In Isabelle, a state is a datatype, a pair or a record (fields cars s, values ⦇cars = …, …⦈, updates s⦇cars := …⦈). The transition relation is an inductive definition with one rule per event, or a pair of functions guard and effect, which value can run. The reachable states are an inductive definition with a rule for the initial state and a rule for a step, the same as the reflexive–transitive closure r⇧* from the initial state.
  • A safety property must hold in every reachable state. An invariant holds in every reachable state; it is inductive if it holds initially and every step preserves it. Rule induction over the reachable states proves an inductive invariant: a base case and an induction step.
  • A state safety property may be invariant without being inductive. A genuine preservation counterexample identifies a state and event. If that state is unreachable, strengthen the candidate to exclude it; if reachable, its unsafe successor exposes a design error. A failed method alone does not establish a counterexample.
  • Nitpick finds reachable bad states, also of inductive definitions, and with an executable run it finds counterexample traces: lists of events that lead to a bad state. value replays them. Fix the option card to control search scopes, not to guarantee a unique counterexample.
  • A concrete model refines an abstract one if an abstraction function maps initial states to initial states and every concrete step to an abstract step or a stutter step. Then every invariant of the abstract model holds, through the abstraction function, in the concrete one.
  • A liveness property says that something good eventually happens. State invariants and this refinement criterion alone do not establish it; progress arguments and often scheduling assumptions are needed. Temporal logic, model checkers and richer Isabelle developments can express and prove it.
10

Exercises

Exercise 13.1★Runs of the lift

Use the lift of Example 13.1.

  1. Which events can happen in the state where the door is open and the lift stands still, and to which states do they lead?
  2. Give a trace from the initial state to the state where the door is closed and the lift moves, that passes through the state where the door is closing.
  3. Why is the state “door closing, lift moving” unreachable? Look at the events that could lead to it.
Show solution
  1. open (the door stays open: same state), close (the door becomes Closing, the lift still) and stop (same state). shut needs a closing door and start a closed one.
  2. open, close, shut, start: (Closed, still) → (Open, still) → (Closing, still) → (Closed, still) → (Closed, moving).
  3. Only close leads to a closing door, and it keeps the motion as it is, so the state before would have to be “door open, lift moving”. No event leads to that state: open needs a lift that stands still and keeps it still, start needs a closed door, and close, shut and stop never produce an open door with a moving lift. So neither unsafe state can be reached. The proof of lift_safe makes this argument for every state at once.
Exercise 13.2★Safety or liveness?

Say whether each requirement is a safety or a liveness property.

  1. Two trains are never on the same section of track.
  2. Every print job is eventually printed.
  3. The balance of an account never becomes negative.
  4. A message that is sent is eventually delivered.
  5. The program never divides by zero.
  6. The program terminates.
Show solution
  1. Safety: the bad state is two trains on one section, and a finite run can reach it.
  2. Liveness: something good (the printout) must eventually happen; a counterexample is an infinite run in which the job is never printed.
  3. Safety.
  4. Liveness.
  5. Safety: the bad thing is a division by zero, and a finite run that performs one is a counterexample.
  6. Liveness: termination says that the program eventually stops. No finite run shows that a program never stops; the counterexample is an infinite run.
Exercise 13.3★Predict a run

Work out on paper the result of run [Press, Press, ToAmber, ToGreen, ToRed] start, event by event. Then check it with value.

Show solution

Press sets the request. The second Press changes nothing, since the request is already set. ToAmber is enabled (green, request) and makes the car light amber. ToGreen needs red, so run skips it. ToRed makes the car light red. The pedestrians never walk, and the request is still pending:

Isabelle
value "run [Press, Press, ToAmber, ToGreen, ToRed] start"
Output
"⦇cars = Red, peds = DontWalk, req = True⦈"
  :: "crossing"
Exercise 13.4★★Invariant, inductive, or neither?

For the crossing of Section 13.4, decide for each property whether it holds in every reachable state, and whether it is inductive on its own. Use Figure 13.1 for the reachable states. When a property is not inductive, give a state and an event that break the induction step; when it is not an invariant, give a run that breaks it.

  1. peds s = Walk ⟶ req s
  2. cars s = Amber ⟶ req s
  3. peds s = DontWalk
  4. cars s = Amber ⟶ peds s = DontWalk
Show solution
  1. Invariant and inductive. Only StartWalk makes the pedestrians walk, and its guard needs the request. While they walk, only EndWalk clears the request, and it ends the walk. No other event changes the two fields involved, except Press, which sets the request. (This is the part that Section 13.5 added to safe.)
  2. Invariant, not inductive. The only reachable state with amber has a request. But take the unreachable state ⦇cars = Amber, peds = Walk, req = True⦈: it satisfies the property, and EndWalk clears the request and keeps the amber light. Exercise 13.7 proves the invariant.
  3. Not an invariant, so not inductive either. The run Press, ToAmber, ToRed, StartWalk reaches a state where the pedestrians walk.
  4. Invariant, not inductive. In the reachable states, amber comes only with don’t walk. But the unreachable state ⦇cars = Green, peds = Walk, req = True⦈ satisfies the property (the cars are not amber), and ToAmber leads to amber while the pedestrians walk.
Exercise 13.5★★Runs reach reachable states

Prove that every state that run produces from a reachable state is reachable, and conclude that run es start is reachable for every list of events es. Which variable must be generalised in the induction, and why?

Show solution

Induct on es. In the recursive call run es (…), the state changes, so the induction hypothesis must hold for every state: generalise s with arbitrary: (Module 11).

Isabelle
lemma reach_run: "reach s ⟹ reach (run es s)"
  by (induction es arbitrary: s) (auto intro: reach.step)

corollary "reach (run es start)"
  by (simp add: reach.init reach_run)

In the induction step, the simplifier splits the if in the definition of run. If the guard holds, the next state is reachable by reach.step; if not, it is s itself. Together with crossing_safe, this shows that no run of events leads to an unsafe state: the property that Nitpick refuted for the colleague’s design in Section 13.6 holds for the design of Section 13.4.

Exercise 13.6★★Fix the guard instead

Keep the colleague’s effects effect_early from Section 13.6, but give ToGreen the guard cars s = Red ∧ peds s = DontWalk ∧ ¬ req s. Define the new guard function guard_safe and the reachable states reach_fixed of this design, and prove that every reachable state is safe. Do you need to strengthen safe?

Show solution

Only one equation of the guard changes; as in Section 13.6, a final equation covers the other events.

Isabelle
fun guard_safe :: "event ⇒ crossing ⇒ bool" where
  "guard_safe ToGreen s = (cars s = Red ∧ peds s = DontWalk ∧ ¬ req s)"
| "guard_safe e s = guard e s"

inductive reach_fixed :: "crossing ⇒ bool" where
  init: "reach_fixed start"
| step: "reach_fixed s ⟹ guard_safe e s ⟹ reach_fixed (effect_early e s)"

lemma "reach_fixed s ⟹ safe s"
proof (induction rule: reach_fixed.induct)
  case init
  show ?case by (simp add: safe_def start_def)
next
  case (step s e)
  then show ?case by (cases e) (auto simp: safe_def)
qed

No strengthening is needed: safe is inductive in this design. The guard of ToGreen now checks the pedestrian signal itself, so the step that broke the proof in Section 13.5 is no longer possible. A guard that checks the property it protects makes the proof short; a design that relies on another variable, as the request did, needs an invariant that relates the two.

Exercise 13.7★★One invariant helps another

Prove that in every reachable state of the crossing, the car light is amber only while a request is pending: reach s ⟹ cars s = Amber ⟶ req s. The rule induction alone fails (Exercise 13.4). Use the invariant reach_invar, which you have already proved.

Show solution

In the induction step, the premise reach s is available, so reach_invar gives invar s for the state before the event. That is the missing fact: in the state where EndWalk clears the request, the pedestrians walk, so by invar the cars have red, not amber.

Isabelle
lemma "reach s ⟹ cars s = Amber ⟶ req s"
proof (induction rule: reach.induct)
  case init
  show ?case by (simp add: start_def)
next
  case (step s e)
  moreover from ‹reach s› have "invar s" by (rule reach_invar)
  ultimately show ?case by (cases e) (auto simp: invar_def)
qed

Using an invariant that is already proved is often easier than putting everything into one big invariant: each proof stays small, and later proofs can use the earlier ones.

Exercise 13.8★★★A turnstile

A turnstile is locked until a coin is inserted. A coin unlocks it; pushing an unlocked turnstile lets one person through and locks it again. It counts coins and passes:

Isabelle
record gate =
  locked :: bool
  coins :: nat
  passes :: nat

inductive greach :: "gate ⇒ bool" where
  "greach ⦇locked = True, coins = 0, passes = 0⦈"
| "greach g ⟹ greach (g⦇locked := False, coins := coins g + 1⦈)"
| "greach g ⟹ ¬ locked g ⟹ greach (g⦇locked := True, passes := passes g + 1⦈)"

The safety property is that nobody passes without paying: passes g ≤ coins g. Try to prove that it holds in every reachable state, read the goal that is left, and strengthen the invariant until the proof works.

Show solution

The direct attempt leaves the push:

Isabelle
lemma "greach g ⟹ passes g ≤ coins g"
  apply (induction rule: greach.induct)
  apply auto
Output
proof (prove)
goal (1 subgoal):
 1. ⋀g. ⟦greach g; passes g ≤ coins g; ¬ locked g⟧
        ⟹ Suc (passes g) ≤ coins g
Isabelle
  oops

The goal is the push. From passes g ≤ coins g and an unlocked turnstile, it must show that one more pass still fits, Suc (passes g) ≤ coins g. That fails when passes and coins are equal: an unlocked turnstile with as many passes as coins satisfies the invariant, and a push lets someone through without paying. That state is unreachable, because a turnstile is unlocked only by a coin that has not been used for a pass yet. Say so in the invariant: when the turnstile is unlocked, passes are strictly fewer than coins.

Isabelle
lemma "greach g ⟹ passes g ≤ coins g ∧ (¬ locked g ⟶ passes g < coins g)"
  by (induction rule: greach.induct) auto

The safety property is the first half of the strengthened invariant. The second half is the fact about reachable states that the failed goal violated.

Exercise 13.9★★★A lazy controller

A lazy controller accepts presses and does nothing else:

Isabelle
inductive lazy :: "crossing ⇒ bool" where
  init:  "lazy start"
| press: "lazy s ⟹ lazy (s⦇req := True⦈)"
  1. Each step of the lazy controller is the abstract event Press, so it refines the crossing, with the identity as abstraction function. Prove what follows by Fact 13.2, lazy s ⟹ reach s, by rule induction as for treach_reach, and conclude that the lazy controller is safe.
  2. Prove that in the lazy controller the cars always have green.
  3. What do 1 and 2 say about requirement R2, and about what refinement preserves?
Show solution
  1. In case press, the step is the abstract event Press from a reachable state:

    Isabelle
    lemma lazy_reach: "lazy s ⟹ reach s"
    proof (induction rule: lazy.induct)
      case init
      show ?case by (rule reach.init)
    next
      case (press s)
      from press.IH have "reach (effect Press s)" by (rule reach.step) simp
      then show ?case by simp
    qed
    
    corollary "lazy s ⟹ safe s"
      by (simp add: crossing_safe lazy_reach)

    The have states the new state in the form that reach.step produces: rule reach.step takes the induction hypothesis reach s for its first premise and leaves the guard guard Press s, which simp proves. In the last step, simp turns effect Press s into s⦇req := True⦈.

  2. The cars have green in start, and a press does not change the car light:

    Isabelle
    lemma "lazy s ⟹ cars s = Green"
      by (induction rule: lazy.induct) (auto simp: start_def)
  3. The lazy controller is safe, and it never lets anyone cross: after a press, the pedestrians never walk, so it breaks R2. Refinement preserves safety properties, but not liveness properties. A refinement may do less than the abstract model, including nothing at all.

11

Check yourself

1
In a model of a state machine, what does the guard of an event describe?
2
A property I holds in the initial state and in every reachable state. What else must hold for I to be inductive?
3
A genuine counterexample to preservation gives a state s satisfying I and an enabled event e whose successor violates I. What should you find out next?
4
Why can Quickcheck test safe (run es start) but not reach s ⟹ safe s?
5
In a refinement proof, a concrete step changes only the timer, and the abstraction function forgets the timer. What is this step in the abstract model?
6
Which requirement is a liveness property?
Finished this module?