Proving Programs Correct
If testing can only show that bugs are present, how do we prove that a program has none?
The part opens on three bugs in tested programs, Ariane 5, Therac-25 and Heartbleed, and on binary search's midpoint posed as a SAT problem over 16-bit integers: the solver finds lo = 8,997 and hi = 27,291, whose sum wraps to -29,248, and proves the repaired midpoint for every lo < hi. Rice's theorem rules out deciding correctness in general, and the part takes three ways round it. The first is to write the invariant ourselves: Turing's 1949 proof, Floyd-Hoare logic, Dijkstra's weakest preconditions, and verification conditions bit-blasted for Part 26's solver, with separation logic for pointers. The second is to exhaust a finite state space: a model checker finds the bugs planted in Peterson's lock, two-phase commit and a Raft election, and BDDs and bounded model checking push past the state explosion. The third is to approximate soundly, with intervals and widening, and with types. The part then turns to who checks the proofs: an LCF kernel of 69 lines, CompCert and seL4, TLA+. It ends with testing treated as science, a fuzzer that finds a bug planted in our own compiler and shrinks the failing program from 75 lines to 9, and the open problem of inferring invariants for loops with multiplication.
What you need. Propositional logic and proof by induction; two's-complement arithmetic as in Part 4.
- Mathematics, ideas and history
- Hoare logic, weakest preconditions, separation logic, model checking with BDDs and SAT, abstract interpretation, proof assistants, CompCert and seL4, fuzzing
- What we build or compute
- a verifier, a model checker and a fuzzer
What you will be able to do
Degree
- Write a precondition, a postcondition and a loop invariant for a short program, and check the invariant on a run.
- Push an assertion backward through assignments with the assignment axiom.
- Explain why (lo + hi) >> 1 fails on machine integers and which repairs hold for which inputs.
Graduate
- Compute weakest preconditions and the five verification conditions of a loop with an invariant and a variant.
- Compute EF and EG on a Kripke structure as least and greatest fixpoints, and read a lasso as a liveness counterexample.
- Run interval analysis on a loop with widening and narrowing, and say why the result is sound.
Research
- Prove that widening reaches a post-fixpoint in at most 2n strict steps per loop head and that narrowing stays above the least fixpoint.
- State the invariant-inference problem for loops with multiplication and what a complete procedure for a fixed class of invariants would have to show.
Industry
- Specify a protocol as a state machine, model-check it at a small scope and read the shortest counterexample.
- Set up differential fuzzing of a compiler and reduce a failing program by delta debugging.
- Say what remains trusted in a verified system: the specification, the kernel, the hardware.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 21 min · Graduate 50 min · Research 51 min · Industry 30 min.
- 0The cost of bugsDegree2 min
- 1Specifications, and the first program proofDegree3 min
- 2Floyd-Hoare logicDegree3 min
- 3Binary search, provedDegree4 min
- 4Weakest preconditions, checked by SATGraduate3 min
- 5Separation logicGraduate3 min
- 6Model checkingDegree4 min
- 7Symbolic and bounded model checkingGraduate3 min
- 8Abstract interpretationGraduate3 min
- 9Types as lightweight proofsGraduate3 min
- 10Proof assistantsGraduate3 min
- 11Verified systemsIndustry3 min
- 12Specifying systems: TLA+Industry3 min
- 13Testing as scienceDegree3 min
- 14Fuzzing and validating our compilerIndustry3 min
- 15Frontier: proofs at scaleResearch1 min
- Recap, problems, and where this comes backAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
The cost of bugsDegree2 min
Three bugs. In 1996 the first Ariane 5 rocket destroyed itself thirty-seven seconds after launch, because reused code converted a sixty-four-bit floating-point number to a sixteen-bit integer, and it overflowed. Between 1985 and 1987 race conditions in the software of the Therac-25 radiation machine gave patients massive overdoses, and some died. In 2014 a single missing bounds check in OpenSSL let anyone read secrets out of a server's memory. All three programs had been tested. Edsger Dijkstra said it in 1970: testing can show that bugs are present, never that they are absent.
Here is a bug of the famous kind. Binary search needs the midpoint to lie between low and high. The textbook line adds them and halves the sum. We turned that requirement into a logical formula over sixteen-bit integers and handed it to our own SAT solver from Part 26. In 0.03 seconds it found a counterexample: their sum overflows, wraps to a negative number, and the midpoint falls outside the range. The repaired line, which shifts the difference without a sign, makes the formula unsatisfiable: correct for every sixteen-bit input, a proof, not a test. Joshua Bloch reported in 2006 that this overflow had sat in Java's binary search for nine years. Rice's theorem says correctness cannot be decided in general, so this part goes around it three ways.
1Specifications, and the first program proofDegree3 min
A program is correct only relative to a specification of what it should do. The usual form is a pair of conditions. The precondition is what the caller promises: for this maximum function, nothing at all, so it is simply true. The postcondition is what the code promises in return: the result is at least a, at least b, and equal to one of them. The specification says what; the code says how. A proof shows that they agree on every input, not only on the inputs we happened to try.
Writing the specification is half the work, and it is easy to get wrong. Drop the last clause of our postcondition. Returning a alone still fails. But returning thirty-two thousand seven hundred and sixty-seven, the largest sixteen-bit integer, is at least a and at least b for every input: it meets the weakened specification, and it is useless. The classic case is sorting. Ask only that the output be sorted, and returning the empty list is correct. The output must also be a permutation of the input.
Some specifications must talk about the past. To say that this code swaps x and y, the postcondition needs their starting values. We name them capital X and capital Y: ghost variables, never read or written by the program, living only in the specification. Run the three lines on sixteen-bit integers. The first adds, and the sum overflows and wraps round to a negative number. The second subtracts, and the wrap undoes itself: y now holds the old x. The third gives x the old y. In Chapter four our SAT solver proves this for every pair of values.
The idea of proving a program is as old as the stored-program computer. In June 1949, at a conference in Cambridge, Alan Turing gave a short talk called Checking a Large Routine. His example computed n factorial by repeated addition, one loop inside another, on a machine with no multiplier. Here is a routine in that spirit. Turing attached assertions to points of the flow diagram: whenever control passes here, u equals r factorial; inside the inner loop, u is s times r factorial. At the stop box the assertion is the specification itself. A run with n equal to five shows the assertion holding at every visit; the argument covers every n.
2Floyd-Hoare logicDegree3 min
Hoare's logic has one kind of sentence. P, c, Q says: if P holds before c runs, and c finishes, then Q holds afterwards. Think of each assertion as a set of states: every run that starts in P and ends, ends in Q. A run that never ends satisfies the triple trivially. This is partial correctness, and termination needs its own proof. If x is five, then after x gets x plus one, x is six.
Assignment comes first, and it runs backwards. To know what must hold before x gets e, take what we want afterwards and write e wherever it says x. We want x greater than five after x gets x plus one. Substitute: x plus one greater than five. Simplify: x greater than four. Our tool does the same to real code, here the swap's last line. Going forwards is harder: the assignment destroys the old x, and the rule needs an existential to remember it.
Sequencing glues triples together: if c one takes P to R, and c two takes R to Q, the pair takes P to Q. That gives a mechanical method. Start from the swap's postcondition at the bottom. Push it up through each line by substitution. Each assertion between two lines is the R of the rule, and no cleverness was needed. What arrives at the top must now be compared with the precondition.
The rule of consequence lets us strengthen a precondition or weaken a postcondition. This is what arrived at the top of the swap. x plus y minus y is x. And x plus y minus x is y. Reordered, it is the precondition, and the swap is proved. These identities hold in sixteen-bit wrap-around arithmetic too, so the swap is right even when the sum overflows. What remains is a statement about integers, a verification condition, for a machine to check.
For a conditional, prove both branches, each knowing which way the test went. Push the maximum's postcondition up each branch. In one, m becomes a; in the other, b. When a is at least b, every part of the first is true; otherwise b exceeds a, and every part of the second is true. The precondition of the whole if combines the two, and it always holds, so true suffices.
Loops need the one ingredient a machine cannot supply: an invariant. If the body, entered with the invariant and the test true, restores the invariant, then the loop leaves with the invariant and the test false. Gauss's loop adds one, two, three, up to n, and its invariant says twice s is i times i plus one. After the body, twice the new s is twice s plus twice i plus one. The invariant replaces twice s; factor out i plus one, and it is the invariant again, one step on. At the exit, i equals n: Gauss's formula.
3Binary search, provedDegree4 min
Binary search is the classic test of reasoning about a loop. We look in a sorted array for the first element at least x. Two indices, low and high, bracket the answer. The invariant: everything left of low is less than x, everything from high on is at least x, and low never passes high. Each step looks at the middle and moves one end, keeping the invariant true. When low meets high nothing unknown is left, and the invariant alone says that low is the answer.
Our checker sees the loop's skeleton. The comparison with the array becomes an unknown c, chosen afresh on every pass, so whatever is proved holds for every array and every target. The assertion inside is the array access: the middle index must be in range. We supply the invariant, low between zero and high, and a variant, high minus low. Out come five verification conditions. Bit-blasted over sixteen-bit integers and given to our SAT solver from Part 26, all five are valid; the hardest took about one and a half seconds. The search property itself needs reasoning about arrays, which this small checker leaves out.
Now restore the textbook midpoint: add low and high, and halve. The solver no longer proves the invariant preserved. It returns a counterexample: low fifteen thousand and seventy-two, high twenty-five thousand five hundred and fifty-eight. Their sum, forty thousand six hundred and thirty, is beyond the largest sixteen-bit integer, and wraps round to minus twenty-four thousand nine hundred and six. Halved, that is minus twelve thousand four hundred and fifty-three, far below low: the array access fails. Joshua Bloch reported in 2006 that this line was in Java's library, and in the binary search Jon Bentley had proved correct in Programming Pearls. That proof was right about mathematical integers, and wrong about the machine.
The solver can judge every proposed repair. The textbook midpoint fails. Bloch's first fix, low plus half the difference, is proved for non-negative indices; his second, an unsigned shift of the sum, is proved too, because the shift reads the lost carry back as the top bit. Drop the assumption that low is non-negative, and the first fix fails as well: the difference itself overflows. Shifting the difference without a sign is right for every low below high. Each verdict took a fraction of a second.
Partial correctness says nothing if the loop runs for ever; total correctness adds termination, and the tool is a variant. Find a quantity that stays non-negative and that every pass makes strictly smaller. Here it is high minus low. Moving low to mid plus one shrinks the gap, because mid is at least low; moving high to mid shrinks it, because mid is below high. Both lean on the midpoint lying in range, and with the textbook midpoint the solver refutes this condition too. In a run the gap falls at every pass, and a natural number cannot fall for ever.
4Weakest preconditions, checked by SATGraduate3 min
Hoare's rules check a proof; Dijkstra's weakest preconditions compute one. For a statement c and a postcondition Q, the weakest precondition is the set of all starting states from which c is sure to finish inside Q. Every valid precondition lies inside it, so a triple holds exactly when its precondition implies the weakest one. Dijkstra introduced the idea in 1975, with his guarded commands, as a calculus for deriving programs together with their proofs. Read as a function from postconditions to preconditions, it turns proving into calculating.
The rules become equations. Assignment is substitution. A sequence takes the second statement first, then the first. A conditional splits on its test. An assertion adds a conjunct, and havoc, an unknown value, means the condition must hold for every value. Here is our tool on the start of Gauss's loop. The loop contributes its invariant. Pushing it up through s gets zero writes zero for s; through i gets zero, zero for i. What remains must follow from the precondition, n at least zero. That implication is the first verification condition, and it is plainly true.
Loops are where the calculation needs help. We give the generator the loop's invariant and a variant. It turns the program into five closed formulas: the invariant is established on entry, preserved by the body, and together with the exit test gives the postcondition; the variant stays non-negative, and falls on every pass. Each formula speaks only about integers. The program has disappeared. If all of them are valid, the program is correct; if one fails, either the program or its annotation is wrong.
How does a SAT solver judge a statement about integers? A formula is valid exactly when its negation has no satisfying assignment. So we negate it, and translate. Each sixteen-bit integer becomes sixteen Boolean variables, and addition becomes a chain of full adders passing carries along, the circuit of Part 4. Every gate becomes a new variable and a few clauses; for an and gate, three. For the swap, the result is four hundred and twenty-five variables and one thousand two hundred and thirty-nine clauses. Our CDCL solver from Part 26 shows them unsatisfiable in about a quarter of a second, so the swap is right for every pair of sixteen-bit values.
Here is every program of this part so far. The maximum, the swap and the binary search loop are proved at sixteen bits. Gauss's loop is proved at eight bits, for a reason we are about to see. The binary search with the textbook midpoint is refuted: two of its five conditions fail, each with concrete values from the solver. A counterexample is never taken on trust. The tool evaluates the formula on the solver's values and checks that it really is false.
5Separation logicGraduate3 min
Hoare's logic treats each variable as its own box, and pointers break that. Suppose y's field holds two, and we store three through x. The assignment axiom says y's field still holds two, since the postcondition never mentions x. If x and y point to different cells, that is right. If they point to the same cell, it is false. The classical repair treats the heap as one big array, and every read must then ask whether two pointers are equal. With n pointers, that is about n squared over two cases.
Around two thousand and one, John Reynolds, Peter O'Hearn and Hongseok Yang made each assertion describe a piece of the heap. Emp holds of the empty heap; x points to v holds of exactly one cell. The separating conjunction, P star Q, says the heap splits into two disjoint parts, P holding of one and Q of the other. Two cells joined by the star are at different addresses; joined by an ordinary and, they must be the same cell. A list is either empty, or a first node separately joined to the rest of the list.
The heap's rules are small. A store into the cell at x needs exactly that cell; reading, allocating and freeing are just as local. Everything else comes back through the frame rule: if c takes P to Q, it takes P star R to Q star R, provided c changes none of R's variables. What c touches is its footprint; the rest is the frame. Our store: the small axiom gives x points to three. Frame on y points to two. The star already excludes aliasing, so there is no case split. O'Hearn calls this local reasoning.
Reynolds' showcase was reversing a linked list in place. The variable i walks down the old list, j collects the reversed part, and k remembers the way on. Each pass saves i's successor, turns i's next pointer round to j, and moves both one node on. One node at a time leaves i's list for the front of j's, until i is nil. Nothing is allocated or freed. Correctness means the two lists never share a cell and never lose one, which is exactly what the star can say.
One invariant does it. Two lists, alpha from i and beta from j, kept apart by the star; and the original list reversed equals alpha reversed followed by beta. Enter the body with i not nil: i's list has a first node, a. Unfold it; reading i dot next names the rest k. The store into i dot next touches one cell. The small axiom handles it, and the frame rule carries both other lists through. Fold: i now heads the list a followed by beta. Renaming restores the invariant. At the exit alpha is empty, and j holds the list reversed.
6Model checkingDegree4 min
A model checker explores behaviour rather than text. Behaviour is a Kripke structure, after Saul Kripke's semantics for modal logic: a set of states, some of them initial. Transitions say which state can follow which; every state has a successor, so every run is an infinite path. Each state is labelled with the simple facts true in it. Peterson's lock from Part 33, explored breadth first by our checker, has twenty states and forty-six transitions.
Unroll the structure from its initial state, and you get a tree of every possible future. Amir Pnueli's linear temporal logic, of 1977, speaks of one path at a time: always, eventually, until. Clarke and Emerson's CTL, of 1981, adds path quantifiers: A for all paths, E for some. E F q: some path reaches q. True. A G p: p everywhere, on every path. False. A F q: every path reaches q. False: this one stays in the dead end. E G p: some path keeps p for ever. True, round the loop.
CTL is checked backwards, over sets of states. E F q holds now, or one step later. That is an equation in an unknown set, and E F q is its least solution. Iterate: start with the q states, add every state with a successor in the set, and repeat. The set grows backwards along the transitions. After four rounds nothing changes, and the dead end never joins. E G is a greatest fixpoint, the rest follow by duality, and the whole check takes time linear in the structure, as Clarke, Emerson and Sistla showed in 1986.
Now a real algorithm. Peterson's lock: raise your flag, give the other process the turn, and wait until its flag is down or the turn is yours. Our checker answers six questions over all twenty states. Mutual exclusion holds; the lock never gets stuck; a waiting process can always get in. But a waiting process does not always get in. Part 33's checker, working with single loads and stores, agrees on mutual exclusion.
That failure is about liveness: something good must eventually happen. Whenever process zero tries, it eventually gets in. The counterexample is a lasso, a stem followed by a cycle repeated for ever. Process zero raises its flag and gives away the turn. The door is open, but the scheduler only ever runs process one, which idles. No real scheduler is that unfair. Assume weak fairness, that a step which stays enabled is eventually taken, and the property holds for both processes.
The catch is size. Dijkstra's dining philosophers: two have six states; eight have one thousand one hundred and fifty-four. Each philosopher multiplies the count by about two point four: the state explosion. For every size the checker finds the deadlock, everyone holding a left fork, in n steps. Take forks in a global order, Part 33's cure, and no deadlock is reachable. Yet a philosopher can still starve under weak fairness, though not under strong. To go further, we must stop listing states one by one.
7Symbolic and bounded model checkingGraduate3 min
Explicit checking lists states one at a time; symbolic checking describes whole sets with formulas. Give each philosopher two bits: holding its first fork, and eating. A state of three philosophers is six bits, and a set of states is a Boolean function, true exactly on its members. Moves become formulas over the current bits and a primed copy for the next. Philosopher zero may take fork zero if it is not holding it and philosopher two, who shares it, is not eating. Afterwards it holds it. Every other bit stays put. The disjunction over all commands is the whole system.
Part 3 built the data structure for such functions. This function of four bits says two pairs are equal. As a decision tree it needs fifteen tests. Randal Bryant's reduction, of 1986, merges identical subgraphs and skips tests whose branches agree: six nodes remain. The result is canonical: for a fixed order each function has one diagram, so comparing two sets of states is a single pointer comparison. But order matters. Read both x bits before either y bit, and the diagram must remember x one while reading x two: nine nodes.
Reachability becomes a loop over formulas. The image of a set, its successors, is one relational product: conjoin with the transition relation, then quantify away the current bits. The relation is kept as one small piece per command. Start from the initial states, add the image, rename, repeat; each round reaches one step further. When a round adds nothing, we have every reachable state, and canonicity makes noticing that one comparison. Sixteen philosophers take sixteen images: one million three hundred and thirty-one thousand seven hundred and fourteen states, in under a second.
Here is the pay-off. In yellow, the reachable states, past a million at sixteen philosophers. In green, the diagram that holds them: it grows by just eight nodes per philosopher, to one hundred and seventeen. Up to eight philosophers the explicit checker's counts agree exactly. And the deadlock is found symbolically too. The lesson: structure, not size, decides. A ring of identical neighbours suits a BDD; a multiplier does not.
SAT solvers attack the explosion from the other side. Bounded model checking, from Biere, Cimatti, Clarke and Zhu in 1999, unrolls the transitions k times: an initial state, k steps, and a deadlock at the end. A satisfying assignment is a counterexample. For seven philosophers we try k equals zero, one, two, and so on. The refutations get harder: k equals six costs two thousand five hundred and ninety-eight conflicts. At seven the formula is satisfiable, and the decoded model is the deadlock. With ordered forks, every bound up to seven is unsatisfiable, and every reachable state lies within five steps, so that is a proof. Without a known diameter, k-induction and IC3 prove unbounded properties with the same solvers.
8Abstract interpretationGraduate3 min
The third way around Rice's theorem is to approximate soundly, a theory Patrick and Radhia Cousot set out in 1977. A loop with two counters reaches eleven states at its head, all on a line. Instead of exact sets, compute with simpler ones: here a box, one range per variable. The box contains every real state, so if it misses the bad states, so does the program: a proof. A coarser box may touch the bad region and raise an alarm, though no real state is bad. A sound analysis never misses a bug; the price is false alarms.
For one variable the simpler sets are intervals, and they form a lattice. At the bottom, the empty interval, for unreachable code; at the top, all integers; each interval sits below those that contain it. Where two branches meet, intervals are joined by taking their hull, which picks up values neither branch had. Abstraction maps a set to the smallest interval holding it; concretization maps an interval back to its numbers. Together they form a Galois connection: the abstraction is the best interval possible, yet it still gains numbers. And the lattice has chains that climb for ever.
What holds at a loop's head? Here x counts from zero to a hundred. At the head, x is zero on entry, or one more than a value that passed the test: an equation over intervals. Solve it by iterating from the entry state. Each round the interval grows by one: zero to zero, zero to one, zero to two. After one hundred and one rounds it stops changing. At the exit, the failed test leaves exactly a hundred, and the assertion is proved. A loop to two billion would take two billion rounds.
Widening, also from the Cousots, forces the iteration to finish. A bound that has not moved stays; a bound that moved jumps straight to infinity. The first round moves x's upper bound from zero to one, so it jumps to infinity. The next round computes zero to a hundred, which fits inside: a fixpoint. That is too big, so narrowing runs the loop again, letting only the infinite bound come back down: zero to a hundred. Two rounds and two narrowing steps, instead of a hundred and one. On the two-counter loop, plain iteration never stops.
Intervals have a blind spot. Here i counts to ten and j goes up by two, so j is always twice i, and ends at twenty. Plain iteration bounds i by the test, but nothing bounds j on its own, and its interval climbs by two every round, for ever. Widening sends j to infinity, and narrowing cannot bring it back. So the assertion that j is twenty is not proved: a false alarm, on a correct program. What was lost is the relation. Relational domains keep j equal to two i, and with i equal to ten, j is twenty.
9Types as lightweight proofsGraduate3 min
A type checker proves a theorem about every run of a program. Picture every execution as a branch of a tree. Tests walk a few branches. A type checker reads the code once and speaks for all of them. Part 14 proved what its verdict means. Progress: a well-typed term is a value, or it can take a step. Preservation: a step keeps the type. Chain the two by induction on the number of steps, and a well-typed program never gets stuck. That is Milner's slogan: well-typed programs cannot go wrong.
Why is checking so cheap? A type checker is an abstract interpreter, in the sense of chapter eight: it runs the program on types instead of values. Types flow up the tree. x plus one is an int; both branches of the if are ints; so the whole expression is an int. Patrick Cousot made the connection precise in 1997. And like intervals, the abstraction loses information. This expression never goes wrong, because its condition is always true, but its two branches have different types, so it is rejected. Sound, and therefore incomplete.
Tim Freeman and Frank Pfenning introduced refinement types in 1991. A refinement type is a base type with a predicate. Int is every integer. The naturals are the integers v with v at least zero. The valid indices of an array of length n run from zero up to n, excluded. A subtype is a subset, which is an implication: whatever satisfies p satisfies q. So every index is a natural, because zero at most v below n implies zero at most v. Type checking has become logic, and the logic can go to a solver.
The hook's midpoint, as a type. Declare low a natural and high greater than low, and demand that mid lie from low up to high, excluded. The checker gives the expression its exact type, v equals m, and asks whether that is a subtype. Under the facts in scope, that is an implication, and written out it is exactly the verification condition our SAT solver handled in chapter three. For the repaired midpoint it is valid over sixteen-bit words, so the program type-checks. For Bloch's original line the solver's counterexample becomes a type error: the bug, rejected before the program runs.
10Proof assistantsGraduate3 min
In 1972 Robin Milner built LCF, a program for checking proofs that could be trusted without trusting most of it. A theorem is a value of an abstract type, and only the inference rules, gathered in a small kernel, can make one. Everything else, tactics, proof search, scripts, the user, can call the rules but cannot forge a result. Here is one rule of our own kernel: modus ponens checks that the second premise is the antecedent of the first, or refuses. Our kernel has sixty-nine lines and eleven rules. For Edinburgh LCF, Milner's group designed a language for writing tactics: ML, the ancestor of Standard ML and OCaml.
The kernel's logic is natural deduction, Gerhard Gentzen's system from the 1930s. A sequent says: from these hypotheses, this conclusion. Assumption starts every proof: A, from A. Each connective has a rule to introduce it and one to use it. Implication is introduced by discharging a hypothesis, and used by modus ponens. Then conjunction, disjunction, and falsehood, from which anything follows. The eleventh rule, double negation, is the only classical one; without it the logic is intuitionistic, the logic of Part 14's programs.
Here is a proof our kernel made: A and B implies B and A. It starts from one assumption, A and B, used twice. The elimination rules take it apart, into B and into A. Introduction puts them together the other way round. Discharging the assumption leaves the theorem with no hypotheses, after five kernel calls, and a truth table agrees. In Lean the proof is one line, which Lean's kernel checks as a typed program: Part 14's propositions as types.
Every illegal step is refused. Making a theorem directly, without a rule. Modus ponens, with the wrong antecedent. Taking apart a conjunction that is really an implication. Double negation, applied to a single negation. And editing the conclusion of a finished theorem. Each stops at the kernel with a message. One caution: Python cannot seal a type the way ML can, so our guard stops honest mistakes, not a determined forger. Serious systems also meet what is called the de Bruijn criterion: their proofs can be rechecked by a small, independent program.
Proof assistants now check real mathematics. In 1976 Kenneth Appel and Wolfgang Haken proved the four colour theorem with a computer checking many cases, and many mathematicians were uneasy. In 2005 Georges Gonthier, with Benjamin Werner, completed a proof checked end to end in Coq. Thomas Hales's 1998 proof of the Kepler conjecture also leaned on computation; his Flyspeck project finished a formal proof in HOL Light and Isabelle in 2014. In 2012 Gonthier's team checked the odd order theorem, and in 2022 Lean's users finished the Liquid Tensor Experiment, Peter Scholze's challenge, on top of mathlib, which AI, Built met in Part 25.
11Verified systemsIndustry3 min
CompCert, from Xavier Leroy and colleagues at Inria, is a C compiler with a theorem; Leroy described its verified back end in 2006. It translates C through a chain of intermediate languages to assembly, optimizing in the middle, on a language called RTL. Each pass is written in Coq with a proof: if it produces output, every behaviour of the output is a behaviour of its input. Inclusion is transitive, so the proofs chain. For a source program with no undefined behaviour, the assembly can only do what the C could do.
In 2011 John Regehr's group at the University of Utah published Csmith, which generates random C programs with no undefined behaviour, and compared what compilers made of them. In GCC and LLVM it found hundreds of unknown bugs, many of them silent wrong code. In CompCert's verified middle it found no wrong-code bugs at all. The bugs it did find in CompCert were outside the proof, in parts such as the unverified front end. The proof did its job, and testing showed where the proof ended.
In 2009 Gerwin Klein and his colleagues at NICTA in Sydney proved the seL4 microkernel correct. An abstract specification says what each system call does. An executable specification, translated from a Haskell prototype, refines it. The C code, about eight thousand seven hundred lines, refines that, in a proof of about two hundred thousand lines of Isabelle. The 2009 proof assumed the compiler, about six hundred lines of assembly, the boot code and the hardware. In 2013 the compiled binary was checked against the C, taking the compiler off that list, by a technique chapter fourteen returns to.
Both proofs rest on one picture, the simulation square. Relate each concrete state to an abstract one. When the concrete machine takes a step, the abstract machine must be able to match it and keep the relation, or stand still, a stutter, when the concrete step is internal bookkeeping. Tile the squares along a run, by induction, and every concrete run is shadowed by an abstract one, so every safety property of the specification holds of the code. The next chapter checks exactly this for a protocol.
12Specifying systems: TLA+Industry3 min
Leslie Lamport's temporal logic of actions, TLA, from 1994, describes a system as a state machine written in ordinary mathematics. A state gives a value to every variable; a behaviour is an infinite sequence of states. A specification is a formula true of the right behaviours. It starts in an initial state, and always, each step satisfies the next-state relation, or leaves the variables unchanged: a stutter, which lets a finer-grained implementation take steps of its own. Fairness adds that something good eventually happens. TLA plus is the language built around this formula, and TLC is its model checker.
Jim Gray and Leslie Lamport's TCommit says what commit means. Each resource manager starts working, may prepare, then commits or aborts. It may commit only when every manager is prepared or committed, and abort only when nobody has committed. The property we want is consistency: never one committed and another aborted. How many states are reachable? Either nobody has committed, and each manager is working, prepared or aborted: three to the n. Or someone has, and all are prepared or committed, at least one committed: two to the n, minus one. Our checker agrees for two to five managers.
Two-phase commit, the protocol, adds a transaction manager and messages. Each resource manager that is ready prepares, and sends a Prepared message. The transaction manager collects them, and when every one has prepared, it decides to commit and sends Commit. Each resource manager that receives it commits. As in Lamport's specification, messages are never lost: once sent, a message stays in the bag. The checker explores every interleaving: two hundred and eighty-eight states for three managers, eight thousand eight hundred and thirty-two for five, and consistency holds in all of them.
Now plant a bug that looks like good engineering: a timeout. If the coordinator has waited too long, it commits without hearing from everyone. With three managers the checker explores six hundred and twenty-three states and returns a counterexample of three steps. The coordinator times out, and commits before anyone has prepared. Resource manager zero, still working, chooses to abort, as it is allowed to. Resource manager one receives Commit, and commits. One committed and one aborted: the invariant is broken. A coordinator that times out may abort, never commit.
Is the protocol a correct implementation of the specification? In TLA, implementation is implication. Map each protocol state to its resource managers' states, forgetting the coordinator and the messages. Then every protocol step must be a TCommit step, or leave the managers unchanged. Preparing and committing map to TCommit's own steps; the coordinator's bookkeeping maps to stutters, which is exactly why TLA allows them. Our checker tried every reachable step for two, three and four managers: the protocol refines the specification. So its consistency follows from TCommit's, by chapter eleven's square, and so does every other safety property that TCommit has.
13Testing as scienceDegree3 min
Coverage measures where the tests have been. Glenford Myers's triangle classifier, from his 1979 book on testing, takes three sides and names the triangle. Run three hundred random tests, with sides from one to a hundred. They reach seven of the nine lines, and six of the eight branch outcomes. Two lines never ran. No side was ever zero or negative, and no triangle was equilateral: with random sides, all three agree once in ten thousand draws. Coverage points at exactly what the tests missed.
Full coverage proves less than it seems. This insert puts a number into a sorted list, and its scan stops one element early. Three unit tests pass, and between them they run every line and both outcomes of the loop test: full coverage. A property test checks that the output is ordered and holds the right elements. It fails on its ninth random input, shrunk to inserting one into the list holding zero, and the answer comes out one, zero. Coverage says where tests have been, not that what they saw was right.
Mutation testing, proposed by Richard DeMillo, Richard Lipton and Frederick Sayward in 1978, asks whether the tests would notice a bug. Make small changes to the correct program: each is a mutant. Stopping the scan one early survives the unit tests; it is the very bug they missed. Less-or-equal survives too, but no test could kill it: inserting before or after an equal element gives the same list. It is an equivalent mutant. Greater-than is killed by two tests. Stepping by two survives. The score is killed over non-equivalent mutants: one in three. The tests are weak, and now we know where.
Property-based testing replaces examples with laws; Koen Claessen and John Hughes's QuickCheck made it practical in 2000. The law for a sort: the output is in order, and rearranges the input. Random lists come small ones first. This sort goes through a set, and the twenty-seventh list breaks it: three, minus three, minus three, one. Then it shrinks. Without the three, still failing. Without the one, still failing. Both copies of minus three move toward zero together: zero, zero. After eleven candidates the report is the smallest failing case: sorting zero, zero returns one zero.
In 1990 Barton Miller's students fed random characters to Unix utilities, and crashed or hung about a quarter to a third of them. But pure random input rarely gets deep. To reach this crash it must guess three bytes at once, about one chance in seventeen million. Michał Zalewski's American Fuzzy Lop, in 2013, watches which branches each input takes. An input that reaches a new branch is kept, and mutated further. The F is found, then the U, then the Z, a few hundred tries each. Since 2016 Google's OSS-Fuzz has run such fuzzers continuously on open-source projects.
14Fuzzing and validating our compilerIndustry3 min
Part 13's generator writes random Pebble programs that are always well defined, so every correct implementation prints the same bytes. Each runs on the IR interpreter, which says what it means, and compiled at all four levels on the emulator. Now plant a bug: the SCCP pass's constant folder divides by Python's rule, rounding down, not Pebble's, which truncates toward zero. Both rules satisfy a equals q b plus r. For minus seven over two hundred and fifty-six, truncation gives zero, remainder minus seven; rounding down gives minus one, remainder two hundred and forty-nine.
Then we hunt. Program by program, the fuzzer generates and compares; one program did not finish within the step limit and was skipped. The fifth, seed four, disagrees: seventy-five lines, six functions, ninety-two bytes of output. Levels zero, one and two print what the interpreter prints; level three differs from byte one on. Level three inlines, so a call's argument becomes a constant, and the broken folder divides it. With the bug removed, every program tried agrees at every level: the fuzzer found the bug, not noise.
Delta debugging, from Andreas Zeller and Ralf Hildebrandt in 2002, shrinks a failing input while the failure persists. Ours tries removing each statement or block, from the bottom up, and keeps a removal if the program still shows the disagreement. Seventy-five tests, fifty-four accepted removals, under five seconds. Nine lines are left. f1 of minus seven returns minus seven. The second byte printed is minus seven over two hundred and fifty-six: zero for Pebble, minus one for the broken folder, so the byte is F F instead of zero zero. The bug, in one line.
The real test is the Job, Part 13's word-counting program. We compile it at every level and run it on five texts, up to two hundred and twenty-six bytes. Every level prints exactly what the interpreter prints, and the interpreter agrees with an independent Python version. The optimizations pay: on the longest text, level three takes twelve thousand eight hundred and fifty-four steps, against thirty-eight thousand six hundred and thirty-three unoptimized. But five agreeing inputs are evidence, not proof.
Translation validation, from Amir Pnueli, Michael Siegel and Eli Singerman in 1998, checks every compilation instead of sampling inputs. Proving a compiler correct for every program is CompCert's hard road. Instead, after each run, a validator checks that this output means the same as this input; only the validator must be trusted. For our bug, a validator for constant folding would recompute each folded constant by Pebble's rules: minus seven over two hundred and fifty-six is zero, not minus one, so the compilation is refused. Equivalence is undecidable in general, so validators target particular passes and may answer don't know. CompCert's register allocation is checked this way, by a validator proved in Coq.
15Frontier: proofs at scaleResearch1 min
Can proof become as routine as testing? Proof is already routine in some places. Amazon's engineers described in 2015 how model-checking TLA-plus specifications of their storage and messaging services found subtle bugs before any code was written. Formally verified cryptographic code, from projects such as HACL-star and Fiat-Crypto, now runs inside major browsers and libraries. And static analysers run on every change at large companies, reporting bugs found by sound approximation. The pattern is to prove the small, critical, stable parts, and test the rest.
The newest change is who writes the proofs. In our LCF kernel from chapter ten, only 69 lines have to be trusted; everything else, including whatever produced the proof, can be wrong without harm, because every step passes through the kernel. That is why language models can be put to work: they now write proofs in Lean, Coq and Dafny, and suggest loop invariants, and in 2024 systems that combined them with search solved olympiad problems with proofs that a kernel checked. The question is no longer whether a machine's proof can be trusted, but how much of a real program's specification it can find and prove on its own.
Recap, problems, and where this comes backAll tracks2 min
What we built in this part. Floyd–Hoare logic and its rules, with invariants for loops and variants for termination. Weakest preconditions, turned into formulas and checked by our own SAT solver, which found the binary search overflow and proved the fix. Separation logic, so that proofs about the heap can be local. Model checking: explicit, symbolic with BDDs, and bounded with SAT, on Peterson's lock, the philosophers, two-phase commit and Raft. Abstract interpretation with widening; an LCF kernel; and a fuzzer that caught a planted bug in our own compiler. One idea runs through it: correctness cannot be decided in general, but it can be proved in particular.
Where this comes back. Part 55 asks whether a compiler can be trusted at all. Part 58 gives programs the mathematical meaning these proofs rest on. Part 59 proves the limits of distributed protocols. Part 60 checks hardware against its specification. And Part 61 treats proof as a research method.
In practice. Write invariants as assertions, so they document and test at the same time. State properties rather than examples, and let the tool shrink the failures. Fuzz in continuous integration, with sanitizers, and keep the corpus. Model every tricky protocol before writing it. And prove the small critical core: parsers, cryptography, kernels.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: plant a bug of your own in the optimizer and count how many random programs it takes the fuzzer to find it. The last, marked with a star, is a research problem: complete and practical invariant inference for loops with multiplication.
Next time, Part 55, the finale of the degree: trusting trust. Security is a property of the whole tower, and every layer leaks. We build Ken Thompson's backdoored compiler against our own, catch it, and walk the tower one last time, from a NAND gate to a cluster.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 55 asks whether the compiler itself can be trusted. Part 58 gives programs the mathematical meaning these proofs rest on, Part 59 proves the limits of distributed protocols, Part 60 checks hardware against its specification, and Part 61 treats proof as a research method.
Key results
The part's results in one place, for revision.
Try it
Lab 54 · Five midpoints, one solver, and every 8-bit input
Ask the series' verifier whether each of five midpoint formulas meets lo <= mid < hi for all signed 8-bit inputs, compare each verdict with a brute-force run over all 65,536 pairs, then count the rounds interval analysis needs with and without widening and the nodes of one BDD under two variable orders.
python -m videos.cs.labs 54
needs numpy, scipy, matplotlib · download lab54.py ·
source on GitHub(lo + hi) >> 1 given 0 <= lo && lo < hi solver: invalid (399 clauses) brute force: 4,032 of 8,128 inputs fail e.g. lo = 45, hi = 100
lo + ((hi - lo) >> 1) given 0 <= lo && lo < hi solver: valid (507 clauses) brute force: 0 of 8,128 inputs fail
(lo + hi) >>> 1 given 0 <= lo && lo < hi solver: valid (379 clauses) brute force: 0 of 8,128 inputs fail
lo + ((hi - lo) >> 1) given lo < hi solver: invalid (504 clauses) brute force: 8,256 of 32,640 inputs fail e.g. lo = -105, hi = 100
lo + ((hi - lo) >>> 1) given lo < hi solver: valid (494 clauses) brute force: 0 of 32,640 inputs fail
textbook midpoint, random tests with hi < 2^(W-2) 0 failures in 1,881 tests
count to 100: rounds to the fixpoint [0, 100] 101 by plain iteration, 2 + 2 with widening and narrowing
i counts to 10, j = 2i: assert j == 20 not proved; head {'i': [0, 10], 'j': [0, '+inf']}
equality of two 10-bit words as a BDD 30 nodes interleaved (3n), 3,069 separated (3 * 2^n - 3)
The solver's five verdicts are the truth about all 65,536 inputs; tests on small arrays never reach the overflow; widening trades 101 rounds for 4; a BDD's size is a matter of variable order.
The code (115 lines; it asserts its own result)
"""Lab 54: let the SAT solver judge five binary-search midpoints, and check its verdicts against every 8-bit input."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import numpy as np
from explainer.cs.verify import absint, bdd, hoare
TITLE = "Five midpoints, one solver, and every 8-bit input"
GOAL = ("Ask the series' verifier whether each of five midpoint formulas meets lo <= mid < hi for all signed 8-bit "
"inputs, compare each verdict with a brute-force run over all 65,536 pairs, then count the rounds interval "
"analysis needs with and without widening and the nodes of one BDD under two variable orders.")
TASKS = [
"Change W to 10 and to 12. Do the five verdicts change, and how do the solver's clause counts and times grow against the brute-force count of 4^W pairs?",
"Run hoare.verify(hoare.midpoint_program('hi - ((hi - lo) >> 1)'), 8). Does this midpoint meet lo <= mid < hi? Read the counterexample and say what it does to the search loop.",
"Analyze absint.two_counter_program() with widen=False and max_iter=60, then with widening. Which bound never settles, and why can no interval prove j == 20?",
]
W = 8
def machine_mid(index, lo, hi):
"""The five midpoints of hoare.MIDPOINTS on numpy arrays of signed W-bit values, written out independently."""
mask, half = (1 << W) - 1, 1 << (W - 1)
def wrap(v):
return ((v + half) & mask) - half
if index == 0:
return wrap(lo + hi) >> 1 # the textbook: the sum can wrap
if index in (1, 3):
return wrap(lo + (wrap(hi - lo) >> 1)) # the first fix: the difference can wrap if lo < 0
if index == 2:
return wrap((wrap(lo + hi) & mask) >> 1) # the unsigned shift reads the carry
return wrap(lo + ((wrap(hi - lo) & mask) >> 1)) # the difference read as unsigned
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the solver's verdict on each midpoint, against all 4^W inputs
grid = np.arange(-(1 << (W - 1)), 1 << (W - 1))
lo, hi = np.meshgrid(grid, grid, indexing="ij")
study = hoare.midpoint_study(W)
fails = []
for k, row in enumerate(study):
pre = (lo < hi) & ((lo >= 0) if "0 <= lo" in row["pre"] else True)
mid = machine_mid(k, lo, hi)
bad = pre & ~((lo <= mid) & (mid < hi))
fails.append(bad)
assert (row["status"] == "valid") == (not bad.any()), "the solver and the brute force agree on every formula"
cex = row["counterexample"]
if cex is not None:
assert bad[cex["lo"] + (1 << (W - 1)), cex["hi"] + (1 << (W - 1))], "the counterexample is a real failure"
lab.row(f"{row['mid']:<24} given {row['pre']}",
f"solver: {row['status']:<7} ({row['clauses']:,} clauses) brute force: {int(bad.sum()):,} of "
f"{int(pre.sum()):,} inputs fail" + (f" e.g. lo = {cex['lo']}, hi = {cex['hi']}" if cex else ""))
assert [r["status"] for r in study] == ["invalid", "valid", "valid", "invalid", "valid"]
# 2. random testing of the textbook midpoint on small arrays never sees the bug
n = rng.integers(1, 1 << (W - 2), 2000) # array lengths below a quarter of the range
a, b = np.sort(rng.integers(0, n + 1, (2, 2000)), axis=0)
ok = a < b
small_fail = int(fails[0][a[ok] + (1 << (W - 1)), b[ok] + (1 << (W - 1))].sum())
assert small_fail == 0 and fails[0].sum() > 0, "the overflow needs lo + hi >= 2^(W-1): small tests cannot reach it"
lab.row("textbook midpoint, random tests with hi < 2^(W-2)", f"{small_fail} failures in {int(ok.sum()):,} tests")
# 3. interval analysis: plain iteration against widening and narrowing
plain = absint.analyze(absint.counter_program(), widen=False, max_iter=200)
wide = absint.analyze(absint.counter_program(), widen=True)
lp, lw = plain["loops"][0], wide["loops"][0]
assert lp["head"] == lw["head"] == {"x": [0, 100]} and plain["asserts"][0]["proved"] and wide["asserts"][0]["proved"]
assert lp["ascending"] == 101 and lw["ascending"] + lw["narrowing"] <= 4
lab.row("count to 100: rounds to the fixpoint [0, 100]", f"{lp['ascending']} by plain iteration, "
f"{lw['ascending']} + {lw['narrowing']} with widening and narrowing")
two = absint.analyze(absint.two_counter_program(), widen=True)
assert not two["asserts"][0]["proved"], "intervals lose j = 2i, so j == 20 is a false alarm"
lab.row("i counts to 10, j = 2i: assert j == 20", f"not proved; head {two['loops'][0]['head']}")
# 4. one function, two variable orders
orders = bdd.order_effect(range(1, 11))
for r in orders:
assert r["interleaved"] == 3 * r["n"] and r["separated"] == 3 * 2 ** r["n"] - 3
lab.row("equality of two 10-bit words as a BDD", f"{orders[-1]['interleaved']} nodes interleaved (3n), "
f"{orders[-1]['separated']:,} separated (3 * 2^n - 3)")
lab.note = ("The solver's five verdicts are the truth about all 65,536 inputs; tests on small arrays never reach "
"the overflow; widening trades 101 rounds for 4; a BDD's size is a matter of variable order.")
fig, ax = labs.figure(2, size=(11, 4.4))
shade = np.zeros(lo.shape)
shade[lo < hi] = 1
shade[(lo < hi) & (lo >= 0)] = 2
shade[fails[0]] = 3
from matplotlib.colors import ListedColormap
ax[0].imshow(shade.T, origin="lower", extent=(grid[0], grid[-1] + 1, grid[0], grid[-1] + 1), interpolation="nearest",
cmap=ListedColormap([labs.BG, labs.GRID, labs.BLUE, labs.RED]), vmin=0, vmax=3)
c = study[0]["counterexample"]
ax[0].plot([c["lo"]], [c["hi"]], "o", color=labs.GOLD, label=f"the solver's counterexample ({c['lo']}, {c['hi']})")
ax[0].plot([], [], "s", color=labs.BLUE, label="0 <= lo < hi, mid in range")
ax[0].plot([], [], "s", color=labs.RED, label="lo + hi wraps: mid < lo")
ax[0].plot([], [], "s", color=labs.GRID, label="lo < 0: outside the precondition")
ax[0].grid(False)
ax[0].set(title="(lo + hi) >> 1 on every signed 8-bit pair", xlabel="lo", ylabel="hi")
ax[0].legend(loc="lower right")
for res, color, name in ((plain, labs.BLUE, "plain iteration"), (wide, labs.GOLD, "widening, then narrowing")):
tr = [t for t in res["trace"] if "head" in t]
ub = [150 if t["head"]["x"][1] == "+inf" else t["head"]["x"][1] for t in tr]
ax[1].plot(range(len(ub)), ub, "o-" if len(ub) < 10 else "-", color=color, label=name, ms=5)
ax[1].axhline(100, color=labs.MUTED, ls="--", lw=1)
ax[1].set(title="Upper bound of x at the loop head, round by round", xlabel="round", ylabel="upper bound",
yticks=[0, 50, 100, 150], yticklabels=["0", "50", "100", "+inf"], ylim=(-5, 160))
ax[1].legend(loc="lower right")
lab.fig = fig
return lab
Now change it
- Change W to 10 and to 12. Do the five verdicts change, and how do the solver's clause counts and times grow against the brute-force count of 4^W pairs?
- Run hoare.verify(hoare.midpoint_program('hi - ((hi - lo) >> 1)'), 8). Does this midpoint meet lo <= mid < hi? Read the counterexample and say what it does to the search loop.
- Analyze absint.two_counter_program() with widen=False and max_iter=60, then with widening. Which bound never settles, and why can no interval prove j == 20?
Problems, with solutions
Try each problem before opening its solution.
-
Gauss's loop. Prove {n ≥ 0} the summation loop {s = n(n+1)/2} with an invariant and a variant.
Solution
The loop is
i = 0; s = 0; while i < n: i = i + 1; s = s + i. Take the invariant I: 0 ≤ i ≤ n ∧ 2s = i(i + 1) and the variant V = n − i. Five conditions. Established: with i = s = 0, I reads 0 ≤ 0 ≤ n ∧ 0 = 0·1, which follows from n ≥ 0. Preserved: from I and i < n, the body gives i' = i + 1 and s' = s + i + 1; then 0 ≤ i' and i' ≤ n (integers, i < n), and 2s' = 2s + 2(i + 1) = i(i + 1) + 2(i + 1) = (i + 1)(i + 2) = i'(i' + 1). Exit: I and ¬(i < n) give i = n, so 2s = n(n + 1); since n(n + 1) is a product of consecutive integers it is even, and s = n(n+1)/2. Variant non-negative: i < n gives n − i > 0. Variant decreases: n − (i + 1) < n − i. The variant is a natural number that falls by one on each pass, so the loop stops after exactly n passes, and the triple holds in the total sense. Our checker discharges the five conditions at 8 bits (4,976 clauses, 0.39 s); there the equation is read modulo 2⁸, and i + 1 cannot overflow because i < n ≤ 127. Note that 2s ≡ n(n + 1) (mod 2ʷ) fixes s only modulo 2ʷ⁻¹, a weaker statement than the loop's actual result. -
The swap's weakest precondition. Compute wp for the swap without a temporary, and show that it holds for all w-bit values.
Solution
Push the postcondition x = Y ∧ y = X up from the last line. Through
x = x - y: x − y = Y ∧ y = X. Throughy = x - y: x − (x − y) = Y ∧ x − y = X. Throughx = x + y: (x + y) − ((x + y) − y) = Y ∧ (x + y) − y = X. The condition is x = X ∧ y = Y ⇒ that. In the integers (x + y) − y = x and (x + y) − x = y, so it reduces to y = Y ∧ x = X, which is the hypothesis. For w-bit words, two's-complement +, − are the operations of the ring ℤ/2ʷℤ: each computed value is congruent modulo 2ʷ to the same expression evaluated in ℤ, so the final x is congruent to the initial y and the final y to the initial x; both lie in the representative range [−2ʷ⁻¹, 2ʷ⁻¹), where congruent numbers are equal. With 16 bits, 30,000 and 20,000: x becomes −15,536 (50,000 wrapped), then y = −35,536 + 65,536 = 30,000 and x = −45,536 + 65,536 = 20,000. Our SAT solver confirms it for every 16-bit pair: 425 variables, 1,239 clauses, UNSAT in 0.24 s. The proof needs wrap-around: with saturating or floating-point arithmetic it fails, and if x and y name the same storage the three lines leave 0. -
List reversal. Show that in-place list reversal is correct in separation logic.
Solution
The program is
j = nil; while i != nil: k = i.next; i.next = j; j = i; i = k, with precondition list(α₀, i) and postcondition list(rev(α₀), j), where list(ε, i) ⇔ emp ∧ i = nil and list(a·α, i) ⇔ ∃k. i ↦ a, k ∗ list(α, k). Invariant I: ∃α, β. list(α, i) ∗ list(β, j) ∧ rev(α₀) = rev(α)·β. Established: afterj = nil, list(ε, j) is emp, so list(α₀, i) ∗ list(ε, j) holds with α = α₀, β = ε. Preserved: i ≠ nil rules out α = ε (that case says i = nil), so α = a·α', and unfolding gives i ↦ a, k₀ ∗ list(α', k₀) ∗ list(β, j). The readk = i.nexttouches only the first cell and sets k = k₀. The storei.next = jis the small axiom on that one cell, {i.next ↦ −} i.next := j {i.next ↦ j}, and the frame rule carries list(α', k) ∗ list(β, j) through unchanged; the star guarantees that the cell is in neither list, so no case split for aliasing is needed. Folding, i ↦ a, j ∗ list(β, j) is list(a·β, i), so we have list(α', k) ∗ list(a·β, i), andj = i; i = krenames it to list(α', i) ∗ list(a·β, j). The ghost equation holds since rev(a·α')·β = rev(α')·a·β. Exit: I and i = nil give α = ε (list(α, nil) forces it) and emp for that part, so list(β, j) with rev(α₀) = β, the postcondition. Every dereference is of a cell the assertion owns, so the program is also memory-safe, and the length of α is a variant. -
Widening. Show that interval analysis without widening may not terminate, and that widening makes it terminate.
Solution
Take
i = 0; j = 0; while i < 10: i = i + 1; j = j + 2. Kleene iteration at the loop head computes X₀ = (i ∈ [0, 0], j ∈ [0, 0]) and X_{k+1} = X₀ ⊔ body(X_k ⊓ (i < 10)). By induction X_k = (i ∈ [0, min(k, 10)], j ∈ [0, 2k]): the filter i < 10 bounds i but says nothing about j, the body adds 1 and 2, and the join with X₀ keeps the lower bounds at 0. So j's upper bound grows for ever (round 60 of our analyser has j ∈ [0, 120]); the interval lattice has infinite ascending chains, and nothing in the program bounds j on its own. (Iteration can terminate without widening, as counting to 100 does in 101 rounds, but only by climbing the chain one step at a time.) With widening, Y_{k+1} = Y_k ∇ F(Y_k), where a bound that moved goes to ±∞ and a stable bound stays. Whenever Y_{k+1} ≠ Y_k some finite bound has become infinite, and an infinite bound never changes again, so with n variables there are at most 2n strict steps per loop head. When Y_{k+1} = Y_k, every bound of F(Y_k) lies within Y_k's (otherwise it would have been widened), so F(Y) ⊑ Y: a post-fixpoint, which by Tarski's theorem lies above the least fixpoint and is therefore sound. Narrowing then lets only infinite bounds come back down, so it too stops within 2n steps and stays above the least fixpoint. Our analyser: counting to 100, two rounds and two narrowing steps instead of 101; to an input n ≤ 50, the same instead of 51; on the two-counter loop it stops at i ∈ [0, 10], j ∈ [0, +∞], where plain iteration never stops. -
Build. Plant a different bug in our compiler's optimizer, and measure how many random programs the fuzzer needs.
Solution
Solution notes. In
explainer/cs/verify/testing.py, add an entry toBUGSand make_BuggyFolderdispatch on the kind (as written,planted_buginstalls the floor-division folder whatever kind it is given). Bugs that fit the folder, which SCCP calls throughinterp.binopfor every operator: folding shifts without masking the count to five bits (ub & 31), folding a signed comparison as unsigned, or a remainder that takes the sign of the divisor. Check that it is scoped, astests.test_cs54_check.Fuzz.test_planted_bug_is_scopeddoes for the original. Then runhunt(kind, seeds=range(s0, s0 + 200))for, say, twenty disjoint seed ranges:programsis the number generated up to the first disagreement (skipped programs included) andclean_agreemust be true. If each program triggers the bug independently with probability p, the count is geometric with mean 1/p; report the median and quartiles, and estimate p as finds over programs, with a confidence interval. Expect the count to depend on how often the generator makes the operator's operands constant (only level 3 inlines, which is why the planted bug showed at level 3 alone) and on how often the operands hit the buggy case (both signs differing; a shift count of 32 or more). Finish withshrink_programon each find and add a test likeFuzz.test_hunt. -
★ Research. Complete, practical invariant inference for loops with multiplication.
Discussion. Open. Over the integers, even checking that a candidate invariant is inductive means proving a universally quantified formula of nonlinear integer arithmetic, which is undecidable in general (Hilbert's tenth problem, Part 25); over w-bit words it is decidable but, as Gauss's conditions showed (5 ms at 4 bits, over 2 s at 10), multiplier reasoning is the classic hard case for SAT. Known complete methods cover restricted classes: polynomial equalities for loops whose updates are affine, or invariants of bounded degree found with Gröbner bases or linear algebra, while practical tools fall back on templates, interpolation, data-driven guessing and, lately, language models whose guesses a checker filters. A good answer would fix a class of invariants (for instance polynomial equalities of degree at most d together with linear inequalities), a class of loops with polynomial updates and guards, and prove the procedure finds an inductive invariant in the class whenever one exists that proves the assertion, with a stated complexity and an implementation that handles Gauss's loop, cubic sums and integer square root in seconds. Partial results would already be valuable: completeness for one interesting subclass, a sharp decidability boundary between classes, or the same results for modular (bit-vector) arithmetic, where 2s = n(n + 1) no longer determines s.
Notes and sources
Glossary
- specification, precondition, postcondition, ghost variable — what a program should do; what the caller promises; what the code promises; a name for a past value that lives only in the specification.
- Hoare triple, partial and total correctness — {P} c {Q}; correct if it terminates; correct and terminates.
- assignment axiom, sequence, consequence and while rules — Hoare's rules; substitution runs backwards.
- invariant, variant, well-founded order — a fact every pass preserves; a quantity every pass decreases; an order with no infinite descending chain.
- soundness, relative completeness — every derivable triple is true; every true triple is derivable given an oracle for arithmetic (Cook).
- weakest precondition, verification condition (VC) — the largest set of start states from which c surely ends in Q; a closed formula whose validity implies correctness.
- bit-blasting, Tseitin encoding, SMT — words as Boolean variables and circuits as clauses; SAT with theory solvers.
- separation logic, points-to, separating conjunction, frame rule, footprint, bi-abduction — assertions that own heap cells; x ↦ v; P ∗ Q on disjoint heaps; local reasoning; the cells a command touches; inferring footprints and frames.
- Kripke structure, computation tree, LTL, CTL, fixpoint — states, transitions and labels; all futures unrolled; path and branching temporal logics; how CTL is checked.
- safety, liveness, fairness (weak, strong), lasso — nothing bad happens; something good happens; assumptions on the scheduler; a stem and a cycle, the shape of a liveness counterexample.
- state explosion, BDD, variable order, image, bounded model checking, diameter, k-induction, IC3 — exponential state counts; canonical decision diagrams; their sensitivity to order; a set's successors; SAT on k-step unrollings; the longest shortest path; proof by induction over k steps; incremental inductive invariants.
- abstract interpretation, Galois connection, interval domain, widening, narrowing, false alarm — sound approximation; the best abstraction of a set; one range per variable; forcing convergence; recovering precision; a warning about a correct program.
- relational domains: octagons, polyhedra — bounds on ±x ± y; linear inequalities over all variables.
- progress, preservation, refinement type, subtyping, liquid types, qualifier — what a type check proves; a type plus a predicate; implication; inference over conjunctions of candidate facts.
- LCF, kernel, natural deduction, sequent, proof term, de Bruijn criterion — theorems as an abstract type; the trusted rules; Gentzen's system; Γ ⊢ A; a proof as a program; independent re-checkability.
- refinement (of systems), simulation, stuttering — an implementation whose behaviours the specification allows; the square that shows it; steps that change nothing visible.
- TLA+, TLC, TLAPS, small scope hypothesis — Lamport's specification language, its model checker and its prover; most bugs have small counterexamples.
- coverage (line, branch), mutation testing, equivalent mutant, mutation score — where tests have been; testing the tests; a change no test can detect; killed over non-equivalent.
- property-based testing, shrinking, fuzzing, corpus, symbolic and concolic execution, path condition — laws tried on random inputs; reducing a failure; random input guided by coverage; inputs kept for new branches; running on symbols; the constraint for reaching a branch.
- differential testing, delta debugging, translation validation, proof-carrying code — comparing implementations; shrinking a failing input; checking each compilation; code shipped with its proof.
Sources
- M. Huth and M. Ryan, Logic in Computer Science: Modelling and Reasoning about Systems (2nd ed., 2004); C. Baier and J.-P. Katoen, Principles of Model Checking (2008); E. M. Clarke, O. Grumberg, D. Kroening, D. Peled and H. Veith, Model Checking (2nd ed., 2018).
- T. Nipkow and G. Klein, Concrete Semantics with Isabelle/HOL (2014); B. C. Pierce et al., Software Foundations; A. R. Bradley and Z. Manna, The Calculus of Computation (2007); D. Kroening and O. Strichman, Decision Procedures (2nd ed., 2016).
- E. W. Dijkstra, A Discipline of Programming (1976); D. Gries, The Science of Programming (1981); L. Lamport, Specifying Systems (2002); A. Møller and M. I. Schwartzbach, Static Program Analysis; X. Rival and K. Yi, Introduction to Static Analysis (2020); A. Zeller, R. Gopinath, M. Böhme, G. Fraser and C. Holler, The Fuzzing Book.
- J. L. Lions et al., Ariane 5 Flight 501 Failure: Report by the Inquiry Board (1996); N. G. Leveson and C. S. Turner, "An investigation of the Therac-25 accidents", IEEE Computer 1993; CVE-2014-0160 (Heartbleed).
- A. M. Turing, "Checking a large routine", Report of a Conference on High Speed Automatic Calculating Machines, Cambridge, 1949; F. L. Morris and C. B. Jones, "An early program proof by Alan Turing", IEEE Annals of the History of Computing 1984.
- R. W. Floyd, "Assigning meanings to programs", Proc. Symposia in Applied Mathematics 19, 1967; C. A. R. Hoare, "An axiomatic basis for computer programming", CACM 1969; S. A. Cook, "Soundness and completeness of an axiom system for program verification", SIAM J. Comput. 1978; E. W. Dijkstra, "Guarded commands, nondeterminacy and formal derivation of programs", CACM 1975.
- J. Bloch, "Nearly all binary searches and mergesorts are broken", Google Research blog, 2006; J. Bentley, Programming Pearls (1986).
- J. C. Reynolds, "Separation logic: a logic for shared mutable data structures", LICS 2002; P. O'Hearn, J. Reynolds and H. Yang, "Local reasoning about programs that alter data structures", CSL 2001; C. Calcagno, D. Distefano, P. O'Hearn and H. Yang, "Compositional shape analysis by means of bi-abduction", POPL 2009; P. W. O'Hearn, "Resources, concurrency and local reasoning", and S. Brookes, "A semantics for concurrent separation logic", both Theor. Comput. Sci. 2007.
- A. Pnueli, "The temporal logic of programs", FOCS 1977; E. M. Clarke and E. A. Emerson, "Design and synthesis of synchronization skeletons using branching time temporal logic", Logics of Programs 1981; J.-P. Queille and J. Sifakis, "Specification and verification of concurrent systems in CESAR", International Symposium on Programming 1982; E. M. Clarke, E. A. Emerson and A. P. Sistla, "Automatic verification of finite-state concurrent systems using temporal logic specifications", TOPLAS 1986; G. L. Peterson, "Myths about the mutual exclusion problem", IPL 1981.
- R. E. Bryant, "Graph-based algorithms for Boolean function manipulation", IEEE Trans. Computers 1986, and "On the complexity of VLSI implementations and graph representations of Boolean functions with application to integer multiplication", IEEE Trans. Computers 1991; J. R. Burch, E. M. Clarke, K. L. McMillan, D. L. Dill and L. J. Hwang, "Symbolic model checking: 10²⁰ states and beyond", LICS 1990; B. Bollig and I. Wegener, "Improving the variable ordering of OBDDs is NP-complete", IEEE Trans. Computers 1996.
- A. Biere, A. Cimatti, E. Clarke and Y. Zhu, "Symbolic model checking without BDDs", TACAS 1999; M. Sheeran, S. Singh and G. Stålmarck, "Checking safety properties using induction and a SAT-solver", FMCAD 2000; A. R. Bradley, "SAT-based model checking without unrolling", VMCAI 2011.
- P. Cousot and R. Cousot, "Abstract interpretation: a unified lattice model for static analysis of programs by construction or approximation of fixpoints", POPL 1977; M. Karr, "Affine relationships among variables of a program", Acta Informatica 1976; P. Cousot and N. Halbwachs, "Automatic discovery of linear restraints among variables of a program", POPL 1978; A. Miné, "The octagon abstract domain", Higher-Order and Symbolic Computation 2006; B. Blanchet et al., "A static analyzer for large safety-critical software", PLDI 2003.
- R. Milner, "A theory of type polymorphism in programming", JCSS 1978; P. Cousot, "Types as abstract interpretations", POPL 1997; T. Freeman and F. Pfenning, "Refinement types for ML", PLDI 1991; P. M. Rondon, M. Kawaguchi and R. Jhala, "Liquid types", PLDI 2008.
- R. Milner, "Logic for computable functions: description of a machine implementation", Stanford AIM-169, 1972; M. Gordon, "From LCF to HOL: a short history" (2000); G. Gonthier, "Formal proof — the four-color theorem", Notices of the AMS 2008; G. Gonthier et al., "A machine-checked proof of the odd order theorem", ITP 2013; T. Hales et al., "A formal proof of the Kepler conjecture", Forum of Mathematics, Pi 2017.
- X. Leroy, "Formal certification of a compiler back-end, or: programming a compiler with a proof assistant", POPL 2006, and "Formal verification of a realistic compiler", CACM 2009; X. Yang, Y. Chen, E. Eide and J. Regehr, "Finding and understanding bugs in C compilers", PLDI 2011.
- G. Klein et al., "seL4: formal verification of an OS kernel", SOSP 2009; T. Sewell, M. O. Myreen and G. Klein, "Translation validation for a verified OS kernel", PLDI 2013; R. Kumar, M. O. Myreen, M. Norrish and S. Owens, "CakeML: a verified implementation of ML", POPL 2014.
- D. J. Bernstein, "Curve25519: new Diffie–Hellman speed records", PKC 2006; A. Erbsen et al., "Simple high-level code for cryptographic arithmetic — with proofs, without compromises", IEEE S&P 2019; J.-K. Zinzindohoué, K. Bhargavan, J. Protzenko and B. Beurdouche, "HACL*: a verified modern cryptographic library", CCS 2017.
- L. Lamport, "The temporal logic of actions", TOPLAS 1994; J. Gray and L. Lamport, "Consensus on transaction commit", TODS 2006; D. Ongaro and J. Ousterhout, "In search of an understandable consensus algorithm", USENIX ATC 2014; C. Newcombe et al., "How Amazon Web Services uses formal methods", CACM 2015; D. Jackson, Software Abstractions (2006).
- G. J. Myers, The Art of Software Testing (1979); R. A. DeMillo, R. J. Lipton and F. G. Sayward, "Hints on test data selection: help for the practicing programmer", Computer 1978; K. Claessen and J. Hughes, "QuickCheck: a lightweight tool for random testing of Haskell programs", ICFP 2000.
- B. P. Miller, L. Fredriksen and B. So, "An empirical study of the reliability of UNIX utilities", CACM 1990; C. Cadar, D. Dunbar and D. Engler, "KLEE: unassisted and automatic generation of high-coverage tests for complex systems programs", OSDI 2008; P. Godefroid, N. Klarlund and K. Sen, "DART: directed automated random testing", PLDI 2005; A. Zeller and R. Hildebrandt, "Simplifying and isolating failure-inducing input", IEEE TSE 2002; G. Misherghi and Z. Su, "HDD: hierarchical delta debugging", ICSE 2006.
- A. Pnueli, M. Siegel and E. Singerman, "Translation validation", TACAS 1998; S. Rideau and X. Leroy, "Validating register allocation and spilling", CC 2010; G. C. Necula, "Proof-carrying code", POPL 1997; G. Morrisett, D. Walker, K. Crary and N. Glew, "From System F to typed assembly language", POPL 1998.
About this partfrom its README
Part 54 of a sixty-one-part course in computer science (see the series plan and the syllabus), the fourth part of Act X, Horizons and Trust. Testing can show that bugs are present but never that they are absent, and Rice's theorem (Part 25) rules out deciding correctness in general. We prove programs correct anyway, three ways round the theorem: by writing the invariants ourselves and letting Part 26's SAT solver check the verification conditions, by exhausting a finite state space explicitly, with BDDs or with SAT, and by approximating soundly. Along the way the solver finds Bloch's binary-search overflow and proves the repairs, a model checker finds the bugs we plant in Peterson's lock, two-phase commit and a Raft election, an LCF kernel of 69 lines checks proofs, and a fuzzer finds a bug planted in our own compiler and shrinks the program that shows it to nine lines.
The instruments are in explainer/cs/verify/ (tested in tests/test_cs54_logic.py and tests/test_cs54_check.py):
hoare.py: a tiny imperative language (assignment,if,whilewith a given invariant and variant,assert,assume,havoc) over signed w-bit integers; Dijkstra's weakest preconditions and the verification conditions of a program (established, preserved, exit, variant non-negative, variant decreases); a Tseitin bit-blaster (ripple-carry adders, a shift-add multiplier, comparators) that hands the negation of each condition to Part 26's CDCL solver, decoding and re-checking every counterexample by evaluation; assertions flowing backward through a listing; max, the swap without a temporary, Gauss's summation loop, five binary-search midpoints and the search loop; Gauss's conditions timed against the word width.absint.py: the interval domain (join, meet, widening, narrowing) over the same language read on mathematical integers; interval arithmetic and refinement by conditions; a fixpoint iteration that records every round at every loop head; three loops with and without widening, and the relation \(j = 2i\) that intervals cannot hold.models.py: guarded-command models explored breadth first into Kripke structures (so every counterexample is a shortest one); CTL by least and greatest fixpoints; LTL response properties under weak and strong fairness, with lassos as counterexamples; Peterson's lock and a broken variant (checked against Part 33's checker), the dining philosophers naive and with a global fork order, Lamport's TCommit and TwoPhase with a refinement check and a timeout bug, and an abstract Raft election with a voter that forgets its vote.bdd.py: a reduced ordered BDD manager (unique table,apply,ite, restriction, quantification and the relational product); the equality function under two variable orders; symbolic reachability of up to 16 philosophers with one transition relation per command; bounded model checking as CNF for the CDCL solver.lcf.py: an LCF-style kernel for propositional natural deduction (eleven rules, the classical one double-negation elimination), a recorder outside it that logs proofs, four proofs including Peirce's law, five refused steps, and independent checks by truth tables and a two-world Kripke model.testing.py: property-based testing with greedy shrinking; a bug planted in the SCCP pass's constant folder for the duration of awithblock, a fuzzer that hunts it with Part 13's random-program generator and differential runs, and hierarchical delta debugging of the failing program; the Job at every level against the IR interpreter and a Python reference; line and branch coverage withsys.settrace.
Chapter notes
- Hook. Three bugs (Ariane 5 in 1996, Therac-25 in 1985–1987, Heartbleed in 2014) in tested programs, and
Dijkstra's 1970 dictum. Binary search's midpoint as a SAT problem over 16-bit integers: in 0.03 s the solver finds
lo = 8,997, hi = 27,291, whose sum 36,288 wraps to −29,248;
lo + ((hi - lo) >>> 1)is UNSAT, a proof for every 16-bit lo < hi (342 variables, 1,022 clauses). Rice's theorem and the three ways round it. - 1. Specifications, and the first program proof. Pre- and postconditions for max; a weakened specification met
by the useless
m = 32767, and a sort that returns[]; ghost variables for the swap, run on 30,000 and 20,000, whose sum wraps; Turing's 1949 "Checking a Large Routine", n! by repeated addition with assertions u = r! and u = s·r!, a run with n = 5; his column-addition analogy (1374 + 5926 + 2085, carries supplied); the paper largely overlooked until Morris and Jones (1984), while Floyd (1967) and Hoare (1969) rebuilt the idea as a logic. - 2. Floyd–Hoare logic. The triple and partial correctness; the assignment axiom by backward substitution (x > 5 after x := x + 1 needs x > 4), and the forward rule's existential; sequence on the swap, assertions pushed up line by line; consequence, with the identities true in wrap-around arithmetic; conditionals on max; the while rule and Gauss's invariant 2s = i(i + 1) preserved by algebra; soundness, incompleteness, and Cook's relative completeness (1978).
- 3. Binary search, proved. The invariant on a sorted array of twelve primes, searching for the first element
≥ 20 (answer a[8] = 23). Our checker on the loop's skeleton, the comparison a havoc'd unknown, invariant
0 ≤ lo ≤ hi and variant hi − lo: five conditions, all valid at 16 bits, the hardest (variant decreases, 2,352
clauses) in 1.42 s; the search property itself is out of this checker's reach. With the textbook midpoint the
solver refutes preservation at lo = 15,072, hi = 25,558: the sum 40,630 wraps to −24,906 and halves to −12,453,
below lo (Bloch 2006; Bentley's proof was about mathematical integers). Five midpoints over every 16-bit input:
(lo + hi) >> 1fails (0.028 s),lo + ((hi - lo) >> 1)with 0 ≤ lo is proved (1,035 clauses),(lo + hi) >>> 1is proved (795 clauses), the first fix without 0 ≤ lo fails at lo = −16,034, hi = 25,554, andlo + ((hi - lo) >>> 1)is proved for every lo < hi (1,022 clauses). Total correctness: the textbook midpoint also fails "variant decreases" (lo = 22,568, hi = 27,926); a run of the gap 1000, 499, 249, …, 3, 1, 0. Well-founded orders: pairs in dictionary order, Ackermann's function, Floyd's well-founded sets. - 4. Weakest preconditions, checked by SAT. Dijkstra's wp (1975): {P} c {Q} exactly when P ⇒ wp(c, Q); the rules
as equations (assignment, sequence, conditional,
assert,havoc); Gauss's first condition derived. Five verification conditions from an invariant and a variant. Bit-blasting: 16 Boolean variables per integer, adders as full-adder chains (Part 4), Tseitin's three clauses per and-gate; the swap's condition is 425 variables, 1,239 clauses, 1,337 conflicts, UNSAT in 0.24 s. Every program so far: max (390 clauses), swap and the fixed binary search (5,040 clauses, 1.73 s) proved at 16 bits, Gauss's loop at 8 bits (4,976 clauses, 0.39 s), the textbook search refuted on two of its five conditions with the solver's values, each counterexample re-checked by evaluation. Multipliers are hard: Gauss's two product conditions take 5, 62, 298 and 2,082 ms at 4, 6, 8 and 10 bits. SMT solvers (Z3, 2008), Dafny, and proofs of UNSAT. - 5. Separation logic. Aliasing breaks the assignment axiom ({y.f = 2} x.f := 3 {y.f = 2} fails when x = y); the heap as one array costs a case split per pair of pointers. emp, x ↦ v, the separating conjunction, and the list predicate; the small axioms and the frame rule; Reynolds' in-place list reversal animated on three nodes and proved with one invariant, list(α, i) ∗ list(β, j) ∧ rev(α₀) = rev(α)·β. Bi-abduction (Calcagno, Distefano, O'Hearn and Yang, 2009), Facebook's Infer, concurrent separation logic (the 2016 Gödel Prize), Iris and RustBelt (Part 55).
- 6. Model checking. Kripke structures; Peterson's lock is 20 states and 46 transitions. Computation trees, LTL (Pnueli 1977) and CTL (Clarke and Emerson 1981) on a five-state example (EF q and EG p hold, AG p and AF q fail); EF q as a least fixpoint, stable after four rounds; linear-time CTL checking (Clarke, Emerson and Sistla 1986). Peterson: six CTL questions, mutual exclusion, no deadlock and "can always get in" hold, "always gets in" fails; Part 33's checker (258 states of loads and stores) agrees on mutual exclusion. The liveness failure as a lasso, and weak fairness, under which the response property holds for both processes. Counterexamples: Peterson with the turn given away before the flag is raised, 32 states and a six-step path to both in the critical section; Raft-lite with three nodes and terms up to 2, 2,076 states and at most one leader per term; a voter that forgets its vote, 158,647 states and nodes 0 and 2 both leaders of term 1 after six steps. State explosion: the dining philosophers grow from 6 states (n = 2) to 1,154 (n = 8), about ×2.4 per philosopher, a deadlock in n steps for every n; with ordered forks none (985 states at n = 8), though philosopher 0 can still starve under weak fairness (n = 3), not under strong.
- 7. Symbolic and bounded model checking. Two bits per philosopher; a set of states as a Boolean function, a move as guard ∧ effect ∧ frame over current and primed bits. BDDs (Bryant 1986): the equality of two bit-pairs is a 15-test decision tree, 6 nodes interleaved and 9 separated; at twelve pairs 36 against 12,285 = 3·2ⁿ − 3; best order NP-hard (Bollig and Wegener 1996), no good order for multiplication (Bryant 1991). Image computation and reachability (Burch et al. 1990): sixteen philosophers take 16 images, 1,331,714 states in a final diagram of 117 nodes, 0.87 s; states grow about ×2.4 per philosopher while the diagram grows by 8 nodes; the explicit counts agree up to n = 8; the transition relation is 4,480 nodes at n = 16, and the one deadlock state is found symbolically. Bounded model checking (Biere, Cimatti, Clarke and Zhu 1999) on seven philosophers: UNSAT for k = 0 to 6, the hardest k = 6 at 2,598 conflicts; SAT at k = 7, the decoded deadlock. With ordered forks, five philosophers are UNSAT for every k ≤ 7 and the diameter is 5: a proof. k-induction (2000) and IC3 (2011).
- 8. Abstract interpretation. Sound approximation (Cousot and Cousot 1977): the 11 states at a two-counter
loop's head and their box i ∈ [0, 10], j ∈ [0, 20]; false alarms. The interval lattice, joins as hulls, the Galois
connection ({1, 4, 6} ↦ [1, 6]), infinite ascending chains. Counting to 100: 101 rounds to the fixpoint [0, 100],
the assertion proved. Widening and narrowing: [0, 1] jumps to [0, +∞], then narrows to [0, 100], two rounds and two
narrowing steps; for a count to an input n ≤ 50, 51 rounds against 2 + 2; on the two-counter loop plain iteration
never stops (round 60: j ∈ [0, 120]) and widening gives j ∈ [0, +∞], so
assert j == 20is a false alarm. Karr's linear equalities (1976) and polyhedra (Cousot and Halbwachs 1978) keep j = 2i; octagons (Miné 2006) cut the box to a parallelogram but cannot. Astrée (2003) on the Airbus A340's flight-control software. - 9. Types as lightweight proofs. A type check speaks for every run: progress and preservation (Part 14), Milner's "well-typed programs cannot go wrong". Type checking as abstract interpretation (Cousot 1997), and a harmless expression it rejects. Refinement types (Freeman and Pfenning 1991): idx(n) <: nat as an implication. Bloch's bug as a type error: the repaired midpoint's subtyping condition is valid at 16 bits (346 variables, 1,035 clauses, 0.13 s), the textbook one fails at lo = 8,997, hi = 27,291. Liquid types (Rondon, Kawaguchi and Jhala 2008) by hand: of the qualifiers 0 ≤ v, v = 0, v < n, v ≤ n, two are struck out, leaving 0 ≤ v ≤ n. A ladder from simple types to dependent types.
- 10. Proof assistants. Milner's LCF (1972): only the kernel makes theorems; ours has 69 lines and 11 rules, and ML came from LCF's tactic language. Gentzen's natural deduction, double negation the one classical rule. The kernel proves A ∧ B ⇒ B ∧ A in five calls (the Lean 4 version is one line). Five illegal steps refused with their messages; Python's limits, and the de Bruijn criterion. LCF style (HOL Light, Isabelle) against proof terms (Rocq, Lean, Agda). Mathematics checked: the four colour theorem (1976, in Coq 2005), the Kepler conjecture (1998, Flyspeck 2014), the odd order theorem (2012), the Liquid Tensor Experiment (2022), mathlib.
- 11. Verified systems. CompCert (Leroy 2006): ten languages from CompCert C to Asm, each pass proved to shrink the set of behaviours, the inclusions chained. Csmith (2011) found hundreds of bugs in GCC and LLVM and no wrong-code bugs in CompCert's verified middle. seL4 (2009): abstract and executable specifications refined by about 8,700 lines of C, with about 200,000 lines of Isabelle proof; the 2009 assumptions, and the binary checked against the C in 2013. The simulation square with stuttering. Verified cryptography: p = 2²⁵⁵ − 19, five 51-bit limbs and the 19s in the code; Fiat-Crypto and HACL*. CakeML (2014) and what is left to trust.
- 12. Specifying systems: TLA+. Init ∧ □[Next]_vars ∧ Fairness (Lamport 1994). TCommit (Gray and Lamport 2006): 3ⁿ + 2ⁿ − 1 reachable states, 12, 34, 96 and 274 for two to five managers, as the checker counts. TwoPhase: 56, 288, 1,568 and 8,832 states (115 to 37,589 transitions, longest paths 7 to 16), consistent throughout. A coordinator that commits on a timeout: 623 states and a three-step counterexample, one committed and one aborted. TwoPhase refines TCommit, every reachable step checked for two, three and four managers. States grow ×5.1 to ×5.6 per manager, yet the bug needed three managers and three steps (Jackson's small scope hypothesis); TLAPS for every n.
- 13. Testing as science. Coverage on Myers's triangle classifier (1979): 300 random tests (171 invalid, 124
scalene, 5 isosceles, no equilateral) reach 7 of 9 lines and 6 of 8 branch outcomes. An insert with an off-by-one
passes three unit tests with full coverage; a property test fails on its ninth input and shrinks it to
insert([0], 1), which returns[1, 0]. Mutation testing (DeMillo, Lipton and Sayward 1978): four mutants worked by hand, one equivalent, score 1/3. QuickCheck (2000): a sort through a set fails on its 27th list, [3, −3, −3, 1], shrunk after 11 candidates to [0, 0]. Coverage-guided fuzzing (Miller 1990, AFL 2013, OSS-Fuzz 2016): 256⁻³ = 1/16,777,216 against about 3 × 256 tries. Symbolic and concolic execution: the path condition forequilateralsolved to a = b = c = 1 (KLEE 2008, DART 2005). - 14. Fuzzing and validating our compiler. Differential testing of random Pebble programs on the IR interpreter
and at four levels, with a planted bug: SCCP folds division by floor, so (−7)/256 becomes −1 with remainder 249
instead of 0 and −7. The hunt: five programs in 2.7 s, three agree, one skipped at the step limit, seed 4
disagrees (75 lines, 6 functions, 92 bytes of output), at level 3 only, from byte 1; without the bug every program
agrees. Delta debugging (Zeller and Hildebrandt 2002, hierarchical after Misherghi and Su 2006): 75 tests, 54
accepted removals, 4.4 s, 75 lines down to 9; f1(−7, −78) = −7 prints
f90000againstf9ffff. The Job on five texts up to 226 bytes agrees at every level with the interpreter and a Python reference (38,633 steps unoptimized, 12,854 at level 3): evidence, not proof. Translation validation (Pnueli, Siegel and Singerman 1998), illustrated by a validator for constant folding that would refuse the bad fold (not run); CompCert's validated register allocation. Proof-carrying code (Necula 1997) and its descendants. - 15. Frontier: proofs at scale. TLA+ at Amazon (Newcombe et al. 2015), verified cryptography in browsers, static analysis on every change; machines that write proofs, safe because our kernel's 69 lines check every step; language models writing Lean, Coq and Dafny proofs, and 2024's kernel-checked olympiad solutions. Four open problems (invariant inference, specifications, scale, concurrency and hardware) and the ★ research problem.
- Outro. Recap, payoffs (Parts 55, 58, 59, 60, 61), practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The cost of bugs (Ariane 5, Therac-25, Heartbleed, cited); Dijkstra's dictum; Rice (Part 25) and the three ways around it.
- Specifications; Turing's "Checking a Large Routine" (1949), the first program proof.
- Floyd–Hoare logic (1967, 1969): triples and the rules (assignment by backward substitution, sequence, conditionals, while with its invariant); soundness and relative completeness (Cook 1978).
- Binary search proved: the invariant, and Bloch's 2006 overflow bug; total correctness by variants and well-founded orders.
- Weakest preconditions (Dijkstra 1975); VC generation; our VCs checked by our SAT solver (Part 26), or by z3 if it is installed.
- Separation logic (Reynolds, O'Hearn): the frame rule; in-place list reversal proved; Infer at scale.
- Model checking (Clarke, Emerson, Sifakis; the 2007 Turing Award):
- Kripke structures; LTL and CTL over computation trees;
- state explosion;
- symbolic model checking with BDDs (callback to Part 3) and bounded model checking with SAT;
- Peterson (Part 33) and Raft-lite (Part 38) checked.
- Abstract interpretation (Cousot & Cousot 1977): Galois connections; intervals and widening, the fixpoint converging; Astrée on Airbus flight software (cited).
- Types as lightweight proofs (callback to Part 14); refinement types.
- Proof assistants: the LCF trusted kernel (Milner 1972); Rocq, Isabelle, Lean; a proof on screen; the four-color theorem, Flyspeck, the Liquid Tensor Experiment, mathlib (callback to AI, Built 25).
- Verified systems: CompCert (Leroy; Csmith found no wrong-code bugs in its verified parts), seL4 (2009, about 9k lines of C and 200k lines of proof), verified cryptography (HACL*, Fiat-Crypto), CakeML.
- TLA+ (Lamport): systems as state machines; an invariant checked on a protocol (Part 38); refinement.
- Testing as science: coverage; mutation testing; property-based testing (QuickCheck 2000) with shrinking; coverage-guided fuzzing (Miller 1990; AFL); symbolic and concolic execution (KLEE); differential testing (Csmith). Our fuzzer finds a bug planted in the Pebble compiler.
- Translation validation of our compiler on the Job's code; proof-carrying code (Necula 1997). Outro.
Computed: VCs generated and discharged for several programs; the binary-search overflow found; LTL checks of Peterson and the dining philosophers; BDD reachability sizes; interval analysis with widening; an LCF-style kernel for natural deduction; property tests and fuzzing of the Pebble toolchain. Visuals: assertions flowing backward through code; computation trees with CTL paths lit; the interval lattice's widening jumps; the small trusted kernel inside a large system. In practice: TLA+ at AWS and Azure, static analyzers (Infer, CodeQL), fuzzing in CI (OSS-Fuzz), property-based testing, verified cryptography in browsers. Reading: Huth & Ryan, Logic in Computer Science; Baier & Katoen, Principles of Model Checking; Clarke, Grumberg, Kroening, Peled & Veith, Model Checking; Nipkow & Klein, Concrete Semantics; Pierce et al., Software Foundations; Bradley & Manna, The Calculus of Computation; Kroening & Strichman, Decision Procedures; Dijkstra, A Discipline of Programming; Gries, The Science of Programming; Lamport, Specifying Systems; Møller & Schwartzbach, Static Program Analysis; Rival & Yi; Zeller et al., The Fuzzing Book; Hoare 1969; Floyd 1967; Cousot & Cousot 1977; Reynolds 2002; Leroy 2009; Klein et al. 2009; Claessen & Hughes 2000; Newcombe et al. 2015.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
高斯求和循环。 用一个不变量和一个递减量(变式),证明 {n ≥ 0} 求和循环 {s = n(n+1)/2}。
解答
循环是
i = 0; s = 0; while i < n: i = i + 1; s = s + i。取不变量 I:0 ≤ i ≤ n ∧ 2s = i(i + 1),变式 V = n − i。共五个条件。进入时成立:i = s = 0 时 I 为 0 ≤ 0 ≤ n ∧ 0 = 0·1,由 n ≥ 0 推出。循环体保持:由 I 和 i < n,循环体给出 i' = i + 1、s' = s + i + 1;于是 0 ≤ i',且 i' ≤ n(整数,i < n),并且 2s' = 2s + 2(i + 1) = i(i + 1) + 2(i + 1) = (i + 1)(i + 2) = i'(i' + 1)。退出:I 与 ¬(i < n) 给出 i = n,所以 2s = n(n + 1);n(n + 1) 是 两个相邻整数之积,必为偶数,故 s = n(n+1)/2。变式非负:i < n 给出 n − i > 0。变式递减:n − (i + 1) < n − i。变式是 自然数,每一轮减一,所以循环恰好在 n 轮后停止,三元组在完全正确性的意义下成立。我们的检查器在 8 位上判定这五个条件都 有效(4,976 个子句,0.39 秒);在那里等式按模 2⁸ 理解,而且因为 i < n ≤ 127,i + 1 不会溢出。注意 2s ≡ n(n + 1) (mod 2ʷ) 只把 s 确定到模 2ʷ⁻¹,比循环实际算出的结果要弱。 -
交换的最弱前置条件。 计算无临时变量交换的 wp,并证明它对所有 w 位的值成立。
解答
把后置条件 x = Y ∧ y = X 从最后一行往上推。经过
x = x - y:x − y = Y ∧ y = X。经过y = x - y: x − (x − y) = Y ∧ x − y = X。经过x = x + y:(x + y) − ((x + y) − y) = Y ∧ (x + y) − y = X。验证条件是 x = X ∧ y = Y ⇒ 上式。在整数中 (x + y) − y = x,(x + y) − x = y,所以它化为 y = Y ∧ x = X,正是假设。对 w 位的字, 补码的 +、− 就是环 ℤ/2ʷℤ 的运算:每个算出的值都与同一表达式在 ℤ 中的值模 2ʷ 同余,所以最后的 x 与开始的 y 同余, 最后的 y 与开始的 x 同余;它们都在代表元范围 [−2ʷ⁻¹, 2ʷ⁻¹) 里,同余即相等。16 位下取 30,000 和 20,000:x 变成 −15,536(50,000 回绕),然后 y = −35,536 + 65,536 = 30,000,x = −45,536 + 65,536 = 20,000。我们的 SAT 求解器对 每一对 16 位值确认了这一点:425 个变量,1,239 个子句,0.24 秒内不可满足。这个证明依赖回绕:换成饱和运算或浮点数 就不成立;如果 x 和 y 指的是同一块存储,三行之后只剩 0。 -
链表反转。 用分离逻辑证明原地反转链表是正确的。
解答
程序是
j = nil; while i != nil: k = i.next; i.next = j; j = i; i = k,前置条件 list(α₀, i),后置条件 list(rev(α₀), j),其中 list(ε, i) ⇔ emp ∧ i = nil,list(a·α, i) ⇔ ∃k. i ↦ a, k ∗ list(α, k)。不变量 I: ∃α, β. list(α, i) ∗ list(β, j) ∧ rev(α₀) = rev(α)·β。进入时成立:j = nil之后 list(ε, j) 就是 emp,所以 list(α₀, i) ∗ list(ε, j) 在 α = α₀、β = ε 时成立。循环体保持:i ≠ nil 排除了 α = ε(那种情形要求 i = nil),所以 α = a·α',展开得 i ↦ a, k₀ ∗ list(α', k₀) ∗ list(β, j)。读k = i.next只碰第一个格子,令 k = k₀。写i.next = j是那一个格子上的小公理 {i.next ↦ −} i.next := j {i.next ↦ j},框架规则把 list(α', k) ∗ list(β, j) 原样带过去;分离合取保证这个格子不在两个链表里,所以不必为别名分情况。折叠:i ↦ a, j ∗ list(β, j) 就是 list(a·β, i),于是得到 list(α', k) ∗ list(a·β, i),而j = i; i = k把它改名为 list(α', i) ∗ list(a·β, j)。幽灵 等式成立,因为 rev(a·α')·β = rev(α')·a·β。退出:I 与 i = nil 给出 α = ε(list(α, nil) 迫使如此),那一部分是 emp, 于是 list(β, j) 且 rev(α₀) = β,正是后置条件。每次解引用的格子都归断言所有,所以程序也是内存安全的;α 的长度是变式。 -
加宽。 证明不加宽的区间分析可能不终止,而加宽使它终止。
解答
取
i = 0; j = 0; while i < 10: i = i + 1; j = j + 2。在循环头上的克莱尼迭代计算 X₀ = (i ∈ [0, 0], j ∈ [0, 0]) 和 X_{k+1} = X₀ ⊔ body(X_k ⊓ (i < 10))。归纳可得 X_k = (i ∈ [0, min(k, 10)], j ∈ [0, 2k]):过滤 i < 10 约束了 i,却对 j 什么也没说;循环体加 1 和加 2;与 X₀ 的并把下界保持在 0。所以 j 的上界 永远增长(我们的分析器第 60 轮时 j ∈ [0, 120]);区间格有无限的上升链,程序里也没有什么单独约束 j。(不加宽也可能 终止,比如数到 100 用了 101 轮,但那是沿着链一步一步爬上去的。)加宽时 Y_{k+1} = Y_k ∇ F(Y_k):动过的界送到 ±∞, 稳定的界保留。只要 Y_{k+1} ≠ Y_k,就有某个有限的界变成了无穷,而无穷的界不再改变,所以 n 个变量时每个循环头至多有 2n 次严格上升。当 Y_{k+1} = Y_k 时,F(Y_k) 的每个界都落在 Y_k 之内(否则它会被加宽),所以 F(Y) ⊑ Y:这是一个后 不动点,由塔尔斯基定理它位于最小不动点之上,因而是可靠的。随后的窄化只允许无穷的界降回来,所以也在 2n 步内停止, 并且仍在最小不动点之上。我们的分析器:数到 100,用两轮加两步窄化,而不是 101 轮;数到输入 n ≤ 50,同样是 2 + 2, 而不是 51 轮;在双计数器循环上它停在 i ∈ [0, 10]、j ∈ [0, +∞],而普通迭代永不停止。 -
动手。 在我们编译器的优化器里植入另一个错误,测量模糊测试器需要多少个随机程序。
解答
解答要点。 在
explainer/cs/verify/testing.py里给BUGS加一项,并让_BuggyFolder按种类分派(按现在的写法, 不管传入哪个种类,planted_bug装上的都是向下取整除法的折叠器)。适合这个折叠器的错误(SCCP 对每个运算符都通过interp.binop调用它):折叠移位时不把移位数屏蔽到五位(ub & 31),把有符号比较当成无符号来折叠,或者让余数取除数的 符号。像tests.test_cs54_check.Fuzz.test_planted_bug_is_scoped对原来的错误那样,检查它只在 with 块内生效。然后对 比如二十个互不相交的种子区间运行hunt(kind, seeds=range(s0, s0 + 200)):programs是直到第一次不一致时生成的程序数 (包括跳过的),clean_agree必须为真。如果每个程序独立地以概率 p 触发错误,这个数服从均值为 1/p 的几何分布;报告中位数 和四分位数,并用“找到次数除以程序数”估计 p,附上置信区间。可以预期,这个数取决于生成器多常让该运算符的操作数成为常量 (只有第 3 级做内联,所以植入的错误只在第 3 级出现),也取决于操作数多常落进出错的情形(两数符号不同;移位数不小于 32)。最后对每次发现运行shrink_program,并仿照Fuzz.test_hunt加一个测试。 -
★ 研究。 对带乘法的循环,给出完备而实用的不变量推断。
讨论。 尚未解决。在整数上,即使只是检查一个候选不变量是否归纳,也要证明一个全称量化的非线性整数算术公式,这在一般 情况下不可判定(希尔伯特第十问题,第25部分);在 w 位字上它可判定,但正如高斯循环的条件所示(4 位 5 毫秒,10 位超过 2 秒),乘法器推理是 SAT 的经典难题。已知的完备方法只覆盖受限的类:更新为仿射的循环的多项式等式,或用格罗布纳基、 线性代数求出的有界次数的不变量;实用工具则退而使用模板、插值、数据驱动的猜测,以及近来由检查器筛选其猜测的语言模型。 好的答案应固定一类不变量(例如次数至多为 d 的多项式等式加上线性不等式)和一类带多项式更新与条件的循环,证明只要该类 中存在能证明断言的归纳不变量,过程就能找到一个,给出复杂度,并有一个能在几秒内处理高斯循环、立方和与整数平方根的 实现。部分结果就已有价值:对某个有意思的子类的完备性,类与类之间清晰的可判定性边界,或者在模算术(位向量)下的同样 结果,在那里 2s = n(n + 1) 已不能确定 s。
Build the film
python -m videos.cs.cs54.compute # the part's numbers, into .cache/cs54
python tools/build.py cs54 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs54 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs54. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs54.compute
python -m unittest tests.test_cs54_logic tests.test_cs54_check
python tools/build.py cs54