---
title: "Program Verification: Hoare Logic and Model Checking"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 20
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/20-program-verification-hoare-logic-and-model-checking
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 20 — Program Verification: Hoare Logic and Model Checking

Tests show that a program works on the inputs tried. Verification shows that it works on all of them, or produces an input on which it fails. This chapter builds two kinds of verifier and runs them. The first is deductive: a program carries assertions, [Hoare logic](#def-b3-program-verification-hoare) turns it into formulas called [verification conditions](#def-b3-program-verification-vc), and the [CDCL solver](https://one-course.com/books/computer-science/5/en/chapter/18-approximation-and-exact-methods-for-hard-problems#def-b3-hard-problems-cdcl) of [Chapter 18](https://one-course.com/books/computer-science/5/en/chapter/18-approximation-and-exact-methods-for-hard-problems#ch-b3-hard-problems) decides them over 8-bit machine integers; on binary search it finds the classic overflow of the midpoint, with the values that cause it. The second is [model checking](#def-b3-program-verification-mc): a finite-state system is explored state by state and a temporal formula is decided on its state graph; on Peterson’s algorithm it confirms mutual exclusion, and on a broken variant it prints the run that breaks it. The chapter closes on what limits both: invariants have to be found, and states multiply.

**You already know.**

A precondition and a postcondition specify a program; it is partially correct when every run started in the precondition that terminates ends in the postcondition, and totally correct when it also always terminates. A loop invariant holds before the loop and is kept by every iteration; a variant is a natural number that decreases at each iteration (Year 1 volume). A proof system is sound when everything it proves is true (Year 2 volume). [Big-step semantics](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#def-b3-lambda-calculus-semantics) relates a program and a starting state to its final state ([Definition 5.13](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#def-b3-lambda-calculus-semantics)). A [least fixed point](https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation#def-b3-program-optimisation-lfp) is computed by iterating from the bottom ([Definition 8.3](https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation#def-b3-program-optimisation-lfp)). Peterson’s algorithm gives two threads mutual exclusion with two flags and a turn variable (Year 2 volume).

## 20.1 Hoare triples

The programs of this chapter are written in a small while-language with Python’s syntax: integer variables, assignment, `if`, `while`, `assert` and `pass`. Integers are 8-bit and unsigned, so $255 + 1 = 0$, as in a machine register. A loop may open with `invariant(...)` and `variant(...)`, which do nothing when run, and `unknown()` is a condition outside the program’s control, such as the comparison with an array element that binary search makes. The big-step interpreter `run` executes it.

```python
def run(statements, env, choose=lambda: False, fuel=10_000):
    """Big-step execution; returns the final environment. A failed assert raises."""
    for s in statements:
        match s:
            case ast.Assign(targets=[ast.Name(id=x)], value=e):
                env[x] = value(e, env, choose)
            case ast.If(test=b, body=yes, orelse=no):
                env = run(yes if value(b, env, choose) else no, env, choose, fuel)
            case ast.While(test=b):
                _, _, body = annotations(s)
                while value(b, env, choose):
                    fuel -= 1
                    if fuel < 0:
                        raise RuntimeError("out of fuel")
                    env = run(body, env, choose, fuel)
            case ast.Assert(test=b):
                if not value(b, env, choose):
                    raise AssertionError(f"{ast.unparse(b)}, with {env}")
            case ast.Pass() | ast.Expr():
                pass
    return env
```

***Listing 20.1.** Big-step execution of the while-language; `value` evaluates expressions with 8-bit wrap-around. code/bachelor-3/20-program-verification/listings/whilelang.py*

**Definition 20.1 (Hoare triple, Hoare logic, assignment axiom, rule of consequence).**

A *Hoare triple* $\{P\}\,S\,\{Q\}$ is valid when every run of $S$ from a state satisfying $P$ that terminates ends in a state satisfying $Q$. *Hoare logic* derives triples by the rules below, where $Q[e/x]$ is $Q$ with $e$ substituted for $x$.

- The *assignment axiom* : $\{Q[e/x]\}\; x = e\; \{Q\}$ .
- Sequence: from $\{P\}\,S_1\,\{R\}$ and $\{R\}\,S_2\,\{Q\}$ , derive $\{P\}\,S_1; S_2\,\{Q\}$ .
- If: from $\{P \wedge b\}\,S_1\,\{Q\}$ and $\{P \wedge \neg b\}\,S_2\,\{Q\}$ , derive $\{P\}$ `if b: S1 else: S2` $\{Q\}$ .
- While: from $\{I \wedge b\}\,S\,\{I\}$ , derive $\{I\}$ `while b: S` $\{I \wedge \neg b\}$ .
- The *rule of consequence* : from $P \Rightarrow P'$ , $\{P'\}\,S\,\{Q'\}$ and $Q' \Rightarrow Q$ , derive $\{P\}\,S\,\{Q\}$ .

The [assignment axiom](#def-b3-program-verification-hoare) runs backwards: for $x$ to satisfy $Q$ after $x = e$, the expression $e$ must satisfy it before. The while rule says nothing about termination; a variant adds it. Tony Hoare proposed the logic in 1969, building on Robert Floyd’s earlier rules for flowcharts.

**Theorem 20.2 (Soundness of Hoare logic).**

Every derivable triple is valid for the [big-step semantics](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#def-b3-lambda-calculus-semantics).

The proof is by induction on the derivation, one case per rule: the [assignment axiom](#def-b3-program-verification-hoare) because evaluating $Q$ in the state after $x = e$ is evaluating $Q[e/x]$ in the state before ([Exercise 20.7](#exo-b3-program-verification-7)), the while rule by induction on the number of iterations ([Exercise 20.10](#exo-b3-program-verification-10)), the others directly. `hoare_check.py` checks a derivation node by node, and decides the implications of the [rule of consequence](#def-b3-program-verification-hoare) with the solver of [Section 20.3](#sec-20-3).

![A derivation as a proof tree: each line follows from the one above the bar by the rule named on its right. The two consequence steps need x 10 x < 10 ℝightarrow x + 1 10, which holds for 8-bit integers since x < 10 rules out the wrap, and x 10 (x < 10) ℝightarrow x = 10.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-program-verification/fig-a12faf673f16.svg)

*A derivation as a proof tree: each line follows from the one above the bar by the rule named on its right. The two consequence steps need $x \le 10 \wedge x < 10 \Rightarrow x + 1 \le 10$, which holds for 8-bit integers since $x < 10$ rules out the wrap, and $x \le 10 \wedge \neg (x < 10) \Rightarrow x = 10$.*

```
$ python hoare_check.py
      assign  {x + 1 <= 10} x = x + 1 {x <= 10}
    conseq  {x <= 10 and x < 10} x = x + 1 {x <= 10}
  while   {x <= 10} while x < 10: x = x + 1 {x <= 10 and (not x < 10)}
conseq  {x <= 10} while x < 10: x = x + 1 {x == 10}
  assign  {x + 2 <= 10} x = x + 2 {x <= 10}
rejected: x <= 10 and x < 10 does not imply x + 2 <= 10: {'x': 9}
```

***Output 20.1.** The derivation of the figure, checked from the leaves up; then a wrong step, rejected with the value that refutes its implication.*

## 20.2 Weakest preconditions

**Definition 20.3 (Weakest precondition, strongest postcondition).**

The *weakest precondition* $\mathrm{wp}(S, Q)$ is a formula that holds in exactly the states from which every run of $S$ terminates in a state satisfying $Q$. The *strongest postcondition* $\mathrm{sp}(P, S)$ holds in exactly the states that runs of $S$ from $P$ can end in.

For loop-free programs, wp is computed backwards, one statement at a time:

$$
\mathrm{wp}(x = e, Q) = Q[e/x], \quad \mathrm{wp}(S_1; S_2, Q) = \mathrm{wp}(S_1, \mathrm{wp}(S_2, Q)), \quad \mathrm{wp}(\text{\texttt{assert} } b, Q) = b \wedge Q,
$$

and the `if` gives $(b \Rightarrow \mathrm{wp}(S_1, Q)) \wedge (\neg b \Rightarrow \mathrm{wp}(S_2, Q))$; with `unknown()` as its test, both branches may run, and wp is the conjunction of the two.

**Theorem 20.4 (Weakest preconditions decide triples).**

For a loop-free $S$, $\{P\}\,S\,\{Q\}$ is valid if and only if $P \Rightarrow \mathrm{wp}(S, Q)$ is valid.

By induction on $S$, the formula computed holds in a state exactly when every run of $S$ from it ends in $Q$; the triple is then the implication. Edsger Dijkstra introduced [weakest preconditions](#def-b3-program-verification-wp) in 1975.

```python
def wp(statements, q):
    for s in reversed(statements):  # wp(S1; S2, Q) = wp(S1, wp(S2, Q))
        match s:
            case ast.Assign(targets=[ast.Name(id=x)], value=e):
                q = Substitute(x, e).visit(copy.deepcopy(q))
            case ast.If(
                test=ast.Call(func=ast.Name(id="unknown")), body=yes, orelse=no
            ):
                q = conj(wp(yes, q), wp(no, q))  # either branch may run
            case ast.If(test=b, body=yes, orelse=no):
                q = conj(
                    implies(b, wp(yes, q)),
                    implies(ast.UnaryOp(op=ast.Not(), operand=b), wp(no, q)),
                )
            case ast.Assert(test=b):
                q = conj(b, q)
            case ast.Pass():
                pass
            case _:
                raise ValueError("wp: loops need an invariant (see vcgen.py)")
    return q
```

***Listing 20.2.** [Weakest preconditions](#def-b3-program-verification-wp) of loop-free programs. code/bachelor-3/20-program-verification/listings/wp.py*

```
$ python wp.py
program: y = x + 1 | x = y + y
  wp for x < 100:  x + 1 + (x + 1) < 100
program: t = x | x = y | y = t
  wp for x == a and y == b:  y == a and x == b
program: if x < y: | m = y | else: | m = x
  wp for m >= x:  implies(x < y, y >= x) and implies(not x < y, x >= x)
```

***Output 20.2.** Three [weakest preconditions](#def-b3-program-verification-wp), not simplified: the swap through `t` exchanges $a$ and $b$ in the postcondition.*

A loop has no finite formula for its wp in general; it would be the limit of unrolling the loop again and again. The programmer supplies an invariant instead, and the verifier checks it.

## 20.3 Verification conditions handed to a solver

**Definition 20.5 (Annotated program, verification condition, bit-blasting).**

An *annotated program* carries an invariant on every loop, and optionally a variant. Its *verification conditions* are formulas without programs, whose validity implies that the program meets its specification. *Bit-blasting* turns a formula over fixed-width integers into a propositional formula with one variable per bit, adders and comparators being written as Boolean circuits.

The generator computes wp backwards, but takes a loop’s invariant $I$ as its precondition and emits three conditions for it: *preserved*, $I \wedge b \Rightarrow \mathrm{wp}(S, I)$; *exit*, $I \wedge \neg b \Rightarrow Q$; and, with a variant $V$, *variant*, $I \wedge b \wedge V = v_0 \Rightarrow \mathrm{wp}(S, V < v_0)$. A final condition, *entry*, says that the precondition implies what the program needs at its start.

```python
def awp(statements, q, vcs):
    """Like wp, but a loop's precondition is its invariant, and the loop adds its
    own conditions to the list vcs."""
    for s in reversed(statements):
        if isinstance(s, ast.While):
            inv, var, body = annotations(s)
            vcs.append(("preserved", implies(conj(inv, s.test), awp(body, inv, vcs))))
            vcs.append(("exit", implies(conj(inv, neg(s.test)), q)))
            if var is not None:  # the variant decreases: V < v0 after the body
                v0 = ast.Name(id=f"v{len(vcs)}")
                smaller = ast.Compare(left=var, ops=[ast.Lt()], comparators=[v0])
                start = ast.Compare(
                    left=copy.deepcopy(var), ops=[ast.Eq()], comparators=[v0]
                )
                entered = conj(conj(inv, s.test), start)
                vcs.append(("variant", implies(entered, awp(body, smaller, vcs))))
            q = inv
        elif isinstance(s, ast.If) and not isinstance(s.test, ast.Call):
            yes, no = awp(s.body, q, vcs), awp(s.orelse, q, vcs)
            q = conj(implies(s.test, yes), implies(neg(s.test), no))
        elif isinstance(s, ast.If):  # unknown(): both branches
            q = conj(awp(s.body, q, vcs), awp(s.orelse, q, vcs))
        else:
            q = wp([s], q)
    return q
```

***Listing 20.3.** The [verification conditions](#def-b3-program-verification-vc) of an [annotated program](#def-b3-program-verification-vc). code/bachelor-3/20-program-verification/listings/vcgen.py*

Each condition $F$ is valid exactly when $\neg F$ is unsatisfiable. The bit-blaster gives each 8-bit variable eight Boolean variables and each operation a circuit: a ripple-carry adder for $+$, the same adder on the complement plus one for $-$, a shift for halving, and the borrow of a subtraction for $<$. Each gate becomes a few clauses (Tseitin’s encoding), and CDCL decides the result. A satisfying assignment of $\neg F$ is a counterexample: values of the variables that make the condition false.

```python
    def add(self, x, y, carry=-1):  # carry -1 is the constant false
        out = []
        for a, b in zip(x, y):  # ripple-carry, least significant bit first
            t = self.XOR(a, b)
            out.append(self.XOR(t, carry))
            carry = self.OR(self.AND(a, b), self.AND(t, carry))
        return out, carry

    def word(self, e):
        match e:
            case ast.Constant(value=c):
                return [1 if c >> i & 1 else -1 for i in range(BITS)]
            case ast.Name(id=x):
                if x not in self.words:
                    self.words[x] = [self.fresh() for _ in range(BITS)]
                return self.words[x]
            case ast.BinOp(left=a, op=ast.Add(), right=b):
                return self.add(self.word(a), self.word(b))[0]
            case ast.BinOp(left=a, op=ast.Sub(), right=b):  # a + not b + 1
                return self.add(self.word(a), [-v for v in self.word(b)], 1)[0]
            case ast.BinOp(left=a, op=ast.FloorDiv()):  # // 2: shift right
                return self.word(a)[1:] + [-1]
        raise ValueError(ast.unparse(e))

    def less(self, a, b):
        """a < b (unsigned) exactly when a - b borrows: a + not b + 1 has no carry."""
        return -self.add(self.word(a), [-v for v in self.word(b)], 1)[1]

    def equal(self, a, b):
        bit = 1
        for x, y in zip(self.word(a), self.word(b)):
            bit = self.AND(bit, -self.XOR(x, y))
        return bit
```

***Listing 20.4.** Words of bits, the adder, and comparison through the borrow. code/bachelor-3/20-program-verification/listings/bitblast.py*

![The verification pipeline of this section.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-program-verification/fig-2532471baebe.svg)

*The verification pipeline of this section.*

Binary search keeps an interval $[lo, hi)$ of indices and halves it. Its array test is replaced by `unknown()`, so the proof below covers every array; the assertion checks that the midpoint is a valid index of the interval, and the variant $hi - lo$ proves termination.

```python
SEARCH = """
lo = 0
hi = n
while lo < hi:
    invariant(INV)
    variant(hi - lo)
    mid = MID
    assert lo <= mid and mid < hi
    if unknown():
        lo = mid + 1
    else:
        hi = mid
"""
```

***Listing 20.5.** Binary search, with `MID` and `INV` filled in three ways. code/bachelor-3/20-program-verification/listings/verify_bsearch.py*

```
$ python verify_bsearch.py
midpoint (lo + hi) // 2:
  entry        91 variables    280 clauses  valid
  preserved   633 variables   2066 clauses  FAILS, e.g. {'hi': 192, 'lo': 128, 'n': 192}
  exit        205 variables    614 clauses  valid
  variant     656 variables   2119 clauses  FAILS, e.g. {'hi': 192, 'lo': 128, 'n': 192, 'v2': 64}
  run with n = 255, always going right, the assert fails:
    lo <= mid and mid < hi, with {'n': 255, 'lo': 128, 'hi': 255, 'mid': 63}
midpoint lo + (hi - lo) // 2:
  entry        91 variables    280 clauses  valid
  preserved   833 variables   2746 clauses  valid
  exit        205 variables    614 clauses  valid
  variant     816 variables   2663 clauses  valid
invariant lo < hi (wrong):
  entry        91 variables    280 clauses  FAILS, e.g. {'n': 0}
  preserved   833 variables   2746 clauses  FAILS, e.g. {'hi': 2, 'lo': 0, 'n': 194}
  exit        205 variables    614 clauses  valid
  variant     816 variables   2663 clauses  valid
```

***Output 20.3.** The midpoint $(lo + hi) // 2$ fails, with a counterexample that the invariant allows; $lo + (hi - lo) // 2$ is verified; and a wrong invariant is caught at entry ($n = 0$) and when kept.*

With $lo = 128$ and $hi = 192$, $lo + hi = 320$, which wraps to 64 in 8 bits, and the midpoint 32 lies below $lo$. The same failure happens with 32-bit indices on arrays of more than $2^{30}$ elements, and the cure, $lo + (hi - lo)/2$, is the same. That state satisfies the invariant, but no run reaches it: from $lo = 0$, $hi = 192$ the first move to the right already fails, at $lo = 97$. The failure is still not an artefact of the invariant: run on $n = 255$, always choosing the upper half, the interpreter makes the assertion fail at $lo = 128$, $hi = 255$.

## 20.4 Temporal properties

Programs that run forever, such as operating systems, lifts and protocols, are specified by what must hold along their runs: two lifts are never in the shaft together; every request is eventually served.

**Definition 20.6 (Kripke structure, temporal logic, computation tree logic, linear temporal logic).**

A *Kripke structure* is a finite set of states, a successor relation in which every state has at least one successor, and for each state the set of atomic propositions true in it. A *temporal logic* speaks of the runs, infinite paths of states. *Computation tree logic* (CTL) pairs a path quantifier, E (some path) or A (all paths), with a temporal operator, X (next state), F (some future state), G (every future state) or U (until): $\mathrm{E}[f \,\mathrm{U}\, g]$ holds when some path reaches a $g$-state through $f$-states. *Linear temporal logic* (LTL) has the temporal operators without path quantifiers, and a formula holds in a state when it holds on every path from it.

Everything is expressed with EX, EU and EG: $\mathrm{EF}\,g = \mathrm{E}[\mathrm{true} \,\mathrm{U}\, g]$, $\mathrm{AG}\,f = \neg \mathrm{EF} \neg f$, $\mathrm{AF}\,f = \neg \mathrm{EG} \neg f$. E. M. Clarke and E. A. Emerson proposed CTL in 1981; Amir Pnueli proposed LTL for program verification in 1977.

**Theorem 20.7 (Fixed points of CTL).**

$\mathrm{E}[f \,\mathrm{U}\, g]$ is the [least fixed point](https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation#def-b3-program-optimisation-lfp) of $Z \mapsto g \vee (f \wedge \mathrm{EX}\,Z)$, and $\mathrm{EG}\,f$ is the greatest [fixed point](https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation#def-b3-program-optimisation-lfp) of $Z \mapsto f \wedge \mathrm{EX}\,Z$, sets of states being ordered by inclusion.

For EF, the $k$-th iterate from the empty set is the set of states that reach $g$ in fewer than $k$ steps, and the iteration stops after at most as many rounds as there are states ([Exercise 20.11](#exo-b3-program-verification-11)). The greatest [fixed point](https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation#def-b3-program-optimisation-lfp) is computed from the full set downwards. So a CTL formula is checked in time polynomial in the size of the structure, by `ctl.py`.

```python
    def sat(self, f):
        match f:
            case str(p):
                return {s for s in self.states if p in self.labels[s]}
            case ("not", g):
                return self.states - self.sat(g)
            case ("and", g, h):
                return self.sat(g) & self.sat(h)
            case ("or", g, h):
                return self.sat(g) | self.sat(h)
            case ("EX", g):
                return self.pre(self.sat(g))
            case ("EU", g, h):  # least fixed point of Z = h or (g and EX Z)
                keep, z = self.sat(g), self.sat(h)
                while (bigger := z | (keep & self.pre(z))) != z:
                    z = bigger
                return z
            case ("EG", g):  # greatest fixed point of Z = g and EX Z
                z = self.sat(g)
                while (smaller := z & self.pre(z)) != z:
                    z = smaller
                return z
            case ("EF", g):
                return self.sat(("EU", "true", g))
            case ("AX", g):
                return self.sat(("not", ("EX", ("not", g))))
            case ("AG", g):
                return self.sat(("not", ("EF", ("not", g))))
            case ("AF", g):
                return self.sat(("not", ("EG", ("not", g))))
        raise ValueError(f)
```

***Listing 20.6.** A CTL model checker: one case per operator, EU and EG by iteration to a [fixed point](https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation#def-b3-program-optimisation-lfp). code/bachelor-3/20-program-verification/listings/ctl.py*

![The structure of . The shaded region is EF done; state 1 loops on busy forever, so EG busy holds there, and AF done fails at state 0, whose path to state 1 never reaches done.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-program-verification/fig-3685603c89c7.svg)

*The structure of [Output 20.4](#out-b3-program-verification-ctl). The shaded region is EF done; state 1 loops on busy forever, so EG busy holds there, and AF done fails at state 0, whose path to state 1 never reaches done.*

```
$ python ctl.py
done             holds in states [3]
EX done          holds in states [2, 3]
EF done          holds in states [0, 2, 3]
AF done          holds in states [2, 3]
EG busy          holds in states [1]
AG EF done       holds in states []
EF AG busy       holds in states [0, 1, 2, 3]
second structure: AF AG p holds in states [1, 2]
```

***Output 20.4.** Formulas on the four-state structure; and on a second structure, the formula AF AG p, which fails where the LTL formula F G p holds.*

The two logics differ. In the second structure, state 0 loops on $p$ or moves to state 1 ($\neg p$) and then to state 2, which loops on $p$. Every path eventually stays in $p$ for ever, so the LTL formula F G $p$ holds at state 0. But AF AG $p$ fails there: along the path that stays at state 0, no state satisfies AG $p$, since state 1 is still reachable from each of them. Each logic expresses some properties the other cannot; LTL is not built in this chapter.

## 20.5 Model checking finite-state systems

**Definition 20.8 (Model checking, counterexample trace, state explosion).**

*Model checking* decides whether a finite-state system, given as a [Kripke structure](#def-b3-program-verification-kripke), satisfies a temporal formula, by exploring its states. When a [safety property](https://one-course.com/books/computer-science/5/en/chapter/13-concurrency-deadlock-monitors-and-lock-free-structures#def-b3-concurrency-properties) AG $f$ fails, a *counterexample trace* is a path from the start to a state violating $f$. *State explosion* is the growth of the number of reachable states, exponential in the number of components of the system.

[Model checking](#def-b3-program-verification-mc) began with the work of Clarke and Emerson and of J. P. Queille and J. Sifakis in the early 1980s; Clarke, Emerson and Sifakis shared the 2007 Turing Award for it.

The state of Peterson’s algorithm for two processes is the two program counters, the two flags and the turn; a step is one process executing one line. Breadth-first search from the start finds the reachable states and builds the [Kripke structure](#def-b3-program-verification-kripke), and `ctl.py` checks mutual exclusion, AG $\neg(\mathit{crit}_0 \wedge \mathit{crit}_1)$, and that process 0 can always still reach its critical section, AG EF $\mathit{crit}_0$.

```python
def peterson(state, i):
    """The state after process i takes its next step, or None if it is blocked."""
    pc, flag, turn, j = list(state[:2]), list(state[2:4]), state[4], 1 - i
    match pc[i]:
        case 0:  # IDLE: flag[i] = 1
            flag[i], pc[i] = 1, WANT
        case 1:  # WANT: turn = j
            turn, pc[i] = j, WAIT
        case 2:  # WAIT: until flag[j] == 0 or turn == i
            if not (flag[j] == 0 or turn == i):
                return None
            pc[i] = CRIT
        case 3:  # CRIT: leave, flag[i] = 0
            flag[i], pc[i] = 0, IDLE
    return (*pc, *flag, turn)
```

***Listing 20.7.** One step of Peterson’s algorithm. code/bachelor-3/20-program-verification/listings/peterson_mc.py*

```
$ python peterson_mc.py
Peterson: 20 reachable states; AG not (crit0 and crit1): True
Peterson: 20 reachable states; AG EF crit0: True
without turn: 9 reachable states; AG not (crit0 and crit1): False
without turn: 9 reachable states; AG EF crit0: True
  counterexample trace, 4 steps (pc0, pc1, flag0, flag1):
    (0, 0, 0, 0) -> (1, 0, 0, 0) -> (1, 1, 0, 0) -> (3, 1, 1, 0) -> (3, 3, 1, 1)
```

***Output 20.5.** Peterson’s algorithm has 20 reachable states and keeps mutual exclusion; without the turn, a process that tests the other’s flag before raising its own lets both in, and breadth-first search finds a shortest trace, of 4 steps.*

Breadth-first search finds shortest counterexamples, the easiest to read: both processes see the other’s flag down, then both raise their own and enter. A system of $n$ processes with $k$ states each can have up to $k^n$ states, and the weekend problem measures that growth. Model checkers fight it with symbolic representations of sets of states, and with partial-order reduction, which explores only one order of steps that commute; both are told here, not built.

## 20.6 Exercises

**Exercise 20.1 ★.**

Compute $\mathrm{wp}(x = x + y;\; y = x - y;\; x = x - y,\; x = a \wedge y = b)$ by hand, and say what the program does, in 8-bit arithmetic too.

**Solution of Exercise 20.1.**

Backwards: after `x = x - y`, $x - y = a \wedge y = b$; after `y = x - y`, $x - (x - y) = a \wedge x - y = b$; after `x = x + y`, $(x + y) - ((x + y) - y) = a \wedge (x + y) - y = b$, that is $y = a \wedge x = b$. The program swaps $x$ and $y$ without a third variable. In 8-bit arithmetic every step is modulo 256, where these identities still hold, so it swaps there too, even when $x + y$ wraps.

**Exercise 20.2 ★.**

Is $\{x < 200\}\; x = x + 100\; \{x \ge 100\}$ valid with 8-bit unsigned integers? With unbounded integers?

**Solution of Exercise 20.2.**

The [weakest precondition](#def-b3-program-verification-wp) is $x + 100 \ge 100$. With unbounded integers it holds for every $x \ge 0$, so the triple is valid. In 8 bits, for $156 \le x < 200$ the sum wraps to $x - 156 < 100$: not valid; $x = 156$ is a counterexample.

**Exercise 20.3 ★.**

Give an invariant that proves $\{n \le 20\}$ `s = 0; i = 0; while i < n: i = i + 1; s = s + i` $\{2s = n(n + 1)\}$ with unbounded integers. What is the largest $n$ for which the 8-bit loop computes $s$ without wrapping?

**Solution of Exercise 20.3.**

$I$: $2s = i(i + 1) \wedge i \le n$. At entry $s = i = 0$. Kept: from $2s = i(i + 1)$ and $i < n$, after $i = i + 1$ and $s = s + i$ we get $2s' = i(i + 1) + 2(i + 1) = (i + 1)(i + 2)$ and $i + 1 \le n$. At exit $i \ge n$ and $i \le n$, so $i = n$. In 8 bits, $s = n(n + 1)/2 \le 255$ requires $n \le 22$ ($s = 253$); at $n = 23$, $s$ would be 276 and wraps. The product $n(n + 1)$ in the postcondition wraps earlier, from $n = 16$, so an 8-bit proof must state it differently.

**Exercise 20.4 ★.**

States 0 to 3; edges $0 \to 1$, $1 \to 2$, $2 \to 1$, $2 \to 3$, $3 \to 3$; $p$ holds in 1 and 3. Predict what `ctl.py` prints for EX $p$, EG $p$, AF $p$ and E[$\neg p$ U $p$].

**Solution of Exercise 20.4.**

EX $p$: states with a successor in $\{1, 3\}$: $\{0, 2, 3\}$. EG $p$: from $\{1, 3\}$, state 1’s only successor 2 is not in the set, so $\{3\}$. AF $p$: EG $\neg p$ starts from $\{0, 2\}$ and empties, since 0 leads to 1 and 2 leads to 1 or 3; so AF $p$ holds everywhere. E[$\neg p$ U $p$]: from $\{1, 3\}$, add 0 and 2: all four states.

**Exercise 20.5 ★★.**

`exercises/ex5_vcgen.py` generates [verification conditions](#def-b3-program-verification-vc) for loops but forgets one. Find a wrong program and postcondition it accepts, say which condition is missing, and fix it.

**Solution of Exercise 20.5.**

The generator emits no *exit* condition, $I \wedge \neg b \Rightarrow Q$, so the postcondition is never connected to the loop. It accepts `x = 0; while x < 10: x = x + 1` with invariant $x \le 10$ and postcondition $x = 11$, which is false (`test_exercise_5`). The fix appends `("exit", implies(conj(inv, neg(s.test)), q))`, as in [Listing 20.3](#lst-b3-program-verification-vcgen); then $x = 11$ is rejected and $x = 10$ accepted.

**Exercise 20.6 ★★.**

Write `for_vcs`, the [verification conditions](#def-b3-program-verification-vc) of a counted loop `for i in range(a, b)` with invariant $I$, from the rule in the file’s docstring. It is tested on a counting loop and on a wrong one.

**Solution of Exercise 20.6.**

`exercises/ex6_for.py`: entry $\mathit{pre} \Rightarrow I[a/i] \wedge a \le b$; preserved $I \wedge a \le i \wedge i < b \Rightarrow \mathrm{wp}(\mathit{body}, I[i + 1/i])$; exit $I[b/i] \Rightarrow \mathit{post}$. With `c = c + 1`, invariant $c = i \wedge n < 200$ and post $c = n$, all three are valid; with `c = c + 2`, preserved fails (`test_exercise_6`).

**Exercise 20.7 ★★.**

Prove the [assignment axiom](#def-b3-program-verification-hoare) sound: if $Q[e/x]$ holds in state $\sigma$, then $Q$ holds in $\sigma[x \mapsto v]$, where $v$ is the value of $e$ in $\sigma$.

**Solution of Exercise 20.7.**

Facts used: evaluating an expression in a state looks only at the values of its variables.

By induction on the formula $Q$: evaluating $Q[e/x]$ in $\sigma$ replaces each occurrence of $x$ by $e$, whose value in $\sigma$ is $v$; evaluating $Q$ in $\sigma[x \mapsto v]$ reads $v$ for each $x$ and the same values as $\sigma$ for every other variable. The two evaluations agree at every node, so $Q[e/x]$ holds in $\sigma$ exactly when $Q$ holds in $\sigma[x \mapsto v]$, the state after `x = e`. Wrap-around changes nothing, since both sides use the same 8-bit evaluation.

**Exercise 20.8 ★★.**

Starting from the state $(0, 0, 0, 0, 0)$ of [Listing 20.7](#lst-b3-program-verification-peterson), list by hand the states reachable in one and in two steps. Which of them have a process blocked?

**Solution of Exercise 20.8.**

States are (pc0, pc1, flag0, flag1, turn). One step: $(1, 0, 1, 0, 0)$ (process 0 raised its flag) and $(0, 1, 0, 1, 0)$. Two steps: $(2, 0, 1, 0, 1)$, $(1, 1, 1, 1, 0)$ and $(0, 2, 0, 1, 0)$; the middle one is reached both ways. None has a blocked process: a process at line 2 here sees the other’s flag down.

**Exercise 20.9 ★★.**

Write “every request is eventually granted” in CTL and in LTL, with propositions *req* and *grant*. Is `AG EF crit0` of [Output 20.5](#out-b3-program-verification-peterson) such a property? What does a [liveness property](https://one-course.com/books/computer-science/5/en/chapter/13-concurrency-deadlock-monitors-and-lock-free-structures#def-b3-concurrency-properties) of Peterson’s algorithm need that the model lacks?

**Solution of Exercise 20.9.**

CTL: AG(*req* $\Rightarrow$ AF *grant*). LTL: G(*req* $\Rightarrow$ F *grant*). AG EF $\mathit{crit}_0$ is weaker: process 0 can always still get in, on some path, not on all. For a true [liveness property](https://one-course.com/books/computer-science/5/en/chapter/13-concurrency-deadlock-monitors-and-lock-free-structures#def-b3-concurrency-properties) the model needs fairness: a scheduler that lets every process that can move eventually move; without it, the path where only process 1 runs refutes AF $\mathit{crit}_0$.

**Exercise 20.10 ★★★.**

Prove the while rule sound: if every terminating run of $S$ from $I \wedge b$ ends in $I$, then every terminating run of `while b: S` from $I$ ends in $I \wedge \neg b$.

**Solution of Exercise 20.10.**

Facts used: a terminating run of `while b: S` is a finite sequence of runs of $S$, each from a state where $b$ holds, ending in a state where $b$ fails.

Let the run pass through states $\sigma_0, \sigma_1, \ldots, \sigma_k$, where $\sigma_{j+1}$ is the result of $S$ from $\sigma_j$, $b$ holds in $\sigma_0, \ldots, \sigma_{k-1}$ and fails in $\sigma_k$. By induction on $j$, $I$ holds in $\sigma_j$: in $\sigma_0$ by assumption, and if $I$ holds in $\sigma_j$ with $j < k$, then $I \wedge b$ holds there, and the premise gives $I$ in $\sigma_{j+1}$. So $I \wedge \neg b$ holds in $\sigma_k$.

**Exercise 20.11 ★★★.**

Prove that EF $g$ is the [least fixed point](https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation#def-b3-program-optimisation-lfp) of $Z \mapsto g \vee \mathrm{EX}\,Z$, and that iteration from the empty set reaches it in at most $|S|$ rounds.

**Solution of Exercise 20.11.**

Facts used: $F(Z) = g \cup \mathrm{EX}\,Z$ is monotone; the subsets of a finite set $S$ ordered by inclusion have no infinite strictly increasing chain.

EF $g$ is a [fixed point](https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation#def-b3-program-optimisation-lfp): a state reaches $g$ if and only if it is in $g$ or has a successor that reaches $g$. It is the least: if $F(Z) = Z$, then by induction on $k$ every state reaching $g$ in $k$ steps is in $Z$ (for $k = 0$, $g \subseteq Z$; a state reaching $g$ in $k + 1$ steps has a successor in $Z$, so it is in $\mathrm{EX}\,Z \subseteq Z$). Iterating $Z_0 = \emptyset$, $Z_{k+1} = F(Z_k)$ gives $Z_k$ = the states reaching $g$ in fewer than $k$ steps, an increasing chain; it stops growing after at most $|S|$ strict increases, at EF $g$.

**Exercise 20.12 ★★★.**

Verify insertion sort on four values below 16, unrolled into compare-exchange steps, by [bit-blasting](#def-b3-program-verification-vc) the program itself: each variable a word of gates, each `if` merged with multiplexers. Prove that the result is sorted and made of the inputs, report the size of the CNF, and break one comparison to see a counterexample. Why not use wp here?

**Solution of Exercise 20.12.**

`exercises/ex12_sort.py` executes the program on words of gates: an assignment rebinds a variable’s word, and an `if` runs both branches and merges each variable that differs with a multiplexer $c ? x : y$. The [verification condition](#def-b3-program-verification-vc), inputs below 16 implies sorted output each equal to some input and each input equal to some output, gives a CNF of 1,390 variables and 4,538 clauses; the solver finds it valid. Replacing `a2 > a3` by `a2 < a3` gives a counterexample, $b = (0, 0, 0, 8)$ (`test_exercise_12`). wp duplicates the postcondition at each `if`, so six compare-exchange steps give $2^6$ copies, and the formula, built from substituted expressions, grows far faster than the program; the symbolic execution grows linearly. (Checking that the sums agree instead makes the solver’s work much larger: equivalence of adders is hard for CDCL.)

## 20.7 Weekend problem

**Problem 20.1.**

Weekend problem — Two lifts and one shaft

A lift tower shares one section of shaft between its lifts; at most one lift may be in it. Each lift goes from *idle* to *waiting*, then into the *shaft*, and back to idle, and a lock bit guards the shaft. In the correct protocol a waiting lift takes a free lock in one atomic step; in the buggy one it tests the lock in one step and takes it in the next. The model is in `lifts.py`.

```python
def moves(state, atomic):
    """Every state reachable in one step of one lift. A state is (lock, positions)."""
    lock, pos = state
    for i, p in enumerate(pos):

        def at(q, new_lock=lock, i=i):
            return new_lock, pos[:i] + (q,) + pos[i + 1 :]

        if p == IDLE:
            yield i, at(WAIT)
        elif p == WAIT and lock == 0:  # the lock is free
            yield i, at(SHAFT, 1) if atomic else at(READY)
        elif p == READY:  # buggy: takes the lock without testing again
            yield i, at(SHAFT, 1)
        elif p == SHAFT:
            yield i, at(IDLE, 0)
```

***Listing 20.8.** One step of one lift. code/bachelor-3/20-program-verification/listings/lifts.py*

```
$ python lifts.py
lifts   states   buggy: fails after
    1        3   never
    2        8   6 steps
    3       20   6 steps
    4       48   6 steps
    5      112   6 steps
    6      256   6 steps
fit: states = 1.33 * 2.426^n
```

***Output 20.6.** Reachable states of the correct protocol for 1 to 6 lifts, the length of the shortest run that breaks the buggy one, and a fit of the growth.*

**Part I — The model.**

1. What is a state, and how many states are there before asking which are reachable, for $n$ lifts in the correct protocol?
2. Why is every state’s successor set nonempty, as a [Kripke structure](#def-b3-program-verification-kripke) requires?
3. List the reachable states for one lift.
4. Why does interleaving, one lift moving per step, model lifts that run at the same time?
5. List the 8 reachable states for two lifts.
6. Which unreachable states does the lock exclude?

**Part II — The properties.**

7. Write mutual exclusion in CTL for two lifts.
8. Write “a waiting lift can always still get in” in CTL.
9. Why does “a waiting lift eventually gets in”, AG( *wait* $\Rightarrow$ AF *shaft* ), fail in this model?
10. What assumption about the scheduler would make it true?
11. Is mutual exclusion a safety or a [liveness property](https://one-course.com/books/computer-science/5/en/chapter/13-concurrency-deadlock-monitors-and-lock-free-structures#def-b3-concurrency-properties) , and what does a counterexample to each look like?
12. Why is AG $f$ checked by reachability alone?

**Part III — The bug.**

13. Give the 6-step trace that breaks the buggy protocol for two lifts.
14. Why is it the shortest?
15. Why is it also 6 steps for 3, 4, 5 and 6 lifts?
16. Would testing many times before taking the lock fix the bug?
17. Which instruction of a processor makes the correct protocol’s atomic step possible?
18. Relate the bug to Peterson’s variant without turn.

**Part IV — State explosion.**

19. Prove that the correct protocol has $(n + 2) 2^{n - 1}$ reachable states, and check the table.
20. What growth rate $b$ does the fit report, and why is it above 2?
21. How many states for 20 lifts, and for 40?
22. The search stores each state once. At about 100 bytes per state in Python, what memory do 40 lifts need?
23. The lifts are identical. How could symmetry reduce the count, and to how many states for $n$ lifts?
24. Sum up: what is verified, what failed and in how many steps, and how the work grows with $n$ .

**Solution of Problem 20.1.**

**1.** The lock bit and the position of each lift, idle, waiting or in the shaft: $2 \cdot 3^n$ combinations.

**2.** An idle lift can always move to waiting, and a lift in the shaft can always leave; a state with every lift waiting has the lock free (no lift holds it), so one of them can enter.

**3.** (0, I), (0, W), (1, S).

**4.** Moves of different lifts that happen at the same time can be put in either order, and every order is explored.

**5.** Lock 0: II, IW, WI, WW; lock 1: SI, SW, IS, WS.

**6.** Lock 0 with a lift in the shaft, lock 1 with none, and two lifts in the shaft.

**7.** AG $\neg(\mathit{shaft}_0 \wedge \mathit{shaft}_1)$.

**8.** AG($\mathit{wait}_0 \Rightarrow$ EF $\mathit{shaft}_0$).

**9.** On the path where lift 1 enters, leaves and enters again for ever, lift 0 waits for ever.

**10.** Strong fairness for the waiting lift, or a queue; the protocol as modelled has no queue.

**11.** Safety: a counterexample is a finite trace ending in a bad state. Liveness: a counterexample is an infinite path, in a finite model a lasso, a prefix followed by a loop.

**12.** AG $f$ fails exactly when a reachable state violates $f$; reaching it is all the counterexample needs.

**13.** Lift 0 waits, lift 1 waits, lift 0 tests the free lock, lift 1 tests the free lock, lift 0 takes it and enters, lift 1 takes it and enters.

**14.** Breadth-first search finds states in order of distance; and each lift needs 3 steps of its own to be in the shaft, so two lifts need 6.

**15.** The same two lifts can do it; the other lifts staying idle does not shorten it.

**16.** No: between the last test and the take, the other lift can still test and take.

**17.** An atomic test-and-set or [compare-and-swap](https://one-course.com/books/computer-science/5/en/chapter/13-concurrency-deadlock-monitors-and-lock-free-structures#def-b3-concurrency-atomics).

**18.** Both test a shared flag, then act on it in a later step, so both can pass the test before either acts.

**19.** With the lock free, no lift is in the shaft and each lift is idle or waiting: $2^n$ states. With the lock taken, exactly one lift is in the shaft, $n$ choices, and the others are idle or waiting: $n 2^{n-1}$. Each is reachable, and the total is $(n + 2) 2^{n - 1}$: 3, 8, 20, 48, 112, 256, as in the table.

**20.** 2.426 per lift, because the factor $n + 2$ grows too, from 3 to 8 between 1 and 6 lifts, and the fit puts that growth into $b$; as $n$ grows, the rate per lift tends to 2.

**21.** $22 \cdot 2^{19} = 11{,}534{,}336$ for 20 lifts; $42 \cdot 2^{39} \approx 2.3 \times 10^{13}$ for 40.

**22.** About $2.3 \times 10^{15}$ bytes, more than two thousand terabytes: out of reach.

**23.** Count only how many lifts are idle, waiting or in the shaft: with the lock free, $k$ waiting for $k = 0, \ldots, n$; with it taken, one in the shaft and $k$ waiting for $k = 0, \ldots, n - 1$: $2n + 1$ states.

**24.** The correct protocol keeps AG $\neg$(two lifts in the shaft) over its $(n + 2)2^{n-1}$ reachable states, 256 for 6 lifts; the buggy one fails after 6 steps for every $n \ge 2$; and the state count grows about 2.4 times per lift, which is why model checkers need symmetry and symbolic methods.
