NAME

App::Test::Generator::CoverageGuidedFuzzer - AFL-style coverage-guided fuzzing for App::Test::Generator

VERSION

Version 0.49

SYNOPSIS

"Fuzzing" means calling a function many times with machine-made input, to find input that makes it fail. The "corpus" is the list of inputs that the fuzzer decided to keep.

Pattern 1: fuzz a function that takes one number, then show the failures. The input key of the schema describes the one argument.

use App::Test::Generator::CoverageGuidedFuzzer;

my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
    schema     => { input => { type => 'integer', min => 0, max => 100 } },
    target_sub => \&My::Module::validate,
    iterations => 200,
    seed       => 42,
);

my $report = $fuzzer->run();
printf "%d failures in %d calls\n",
    $report->{bugs_found}, $report->{total_iterations};
print "  failed with: $_->{error}" for @{ $report->{bugs} };

Pattern 2: keep what was learned between two runs of your program.

my $file = 't/corpus/validate.json';
$fuzzer->load_corpus($file) if -e $file;   # start from the last run
$fuzzer->run();

# Optional: trim corpus to minimum branch-covering subset before saving
my $stats = $fuzzer->minimize_corpus();
printf "corpus %d -> %d entries\n", $stats->{before}, $stats->{after};

$fuzzer->save_corpus($file);

Pattern 3: fuzz a method of an object. The object is passed first and the generated input second.

my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
    schema     => { input => { type => 'string', max => 20 } },
    target_sub => \&My::Parser::parse,
    instance   => My::Parser->new(),
);
$fuzzer->run();

Pattern 4: test with your own special values, here with non-ASCII text. About 4 in 10 new inputs are taken from edge_case_array.

use utf8;
my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
    schema => {
        input => {
            type            => 'string',
            edge_case_array => [ '', 'na\x{EF}ve', "\x{1F600}" ],
        },
    },
    target_sub => sub { length $_[0] },
    timeout    => 2,
);
$fuzzer->run();

DESCRIPTION

Implements coverage-guided fuzzing on top of App::Test::Generator's existing schema-driven input generation. Instead of purely random generation it:

1. Generates or mutates a structured input
2. Runs the target sub under Devel::Cover to capture branch hits
3. Keeps inputs that discover new branches in a corpus
4. Preferentially mutates corpus entries in future iterations

This is the Perl equivalent of what AFL/libFuzzer do at the byte level, but operating on typed, schema-validated Perl data structures.

METHODS

new

Construct a new coverage-guided fuzzer.

my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
    schema     => $yaml_schema,
    target_sub => \&My::Module::validate,
    iterations => 200,
    seed       => 42,
    instance   => $obj,   # optional pre-built object for method calls
);

Arguments

  • schema

    A hashref representing the parsed YAML schema for the target function. Required. Only two keys are used: input, which describes the single argument that will be generated, and input_style. Inside input the keys type, min, max, matches, items, properties, optional and edge_case_array are used. For a string, min and max are lengths counted in characters.

  • target_sub

    A CODE reference to the function under test. Required.

  • iterations

    Number of fuzzing iterations to run. Optional - defaults to 100.

  • seed

    Random seed for reproducible runs. Optional - defaults to time().

  • instance

    An optional pre-built object to use as the invocant when calling the target sub as a method.

  • timeout

    Seconds to allow each target_sub call before it is aborted via alarm() and recorded as a bug. Optional - defaults to 5. Set to 0 to disable the timeout (e.g. for target subs that legitimately block).

Returns

A blessed hashref. Croaks if schema or target_sub is missing.

Side effects

Calls Perl's srand with the seed. This restarts the random number sequence for the whole program, not only for this object. Prints one warning per program if Devel::Cover cannot be loaded.

API SPECIFICATION

input

{
    schema     => { type => HASHREF },
    target_sub => { type => CODEREF },
    iterations => { type => SCALAR,  optional => 1 },
    seed       => { type => SCALAR,  optional => 1 },
    instance   => { type => OBJECT,  optional => 1 },
    timeout    => { type => SCALAR,  optional => 1 },
}

output

{
    type => OBJECT,
    isa  => 'App::Test::Generator::CoverageGuidedFuzzer',
}

EXAMPLE

my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
    schema     => { input => { type => 'string' } },
    target_sub => sub { length($_[0]) },
    iterations => 50,
    seed       => 1234,
);

MESSAGES

schema required

schema was not supplied or was falsy (e.g. undef or 0).

target_sub required

target_sub was not supplied or was falsy.

The mathematical description is in "FORMAL SPECIFICATION".

run

Run the coverage-guided fuzzing loop and return a summary report.

my $report = $fuzzer->run();
printf "Branches covered: %d\n", $report->{branches_covered};
printf "Bugs found:       %d\n", $report->{bugs_found};

Arguments

None beyond $self.

Returns

A hashref with keys total_iterations, interesting_inputs, corpus_size, branches_covered, bugs_found, and bugs.

The numbers are totals for the life of the object. If you call run twice, total_iterations is twice the iterations value.

Side effects

Calls target_sub once per iteration. Adds five new random inputs to the corpus at the start of every call. Uses alarm and the ALRM signal for the timeout, so any alarm that your own program had set is cancelled.

Notes

A call that takes longer than timeout seconds is stopped and recorded as a bug with the error target_sub timed out after Ns.

The same failing input can be recorded more than once. The bugs list is not checked for duplicates.

A target_sub call that dies is only recorded in bugs when the input that triggered it is valid per schema. A die triggered by an input the schema itself marks invalid (e.g. out of the declared min/max range) is expected behaviour, not a bug, and is silently discarded.

API SPECIFICATION

input

{
    self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' },
}

output

{
    type => HASHREF,
    keys => {
        total_iterations   => { type => SCALAR  },
        interesting_inputs => { type => SCALAR  },
        corpus_size        => { type => SCALAR  },
        branches_covered   => { type => SCALAR  },
        bugs_found         => { type => SCALAR  },
        bugs               => { type => ARRAYREF },
    },
}

EXAMPLE

my $report = $fuzzer->run();
printf "Iterations:  %d\n", $report->{total_iterations};
printf "Corpus size: %d\n", $report->{corpus_size};
printf "Bugs found:  %d\n", $report->{bugs_found};
for my $bug (@{ $report->{bugs} }) {
    printf "  input=%s  error=%s\n", $bug->{input}, $bug->{error};
}

The mathematical description is in "FORMAL SPECIFICATION".

PSEUDOCODE

seed corpus with SEED_CORPUS_SIZE random inputs
for i in 1..iterations:
    if corpus non-empty and rand < CORPUS_MUTATE_RATIO:
        input = mutate(random corpus entry)
    else:
        input = generate_random()
    run target_sub(input), record coverage and bugs
return report hashref

corpus

Return the accumulated corpus as an arrayref of hashrefs with keys input and coverage.

my $corpus = $fuzzer->corpus();

The arrayref is the fuzzer's own list, not a copy. Do not change it. The list is empty until run or load_corpus has been called.

API SPECIFICATION

input

{ self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } }

output

{ type => ARRAYREF }

EXAMPLE

my $corpus = $fuzzer->corpus();
printf "%d entries in corpus\n", scalar @{$corpus};
# Each entry: { input => ..., coverage => { 'file:line:branch' => 1, ... } }

bugs

Return bugs found as an arrayref of hashrefs with keys input and error.

my $bugs = $fuzzer->bugs();

The arrayref is the fuzzer's own list, not a copy. Do not change it. error is always text. input can be undef.

API SPECIFICATION

input

{ self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } }

output

{ type => ARRAYREF }

EXAMPLE

my $bugs = $fuzzer->bugs();
for my $b (@{$bugs}) {
    printf "Bug: input=%s  error=%s\n", $b->{input}, $b->{error};
}

save_corpus

Serialise the corpus to a JSON file for replay or extension on future runs.

$fuzzer->save_corpus('t/corpus/validate.json');

Arguments

  • $path

    Path to write the JSON corpus file. Required.

Returns

Nothing useful. Croaks if the file cannot be written or no JSON module is available.

Side effects

Writes a JSON file to $path. An existing file is replaced. The file holds the seed, the corpus inputs and the bugs. Branch data is not saved. The file is UTF-8.

API SPECIFICATION

input

{
    self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' },
    path => { type => SCALAR },
}

output

{ type => UNDEF }

EXAMPLE

$fuzzer->run();
$fuzzer->minimize_corpus();
$fuzzer->save_corpus('t/corpus/my_func.json');

MESSAGES

path required

No path argument was supplied.

Cannot write corpus to $path: $!

The file could not be opened for writing (permissions, missing directory, etc.).

No JSON module available; install JSON or JSON::MaybeXS

Neither JSON::MaybeXS nor JSON is installed.

encountered object ... or encountered CODE ...

Raised by the JSON module. A corpus input or bug input holds an object or a code reference, which JSON cannot store. This check happens after the file has been opened, so the file is left empty.

The mathematical description is in "FORMAL SPECIFICATION".

load_corpus

Load a previously saved corpus JSON file, pre-seeding the fuzzer so it continues from where it left off.

$fuzzer->load_corpus('t/corpus/validate.json');

Arguments

  • $path

    Path to the JSON corpus file to load. Required.

Returns

Nothing useful. Croaks if the file cannot be read or no JSON module is available.

Side effects

Appends loaded entries to $self->{corpus}. Entries already in the corpus are kept, so loading the same file twice gives every entry twice. minimize_corpus removes such copies.

API SPECIFICATION

input

{
    self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' },
    path => { type => SCALAR },
}

output

{ type => UNDEF }

EXAMPLE

my $fuzzer2 = App::Test::Generator::CoverageGuidedFuzzer->new(
    schema     => $schema,
    target_sub => \&My::Module::validate,
);
$fuzzer2->load_corpus('t/corpus/my_func.json');
my $report = $fuzzer2->run();

MESSAGES

path required

No path argument was supplied.

Cannot read corpus from $path: $!

The file could not be opened for reading (missing file, permissions, etc.).

malformed JSON string ... and similar

Raised by the JSON module. The file is not valid JSON.

Notes

load_corpus does not restore bugs from the JSON file. The bugs array in the JSON is written by save_corpus but ignored on load. The loaded fuzzer starts with an empty bugs list. Seed values are also not restored; the constructor-supplied seed is retained.

The mathematical description is in "FORMAL SPECIFICATION".

minimize_corpus

Reduce the corpus to the smallest subset that still covers every branch hit by the full corpus, using a greedy set-cover algorithm.

Entries without branch data (loaded from a previous run, or kept by random sampling when Devel::Cover is unavailable) are deduplicated by input fingerprint and retained in full. They cannot be evaluated for coverage contribution without re-running them. Bug-triggering inputs are always kept regardless of coverage contribution.

my $stats = $fuzzer->minimize_corpus();
printf "Corpus: %d -> %d entries (%d branches covered)\n",
    $stats->{before}, $stats->{after}, $stats->{branches};

Returns

A hashref with keys before (corpus size before), after (corpus size after), and branches (total unique branches still covered).

API SPECIFICATION

input

{ self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } }

output

{
    type       => HASHREF,
    constraint => sub { defined $_[0]{before} && defined $_[0]{after} && defined $_[0]{branches} },
}

EXAMPLE

$fuzzer->run();
my $stats = $fuzzer->minimize_corpus();
printf "Corpus: %d -> %d entries (%d branches)\n",
    $stats->{before}, $stats->{after}, $stats->{branches};
$fuzzer->save_corpus('t/corpus/my_func.json');

The mathematical description is in "FORMAL SPECIFICATION".

PSEUDOCODE

partition corpus into with-coverage and without-coverage entries
greedy set-cover: repeatedly pick entry covering most uncovered branches
deduplicate without-coverage entries by JSON fingerprint
unconditionally add all bug inputs not already in minimized set
replace self.corpus with minimized list
return { before, after, branches }

COMMON PITFALLS

Forgetting that load_corpus does not restore bugs

The JSON written by save_corpus contains a bugs array, but load_corpus reads only the corpus key. A freshly loaded fuzzer always starts with an empty bugs list. If you need to carry bugs across sessions, persist them separately.

Assuming coverage guidance is always active

If Devel::Cover is not installed, the fuzzer falls back to random-only mode and emits a warning. Corpus entries in this mode have coverage => {} and are kept using the RANDOM_KEEP_RATIO (20%) heuristic rather than branch novelty. Install Devel::Cover (or cpanm --with-recommends App::Test::Generator) for full coverage-guided behaviour.

Using refaddr on corpus() after minimize_corpus

minimize_corpus replaces $self->{corpus} with a new arrayref. Any caller that holds a reference to the old arrayref (e.g. from a prior corpus() call) will see a stale snapshot. Always call corpus() after minimize_corpus if you need the current list.

Setting timeout => 0 on blocking targets

Setting timeout to 0 disables the per-call alarm(). This is correct for targets that legitimately block (e.g. sleeping, waiting on I/O), but means a hung target_sub will hang the whole fuzzing run indefinitely. Use a process-level timeout (e.g. Sys::AlarmCall) if you need a safety net for blocking code.

A timeout below one second turns the timeout off

timeout is passed to Perl's alarm, which works in whole seconds. A value such as 0.5 becomes 0, and 0 means "no timeout".

A schema without an input key

The generator reads only $schema->{input}. If that key is missing, every generated input is undef, and target_sub is called with undef each time. No error is raised.

schema => { name => { type => 'string' } }             # wrong
schema => { input => { type => 'string' } }            # right
target_sub always gets exactly one generated argument

input describes one value. If input is a list of named parameters without a type key of its own, one random string is generated, not a hash. To pass a hashref, describe it:

input => {
    type       => 'hashref',
    properties => { age => { type => 'integer', min => 0 } },
}
How undef and other false values are handled
  • schema and target_sub must be true values, not only defined. An empty hashref {} is true and is accepted.

  • target_sub is not checked to be a code reference. A wrong value is accepted by new, and then every call in run fails.

  • iterations, seed and timeout use their default only when they are missing or undef. The value 0 is kept: iterations => 0 runs no calls, seed => 0 is a valid fixed seed, timeout => 0 means no time limit.

  • An undef input can be generated (see above) and can be saved. It is written to the JSON file as null and comes back as undef.

  • An undef value for a required field makes an input invalid. An undef value for a field marked optional is valid.

  • save_corpus(undef) and load_corpus(undef) croak with path required.

Nested data is copied only one level deep

When a hashref or arrayref input is mutated, only the top level is copied. Deeper hashes and arrays are shared between the old and the new corpus entry. If your target_sub changes its argument in place, it can silently change other corpus entries too. Write target_sub so that it only reads its argument, or make it take a deep copy first.

load_corpus adds entries. It does not merge or replace.

Loaded entries are put after the entries already in the corpus. Nothing is compared and nothing is overwritten. Load a file twice and you have two copies of each entry.

Every run adds five more random seed inputs

The corpus grows by at least five entries per run call. Call minimize_corpus before save_corpus if the object is used for many runs.

Some warnings are recorded as bugs

A warning from target_sub that contains the word uninitialized, undefined, blessed or invalid is recorded as a bug, even though the call did not die. Warnings are caught during the call, so they are not printed. Other warnings are thrown away.

branches_covered is 0

This means that no branch data was received. Branch data is only available when the whole program is started under Devel::Cover, for example with perl -MDevel::Cover script.pl. Having the module installed is not enough. Without it the run is random-only. Do not read a value of 0 as "the target has no branches".

Branch counts include more than your target

Devel::Cover counts every branch in the program. A few of the branches counted in branches_covered belong to the fuzzer and to other modules, not to target_sub. Use the number to compare two runs, not as an exact size.

ENCODING

  • Inputs given to target_sub

    All strings are Perl character strings. Strings made by the fuzzer use ASCII letters, digits, space, tab, newline and the NUL character. Mutation can also produce any character from 0 to 255. The fuzzer never invents characters above 255 (for example emojis) by itself.

  • edge_case_array and matches in the schema

    Full Unicode is supported, including non-ASCII letters and emojis. Give them as decoded character strings (use utf8 in your source, or a YAML file loaded with YAML::XS). Such values are passed to target_sub unchanged and are mutated one character at a time.

  • String min and max

    Lengths are counted in characters, not bytes.

  • save_corpus and load_corpus

    Full Unicode is supported. The file is written as UTF-8 JSON, and every string, including non-ASCII letters and emojis, is loaded back exactly as it was saved. A corpus file written by version 0.47 or earlier, which could hold Latin-1 bytes, is still read correctly.

  • The path argument

    Passed to the operating system unchanged. ASCII paths always work.

  • Error text in bugs

    The error value is whatever target_sub died with, turned into a string. It is not encoded or decoded.

LIMITATIONS

Single-threaded

All fuzzing iterations run sequentially in the calling process. For large iteration counts, wall-clock time scales linearly. Parallelism requires splitting the iteration budget across multiple fuzzer instances and merging their corpora.

Coverage granularity is branch-level

Branch coverage is the finest granularity Devel::Cover exposes via its public API. Path coverage (distinct sequences of branches) is not tracked. Two inputs that cover the same branches but exercise different call orders are treated as equivalent.

No inter-run learning without save/load

The corpus is entirely in memory. To carry learning across separate invocations, call save_corpus at the end and load_corpus at the start of each subsequent run.

SEE ALSO

Devel::Cover
App::Test::Generator
bin/extract-schemas (the --minimize-corpus flag)

AUTHOR

Nigel Horne, <njh at nigelhorne.com>

Portions of this module's initial design and documentation were created with the assistance of AI.

FORMAL SPECIFICATION

This section describes each method in Z notation. It is for readers who want an exact, mathematical statement. You do not need it to use the module.

How to read it: a name ending in ? is an input, a name ending in ! is an output, and a name ending in ' is the value after the call. Δ before the state name means "this call may change the object". Ξ means "this call does not change the object". # is the number of items in a list or set.

Entry == [ input : VALUE ; coverage : ℙ BRANCH ]
Bug   == [ input : VALUE ; error : STRING ]

┌─ Fuzzer ──────────────────────────────────────────
│ schema : VALUE
│ target_sub : VALUE
│ instance : VALUE
│ iterations, seed, timeout : NUMBER
│ corpus : seq Entry
│ bugs : seq Bug
│ covered : ℙ BRANCH
│ total, interesting : ℕ
├───────────────────────────────────────────────────
│ schema and target_sub are true values
│ ⋃ { e : ran corpus • e.coverage } ⊆ covered
│ interesting ≤ #corpus
└───────────────────────────────────────────────────

new

┌─ New ─────────────────────────────────────────────
│ Fuzzer′
│ schema?, target_sub?, instance? : VALUE
│ iterations?, seed?, timeout? : NUMBER ∪ { undef }
│ result! : Fuzzer
├───────────────────────────────────────────────────
│ pre   schema? is true ∧ target_sub? is true
│ post  schema′ = schema? ∧ target_sub′ = target_sub?
│       instance′ = instance?
│       iterations′ = if iterations? = undef then 100 else iterations?
│       seed′ = if seed? = undef then time() else seed?
│       timeout′ = if timeout? = undef then 5 else timeout?
│       corpus′ = ⟨⟩ ∧ bugs′ = ⟨⟩ ∧ covered′ = ∅
│       total′ = 0 ∧ interesting′ = 0
│       srand(seed′) has been called
│       result! = θ Fuzzer′
└───────────────────────────────────────────────────

schema? is false      ⇒ croak 'schema required'
target_sub? is false  ⇒ croak 'target_sub required'

run

┌─ Run ─────────────────────────────────────────────
│ Δ Fuzzer
│ result! : REPORT
├───────────────────────────────────────────────────
│ post  total′ = total + iterations
│       corpus prefix corpus′
│       #corpus′ ≥ #corpus + 5
│       #corpus′ − #corpus − 5 = interesting′ − interesting
│       bugs prefix bugs′
│       covered ⊆ covered′
│       ∀ b : ran bugs′ ∖ ran bugs •
│           b.input is valid for schema.input
│       result!.total_iterations = total′
│       result!.interesting_inputs = interesting′
│       result!.corpus_size = #corpus′
│       result!.branches_covered = #covered′
│       result!.bugs_found = #bugs′
│       result!.bugs = bugs′
│       schema′ = schema ∧ seed′ = seed
└───────────────────────────────────────────────────

corpus

┌─ Corpus ──────────────────────────────────────────
│ Ξ Fuzzer
│ result! : seq Entry
├───────────────────────────────────────────────────
│ post  result! = corpus      (the same list, not a copy)
└───────────────────────────────────────────────────

bugs

┌─ Bugs ────────────────────────────────────────────
│ Ξ Fuzzer
│ result! : seq Bug
├───────────────────────────────────────────────────
│ post  result! = bugs        (the same list, not a copy)
└───────────────────────────────────────────────────

save_corpus

┌─ SaveCorpus ──────────────────────────────────────
│ Ξ Fuzzer
│ path? : PATH
├───────────────────────────────────────────────────
│ pre   path? ≠ undef ∧ path? can be written
│       every input in corpus and bugs is plain data
│ post  content′(path?) = JSON of
│           [ seed   ↦ seed,
│             corpus ↦ ⟨ e : corpus • [ input ↦ e.input ] ⟩,
│             bugs   ↦ bugs ]
└───────────────────────────────────────────────────

path? = undef             ⇒ croak 'path required'
path? cannot be written   ⇒ croak 'Cannot write corpus to ...'

load_corpus

┌─ LoadCorpus ──────────────────────────────────────
│ Δ Fuzzer
│ path? : PATH
│ loaded : seq VALUE
├───────────────────────────────────────────────────
│ pre   path? ≠ undef ∧ path? holds valid JSON
│ post  loaded = the inputs under the 'corpus' key of the file
│       corpus′ = corpus ⁀ ⟨ v : loaded • [ input ↦ v, coverage ↦ ∅ ] ⟩
│       bugs′ = bugs ∧ seed′ = seed ∧ covered′ = covered
│       total′ = total ∧ interesting′ = interesting
└───────────────────────────────────────────────────

path? = undef          ⇒ croak 'path required'
path? cannot be read   ⇒ croak 'Cannot read corpus from ...'

minimize_corpus

fp(v) == the canonical JSON text of v   (the "fingerprint")

┌─ MinimizeCorpus ──────────────────────────────────
│ Δ Fuzzer
│ result! : [ before, after, branches : ℕ ]
│ with, without : seq Entry
├───────────────────────────────────────────────────
│ post  with = corpus filtered to entries with coverage ≠ ∅
│       without = corpus filtered to entries with coverage = ∅
│       result!.before = #corpus
│       result!.after = #corpus′
│       result!.branches = # ⋃ { e : ran with • e.coverage }
│       ⋃ { e : ran corpus′ • e.coverage }
│           = ⋃ { e : ran corpus • e.coverage }
│       ∀ e : ran without • ∃ k : ran corpus′ •
│           fp(k.input) = fp(e.input)
│       ∀ b : ran bugs • ∃ k : ran corpus′ •
│           fp(k.input) = fp(b.input)
│       corpus′ is a new list (old references are stale)
│       bugs′ = bugs ∧ covered′ = covered
│       total′ = total ∧ interesting′ = interesting
└───────────────────────────────────────────────────

Calling it a second time changes nothing:
result!.before = result!.after on the second call.

STATE DIAGRAM

The state of a fuzzer is the state of its corpus.

    new(schema or target_sub missing or false)
  +--------------------------------------------------+
  |  action: croak, no object                        |
  v                                                  |
+-------------+                                      |
|  NO OBJECT  |--------------------------------------+
+-------------+
      |
      | new(schema, target_sub, ...)
      | action: store settings, call srand(seed),
      |         try to load Devel::Cover
      v
+---------------------+  minimize_corpus()
|                     |-----------------------------------------+
|        EMPTY        |  action: returns 0 / 0 / 0              |
|  (corpus is empty)  |<----------------------------------------+
|                     |
|                     |  save_corpus(path)
|                     |-----------------------------------------+
|                     |  action: write a file with no entries   |
|                     |<----------------------------------------+
+---------------------+
      |
      | run()
      |   action: add 5 random inputs, call target_sub
      |           'iterations' times, keep interesting inputs,
      |           record bugs, return the report
      | load_corpus(path)
      |   action: add the inputs from the file (no branch data)
      v
+---------------------+  run()
|                     |-----------------------------------------+
|       GROWING       |  action: as above; corpus gets bigger,  |
|  (corpus may hold   |  totals are added to the old totals     |
|   copies and spare  |<----------------------------------------+
|   entries)          |
|                     |  load_corpus(path)
|                     |-----------------------------------------+
|                     |  action: add the file's inputs again    |
|                     |<----------------------------------------+
|                     |
|                     |  save_corpus(path)
|                     |-----------------------------------------+
|                     |  action: write the file, no change      |
|                     |<----------------------------------------+
+---------------------+
      |            ^
      |            | run()  or  load_corpus(path)
      |            | action: as above
      | minimize_corpus()
      | action: replace the corpus with a new, smaller list;
      |         keep every covered branch and every bug input;
      |         return before / after / branches
      v            |
+---------------------+  minimize_corpus()
|                     |-----------------------------------------+
|      MINIMIZED      |  action: nothing changes (before=after) |
|  (no spare entries) |<----------------------------------------+
|                     |
|                     |  save_corpus(path)
|                     |-----------------------------------------+
|                     |  action: write the smallest file        |
|                     |<----------------------------------------+
+---------------------+

In every state: corpus() and bugs() return the current lists and
change nothing.  A call that croaks (bad path, unwritable file,
unreadable file) changes nothing.

The usual order of calls in one program run is:

new -> load_corpus -> run -> minimize_corpus -> save_corpus

LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

Usage is subject to GPL2 licence terms. If you use it, please let me know.