Algorithmcore
Seed corpus minimization
Also called corpus distillation, seed selection.
Chooses a small set of seed inputs that keeps the coverage of a large corpus, by a greedy or weighted set cover.
- Time
- O(k z) worst
- Space
- O(z) extra
- Where
- d = the size of the largest coverage set; k = the number of chosen seeds; z = the sum of the sizes of the coverage sets
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alexandre Rebert, Sang Kil Cha, Thanassis Avgerinos, Jonathan Foote, David Warren, Gustavo Grieco, David Brumley, 2014
Seed corpus minimization picks, from a large set of inputs, a small subset that exercises every coverage element (every edge, or every edge with its hit-count bucket) that the whole set exercises. A fuzzer starts from the subset: fewer seeds means each one gets more of the time, and dropping seeds that add nothing new costs no coverage. The problem is weighted set cover, with one set per seed and a weight such as the file size or the run time, so it is NP-hard. The standard method is the greedy set cover rule: take the seed with the most new elements per unit of weight, and repeat until everything is covered. Its weight is at most times the optimum, a theorem of Chvátal (1979). That keeping coverage keeps the seeds' value for fuzzing is a heuristic, which Rebert et al. (2014) tested by measurement.
In plain words
You have thousands of sample files, and many of them make the program do the same things. Run each file once and write down which parts of the program it used. Then build a short list. First take the file that uses the most parts for its size. Next take the file that adds the most parts that are not yet on the list, again for its size. Go on until every part that any file used is on the list. The short list makes the program do everything the big pile did. It may not be the shortest such list, because finding that one is too hard, but it is close enough in practice and it takes little time.
The problem
The input is a corpus of seeds. Seed has a coverage set , measured by one run of the instrumented target, and a weight . Let . A cover is a set of seeds with . The output is a cover with a small total weight . With all weights 1, the goal is the fewest seeds.
The algorithm
MINIMIZE-CORPUS(S_1 .. S_n, w_1 .. w_n)- 1
U <- S_1 ∪ ... ∪ S_n - 2
C <- empty list; R <- U (R is the set of uncovered elements) - 3
while R is not empty do - 4
for each seed i: gain(i) <- |S_i ∩ R| - 5
b <- the seed with gain(b) > 0 and the largest gain(b) / w_b, ties to the smallest index - 6
append b to C - 7
R <- R minus S_b - 8
return C
Line L5 compares the ratios and by cross-multiplying, , so no rounding enters and ties are decided by the index. A seed is chosen at most once, because after line L7 its gain is 0. Line L1 defines the goal as the coverage of the corpus, not of the program: the minimized set cannot cover more than the corpus does.
The coverage sets come from one run of each seed on the target with an edge coverage bitmap. AFL's afl-cmin uses the pairs (edge, hit-count bucket) as elements, so a seed that runs a loop 8 times and one that runs it twice can both be kept.
Example
Six seeds A to F cover the edges 1 to 8. The sizes are the weights.
| seed | edges | size |
|---|---|---|
| A | 1, 2, 3, 4 | 40 |
| B | 5, 6, 7, 8 | 40 |
| C | 1, 2, 3, 5, 6, 7 | 100 |
| D | 4 | 5 |
| E | 8 | 5 |
| F | 2, 3 | 10 |
Unweighted. Step 1 takes C, which has 6 new edges. The uncovered edges are 4 and 8. Step 2 takes A (gain 1, tied with B, D and E, and A has the smallest index), and step 3 takes B for edge 8. The greedy cover has 3 seeds, while A and B alone cover everything. Here greedy is a factor 1.5 from the optimum, within its bound .
Weighted by size. The ratio is new edges per byte.
| step | A | B | C | D | E | F | chosen | uncovered after |
|---|---|---|---|---|---|---|---|---|
| 1 | 4/40 | 4/40 | 6/100 | 1/5 | 1/5 | 2/10 | D | 1, 2, 3, 5, 6, 7, 8 |
| 2 | 3/40 | 4/40 | 6/100 | 1/5 | 2/10 | E | 1, 2, 3, 5, 6, 7 | |
| 3 | 3/40 | 3/40 | 6/100 | 2/10 | F | 1, 5, 6, 7 | ||
| 4 | 1/40 | 3/40 | 4/100 | B | 1 | |||
| 5 | 1/40 | 1/100 | A | none |
The greedy cover is D, E, F, B, A with 100 bytes. The lightest cover is A and B with 80 bytes, found by trying all 64 subsets. The cheap small seeds look good per byte at first, and the rule pays for them later. The test file checks both runs and the optimum.
Correctness
Statement. MINIMIZE-CORPUS returns a cover of after at most steps, and its weight is at most , where , , and is the least weight of a cover.
Key invariant. At the test of line L3, . While is not empty, some seed covers an element of (every element of is in some ), so line L5 finds a seed with positive gain, and falls by at least 1. When is empty, is a cover.
The bound charges each element the price of the step that covers it, so the total price is the weight of , and then shows that the elements of any one set are charged at most in total. The proof file has both parts. The bound is tight up to lower order terms in the worst case, and Feige (1998) showed that no polynomial algorithm does better than unless every problem in NP has an algorithm of time .
Proof: Correctness and the H(d) bound of greedy corpus minimizationfull
Let the seeds have coverage sets and weights , let and . We prove that MINIMIZE-CORPUS (lines L1 to L8) returns a cover of after at most steps, and that its weight is at most , where and is the least weight of a cover. This is the bound of Chvátal (1979); the proof is the usual pricing argument.
Claim 1 (invariant). At each test of line L3, , and no seed occurs twice in .
Proof. After line L2, is empty and . Line L7 removes from at the same time as line L6 adds to , so the equation is kept. A seed already in has by the equation, so its gain is 0, and line L5 only picks seeds with positive gain.
Claim 2 (termination and cover). Each step is well defined and makes smaller, so the loop ends after at most steps with a cover.
Proof. If , take . Since , some contains , so and line L5 has a candidate. The chosen has , so line L7 makes smaller by at least 1. Hence there are at most steps, and by Claim 1 at most . When the loop ends, , and by Claim 1 the sets of cover .
Prices. Number the steps . At step , let be the uncovered set before the step, the chosen seed and . Give each element the price . Each element of is covered at exactly one step, so it gets exactly one price, and
Claim 3 (one set). For every seed , .
Proof. Let and list the elements of in the order in which the algorithm covers them, , with elements covered at the same step in any order. Take , covered at step . Before step , the elements are all uncovered, so . Line L5 chose with the largest ratio of gain to weight, so
(The rule for ties does not matter here: the chosen ratio is at least the ratio of , which is what the first inequality says.) Summing over gives .
Claim 4 (the bound). .
Proof. Let be a cover of weight . Every element of is in at least one set of , and prices are not negative, so
by Claim 3 and because is increasing and .
With all weights equal to 1, the claim is the bound of Johnson (1974) for the number of seeds. Claims 2 and 4 are the statement of the Correctness section.
Complexity
Each step of the loop computes the gains in line L4 by intersecting every set with , in time with hash sets, where . There are steps, so the time is , and . A lazy version keeps the seeds in a priority queue by their last known ratio and recomputes the ratio of the top seed only; since gains only fall, a recomputed top that stays on top is the true maximum, and the time becomes in practice. The space is for the sets. Measuring the coverage costs one run of the target per seed, which in practice dominates.
Properties
- Deterministic. The tie rule fixes the output for given sets and weights.
- Coverage-preserving. The result covers exactly the elements of the corpus.
- Approximate. The weight is within of the optimum; for edge sets of real seeds, is the largest number of edges one seed exercises.
- Not minimal in general. A chosen seed can become redundant after later choices. In the unweighted example, C is redundant once A and B are chosen.
Variants and improvements
- AFL's culling. For each element, find the lightest seed that has it (AFL scores a seed by its run time times its size), walk the elements in order, and when an element is not yet covered, take its winner and mark all its elements; the chosen seeds are favored, and the others are skipped with high probability. In the example the walk takes A for edge 1 and B for edge 5, which is the optimum. It has no ratio bound: with six seeds of weight 2 that cover one element each and one seed of weight 3 that covers all six, it pays 12 where greedy pays 3. The test file has this case.
- afl-cmin. The corpus tool of AFL keeps, for each (edge, hit-count bucket) pair, the smallest file that has it, in the same way.
- Reverse delete. After the greedy cover, drop each chosen seed whose elements are all covered by the others. In the unweighted example this drops C and leaves the optimum.
- Exact methods. For a few hundred seeds, an integer program or a branch and bound search finds the optimum; the greedy cover gives a starting bound.
- Weights. Rebert et al. compared set-cover selections that ignore weights, that weight by file size and that weight by run time, against keeping the whole corpus and other methods, and measured the bugs found.
- Trimming. A different step, often done next, shortens each kept seed while it keeps its coverage, in the spirit of delta debugging.
When to use it
Use it before a long campaign when the seeds come from a large crawl or from an earlier campaign, and when a fuzzer restarts with its own queue. It is also the way to merge the queues of parallel fuzzers. Do not use it to throw away seeds whose value is not in coverage: a seed with an unusual structure can be worth keeping even if its edges are covered, so many people keep a few extra seeds by hand.
Pitfalls
- Comparing rounded ratios. Writing line L5 as
gain(i) / w_i > bestin floating point can break ties by rounding and make the output depend on the platform. The right line compares in integers. - Picking the largest set instead of the largest gain. Writing line L4 as
gain(i) <- |S_i|makes the loop pick the same seed again, or seeds that add nothing. The right line intersects with the uncovered set . - Edges without hit counts. Using bare edges as elements merges seeds that differ only in loop counts, which AFL treats as different behavior. The right element is the pair of the edge and its count bucket, when the fuzzer uses buckets.
- Flaky coverage. A target with randomness or timing gives different sets on different runs; minimizing on one run can drop a seed that sometimes reaches a rare edge. Run each seed more than once, or treat unstable edges apart.
- Reading the bound as a promise about bugs. The bound is about weight. Whether a smaller corpus finds more bugs is a measured question.
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/seed-corpus-minimization/. The authors are listed in prov/SRAZAY.jsonl.
"""Seed corpus minimization by greedy weighted set cover.
Each seed of a corpus has a coverage set (for example the edges, or the
edge and hit-count pairs, that it exercises) and a positive weight (for
example its size or its run time). The goal is a subset of the seeds that
covers every element that the whole corpus covers, with a small total
weight. This is weighted set cover, which is NP-hard; the greedy rule
picks, again and again, the seed with the most new elements per unit of
weight. Its total weight is at most H(d) times the optimum, where d is the
size of the largest coverage set and H(d) = 1 + 1/2 + ... + 1/d (Chvatal
1979). Using coverage as the thing to keep is itself a heuristic: two
seeds with the same coverage can still behave differently under mutation.
"""
from typing import Hashable, Sequence
def minimize_corpus(coverage: Sequence[frozenset[Hashable]], weights: Sequence[int] | None = None) -> list[int]:
"""Return the indices of the seeds chosen by the greedy rule, in order.
The ratio gain / weight is compared by cross-multiplication, so there is
no rounding; ties go to the smallest index. With weights None, every
weight is 1.
Precondition: weights, if given, are positive integers, one per seed.
Cost: O(k z) for k chosen seeds and z the sum of the coverage sizes.
"""
n = len(coverage)
w = [1] * n if weights is None else list(weights)
if len(w) != n or any(x <= 0 for x in w):
raise ValueError("need one positive weight per seed")
universe: set[Hashable] = set()
for c in coverage:
universe |= c # @line L1
chosen: list[int] = [] # @line L2
uncovered = set(universe)
while uncovered: # @line L3
best = -1
best_gain = 0
for i in range(n):
gain = len(coverage[i] & uncovered) # @line L4
if gain > 0 and (best < 0 or gain * w[best] > best_gain * w[i]):
best, best_gain = i, gain # @line L5
chosen.append(best) # @line L6
uncovered -= coverage[best] # @line L7
return chosen # @line L8
def cull_best_per_element(coverage: Sequence[frozenset[Hashable]], weights: Sequence[int]) -> list[int]:
"""Return the seeds chosen by the culling rule of AFL, in order.
For each element, its winner is the lightest seed that covers it (ties to
the smallest index). Walk the elements in sorted order; when an element
is not yet covered, take its winner and mark everything the winner
covers. The result covers the union, but it has no approximation bound.
Precondition: the elements can be sorted, one positive weight per seed.
Cost: O(z + u log u) for z the sum of the coverage sizes and u the number
of elements.
"""
if len(weights) != len(coverage) or any(x <= 0 for x in weights):
raise ValueError("need one positive weight per seed")
winner: dict[Hashable, int] = {}
for i, c in enumerate(coverage):
for e in c:
j = winner.get(e)
if j is None or weights[i] < weights[j]:
winner[e] = i
done: set[Hashable] = set()
chosen: list[int] = []
for e in sorted(winner):
if e not in done:
j = winner[e]
chosen.append(j)
done |= coverage[j]
return chosen
def covered(coverage: Sequence[frozenset[Hashable]], chosen: Sequence[int]) -> set[Hashable]:
"""Return the union of the coverage sets of the chosen seeds. Cost: O(z)."""
out: set[Hashable] = set()
for i in chosen:
out |= coverage[i]
return out
def total_weight(weights: Sequence[int], chosen: Sequence[int]) -> int:
"""Return the sum of the weights of the chosen seeds. Cost: O(k)."""
return sum(weights[i] for i in chosen)
test_seed_corpus_minimization.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/seed-corpus-minimization/. The authors are listed in prov/SRAZAY.jsonl.
import itertools
import random
from fractions import Fraction
import pytest
from seed_corpus_minimization import covered, cull_best_per_element, minimize_corpus, total_weight
# The corpus of the page: seeds A to F, their edges and their sizes in bytes.
COV = [
frozenset({1, 2, 3, 4}), # A
frozenset({5, 6, 7, 8}), # B
frozenset({1, 2, 3, 5, 6, 7}), # C
frozenset({4}), # D
frozenset({8}), # E
frozenset({2, 3}), # F
]
SIZE = [40, 40, 100, 5, 5, 10]
A, B, C, D, E, F = range(6)
def brute_force_optimum(coverage, weights):
"""The lightest cover of the union, by trying every subset."""
universe = covered(coverage, range(len(coverage)))
best = None
for r in range(len(coverage) + 1):
for sub in itertools.combinations(range(len(coverage)), r):
if covered(coverage, sub) == universe:
w = total_weight(weights, sub)
if best is None or w < best:
best = w
return best
def harmonic(d):
return sum((Fraction(1, k) for k in range(1, d + 1)), Fraction(0))
def reference_greedy(coverage, weights):
"""A second version of the greedy rule with exact rational ratios."""
left = covered(coverage, range(len(coverage)))
out = []
while left:
ratios = [(Fraction(len(c & left), w), -i) for i, (c, w) in enumerate(zip(coverage, weights))]
r, neg = max(ratios)
out.append(-neg)
left -= coverage[-neg]
return out
def test_page_example_unweighted():
chosen = minimize_corpus(COV)
assert chosen == [C, A, B]
assert brute_force_optimum(COV, [1] * 6) == 2 # A and B
def test_page_example_weighted():
chosen = minimize_corpus(COV, SIZE)
assert chosen == [D, E, F, B, A]
assert total_weight(SIZE, chosen) == 100
assert brute_force_optimum(COV, SIZE) == 80 # A and B again
assert total_weight(SIZE, chosen) <= harmonic(6) * 80
def test_page_example_afl_culling():
chosen = cull_best_per_element(COV, SIZE)
# Winners: 1 -> A, 2 -> F, 3 -> F, 4 -> D, 5 -> B, 6 -> B, 7 -> B, 8 -> E.
# Element 1 takes A, which covers 1 to 4; element 5 takes B, which covers 5 to 8.
assert chosen == [A, B]
assert total_weight(SIZE, chosen) == 80
assert covered(COV, chosen) == set(range(1, 9))
def test_culling_has_no_ratio_bound():
# Six seeds of weight 2 that cover one element each, and one of weight 3
# that covers all six: culling pays 12, greedy and the optimum pay 3.
k = 6
coverage = [frozenset({i}) for i in range(k)] + [frozenset(range(k))]
weights = [2] * k + [3]
assert total_weight(weights, cull_best_per_element(coverage, weights)) == 2 * k
assert minimize_corpus(coverage, weights) == [k]
assert brute_force_optimum(coverage, weights) == 3
def test_edge_cases():
assert minimize_corpus([]) == []
assert minimize_corpus([frozenset(), frozenset()]) == []
assert minimize_corpus([frozenset({1}), frozenset({1})]) == [0]
assert minimize_corpus([frozenset({1}), frozenset({1})], [3, 2]) == [1]
with pytest.raises(ValueError):
minimize_corpus([frozenset({1})], [0])
with pytest.raises(ValueError):
cull_best_per_element([frozenset({1})], [])
assert cull_best_per_element([], []) == []
def test_random_against_brute_force():
rng = random.Random(2024)
for _ in range(700):
n = rng.randint(1, 7)
u = rng.randint(1, 7)
coverage = [frozenset(e for e in range(u) if rng.random() < 0.4) for _ in range(n)]
weights = [rng.randint(1, 6) for _ in range(n)]
universe = covered(coverage, range(n))
g = minimize_corpus(coverage, weights)
assert g == reference_greedy(coverage, weights)
assert covered(coverage, g) == universe
assert len(set(g)) == len(g)
opt = brute_force_optimum(coverage, weights)
d = max((len(c) for c in coverage), default=0)
assert total_weight(weights, g) <= harmonic(d) * opt
a = cull_best_per_element(coverage, weights)
assert covered(coverage, a) == universe
assert total_weight(weights, a) >= opt
def branches(x: bytes) -> frozenset[str]:
"""A toy target with nested branches on bytes; it returns the branches it took."""
took = {"entry"}
if len(x) >= 1 and x[0] == 1:
took.add("x0 is 1")
if len(x) >= 2 and x[1] == 2:
took.add("x1 is 2")
else:
took.add("x1 is not 2")
elif len(x) >= 1:
took.add("x0 is not 1")
if x[0] == 2 and len(x) == 2:
took.add("x0 is 2 and length 2")
else:
took.add("empty")
return frozenset(took)
def test_toy_target_over_all_small_inputs():
corpus = [bytes(t) for n in range(3) for t in itertools.product(range(3), repeat=n)]
coverage = [branches(x) for x in corpus]
sizes = [len(x) + 1 for x in corpus]
full = covered(coverage, range(len(corpus)))
assert len(full) == 7
for weights in (None, sizes):
chosen = minimize_corpus(coverage, weights)
# Run the target again on the kept seeds only.
assert set().union(*(branches(corpus[i]) for i in chosen)) == full
assert len(chosen) == 4
assert brute_force_optimum(coverage, [1] * len(coverage)) == 4
History
Set cover is one of Karp's NP-complete problems (1972). Johnson (1974) and Lovász (1975) analysed the greedy rule for the unweighted case, and Chvátal (1979) proved the bound with weights. Feige (1998) showed that a bound near is the best possible for polynomial algorithms under a standard assumption. In fuzzing, AFL (2013) kept a favored subset of its queue by the culling rule above and shipped afl-cmin for corpora. Rebert et al. (2014) cast seed selection as set cover, compared several selection methods on many programs, and measured that the choice of seeds changes the number of bugs found.
References
- Alexandre Rebert, Sang Kil Cha, Thanassis Avgerinos, Jonathan Foote, David Warren, Gustavo Grieco and David Brumley, Optimizing seed selection for fuzzing, USENIX Security 2014, pp. 861 to 875, seed selection as set cover and the experiments that compare selection methods
- Michal Zalewski, Technical whitepaper for afl-fuzz, section 4, Culling the corpus
- Vašek Chvátal, A greedy heuristic for the set-covering problem, Mathematics of Operations Research 4(3), 1979, pp. 233 to 235, the H(d) bound for weighted greedy set cover
- David S. Johnson, Approximation algorithms for combinatorial problems, Journal of Computer and System Sciences 9(3), 1974, the analysis of the greedy algorithm for unweighted set cover
- Uriel Feige, A threshold of ln n for approximating set cover, Journal of the ACM 45(4), 1998, pp. 634 to 652, the hardness of approximating set cover below ln n
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, Introduction to Algorithms, fourth edition, Section 35.3, The set-covering problem
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 SRAZAY Edit this page History Report an error Markdown