Algorithmcore
Delta debugging
Also called ddmin, test case minimization.
Shrinks a failing input to a 1-minimal failing one by testing subsets and complements of finer and finer partitions.
- Time
- O(N^2 (t + N)) worstO((t + N) log N) best
- Space
- O(N) extra
- Where
- N = the number of elements of the failing input; t = the cost of one test
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ralf Hildebrandt, Andreas Zeller, 2000
Delta debugging, in the form of the algorithm ddmin of Zeller and Hildebrandt, takes an input that makes a test fail and removes parts of it while the test still fails. It treats the input as a list of elements, such as characters, lines, tokens or instructions, and needs only a test function that answers FAIL, PASS or UNRESOLVED. The result is 1-minimal: removing any single element makes the failure go away. That is a local property. A 1-minimal input is not always a minimum one, and ddmin does not try to find the minimum, which can need exponentially many tests.
In plain words
You have a long input that crashes a program, and you want a short one that a person can read. Cut the input in two halves and try each half. If a half still crashes, keep it and start again. If neither half crashes, cut into more, smaller pieces, and try each piece and each "everything but this piece". Whenever a try still crashes, keep it. When the pieces are single elements and no try crashes any more, stop. At that point no single element can be removed without losing the crash. Some tries give a broken input that the program rejects for another reason; those count as "no crash". The result is small, but another, smaller input that crashes for a different reason can still exist.
The problem
The input is a list of elements and a test function from sub-lists of to , with and . A sub-list keeps the original order. The output is a sub-list with that is 1-minimal: for every element of , .
What is decidable here is simple: everything, because the search space is finite. The question is the number of tests. A minimum failing sub-list, one of the smallest size, can need tests: if every test passes, no algorithm can claim that the full input is the smallest failing one until it has tried every other non-empty sub-list. 1-minimality is the relaxation that the paper adopts, and ddmin reaches it with tests. The test function itself can be any program; ddmin does not need it to be monotone or consistent, and its guarantee holds for whatever answers the test gives.
The algorithm
DDMIN(c, test)- 1
n <- 2 - 2
while |c| >= 2 do - 3
split c into n contiguous parts d_1 ... d_n whose sizes differ by at most 1 - 4
if test(d_i) = FAIL for some i (trying i = 1 ... n in order) then - 5
c <- d_i; n <- 2 - 6
else if n > 2 and test(c - d_i) = FAIL for some i (in order) then - 7
c <- c - d_i; n <- max(n - 1, 2) - 8
else if n < |c| then - 9
n <- min(2n, |c|) - 10
else - 11
stop - 12
return c
Lines L4 and L5 are "reduce to subset", lines L6 and L7 "reduce to complement", lines L8 and L9 "increase granularity", and line L11 "done", as in Fig. 5 of the paper. After a complement reduction, parts keep the same granularity: the old parts other than are the natural parts of the new list. At the two complements are the two subsets, so this implementation does not test them twice.
UNRESOLVED needs no special case. It is any outcome that is not FAIL: a sub-list that does not compile or that the parser rejects is treated like one that passes, and so is never kept.
Example
The elements are . The test fails when the list contains both 0 and 1, or contains 6.
| test | list | outcome | step |
|---|---|---|---|
| 1 | 0 1 2 3 | FAIL | reduce to subset, |
| 2 | 0 1 | FAIL | reduce to subset, |
| 3 | 0 | PASS | |
| 4 | 1 | PASS | equals the size of , done |
ddmin returns after 4 tests. It is 1-minimal: and both pass. But fails and is smaller, so is not a minimum. ddmin never sees 6 again after the first test, because the first half already failed. A brute-force search over all 256 sub-lists confirms that is the only failing list of size 1.
A second example uses the toy IR. A program of one block has 12 instructions and ends in a division by zero:
a = 5; b = 3; x = a * 7; c = a - b; y = x + b; d = c * 2
e = b + 1; z = y - 1; f = d - 4; w = z / e; g = e / f; h = g + a
The test builds a block from a sub-list, returns UNRESOLVED if an instruction reads a name that no earlier instruction defines, and FAIL if the run traps. ddmin needs 124 tests, most of them UNRESOLVED, and returns the 7 instructions that define and . Here the result is also a minimum: the brute-force search over all 4096 sub-lists finds no failing list of fewer than 7 instructions.
Correctness
The proof file has the details.
- The invariant. At the start of each iteration, and . Line L5 keeps a failing part; line L7 keeps a failing complement of parts, each non-empty, so ; line L9 caps at .
- Termination. Each iteration either makes shorter, or keeps and makes larger, or stops. , so the loop ends.
- 1-minimality. If the loop ends with , removing the element gives the empty list, which passes. If it ends at line L11, then , so each part is one element. If , every complement was tested and did not fail. If , the two complements are the two parts, which were tested and did not fail.
What is not claimed. The result is not a minimum, and different 1-minimal results can differ in size. The result depends on the order of the elements and on the order of the tests. With a test that is not consistent, for example a flaky one, 1-minimality holds only for the answers that the test happened to give.
Proof: ddmin returns a 1-minimal failing input after O(N^2) testsfull
Setting. is a list of elements and is any function from sub-lists of to with and . Nothing else is assumed: the test need not be monotone. A sub-list keeps the original order; for a part of a list , is without the elements of . A failing list is 1-minimal when for every element of . SPLIT, for , returns contiguous parts whose sizes differ by at most 1, so each has at least element and their concatenation is .
Lemma 1: the loop invariant
Claim. Each time the test of line L2 is evaluated, is a sub-list of , , and .
Proof. At the start, fails and . Assume the claim at the top of an iteration with ; then , so SPLIT is defined and gives non-empty parts.
- Line L5: becomes a part with , and .
- Line L7: becomes with . It is the union of the other parts, each non-empty, so . The new is ; if it is at most , and otherwise it is .
- Line L9: is unchanged and the new is , which lies between and because .
A sub-list of a sub-list is a sub-list, so the claim holds again.
Theorem 1: termination and 1-minimality
Claim. DDMIN stops and returns a sub-list of that fails and is 1-minimal.
Proof. Termination. Consider the pair in lexicographic order. Lines L5 and L7 make smaller: a part with non-empty parts misses at least one element, and so does because is not empty. Line L9 keeps and makes larger. Both and are bounded, so only finitely many iterations happen before line L11 or the test of line L2 ends the loop.
The result fails by Lemma 1, and it is a sub-list of .
1-minimality. There are two ways to leave the loop.
- . is impossible, because fails and the empty list passes. So , and removing its element gives the empty list, which passes.
- Line L11, in an iteration where no subset and no complement failed and . With Lemma 1, , so every part is one element, and the parts are all the elements of . If , line L6 tested for every element and none failed. If , then , and and ; both parts were tested on line L4 and did not fail.
In both cases no removal of one element gives FAIL.
Theorem 2: the number of tests
Claim. DDMIN calls at most times for , and never for . So the number of tests is .
Proof. An iteration at granularity tests at most parts on line L4 and, only when , at most complements on line L6. So it makes at most tests.
Group the iterations into phases: a phase is a maximal run of consecutive iterations with the same . Inside a phase, every iteration but the last one ends on line L9, and the last one ends on line L5, L7 or L11. Let the phase have size and let its iterations have the granularities .
- For , , and the iteration at did not stop, so . All with satisfy except possibly the last of them, so is a doubling sequence with and . Its sum is . The tests of these iterations number at most , and none happen when .
- The last iteration has by Lemma 1, so it makes at most tests.
A phase of size makes at most tests if , and at most tests if . In the second case forces , where ; for , the bound . So every phase of size makes at most tests.
Each phase but the last ends on line L5 or L7, which makes strictly shorter, as in Theorem 1. The phases therefore have pairwise different sizes, all between 2 and , and the total is at most
For the loop does not run.
Remarks. The bound is not tight. Zeller and Hildebrandt state tests in the worst case for their version (Proposition 12), from a scenario in which every test is UNRESOLVED until and then only the last complement fails, one element at a time. The tests of the page check the bound on every test function for and on random ones up to .
In the best case of the paper, one element makes every list that contains it fail and every other list pass. Then at one of the two halves fails, so every iteration replaces by a part of size or less with at most 2 tests. After iterations one element is left, and the total is at most ; the paper states (Proposition 13).
A 1-minimal result need not be a minimum
Let the elements be and let a list fail exactly when it contains both 0 and 1, or contains 6. DDMIN tests (FAIL), then (FAIL), then and (both PASS), and returns , which is 1-minimal by Theorem 1. The list fails and has one element, so the result is not a minimum. More generally, deciding that a failing list of size is a minimum, with the test as a black box, needs the outcome of every non-empty list of size less than : an adversary that answers PASS can make any untested one of them FAIL. When that is tests, so no algorithm can match the bound of Theorem 2 for minimum results.
Complexity
Each iteration at granularity makes at most tests, subsets and complements. The proof file shows the worst-case total of tests for this implementation: in a phase at a fixed size , the doublings of cost at most tests in total, the last iteration costs at most , and the size goes down by at least 1 from one phase to the next. The paper states tests in the worst case for its version (Proposition 12), which also tests the complements at . Each test gets a list of at most elements, so building the lists costs per test, and the total is .
In the best case, when a single element causes the failure and every list that contains it fails, every iteration halves the list, as in binary search, and ddmin needs at most tests (Proposition 13 of the paper). The space is .
The tests on this page run ddmin on every test function for , and on random monotone and non-monotone test functions for , and compare the result with a brute-force minimum.
Properties
- Black box. ddmin needs only the test function, not the program or the structure of the input.
- 1-minimal, not minimum. The output is a local minimum for the removal of one element.
- Monotonicity not needed. The guarantee holds for any test function; with a monotone test (every superset of a failing list fails), the subset steps behave like binary search.
- Deterministic. The same input and test give the same tests in the same order.
- Order-sensitive. Contiguous parts help when related elements are close together, as lines of one function are.
Variants and improvements
- Isolation (dd). The second algorithm of the paper starts from a passing and a failing input and narrows the difference between them until a 1-minimal difference remains, with the same worst case.
- Caching. A table of the test outcomes avoids testing the same list twice, which happens after complement reductions.
- Hierarchical delta debugging. Misherghi and Su apply ddmin to the levels of a syntax tree, from the root down, so most tried inputs are syntactically valid and fewer tests are UNRESOLVED. See abstract syntax tree.
- Domain-specific reducers. C-Reduce of Regehr and others combines many program transformations, in a fixed-point loop, and produces much smaller C programs than a line-based delta tool for compiler bugs, such as those found by equivalence modulo inputs.
- Trimming in fuzzers. A coverage-guided fuzzer shrinks each new input with a cheap relative of ddmin that keeps the coverage the same, instead of the failure.
- Shrinking in property-based testing. Property-based testing libraries shrink a failing random value with type-specific moves, a greedy local search that, like ddmin, stops at a local minimum.
When to use it
Use ddmin to reduce a crashing input, a failing test program for a compiler, or a sequence of user actions, before a person debugs it. It suits cases where a test is cheap compared with human time, and where the input has no structure that a better reducer knows. For structured inputs such as programs, start with a structure-aware reducer, and use plain ddmin on lines or tokens as a final pass.
Pitfalls
- Expecting a minimum. The output is 1-minimal only. Run ddmin again on the result, or try other element orders, to get smaller results.
- Changing failures. A test that only checks "the program crashed" can lead to a different bug. Make the test check the exact error message or location.
- Flaky tests. A test that sometimes fails and sometimes passes breaks the guarantee and can give a result that does not fail on the next run.
- Wrong granularity of elements. Characters give many UNRESOLVED tests on structured input. Lines or tokens are usually better.
- The empty list. ddmin assumes that the empty list passes and never tests it. If the empty list fails, the result of size 1 is not 1-minimal.
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/delta-debugging/. The authors are listed in prov/25NQX4.jsonl.
"""The minimizing delta debugging algorithm ddmin of Zeller and Hildebrandt.
test(c) gets a list, a sub-list of the input in the original order, and
returns FAIL, PASS or UNRESOLVED. ddmin(items, test) assumes that
test(items) is FAIL and that the test of the empty list is PASS. It returns
a failing sub-list that is 1-minimal: removing any one element of it does
not give FAIL. It is not always a failing sub-list of the smallest size.
When the granularity is 2, the two complements are the two subsets, so they
are not tested again. Apart from that, the order of the tests is the one of
the paper: all subsets, then all complements.
"""
FAIL = "FAIL"
PASS = "PASS"
UNRESOLVED = "UNRESOLVED"
def split(c, n):
"""Split the list c into n contiguous parts whose sizes differ by at most 1."""
parts = []
start = 0
for i in range(n):
end = start + (len(c) - start) // (n - i)
parts.append(c[start:end])
start = end
return parts
def ddmin(items, test):
"""Return (result, number of calls of test)."""
calls = 0
def run(c):
nonlocal calls
calls += 1
out = test(c)
if out not in (FAIL, PASS, UNRESOLVED):
raise ValueError("test must return FAIL, PASS or UNRESOLVED")
return out
c = list(items)
n = 2 # @line L1
while len(c) >= 2: # @line L2
parts = split(c, n) # @line L3
reduced = False
for d in parts: # @line L4
if run(d) == FAIL:
c, n = d, 2 # @line L5
reduced = True
break
if not reduced and n > 2: # @line L6
for i in range(n):
comp = [x for j, p in enumerate(parts) if j != i for x in p]
if run(comp) == FAIL:
c, n = comp, max(n - 1, 2) # @line L7
reduced = True
break
if reduced:
continue
if n < len(c): # @line L8
n = min(2 * n, len(c)) # @line L9
else: # @line L10
break # @line L11
return c, calls # @line L12
def is_one_minimal(c, test):
"""True when no sub-list of c with one element removed fails."""
return all(test(c[:i] + c[i + 1:]) != FAIL for i in range(len(c)))
# ------------------------------------------------- a use on toy IR programs
def program_test(instrs, ret, oracle):
"""A test on lists of toy IR instructions of one block that ends with
"ret ret". A list that reads a name before it is defined is UNRESOLVED,
as an invalid program is in a real reducer. oracle(outcome) says whether
the outcome of toyir.run shows the failure."""
import toyir
def test(sub):
defined = set()
for ins in sub:
if any(a not in defined for a in toyir.uses(ins)):
return UNRESOLVED
defined.add(toyir.defs(ins))
if isinstance(ret, str) and ret not in defined:
return UNRESOLVED
prog = toyir.Program([], {"entry": toyir.Block(list(sub), ("ret", ret))})
return FAIL if oracle(toyir.run(prog, [])) else PASS
return test
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.
A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:
("const", x, k) x = k
("copy", x, a) x = y
("op", x, op, a, b) x = a op b
("phi", x, {pred: a}) x = phi [pred: a, ...]
("addr", p, x) p = &x
("load", x, p) x = *p
("store", p, a) *p = a
("alloc", p) p = alloc
("call", x, f, args) x = call f(a, b) (args is a list)
Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""
from dataclasses import dataclass, field
import re
OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")
@dataclass
class Block:
instrs: list = field(default_factory=list)
term: tuple = ("ret", 0)
@dataclass
class Program:
params: list
blocks: dict
@property
def entry(self):
return next(iter(self.blocks))
class UndefinedName(Exception):
"""A name was read before any definition."""
# ---------------------------------------------------------------- text form
_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"
def _operand(tok):
if re.fullmatch(_INT, tok):
return int(tok)
if re.fullmatch(_NAME, tok):
return tok
raise ValueError("bad operand: %r" % tok)
def _name(tok):
if not re.fullmatch(_NAME, tok):
raise ValueError("bad name: %r" % tok)
return tok
def _parse_instr(line):
toks = line.split()
if toks[0] == "jump" and len(toks) == 2:
return "term", ("jump", _name(toks[1]))
if toks[0] == "br" and len(toks) == 4:
return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
if toks[0] == "ret" and len(toks) == 2:
return "term", ("ret", _operand(toks[1]))
lhs, eq, rhs = line.partition("=")
if not eq:
raise ValueError("bad line: %r" % line)
lhs, rhs = lhs.strip(), rhs.strip()
if lhs.startswith("*"):
return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
x = _name(lhs)
if rhs.startswith("phi"):
body = rhs[3:].strip()
if not (body.startswith("[") and body.endswith("]")):
raise ValueError("bad phi: %r" % line)
args = {}
inner = body[1:-1].strip()
if inner:
for part in inner.split(","):
pred, colon, a = part.partition(":")
if not colon:
raise ValueError("bad phi: %r" % line)
args[_name(pred.strip())] = _operand(a.strip())
return "instr", ("phi", x, args)
if rhs.startswith("call "):
m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
if not m:
raise ValueError("bad call: %r" % line)
inner = m.group(2).strip()
args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
return "instr", ("call", x, m.group(1), args)
if rhs == "alloc":
return "instr", ("alloc", x)
if rhs.startswith("&"):
return "instr", ("addr", x, _name(rhs[1:].strip()))
if rhs.startswith("*"):
return "instr", ("load", x, _name(rhs[1:].strip()))
parts = rhs.split()
if len(parts) == 1:
a = _operand(parts[0])
if isinstance(a, int):
return "instr", ("const", x, a)
return "instr", ("copy", x, a)
if len(parts) == 3 and parts[1] in OPS:
return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
raise ValueError("bad instruction: %r" % line)
def parse(text):
"""Parse the text form. A line "# params: a, b" gives the parameters;
without it, the parameters are the names that are read and never
defined, in the order of their first use."""
params = None
blocks = {}
cur = None
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if line.startswith("#"):
m = re.fullmatch(r"#\s*params:(.*)", line)
if m:
inner = m.group(1).strip()
params = [_name(p.strip()) for p in inner.split(",")] if inner else []
continue
if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
label = line[:-1]
if label in blocks:
raise ValueError("duplicate label: %r" % label)
cur = label
blocks[label] = Block([], None)
continue
if cur is None:
raise ValueError("instruction outside a block: %r" % line)
if blocks[cur].term is not None:
raise ValueError("instruction after the terminator in %r" % cur)
kind, item = _parse_instr(line)
if kind == "term":
blocks[cur].term = item
else:
blocks[cur].instrs.append(item)
for label, b in blocks.items():
if b.term is None:
raise ValueError("block %r has no terminator" % label)
if not blocks:
raise ValueError("empty program")
prog = Program([], blocks)
if params is None:
params = _free_names(prog)
prog.params = params
return prog
def _free_names(prog):
defined = set()
for b in prog.blocks.values():
for ins in b.instrs:
d = defs(ins)
if d is not None:
defined.add(d)
out = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins):
if a not in defined and a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in defined and a not in out:
out.append(a)
return out
def _show_instr(ins):
k = ins[0]
if k == "const":
return "%s = %d" % (ins[1], ins[2])
if k == "copy":
return "%s = %s" % (ins[1], ins[2])
if k == "op":
return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
if k == "phi":
return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
if k == "addr":
return "%s = &%s" % (ins[1], ins[2])
if k == "load":
return "%s = *%s" % (ins[1], ins[2])
if k == "store":
return "*%s = %s" % (ins[1], ins[2])
if k == "alloc":
return "%s = alloc" % ins[1]
if k == "call":
return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
raise ValueError("bad instruction: %r" % (ins,))
def _show_term(t):
if t[0] == "jump":
return "jump %s" % t[1]
if t[0] == "br":
return "br %s %s %s" % (t[1], t[2], t[3])
if t[0] == "ret":
return "ret %s" % (t[1],)
raise ValueError("bad terminator: %r" % (t,))
def show(prog):
lines = ["# params: " + ", ".join(prog.params)]
for label, b in prog.blocks.items():
lines.append(label + ":")
for ins in b.instrs:
lines.append(" " + _show_instr(ins))
lines.append(" " + _show_term(b.term))
return "\n".join(lines) + "\n"
# ---------------------------------------------------------- names and graph
def defs(ins):
"""The name an instruction defines, or None for a store."""
return None if ins[0] == "store" else ins[1]
def uses(ins):
"""The names an instruction reads, in order (phi operands included)."""
k = ins[0]
if k == "const" or k == "alloc" or k == "addr":
ops = []
elif k == "copy":
ops = [ins[2]]
elif k == "op":
ops = [ins[3], ins[4]]
elif k == "phi":
ops = list(ins[2].values())
elif k == "load":
ops = [ins[2]]
elif k == "store":
ops = [ins[1], ins[2]]
elif k == "call":
ops = list(ins[3])
else:
raise ValueError("bad instruction: %r" % (ins,))
return [a for a in ops if isinstance(a, str)]
def term_uses(t):
if t[0] == "br" or t[0] == "ret":
return [t[1]] if isinstance(t[1], str) else []
return []
def succs(prog, label):
"""Successor labels of a block, without repeats, in terminator order."""
t = prog.blocks[label].term
if t[0] == "jump":
return [t[1]]
if t[0] == "br":
return [t[2]] if t[2] == t[3] else [t[2], t[3]]
return []
def edges(prog):
return [(a, b) for a in prog.blocks for b in succs(prog, a)]
def preds(prog):
"""Dict from label to the list of predecessor labels, in block order."""
out = {label: [] for label in prog.blocks}
for a, b in edges(prog):
out[b].append(a)
return out
def is_acyclic(prog):
color = {label: 0 for label in prog.blocks}
for root in prog.blocks:
if color[root]:
continue
color[root] = 1
stack = [(root, iter(succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
color[v] = 2
stack.pop()
elif color[w] == 1:
return False
elif color[w] == 0:
color[w] = 1
stack.append((w, iter(succs(prog, w))))
return True
def paths(prog):
"""Every path from the entry to a ret block, as a list of labels.
The CFG must be acyclic."""
if not is_acyclic(prog):
raise ValueError("paths needs an acyclic CFG")
out = []
def walk(path):
last = path[-1]
s = succs(prog, last)
if not s:
out.append(list(path))
for w in s:
path.append(w)
walk(path)
path.pop()
walk([prog.entry])
return out
# ------------------------------------------------------------------ running
class _Trap(Exception):
pass
class _Fuel(Exception):
pass
def _binop(op, a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("arithmetic on a pointer")
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" or op == "%":
if b == 0:
raise _Trap()
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
if op == "&":
return a & b
if op == "|":
return a | b
if op == "^":
return a ^ b
if op == "<<" or op == ">>":
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
if op == "<":
return int(a < b)
if op == "<=":
return int(a <= b)
if op == "==":
return int(a == b)
if op == "!=":
return int(a != b)
raise ValueError("bad operator: %r" % op)
class _Frame:
"""One activation: its program, its variables and its position."""
def __init__(self, prog, args, fid):
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
self.prog = prog
self.env = dict(zip(prog.params, args))
self.fid = fid
self.label = prog.entry
self.prev = None
self.pc = 0 # 0 means: the phis of the block have not run yet
self.dest = None # the name that receives the value of a pending call
def val(self, a):
if isinstance(a, int):
return a
if a not in self.env:
raise UndefinedName(a)
return self.env[a]
def _run(prog, args, fuel, funcs):
"""Run with an explicit stack of frames, so deep recursion in the toy
program does not use Python recursion."""
heap = {}
envs = {}
stack = []
fr = _Frame(prog, args, 0)
envs[0] = fr.env
nframes = 1
def tick():
nonlocal fuel
if fuel <= 0:
raise _Fuel()
fuel -= 1
while True:
block = fr.prog.blocks[fr.label]
instrs = block.instrs
if fr.pc == 0:
# Phis at the top of the block read all operands first, then assign.
incoming = []
i = 0
while i < len(instrs) and instrs[i][0] == "phi":
tick()
ins = instrs[i]
if fr.prev not in ins[2]:
raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
incoming.append((ins[1], fr.val(ins[2][fr.prev])))
i += 1
for x, v in incoming:
fr.env[x] = v
fr.pc = i if i > 0 else -1
start = fr.pc if fr.pc > 0 else 0
called = False
env = fr.env
for j in range(start, len(instrs)):
ins = instrs[j]
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = fr.val(ins[2])
elif k == "op":
env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
elif k == "addr":
env[ins[1]] = ("var", fr.fid, ins[2])
elif k == "alloc":
cell = ("heap", len(heap))
heap[cell] = None
env[ins[1]] = cell
elif k == "load":
p = fr.val(ins[2])
if p[0] == "var":
if p[2] not in envs[p[1]]:
raise UndefinedName(p[2])
env[ins[1]] = envs[p[1]][p[2]]
else:
if heap[p] is None:
raise UndefinedName(repr(p))
env[ins[1]] = heap[p]
elif k == "store":
p = fr.val(ins[1])
if p[0] == "var":
envs[p[1]][p[2]] = fr.val(ins[2])
else:
heap[p] = fr.val(ins[2])
elif k == "call":
if funcs is None or ins[2] not in funcs:
raise ValueError("unknown function %r" % ins[2])
vals = [fr.val(a) for a in ins[3]]
fr.pc = j + 1
fr.dest = ins[1]
stack.append(fr)
fr = _Frame(funcs[ins[2]], vals, nframes)
envs[nframes] = fr.env
nframes += 1
called = True
break
elif k == "phi":
raise ValueError("phi after a non-phi instruction")
else:
raise ValueError("bad instruction: %r" % (ins,))
if called:
continue
tick()
t = block.term
if t[0] == "jump" or t[0] == "br":
if t[0] == "jump":
nxt = t[1]
else:
nxt = t[2] if fr.val(t[1]) != 0 else t[3]
fr.prev, fr.label, fr.pc = fr.label, nxt, 0
continue
v = fr.val(t[1])
if not stack:
return ("ret", v), fuel
fr = stack.pop()
fr.env[fr.dest] = v
def run(prog, args, fuel=10000, funcs=None):
"""Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
Each instruction, phi and terminator uses one unit of fuel. funcs is an
optional dict from function name to Program, used by call; deep
recursion in the toy program is fine, because the frames are kept on an
explicit stack."""
try:
out, _ = _run(prog, list(args), fuel, funcs)
return out
except _Trap:
return ("trap",)
except _Fuel:
return ("fuel",)
# ------------------------------------------------------------ random programs
_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")
def random_program(rng, nvars, nblocks, acyclic):
"""A random program with blocks B0 .. B(nblocks-1) and variables
x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
others, so no run reads an undefined name. A division by a variable can
trap. Every block is reachable from
B0 and B0 has no predecessor. With acyclic=False, each loop has its own
counter c that is set to 0 in B0 and never reset, and the back edge is
taken only while c < m and c < 4, where m is the first parameter. So the
whole run takes each back edge at most 3 times."""
nvars = max(nvars, 1)
nblocks = max(nblocks, 1)
xs = ["x%d" % i for i in range(nvars)]
params = xs[:2]
labels = ["B%d" % i for i in range(nblocks)]
def operand():
if rng.random() < 0.25:
return rng.randint(-3, 9)
return rng.choice(xs)
def instr():
x = rng.choice(xs)
r = rng.random()
if r < 0.15:
return ("const", x, rng.randint(-5, 9))
if r < 0.25:
return ("copy", x, rng.choice(xs))
if r < 0.3:
# A division by a variable may trap.
return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
if r < 0.4:
op = rng.choice(_CONST_RIGHT)
k = rng.randint(1, 5)
return ("op", x, op, rng.choice(xs), k)
return ("op", x, rng.choice(_SAFE), operand(), operand())
blocks = {}
has_pred = [False] * nblocks
has_pred[0] = True
for i in range(nblocks):
instrs = [instr() for _ in range(rng.randint(1, 3))]
if i == 0:
instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
if i == nblocks - 1:
term = ("ret", rng.choice(xs))
elif has_pred[i + 1] and rng.random() < 0.2:
term = ("ret", rng.choice(xs))
else:
first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
if rng.random() < 0.5:
term = ("jump", labels[first])
has_pred[first] = True
else:
second = rng.randrange(i + 1, nblocks)
if second == first:
term = ("jump", labels[first])
else:
term = ("br", rng.choice(xs), labels[first], labels[second])
has_pred[second] = True
has_pred[first] = True
blocks[labels[i]] = Block(instrs, term)
if not acyclic and nblocks > 1:
nloops = rng.randint(1, max(1, nblocks // 3))
for k in range(nloops):
latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
if not latches:
break
t = rng.choice(latches)
h = labels[rng.randint(1, labels.index(t))]
c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
out = blocks[t].term[1]
blocks[t].instrs += [
("op", c, "+", c, 1),
("op", w1, "<", c, m),
("op", w2, "<", c, 4),
("op", w, "&", w1, w2),
]
blocks[t].term = ("br", w, h, out)
return Program(list(params), blocks)
test_delta_debugging.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delta-debugging/. The authors are listed in prov/25NQX4.jsonl.
import itertools
import math
import random
import toyir
from delta_debugging import FAIL, PASS, UNRESOLVED, ddmin, is_one_minimal, program_test, split
def bound(n):
"""The worst-case number of tests proved in the proof file."""
return (3 * n - 2) * (n - 1) if n >= 2 else 0
def brute_force_minimum(items, test):
"""A failing sub-list of the smallest size, the first one in the order of
itertools.combinations."""
for k in range(len(items) + 1):
for comb in itertools.combinations(items, k):
if test(list(comb)) == FAIL:
return list(comb)
return None
def check(items, test):
"""Run ddmin and check what the page promises. Returns (result, minimum)."""
res, calls = ddmin(items, test)
assert test(res) == FAIL
it = iter(items)
assert all(x in it for x in res) # a sub-list, in the original order
assert is_one_minimal(res, test)
assert calls <= bound(len(items))
m = brute_force_minimum(items, test)
assert len(m) <= len(res)
return res, m
def test_split():
for size in range(1, 30):
c = list(range(size))
for n in range(1, size + 1):
parts = split(c, n)
assert len(parts) == n
assert [x for p in parts for x in p] == c
sizes = [len(p) for p in parts]
assert max(sizes) - min(sizes) <= 1 and min(sizes) >= 1
def test_one_minimal_is_not_minimum():
def t(s):
return FAIL if {0, 1} <= set(s) or 6 in s else PASS
log = []
def logged(s):
out = t(s)
log.append((list(s), out))
return out
res, calls = ddmin(list(range(8)), logged)
assert res == [0, 1] and calls == 4
assert log == [([0, 1, 2, 3], FAIL), ([0, 1], FAIL), ([0], PASS), ([1], PASS)]
assert is_one_minimal(res, t)
assert brute_force_minimum(list(range(8)), t) == [6]
def test_single_culprit_set_is_found_exactly():
# With a monotone test that fails exactly on the supersets of K, the only
# 1-minimal failing set is K, so ddmin must return it.
rng = random.Random(1)
for n in range(1, 13):
for _ in range(20):
k = rng.randint(1, n)
K = set(rng.sample(range(n), k))
res, m = check(list(range(n)), lambda s: FAIL if K <= set(s) else PASS)
assert set(res) == K and len(m) == k
def test_against_brute_force_up_to_12():
rng = random.Random(2)
larger = 0
for n in range(1, 13):
for _ in range(12):
# Monotone: fails when the input contains one of a few culprit sets.
culprits = [set(rng.sample(range(n), rng.randint(1, min(n, 4)))) for _ in range(rng.randint(1, 3))]
culprits.append(set(range(n)))
def mono(s, culprits=culprits):
return FAIL if any(c <= set(s) for c in culprits) else PASS
res, m = check(list(range(n)), mono)
larger += len(res) > len(m)
# Not monotone, with UNRESOLVED outcomes: a random fixed table.
table = {}
def chaos(s, table=table, n=n):
key = frozenset(s)
if not key:
return PASS
if len(key) == n:
return FAIL
if key not in table:
r = rng.random()
table[key] = FAIL if r < 0.15 else (UNRESOLVED if r < 0.5 else PASS)
return table[key]
check(list(range(n)), chaos)
assert larger > 0
def test_every_test_function_up_to_4():
for n in range(1, 5):
full = frozenset(range(n))
middle = [frozenset(c) for k in range(1, n) for c in itertools.combinations(range(n), k)]
for mask in range(1 << len(middle)):
fails = {middle[i] for i in range(len(middle)) if mask >> i & 1} | {full}
res, calls = ddmin(list(range(n)), lambda s: FAIL if frozenset(s) in fails else PASS)
assert frozenset(res) in fails
assert all(frozenset(res) - {x} not in fails for x in res)
assert calls <= bound(n)
def test_best_case_is_logarithmic():
for k in range(1, 11):
n = 1 << k
for culprit in (0, n // 3, n - 1):
res, calls = ddmin(list(range(n)), lambda s: FAIL if culprit in s else PASS)
assert res == [culprit]
assert calls <= 2 * math.log2(n)
def test_all_unresolved_keeps_the_input():
for n in range(1, 13):
res, calls = ddmin(list(range(n)), lambda s: FAIL if len(s) == n else UNRESOLVED)
assert res == list(range(n))
assert calls <= bound(n)
PROGRAM = """
entry:
a = 5
b = 3
x = a * 7
c = a - b
y = x + b
d = c * 2
e = b + 1
z = y - 1
f = d - 4
w = z / e
g = e / f
h = g + a
ret 0
"""
def test_toy_ir_program():
prog = toyir.parse(PROGRAM)
assert toyir.run(prog, []) == ("trap",)
instrs = prog.blocks["entry"].instrs
test = program_test(instrs, 0, lambda out: out == ("trap",))
outcomes = []
def logged(s):
out = test(s)
outcomes.append(out)
return out
res, calls = ddmin(instrs, logged)
assert [toyir.defs(i) for i in res] == ["a", "b", "c", "d", "e", "f", "g"]
assert calls == 124
assert outcomes.count(UNRESOLVED) > outcomes.count(PASS)
small = toyir.Program([], {"entry": toyir.Block(res, ("ret", 0))})
assert toyir.run(small, []) == ("trap",)
assert len(brute_force_minimum(instrs, test)) == len(res)
assert calls <= bound(len(instrs))
def test_bad_outcome_is_rejected():
try:
ddmin([1, 2, 3], lambda s: True)
except ValueError:
return
raise AssertionError("expected ValueError")
History
Zeller introduced delta debugging in 1999 to find the change, among the many changes between a working and a failing version of a program, that causes a failure. Hildebrandt and Zeller applied the idea to inputs at ISSTA 2000, with the minimizing algorithm ddmin, and the journal version of 2002 gives the definitions, the proof of 1-minimality and the bounds on the number of tests. Its case studies minimized a C program that crashed GCC and HTML input that crashed the Mozilla web browser. Misherghi and Su adapted it to syntax trees in 2006, and test-case reducers for compilers, such as C-Reduce, grew from it.
References
- Andreas Zeller and Ralf Hildebrandt, Simplifying and isolating failure-inducing input, IEEE Transactions on Software Engineering 28(2), 2002, pp. 183 to 200; Definition 10 (n-minimal test case) on p. 186, Fig. 5 (ddmin) on p. 187, Propositions 11 to 13 on p. 188
- Ralf Hildebrandt and Andreas Zeller, Simplifying failure-inducing input, Proceedings of ISSTA 2000, pp. 135 to 145, the first form of the minimizing algorithm
- Andreas Zeller, Yesterday, my program worked. Today, it does not. Why?, Proceedings of ESEC/FSE 1999, pp. 253 to 267, delta debugging of the changes between two versions of a program
- Ghassan Misherghi and Zhendong Su, HDD, hierarchical delta debugging, Proceedings of ICSE 2006, pp. 142 to 151, ddmin applied level by level to a syntax tree
- John Regehr, Yang Chen, Pascal Cuoq, Eric Eide, Chucky Ellison and Xuejun Yang, Test-case reduction for C compiler bugs, Proceedings of PLDI 2012, pp. 335 to 346, the comparison of C-Reduce with delta debugging
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 25NQX4 Edit this page History Report an error Markdown