Algorithmadvanced
Houdini
Also called Houdini annotation inference.
Guesses many candidate invariants and removes those a verifier refutes until the rest are inductive, the largest such subset.
- Time
- O(c T + c^2) worst
- Space
- O(c) extra
- Where
- T = the cost of one call of the prover; c = the number of candidate invariants
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Cormac Flanagan, K. Rustan M. Leino, Rajeev Joshi, 2001
Houdini finds loop invariants by elimination. It starts from a large set of candidate formulas, guessed from the program text, and asks a verifier whether their conjunction is an inductive invariant. Each time the verifier gives a counterexample, Houdini removes every candidate that the counterexample refutes, and asks again. When the verifier accepts, the remaining conjunction is the largest inductive subset of the candidates, and with candidates this takes at most verifier calls.
In plain words
You cannot easily invent the right facts about a loop, but you can cheaply guess hundreds: "this variable is never negative", "this pointer is never null", "this index stays below that length". Most guesses are wrong. Assume all of them at once and ask a checker whether they hold at the start and whether one turn of the loop keeps them all. If not, the checker shows a state where some guesses break. Throw those guesses away and ask again. A wrong guess never comes back, so the list only gets shorter. When the checker is finally happy, the guesses that are left hold together, and no good guess was thrown away on the way, because each throw was forced by a real broken state.
The problem
The input is a loop, given by its initial states , a guard and a body, a finite set of candidate formulas, and a prover. The output is the largest whose conjunction is inductive: every initial state satisfies , and one turn of the body from a state of ends in . The loop invariant synthesis page explains why such sets matter; Houdini solves the special case where the language is "conjunctions of candidates from ".
The prover decides whether a conjunction is inductive and, if not, returns a counterexample. A real tool builds the two verification conditions and asks an SMT solver, which is a decision procedure when the candidates and the loop lie in a decidable theory such as Presburger arithmetic. This page has no solver. Its prover tries every state of a box of integers and returns the first counterexample in lexicographic order, so "inductive" here means inductive on the box, a bounded check, not a proof. The theorem below holds for any fixed domain of states, the box or all of .
The algorithm
HOUDINI(C, PROVE)- 1
H <- C - 2
loop - 3
cex <- PROVE(H) - 4
if cex = none then return H - 5
if cex is an initial state s then H <- {h in H : s satisfies h} - 6
else cex is a step from s to t: H <- {h in H : t satisfies h}
PROVE gets the current set . An initial counterexample is an initial state that falsifies . A step counterexample is a state that satisfies and the guard, with a successor that falsifies . Line L5 removes the candidates that are false at the start of the loop, and line L6 removes the candidates that one turn breaks. Line L6 looks only at : a candidate that is false at is not removed, since may be a state that no run reaches.
Example
The loop is , entered with . The eight candidates are , , , , , , and . The prover checks the box over in lexicographic order.
| call | candidates left | counterexample | removed |
|---|---|---|---|
| 1 | all 8 | initial state | |
| 2 | 7 | step from to | , |
| 3 | 5 | none |
Houdini returns after 3 calls, below the bound . Brute force over all 256 subsets gives the same largest inductive subset. With the exit condition , the result gives and , the postcondition one wants. The candidate is true on many runs, but the initial state with refutes it. The step of call 2 removes two candidates at once.
Correctness
The full proof is in the proof file. Fix the domain of states that the prover checks, and say "inductive" for "inductive on ".
- Inductive sets are closed under union. If and are inductive, a state of satisfies both and , so its successors satisfy both conjunctions. The empty set is inductive. So the union of all inductive subsets is inductive and is the unique largest one.
- The invariant . An initial counterexample satisfies , since holds initially. A step counterexample starts in , hence in , so its end satisfies . Either way, lines L5 and L6 remove no candidate of .
- Progress. A counterexample falsifies at or , so at least one candidate goes. At most calls fail, and the call after the last failure succeeds: at most calls.
- The end. The returned is inductive, so , and by step 2, .
The proof needs an exact prover. With an incomplete prover, a spurious counterexample can remove a good candidate, and the result is inductive but smaller.
Proof: Houdini returns the largest inductive subset with at most c + 1 prover callsfull
Setting. A loop has a set of initial states , a guard and a body. For a state that satisfies , is the set of states that one turn of the body can reach from ; the body may be nondeterministic, and the proof does not need it to be deterministic. Fix a set of states , the domain of the check: all states for a real prover, or a box of integers for the prover of the page. is a finite set of candidate formulas. For , write for the conjunction, which is true everywhere when is empty.
is inductive on when
- every satisfies , and
- for every with and every , .
PROVE is exact on : it returns "none" when is inductive on , and otherwise a counterexample, either an initial state with , or a step with , , and .
Lemma 1: a largest inductive subset exists
Claim. If and are inductive on , so is . Hence the union of all subsets of that are inductive on is itself inductive on , and it contains every inductive subset.
Proof. Condition 1: a state of satisfies and , so it satisfies , the conjunction of the two. Condition 2: let satisfy and let . Then , so because is inductive, and in the same way . So . The empty set is inductive, because condition 1 asks nothing of the empty conjunction and condition 2 asks only that satisfies . has finitely many subsets, so is a finite union of inductive sets and is inductive by the first part.
Note that the union of candidate sets is the conjunction of more formulas, that is, a stronger invariant. "Largest" means the strongest inductive invariant that is a conjunction of candidates.
Lemma 2: Houdini never removes a candidate of
Claim. At every call of PROVE, .
Proof. At the first call . Suppose and PROVE returns a counterexample.
- An initial state . Line L5 removes the candidates false in . By condition 1 for , every candidate of is true in , so none of them is removed.
- A step with and . Since , , and by condition 2 for , . Line L6 removes the candidates false in , so none of is removed.
Lemma 3: every failed call removes a candidate
Claim. When PROVE returns a counterexample, the next is strictly smaller.
Proof. An initial counterexample falsifies , so some candidate of is false in and line L5 removes it. A step counterexample has , so some candidate of is false in and line L6 removes it.
Theorem
Claim. HOUDINI stops after at most calls of PROVE and returns , the largest subset of that is inductive on .
Proof. By Lemma 3, each call that returns a counterexample makes smaller by at least one. starts at and cannot go below 0, so at most calls fail, and the next call returns "none". That is at most calls. When PROVE returns "none", is inductive on because PROVE is exact, so by Lemma 1. By Lemma 2, . So .
The bound is tight. For the loop from with guard and the candidates , checked on a box that contains , the first counterexample in increasing order of is the step for the smallest bound still present, and it falsifies only . So each failed call removes one candidate, and Houdini makes exactly calls. The tests check this for .
Weaker provers. If PROVE is sound but may return a spurious counterexample, Lemma 2 can fail and Houdini can return a smaller set; the result is still inductive, since the last call said "none". If PROVE may say "none" for a set that is not inductive, the result need not be inductive.
Complexity
By step 3 there are at most calls of PROVE. Each round filters with one evaluation per candidate, , so the total is , where is the cost of one prover call. The bound is tight: for from with the candidates , each counterexample refutes one bound, and the tests check that takes 4 calls. The box prover of this page costs evaluations for the box . A real prover pays one SMT call, and in the worst case that call is as hard as the theory: NP-complete for quantifier-free linear integer arithmetic.
Properties
- Largest, hence strongest. The result is the strongest invariant that is a conjunction of candidates. Any proof that uses only candidates from also works with it.
- Monotone removal. A candidate, once removed, never returns, so the run is a descending chain in a finite lattice. This is the greatest fixed point of a monotone operator on subsets of , and Houdini computes it by iteration from the top.
- Independent of the order. The result does not depend on which counterexample the prover returns, only on the set of candidates and the domain. The number of calls does depend on it.
- Modular. In ESC/Java the candidates are the preconditions, postconditions and invariants of all methods at once. One run of the modular checker refutes some of them, and the same argument shows that the largest consistent set is found.
- Only conjunctions. Houdini never builds a disjunction or a new formula. If the needed invariant is not a conjunction of candidates, it is not found.
Variants and improvements
- Whole-program Houdini. The original tool guessed annotations for every method of a Java program, ran ESC/Java on the whole program, and removed every annotation with a warning. Each run of the checker can refute many candidates.
- Predicate abstraction with conjunctions. Predicate abstraction over the candidates as predicates, restricted to the conjunction domain, gives the same result. With the full boolean domain over the same predicates, it can also find disjunctions, at an exponential cost.
- Learning with counterexamples. Data-driven methods, in the style of CEGIS, also learn invariants from counterexamples, but they can add formulas, not only remove them, and they use implication counterexamples in both directions.
- Seeding other tools. Houdini output is a cheap first invariant for k-induction, IC3 and abstract interpretation, which then strengthen it.
- Parallel and incremental. Since the checks of different procedures are independent, tools run them in parallel, and keep the solver state between calls because each query differs from the last only by removed candidates.
When to use it
Use Houdini when cheap guesses are plentiful and most of the needed facts are simple: bounds of indices, signs, non-null pointers, relations between two variables. It is a good first pass before a verifier asks a person for invariants. Use constraint-based generation when the needed invariant is a linear inequality whose coefficients you cannot guess, and abstract interpretation when there is no target property and you want the strongest facts in a domain.
Pitfalls
- Expecting more than conjunctions. For the loop from , the candidates and are both kept, but their conjunction allows and cannot prove . Houdini finds only when it is itself a candidate. The tests check both cases.
- Removing at the wrong state. Line L6 must test the candidates at the successor . Testing them at , or removing every candidate that is false somewhere in the domain, removes candidates of that only fail at unreachable states.
- Assuming the result proves the property. The largest inductive subset can still be too weak for the postcondition. Houdini then reports the property as unproved; it is not evidence that the program is wrong.
- Taking a bounded check for a proof. The prover of this page only checks a box. A conjunction can be inductive on and fail at a larger state, so the result is only evidence. With an SMT solver over a decidable theory, it is a proof.
- A prover that times out. If a timeout is treated as a counterexample with no state, there is nothing to remove and the loop does not progress. If it is treated as "none", the result is unsound. Real tools remove the candidate that the checker could not prove, and accept that the result may then be smaller than .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/houdini-algorithm/. The authors are listed in prov/8FP30Z.jsonl.
"""The Houdini algorithm on a single loop of a small while language.
Expressions are tuples: ("int", c), ("var", x), (op, a, b) for op in
+ - * < <= == != and or, ("not", a) and ("ite", c, a, b).
A Loop has a list of variable names, a precondition init, a guard and a
body. The body is a list of assignments (x, e) run in order, so it is
deterministic; use ite for a branch.
houdini(candidates, prove) is the algorithm. prove(h) gets a tuple of
candidate indices and returns None when the conjunction of those candidates
is inductive, or a counterexample: ("init", s), a state of the
precondition that falsifies the conjunction, or ("step", s, t), a state s
that satisfies the conjunction and the guard and whose successor t does not.
box_prover(loop, candidates, lo, hi) is the prover of the page. It has no
SMT solver: it tries every state of the box [lo, hi]^k in a fixed order and
returns the first counterexample. "Inductive" then means inductive on the
box, a bounded check, not a proof.
"""
import itertools
_OPS = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"<": lambda a, b: a < b,
"<=": lambda a, b: a <= b,
"==": lambda a, b: a == b,
"!=": lambda a, b: a != b,
}
def evaluate(e: tuple, env: dict):
"""The value of e in the state env. Cost: O(size of e)."""
tag = e[0]
if tag == "int":
return e[1]
if tag == "var":
return env[e[1]]
if tag in _OPS:
return _OPS[tag](evaluate(e[1], env), evaluate(e[2], env))
if tag == "and":
return evaluate(e[1], env) and evaluate(e[2], env)
if tag == "or":
return evaluate(e[1], env) or evaluate(e[2], env)
if tag == "not":
return not evaluate(e[1], env)
if tag == "ite":
return evaluate(e[2], env) if evaluate(e[1], env) else evaluate(e[3], env)
raise ValueError("unknown expression %r" % (tag,))
class Loop:
"""while guard do body, entered from the states of init."""
__slots__ = ("names", "init", "guard", "body")
def __init__(self, names, init, guard, body):
self.names = list(names)
self.init = init
self.guard = guard
self.body = list(body)
def step(self, s: dict) -> dict:
"""The state after one turn of the body from s."""
t = dict(s)
for x, e in self.body:
t[x] = evaluate(e, t)
return t
def houdini(candidates, prove):
"""Return (h, calls): h is the tuple of indices of the largest subset of
candidates whose conjunction prove accepts, calls is the number of calls
to prove. Precondition: prove answers for a fixed notion of
"inductive" that is closed under union of candidate sets, and each
counterexample it returns is genuine. Cost: at most c + 1 calls to
prove, where c = len(candidates), and O(c) evaluations per call."""
h = list(range(len(candidates))) # @line L1
calls = 0
while True: # @line L2
calls += 1
cex = prove(tuple(h)) # @line L3
if cex is None:
return tuple(h), calls # @line L4
if cex[0] == "init":
s = cex[1] # @line L5
h = [i for i in h if evaluate(candidates[i], s)]
else:
t = cex[2] # @line L6
h = [i for i in h if evaluate(candidates[i], t)]
def box_states(names, lo: int, hi: int):
"""Every state of the box [lo, hi]^k, in lexicographic order."""
for vals in itertools.product(range(lo, hi + 1), repeat=len(names)):
yield dict(zip(names, vals))
def box_prover(loop: Loop, candidates, lo: int, hi: int):
"""A prover for houdini that checks initiation and consecution in every
state of the box and returns the first counterexample. Each call costs
O((hi - lo + 1)^k) evaluations of the candidates. It also counts its
calls in the attribute calls."""
states = list(box_states(loop.names, lo, hi))
def holds(h, s):
return all(evaluate(candidates[i], s) for i in h)
def prove(h):
prove.calls += 1
for s in states:
if evaluate(loop.init, s) and not holds(h, s):
return ("init", s)
for s in states:
if holds(h, s) and evaluate(loop.guard, s):
t = loop.step(s)
if not holds(h, t):
return ("step", s, t)
return None
prove.calls = 0
return prove
def inductive_on_box(loop: Loop, candidates, h, lo: int, hi: int) -> bool:
"""Whether the conjunction of the candidates in h is inductive on the box:
every state of the box in init satisfies it, and every state of the box
that satisfies it and the guard has a successor that satisfies it."""
return box_prover(loop, candidates, lo, hi)(tuple(h)) is None
test_houdini_algorithm.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/houdini-algorithm/. The authors are listed in prov/8FP30Z.jsonl.
import itertools
import random
import unittest
from houdini_algorithm import Loop, box_prover, evaluate, houdini, inductive_on_box
def V(x):
return ("var", x)
def K(c):
return ("int", c)
# The worked example of the page.
PAGE_LOOP = Loop(
["i", "j", "n"],
("and", ("==", V("i"), K(0)), ("and", ("==", V("j"), K(0)), ("<=", K(0), V("n")))),
("<", V("i"), V("n")),
[("i", ("+", V("i"), K(1))), ("j", ("+", V("j"), K(2)))],
)
PAGE_CANDS = [
("<=", K(0), V("i")),
("<=", V("i"), V("n")),
("==", V("j"), ("*", K(2), V("i"))),
("<=", V("j"), V("n")),
("==", V("i"), V("j")),
("<=", K(0), V("n")),
("<=", V("j"), ("*", K(2), V("n"))),
("<=", V("n"), K(3)),
]
def largest_inductive(loop, cands, lo, hi):
"""The brute-force oracle: the union of all subsets that are inductive
on the box."""
best = set()
for r in range(len(cands) + 1):
for sub in itertools.combinations(range(len(cands)), r):
if inductive_on_box(loop, cands, sub, lo, hi):
best |= set(sub)
return tuple(sorted(best))
class TestPage(unittest.TestCase):
def test_page_example(self):
prove = box_prover(PAGE_LOOP, PAGE_CANDS, -4, 4)
h, calls = houdini(PAGE_CANDS, prove)
self.assertEqual(h, (0, 1, 2, 5, 6))
self.assertEqual(calls, 3)
self.assertEqual(prove.calls, 3)
self.assertEqual(h, largest_inductive(PAGE_LOOP, PAGE_CANDS, -4, 4))
def test_page_trace(self):
prove = box_prover(PAGE_LOOP, PAGE_CANDS, -4, 4)
first = prove(tuple(range(8)))
self.assertEqual(first, ("init", {"i": 0, "j": 0, "n": 4}))
second = prove((0, 1, 2, 3, 4, 5, 6))
self.assertEqual(second, ("step", {"i": 0, "j": 0, "n": 1}, {"i": 1, "j": 2, "n": 1}))
def test_result_proves_postcondition(self):
# The result, with the exit i >= n, gives j = 2n on the box.
h, _ = houdini(PAGE_CANDS, box_prover(PAGE_LOOP, PAGE_CANDS, -4, 4))
for vals in itertools.product(range(-4, 5), repeat=3):
s = dict(zip(["i", "j", "n"], vals))
if all(evaluate(PAGE_CANDS[k], s) for k in h) and s["i"] >= s["n"]:
self.assertEqual(s["j"], 2 * s["n"])
def test_empty_candidates(self):
h, calls = houdini([], box_prover(PAGE_LOOP, [], -1, 1))
self.assertEqual((h, calls), ((), 1))
def test_c_plus_one_calls_reached(self):
# From x = 0 the loop counts up for ever. Each call removes exactly
# one bound x <= k, so the c = 3 candidates need c + 1 = 4 calls.
loop = Loop(["x"], ("==", V("x"), K(0)), ("==", K(0), K(0)), [("x", ("+", V("x"), K(1)))])
cands = [("<=", V("x"), K(k)) for k in range(3)]
h, calls = houdini(cands, box_prover(loop, cands, -3, 3))
self.assertEqual((h, calls), ((), 4))
def test_only_conjunctions(self):
# x flips between 1 and -1. Both bounds are inductive, but their
# conjunction allows x = 0, so it cannot prove x != 0. The candidate
# x != 0 itself is found when it is offered.
loop = Loop(["x"], ("==", V("x"), K(1)), ("==", K(0), K(0)), [("x", ("-", K(0), V("x")))])
cands = [("<=", K(-1), V("x")), ("<=", V("x"), K(1))]
h, _ = houdini(cands, box_prover(loop, cands, -3, 3))
self.assertEqual(h, (0, 1))
self.assertTrue(all(evaluate(cands[k], {"x": 0}) for k in h))
cands2 = cands + [("!=", V("x"), K(0))]
h2, _ = houdini(cands2, box_prover(loop, cands2, -3, 3))
self.assertEqual(h2, (0, 1, 2))
NAMES = ["x", "y"]
LO, HI = -3, 3
def rand_term(rng):
a = rng.choice([V("x"), V("y"), K(rng.randint(-2, 2))])
if rng.random() < 0.5:
return a
b = rng.choice([V("x"), V("y"), K(rng.randint(-2, 2))])
return (rng.choice(["+", "-", "*"]), a, b)
def rand_atom(rng):
return (rng.choice(["<", "<=", "==", "!="]), rand_term(rng), rand_term(rng))
class TestRandom(unittest.TestCase):
def test_random_loops(self):
rng = random.Random(2024)
nonempty = 0
for _ in range(500):
init = rand_atom(rng) if rng.random() < 0.3 else ("and", rand_atom(rng), rand_atom(rng))
guard = rand_atom(rng) if rng.random() < 0.8 else ("==", K(0), K(0))
body = [(rng.choice(NAMES), rand_term(rng)) for _ in range(rng.randint(1, 2))]
loop = Loop(NAMES, init, guard, body)
c = rng.randint(0, 6)
cands = [rand_atom(rng) for _ in range(c)]
prove = box_prover(loop, cands, LO, HI)
h, calls = houdini(cands, prove)
self.assertLessEqual(calls, c + 1)
self.assertEqual(calls, prove.calls)
self.assertTrue(inductive_on_box(loop, cands, h, LO, HI))
self.assertEqual(h, largest_inductive(loop, cands, LO, HI))
nonempty += bool(h)
self.assertGreater(nonempty, 100)
if __name__ == "__main__":
unittest.main()
History
Flanagan and Leino presented Houdini at FME 2001 as an annotation assistant for ESC/Java. ESC/Java needed many annotations before it gave useful warnings, and Houdini filled in the simple ones by guessing candidates from the program text and letting ESC/Java refute them. Flanagan, Joshi and Leino gave the general theory in Information Processing Letters in the same year, for any modular checker, with the proof that the algorithm finds the largest valid set of candidate annotations. The same scheme now appears as the "candidate invariant" pass of many verifiers and as a building block of invariant learners.
References
- Cormac Flanagan and K. Rustan M. Leino, Houdini, an annotation assistant for ESC/Java, Proceedings of FME 2001, LNCS 2021, pp. 500 to 517, Section 3 (the Houdini algorithm, the candidate annotations and the refutation loop) and the experience with ESC/Java
- Cormac Flanagan, Rajeev Joshi and K. Rustan M. Leino, Annotation inference for modular checkers, Information Processing Letters 77(2-4), 2001, pp. 97 to 108, the annotation inference algorithm and the proof that it returns the largest valid set of candidate annotations
- Cormac Flanagan and James B. Saxe, Avoiding exponential explosion, generating compact verification conditions, Proceedings of POPL 2001, pp. 193 to 205, the VC generator of ESC/Java that Houdini calls
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 8FP30Z Edit this page History Report an error Markdown