Minimising Test Cases with Delta Debugging
A fuzzer's crash file is mostly noise: hundreds of bytes of random records, of which a handful trigger the bug. Before you debug, report or turn a crash into a regression test, you want the smallest input that still fails the same way. Engines have built-in minimisers (-minimize_crash, afl-tmin), but the general method, usable for any input that some test rejects (a file, a list of HTTP requests, a sequence of system calls, a source file that crashes a compiler), is delta debugging, published by Andreas Zeller and Ralf Hildebrandt in 2002 as the ddmin algorithm.
The algorithm
Treat the failing input as a list of units (bytes, lines, records, requests) and a test that says FAIL (still the same bug), PASS or OTHER (a different failure):
- Split the list into chunks (start with 2).
- Try removing each chunk in turn. If the rest still FAILs, keep it and continue with chunks (at least 2).
- If no chunk can be removed, double for a finer split.
- Stop when equals the number of units and none can be removed: the result is 1-minimal, meaning that removing any single unit makes the failure disappear.
This is the simplified, complement-only form used here; Zeller and Hildebrandt's full ddmin also tests each chunk on its own first ("reduce to subset", then restart with 2 chunks) before trying the complements. It is a binary search for the part that matters, and it needs only the test, no knowledge of the format. Its cost is the number of tests, which is what you watch.
Two details make it reliable in security work:
- Same bug, not any bug. The test must compare the failure signature (sanitizer kind, top frames, or here the crash message), and treat any other failure as PASS. Otherwise the minimiser happily "minimises" into a different, easier bug.
- The units matter. Byte-level ddmin breaks structure: removing 3 bytes out of a 6-byte record shifts every later record and the parser rejects the input as truncated. Choosing structural units (records, tokens, lines, messages) is the difference between a good and a useless result. This idea is called hierarchical or structure-aware delta debugging.
ddmin on a fuzzer's crash
The example builds a 251-byte crash file for the toy TLV1 parser of the fuzzing lessons: the one record that triggers the seeded UTF-16 bug, buried among 40 harmless random records. It minimises the file twice, once with bytes as units and once with records as units, and counts the tests. It runs in your browser:
import random
class Crash(Exception):
pass
def parse(data):
"""The toy TLV1 parser of the fuzzing lessons, with its seeded UTF-16 bug."""
if data[:4] != b"TLV1":
return None
pos = 4
while pos + 2 <= len(data):
typ, ln = data[pos], data[pos + 1]
val = data[pos + 2:pos + 2 + ln]
if len(val) < ln:
return None
if typ == 1 and ln >= 3 and val[0] == 0xFF and val[1] == 0xFE:
i = 2 + 2 * val[2] # BUG: count not checked against ln
if i >= len(val):
raise Crash("utf16-overread")
pos += 2 + ln
return "ok"
def signature(data):
"""The test: 'FAIL' only if it crashes with the SAME bug signature."""
try:
parse(data)
return "PASS"
except Crash as e:
return "FAIL" if str(e) == "utf16-overread" else "OTHER"
def ddmin(units, test):
"""Zeller's delta debugging on a list of units (bytes, records, lines...).
Remove one of n chunks at a time; keep any smaller input that still fails;
when nothing can be removed, split into twice as many chunks."""
n, tests = 2, 0
while len(units) >= 2:
bounds = [len(units) * k // n for k in range(n + 1)]
chunks = [units[bounds[k]:bounds[k + 1]] for k in range(n)]
for k in range(n):
rest = [u for j, c in enumerate(chunks) if j != k for u in c] # drop chunk k
tests += 1
if test(rest) == "FAIL":
units, n = rest, max(n - 1, 2)
break
else:
if n >= len(units):
break # single units, none removable: 1-minimal
n = min(2 * n, len(units))
return units, tests
# A crash as a fuzzer might save it: the bug buried among 40 harmless records.
rng = random.Random(5)
records = [bytes([rng.choice([2, 3, 7]), 4]) + bytes(rng.randrange(256) for _ in range(4)) for _ in range(40)]
records.insert(23, b"\x01\x05\xff\xfe\x09ab") # the record that triggers the bug
crash = b"TLV1" + b"".join(records)
print(f"original: {len(crash)} bytes, test says {signature(crash)}")
# 1. Byte by byte: chunks rarely line up with record boundaries.
units, tests = ddmin(list(crash), lambda u: signature(bytes(u)))
print(f"byte-level ddmin: {len(units):3d} bytes after {tests:3d} tests")
# 2. Structure-aware: the units are the magic and the 41 records.
pos, recs = 4, [crash[:4]]
while pos < len(crash):
recs.append(crash[pos:pos + 2 + crash[pos + 1]])
pos += 2 + crash[pos + 1]
units, tests = ddmin(recs, lambda u: signature(b"".join(u)))
small = b"".join(units)
print(f"record-level ddmin: {len(small):3d} bytes after {tests:3d} tests: {small!r}")original: 251 bytes, test says FAIL
byte-level ddmin: 141 bytes after 596 tests
record-level ddmin: 11 bytes after 33 tests: b'TLV1\x01\x05\xff\xfe\tab'
The byte-level run stops at 141 bytes after 596 tests. That result is 1-minimal for bytes (no single byte can go), yet clearly not small: removing any one byte in the middle of the file misaligns all later records, so the parser sees a truncated record and passes. The record-level run reaches 11 bytes after only 33 tests: the magic and the single record 01 05 ff fe 09 61 62, a name of 5 bytes with the UTF-16 mark and a count of 9 code units. That input is the bug report: 9 units need 18 bytes after the count, the record has 2.
Detection and fixing with a minimal input
A minimal input pays off at every later step:
- Root cause. With 11 bytes, a debugger session is short and every value is meaningful (Root-Cause Analysis with gdb).
- Deduplication. Minimised inputs from the same bucket usually become identical or nearly so, which confirms that they are one bug.
- The fix and its test. The minimal input is the regression test:
assert parse(b"TLV1\x01\x05\xff\xfe\x09ab") is Noneonce the count is checked against the record length. - The report. Vendors act faster on an 11-byte file with a one-line explanation than on a 251-byte blob.
Delta debugging has a second use in security work: minimising the difference between a passing and a failing case, for example between two builds or two configurations, to find the change that introduced a bug. git bisect is the same idea applied to commits.
Other minimisers you will meet
| Tool | Units | Used for |
|---|---|---|
-minimize_crash=1 (libFuzzer), afl-tmin |
bytes, with engine heuristics | crash files |
| C-Reduce, cvise | C/C++ tokens and syntax | compiler crashes and miscompilations |
| Hypothesis shrinking | the generator's choices | property-test failures (Property-Based Testing) |
git bisect |
commits | which change introduced the bug |
Pitfalls
- A test that accepts any crash. Always compare the signature.
- Flaky tests. If the bug depends on timing or uninitialised memory, a unit may look removable once and essential the next time. Run the test twice, or fix the non-determinism first.
- Byte units for structured inputs. Minimise structurally first, then bytes inside the survivors.
- Minimising away context. Some bugs need a preceding message or a state; minimisation keeps it only if the test runs the whole sequence.
Practice
1. Why does removing a single byte almost always make the byte-level result PASS?
Records are framed by length bytes. Removing one byte shifts everything after it, so the next length byte reads garbage and the parser hits the "truncated record" check and returns None, which the test counts as PASS.
2. Change signature to return "FAIL" for any exception. What risk do you take?
If the parser had a second bug (another exception), the minimiser could drift from the UTF-16 bug to that one, and you would debug and fix the wrong thing. With only one bug in this toy you would get the same result, which is exactly why the risk goes unnoticed.
3. Apply ddmin to a list of 12 HTTP requests that crash a toy server only when request 3 precedes request 9. What is the 1-minimal result?
The two requests 3 and 9, in that order: removing either one makes the failure disappear, and every other request can go. ddmin keeps the relative order of the units it keeps.
Test yourself
What does 1-minimal mean for a ddmin result?
- It has one byte
- Removing any single unit makes the failure disappear
- It is the smallest possible input
- It was found in one test
Why did record-level ddmin beat byte-level ddmin here?
- Records are faster to compare
- Removing whole records keeps the framing intact, so the parser still reaches the bug
- Byte-level is broken
- It used a different test
Why must the test compare a crash signature?
- For speed
- So the minimiser does not drift into a different, easier bug
- Sanitizers require it
- To count tests