هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.
University Computer Science — Year 3 · السنة الجامعية 3
20Program 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 turns it into formulas called verification conditions, and the CDCL solver of Chapter 18 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: 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 relates a program and a starting state to its final state (Definition 5.13). A least fixed point is computed by iterating from the bottom (Definition 8.3). 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 , 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.
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
value evaluates expressions with 8-bit wrap-around. code/bachelor-3/20-program-verification/listings/whilelang.pyDefinition 20.1 (Hoare triple, Hoare logic, assignment axiom, rule of consequence)
A Hoare triple is valid when every run of from a state satisfying that terminates ends in a state satisfying . Hoare logic derives triples by the rules below, where is with substituted for .
- The assignment axiom: .
- Sequence: from and , derive .
- If: from and , derive
if b: S1 else: S2. - While: from , derive
while b: S. - The rule of consequence: from , and , derive .
The assignment axiom runs backwards: for to satisfy after , the expression 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.
The proof is by induction on the derivation, one case per rule: the assignment axiom because evaluating in the state after is evaluating in the state before (Exercise 20.7), the while rule by induction on the number of iterations (Exercise 20.10), the others directly. hoare_check.py checks a derivation node by node, and decides the implications of the rule of consequence with the solver of Section 20.3.
$ 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}
20.2 Weakest preconditions
Definition 20.3 (Weakest precondition, strongest postcondition)
The weakest precondition is a formula that holds in exactly the states from which every run of terminates in a state satisfying . The strongest postcondition holds in exactly the states that runs of from can end in.
For loop-free programs, wp is computed backwards, one statement at a time:
and the if gives ; 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 , is valid if and only if is valid.
By induction on , the formula computed holds in a state exactly when every run of from it ends in ; the triple is then the implication. Edsger Dijkstra introduced weakest preconditions in 1975.
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
$ 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)
t exchanges and 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 as its precondition and emits three conditions for it: preserved, ; exit, ; and, with a variant , variant, . A final condition, entry, says that the precondition implies what the program needs at its start.
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
Each condition is valid exactly when 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 is a counterexample: values of the variables that make the condition false.
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
Binary search keeps an interval 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 proves termination.
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
"""
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
With and , , which wraps to 64 in 8 bits, and the midpoint 32 lies below . The same failure happens with 32-bit indices on arrays of more than elements, and the cure, , is the same. That state satisfies the invariant, but no run reaches it: from , the first move to the right already fails, at . The failure is still not an artefact of the invariant: run on , always choosing the upper half, the interpreter makes the assertion fail at , .
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): holds when some path reaches a -state through -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: , , . 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)
is the least fixed point of , and is the greatest fixed point of , sets of states being ordered by inclusion.
For EF, the -th iterate from the empty set is the set of states that reach in fewer than steps, and the iteration stops after at most as many rounds as there are states (Exercise 20.11). The greatest fixed point 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.
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)
$ 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]
The two logics differ. In the second structure, state 0 loops on or moves to state 1 () and then to state 2, which loops on . Every path eventually stays in for ever, so the LTL formula F G holds at state 0. But AF AG fails there: along the path that stays at state 0, no state satisfies AG , 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, satisfies a temporal formula, by exploring its states. When a safety property AG fails, a counterexample trace is a path from the start to a state violating . State explosion is the growth of the number of reachable states, exponential in the number of components of the system.
Model checking 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, and ctl.py checks mutual exclusion, AG , and that process 0 can always still reach its critical section, AG EF .
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)
$ 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)
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 processes with states each can have up to 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 by hand, and say what the program does, in 8-bit arithmetic too.
Solution
Solution of Exercise 20.1.
Backwards: after x = x - y, ; after y = x - y, ; after x = x + y, , that is . The program swaps and 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 wraps.
Exercise 20.2 ★
Is valid with 8-bit unsigned integers? With unbounded integers?
Solution
Solution of Exercise 20.2.
The weakest precondition is . With unbounded integers it holds for every , so the triple is valid. In 8 bits, for the sum wraps to : not valid; is a counterexample.
Exercise 20.3 ★
Give an invariant that proves s = 0; i = 0; while i < n: i = i + 1; s = s + i with unbounded integers. What is the largest for which the 8-bit loop computes without wrapping?
Solution
Solution of Exercise 20.3.
: . At entry . Kept: from and , after and we get and . At exit and , so . In 8 bits, requires (); at , would be 276 and wraps. The product in the postcondition wraps earlier, from , so an 8-bit proof must state it differently.
Exercise 20.4 ★
States 0 to 3; edges , , , , ; holds in 1 and 3. Predict what ctl.py prints for EX , EG , AF and E[ U ].
Solution
Solution of Exercise 20.4.
EX : states with a successor in : . EG : from , state 1’s only successor 2 is not in the set, so . AF : EG starts from and empties, since 0 leads to 1 and 2 leads to 1 or 3; so AF holds everywhere. E[ U ]: from , add 0 and 2: all four states.
Exercise 20.5 ★★
exercises/ex5_vcgen.py generates verification conditions for loops but forgets one. Find a wrong program and postcondition it accepts, say which condition is missing, and fix it.
Solution
Solution of Exercise 20.5.
The generator emits no exit condition, , so the postcondition is never connected to the loop. It accepts x = 0; while x < 10: x = x + 1 with invariant and postcondition , which is false (test_exercise_5). The fix appends ("exit", implies(conj(inv, neg(s.test)), q)), as in Listing 20.3; then is rejected and accepted.
Exercise 20.6 ★★
Write for_vcs, the verification conditions of a counted loop for i in range(a, b) with invariant , from the rule in the file’s docstring. It is tested on a counting loop and on a wrong one.
Solution
Solution of Exercise 20.6.
exercises/ex6_for.py: entry ; preserved ; exit . With c = c + 1, invariant and post , all three are valid; with c = c + 2, preserved fails (test_exercise_6).
Exercise 20.7 ★★
Prove the assignment axiom sound: if holds in state , then holds in , where is the value of in .
Solution
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 : evaluating in replaces each occurrence of by , whose value in is ; evaluating in reads for each and the same values as for every other variable. The two evaluations agree at every node, so holds in exactly when holds in , 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 of Listing 20.7, list by hand the states reachable in one and in two steps. Which of them have a process blocked?
Solution
Solution of Exercise 20.8.
States are (pc0, pc1, flag0, flag1, turn). One step: (process 0 raised its flag) and . Two steps: , and ; 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 such a property? What does a liveness property of Peterson’s algorithm need that the model lacks?
Solution
Solution of Exercise 20.9.
CTL: AG(req AF grant). LTL: G(req F grant). AG EF is weaker: process 0 can always still get in, on some path, not on all. For a true liveness property 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 .
Exercise 20.10 ★★★
Prove the while rule sound: if every terminating run of from ends in , then every terminating run of while b: S from ends in .
Solution
Solution of Exercise 20.10.
Facts used: a terminating run of while b: S is a finite sequence of runs of , each from a state where holds, ending in a state where fails.
Let the run pass through states , where is the result of from , holds in and fails in . By induction on , holds in : in by assumption, and if holds in with , then holds there, and the premise gives in . So holds in .
Exercise 20.11 ★★★
Prove that EF is the least fixed point of , and that iteration from the empty set reaches it in at most rounds.
Solution
Solution of Exercise 20.11.
Facts used: is monotone; the subsets of a finite set ordered by inclusion have no infinite strictly increasing chain.
EF is a fixed point: a state reaches if and only if it is in or has a successor that reaches . It is the least: if , then by induction on every state reaching in steps is in (for , ; a state reaching in steps has a successor in , so it is in ). Iterating , gives = the states reaching in fewer than steps, an increasing chain; it stops growing after at most strict increases, at EF .
Exercise 20.12 ★★★
Verify insertion sort on four values below 16, unrolled into compare-exchange steps, by bit-blasting 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
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 . The verification condition, 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, (test_exercise_12). wp duplicates the postcondition at each if, so six compare-exchange steps give 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.
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)
$ 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
Part I — The model.
- What is a state, and how many states are there before asking which are reachable, for lifts in the correct protocol?
- Why is every state’s successor set nonempty, as a Kripke structure requires?
- List the reachable states for one lift.
- Why does interleaving, one lift moving per step, model lifts that run at the same time?
- List the 8 reachable states for two lifts.
- Which unreachable states does the lock exclude?
Part II — The properties.
- Write mutual exclusion in CTL for two lifts.
- Write “a waiting lift can always still get in” in CTL.
- Why does “a waiting lift eventually gets in”, AG(wait AF shaft), fail in this model?
- What assumption about the scheduler would make it true?
- Is mutual exclusion a safety or a liveness property, and what does a counterexample to each look like?
- Why is AG checked by reachability alone?
Part III — The bug.
- Give the 6-step trace that breaks the buggy protocol for two lifts.
- Why is it the shortest?
- Why is it also 6 steps for 3, 4, 5 and 6 lifts?
- Would testing many times before taking the lock fix the bug?
- Which instruction of a processor makes the correct protocol’s atomic step possible?
- Relate the bug to Peterson’s variant without turn.
Part IV — State explosion.
- Prove that the correct protocol has reachable states, and check the table.
- What growth rate does the fit report, and why is it above 2?
- How many states for 20 lifts, and for 40?
- The search stores each state once. At about 100 bytes per state in Python, what memory do 40 lifts need?
- The lifts are identical. How could symmetry reduce the count, and to how many states for lifts?
- Sum up: what is verified, what failed and in how many steps, and how the work grows with .
Solution
Solution of Problem 20.1.
1. The lock bit and the position of each lift, idle, waiting or in the shaft: 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 .
8. AG( EF ).
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 fails exactly when a reachable state violates ; 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.
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: states. With the lock taken, exactly one lift is in the shaft, choices, and the others are idle or waiting: . Each is reachable, and the total is : 3, 8, 20, 48, 112, 256, as in the table.
20. 2.426 per lift, because the factor grows too, from 3 to 8 between 1 and 6 lifts, and the fit puts that growth into ; as grows, the rate per lift tends to 2.
21. for 20 lifts; for 40.
22. About 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, waiting for ; with it taken, one in the shaft and waiting for : states.
24. The correct protocol keeps AG (two lifts in the shaft) over its reachable states, 256 for 6 lifts; the buggy one fails after 6 steps for every ; and the state count grows about 2.4 times per lift, which is why model checkers need symmetry and symbolic methods.
المصطلحات المعرَّفة في هذا الفصل
- Annotated program, verification condition, bit-blasting
- Hoare triple, Hoare logic, assignment axiom, rule of consequence
- Kripke structure, temporal logic, computation tree logic, linear temporal logic
- Model checking, counterexample trace, state explosion
- Weakest precondition, strongest postcondition