Programming Search⌘K

Conceptcore

Delta debugging

Also called ddmin, test case minimization, test case reduction, input minimization, scientific debugging.

Delta debugging cuts a failing input into parts and tests smaller inputs until no single part can be removed and the failure stays. It turns the minimization of a test case into a search.

Applies to
core-languages

Idea

A bug report often comes with a large input: a long web page, a source file of a thousand lines, or a long list of user actions. Most of it has nothing to do with the failure. A developer who reads the code cannot tell which part matters. A smaller input that still fails is easier to understand, easier to put in a unit test and points closer to the defect.

Delta debugging finds such an input without any knowledge of the program. It needs only a test function that runs the program on an input and says if the failure occurs. The algorithm ddmin cuts the input into parts and runs the test on smaller inputs. It keeps each smaller input that still fails, and it stops when the removal of any single part makes the failure go away.1

In the case study of Zeller and Hildebrandt, Mozilla crashed when it printed a web page of 896 lines. Delta debugging reduced the page to the single line that caused the crash. Then it reduced that line, character by character, to the 8 characters <SELECT>.1

The examples on this page run ddmin on one line of that page. The test function stands for the browser: it "crashes" when the text has <SELECT and a > after it. Each language prints the same trace, and the result is <SELECT> after 147 tests.

How it works

The scientific method of debugging

A failure is the end of a chain. A programmer makes a mistake, which puts a defect in the code. When the code runs, the defect causes a fault in the program state. The fault spreads until the program shows a failure that a user can see. Debugging goes back along this chain, from the failure to the defect.2

Zeller describes this search as the scientific method:2

  1. Formulate a question about the failure.
  2. Invent a hypothesis that may explain it.
  3. From the hypothesis, derive a prediction.
  4. Test the prediction in an experiment.
  5. Repeat steps 2 to 4 until the hypothesis explains all the observations.

The method asks the developer to write down each hypothesis and each experiment in a log, so that the search does not go in circles.2 Delta debugging automates one kind of experiment. Each hypothesis is "this part of the input is not needed for the failure". Each test run confirms or refutes it.

Changes, tests and outcomes

The paper models the input as a set of changes. The failing input c is the set of all its changes, and the empty set stands for a run that works. A change can be a line, a character, a token or a user action. The choice is the granularity of the search.1

The function test runs the program on a subset of the changes and returns one of three outcomes:1

  • ✘ fail. The failure of the bug report occurs.
  • ✔ pass. The program works.
  • ? unresolved. The test cannot decide. For example, the input is not valid, or the program fails in a different way.

ddmin treats an unresolved outcome as a pass. It keeps only the subsets that fail.

1-minimal, not minimal

The ideal result is the smallest failing subset of c, a global minimum. To find it with a test function alone, the algorithm must test all 2^|c| subsets. That cost is exponential.1

ddmin finds a 1-minimal input instead. An input is 1-minimal if the removal of any single change makes the failure go away. Definition 10 of the paper generalizes this to n-minimal: the removal of any n or fewer changes makes the failure go away.1 A 1-minimal input is a local minimum. A different subset can be smaller.

The ddmin algorithm

ddmin(c) calls ddmin2(c, 2). ddmin2 cuts the input into n parts of about equal size, Δ1 to Δn. The complement ∇i is the input with part Δi removed. Then it applies the first rule that fits:1

reduce to subset         if test(Δi) fails for some i:   ddmin2(Δi, 2)
reduce to complement     if test(∇i) fails for some i:   ddmin2(∇i, max(n − 1, 2))
increase granularity     else if n < |c|:                ddmin2(c, min(|c|, 2n))
done                     otherwise:                      return c

The first rule is a binary search. If the failure is in one half, the other half is discarded. The second rule removes one part at a time. It keeps the granularity, so the next round removes parts of the same size. The third rule makes the parts smaller when no part can go. When each part is a single change and no complement fails, every single change is needed, and the result is 1-minimal. Proposition 11 of the paper proves this.1

The paper opens this section with the advice of Kernighan and Pike: "Proceed by binary search. Throw away half the input and see if the output is still wrong; if not, go back to the previous state and discard the other half of the input."1 ddmin is this advice made precise. It also handles the case where neither half fails alone.

A trace

The input of the examples has 55 characters:

<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>

Neither half fails alone. The first half has no <SELECT, and the second half starts in the middle of it. The complement of the first half is the second half, so it does not fail either. ddmin increases the granularity to 4 parts. The complement of the first quarter, <td align=l, fails, and the input shrinks to 42 characters. Each later step removes one more part. The trace shows the length after each step:

complement 42
complement 28
...
complement 8
55 characters reduced to <SELECT> in 147 tests

No step reduces to a subset in this run, because each half breaks the tag. The last tests remove each of the 8 characters in turn and see the failure go away. These tests prove that the result is 1-minimal.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiom
GoIdiom
RustIdiom
KotlinIdiomThe algorithm uses only strings, lists and a function value, as in Java; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: The Java program, which runs on the same JVM.
SQLDoes not applyA query cannot run the program under test; a tool in a general language reduces a failing query or data set.
BashIdiomSubstring expansion ${text:offset:length} cuts the parts, and a function or a separate command serves as the test through its exit status. Alternative: Git bisect run and other tools call a test script and read its exit status.
PowerShellIdiomString.Substring cuts the parts and a script block serves as the test; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML is a common input that delta debugging reduces, but a document cannot hold the algorithm.
CSSDoes not applyA style sheet can be the input that delta debugging reduces, but it cannot hold the algorithm.
Regular expressionsDoes not applyA pattern cannot run a test or repeat a search over parts of its input.

No language has delta debugging in its standard library. The algorithm needs only a sequence that can be cut, a function value for the test and a loop, so every general language writes it in about 20 lines. The differences are in how a language cuts a string and stops at the first part that fails.

Language Verdict Form
Python idiom slices for the parts, next() over a generator for the first failing part
JavaScript idiom slice and Array.prototype.find
TypeScript idiom as JavaScript, with the type (text: string) => boolean for the test
Java idiom substring, Predicate<String> and stream().filter().findFirst()
C# idiom ranges such as chars[lo..hi] and FirstOrDefault over a lazy Select
Go idiom byte slices of a string, a closure for the test
Rust idiom a Vec<char>, a lazy map().find() and an FnMut test
C++ idiom substr, std::ranges::find_if and std::function
C idiom snprintf with %.*s into a fixed buffer, a function pointer for the test
Kotlin idiom as Java, with substring and a lambda
Bash idiom ${text:offset:length}; a test is a command and its exit status
PowerShell idiom Substring and a script block for the test
SQL, Regex, HTML, CSS n/a the language cannot run a test; HTML and CSS are common inputs to reduce

The test function is the part that changes from one project to the next. In the examples it is a closure or a function with a counter, so the program can report the number of tests. See Closure. In a real project the test starts the program as a separate process, feeds it the input and checks the exit status or the output.

Strings differ between languages. Go slices bytes and JavaScript slices UTF-16 code units, so a part can hold half of a character when the input is not ASCII. The Rust example cuts a Vec<char> to avoid this. A tool for real inputs often cuts at a coarser level, such as lines or tokens.

PythonGitHub
def ddmin(chars, fails):
    """Returns a 1-minimal part of chars on which fails() is still true."""
    n = 2
    while len(chars) >= 2:
        size = len(chars)
        bounds = [(i * size // n, (i + 1) * size // n) for i in range(n)]
        subsets = [chars[lo:hi] for lo, hi in bounds]
        complements = [chars[:lo] + chars[hi:] for lo, hi in bounds]
        smaller = next((s for s in subsets if fails(s)), None)
        if smaller is not None:  # reduce to subset
            chars, n = smaller, 2
            print("subset    ", len(chars))
            continue
        smaller = next((c for c in complements if fails(c)), None)
        if smaller is not None:  # reduce to complement
            chars, n = smaller, max(n - 1, 2)
            print("complement", len(chars))
            continue
        if n == size:  # each single character was removed
            break
        n = min(size, 2 * n)  # increase granularity
    return chars


tests = 0


def browser_crashes(text):
    """Stands for one run of the browser: it crashes on a <SELECT ...> tag."""
    global tests
    tests += 1
    start = text.find("<SELECT")
    return start >= 0 and ">" in text[start:]


page = '<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>'
minimal = ddmin(page, browser_crashes)
print(f"{len(page)} characters reduced to {minimal} in {tests} tests")
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests

The test function decides what counts as "the failure". The program below has two bugs. The test treats every exception as the failure, so ddmin drifts from the crash in the bug report to a different bug, an unclosed tag.

This code runs but gives a wrong answer on purpose.

def ddmin(chars, fails):
    n = 2
    while len(chars) >= 2:
        size = len(chars)
        bounds = [(i * size // n, (i + 1) * size // n) for i in range(n)]
        subsets = [chars[lo:hi] for lo, hi in bounds]
        complements = [chars[:lo] + chars[hi:] for lo, hi in bounds]
        smaller = next((s for s in subsets if fails(s)), None)
        if smaller is not None:
            chars, n = smaller, 2
            continue
        smaller = next((c for c in complements if fails(c)), None)
        if smaller is not None:
            chars, n = smaller, max(n - 1, 2)
            continue
        if n == size:
            break
        n = min(size, 2 * n)
    return chars


def render(text):
    """The program under test. It has two different bugs."""
    if text.rfind("<") > text.rfind(">"):
        raise ValueError("unclosed tag")
    start = text.find("<SELECT")
    if start >= 0 and ">" in text[start:]:
        raise RuntimeError("crash in the SELECT layout")


def fails(text):
    try:
        render(text)
    except Exception:  # any error counts as the failure
        return True
    return False


page = '<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>'
print(repr(ddmin(page, fails)))
Output
'<'

The fixed test returns True only for the same failure. Any other error is an unresolved outcome, so it returns False. Zeller and Hildebrandt compare the backtrace for the same reason.

def ddmin(chars, fails):
    n = 2
    while len(chars) >= 2:
        size = len(chars)
        bounds = [(i * size // n, (i + 1) * size // n) for i in range(n)]
        subsets = [chars[lo:hi] for lo, hi in bounds]
        complements = [chars[:lo] + chars[hi:] for lo, hi in bounds]
        smaller = next((s for s in subsets if fails(s)), None)
        if smaller is not None:
            chars, n = smaller, 2
            continue
        smaller = next((c for c in complements if fails(c)), None)
        if smaller is not None:
            chars, n = smaller, max(n - 1, 2)
            continue
        if n == size:
            break
        n = min(size, 2 * n)
    return chars


def render(text):
    """The program under test. It has two different bugs."""
    if text.rfind("<") > text.rfind(">"):
        raise ValueError("unclosed tag")
    start = text.find("<SELECT")
    if start >= 0 and ">" in text[start:]:
        raise RuntimeError("crash in the SELECT layout")


def fails(text):
    try:
        render(text)
    except RuntimeError as error:  # the failure of the bug report
        return str(error) == "crash in the SELECT layout"
    except Exception:  # another bug: the outcome is unresolved
        return False
    return False


page = '<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>'
print(repr(ddmin(page, fails)))
Output
'<SELECT>'
  • Verdict: idiom. The standard library has no delta debugging, and the algorithm is about 20 lines.
  • Slices build each subset and each complement in one expression.
  • next() over a generator stops at the first candidate that fails, so the program runs no extra tests.
  • The test must name one failure. A broad except Exception lets the search move to a different bug.
#include <algorithm>
#include <functional>
#include <print>
#include <string>
#include <vector>

// Returns a 1-minimal part of chars on which fails is still true.
std::string ddmin(std::string chars, const std::function<bool(const std::string &)> &fails) {
    std::size_t n = 2;
    while (chars.size() >= 2) {
        std::size_t size = chars.size();
        std::vector<std::string> subsets, complements;
        for (std::size_t i = 0; i < n; i++) {
            std::size_t lo = i * size / n, hi = (i + 1) * size / n;
            subsets.push_back(chars.substr(lo, hi - lo));
            complements.push_back(chars.substr(0, lo) + chars.substr(hi));
        }
        if (auto s = std::ranges::find_if(subsets, fails); s != subsets.end()) {
            chars = *s; // reduce to subset
            n = 2;
            std::println("subset     {}", chars.size());
            continue;
        }
        if (auto c = std::ranges::find_if(complements, fails); c != complements.end()) {
            chars = *c; // reduce to complement
            n = std::max<std::size_t>(n - 1, 2);
            std::println("complement {}", chars.size());
            continue;
        }
        if (n == size) { // each single character was removed
            break;
        }
        n = std::min(size, 2 * n); // increase granularity
    }
    return chars;
}

int main() {
    int tests = 0;
    // Stands for one run of the browser: it crashes on a <SELECT ...> tag.
    auto browser_crashes = [&tests](const std::string &text) {
        tests++;
        auto start = text.find("<SELECT");
        return start != std::string::npos && text.find('>', start) != std::string::npos;
    };
    const std::string page = R"(<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>)";
    std::string minimal = ddmin(page, browser_crashes);
    std::println("{} characters reduced to {} in {} tests", page.size(), minimal, tests);
}
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests
  • Verdict: idiom. The C++ standard library has no delta debugging.
  • std::ranges::find_if returns an iterator to the first part that fails, or end().
  • A lambda captures the counter by reference, and std::function holds it.
  • substr copies, so each part is a separate string.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;

public class Main {
    static int tests = 0;

    // Returns a 1-minimal part of chars on which fails is still true.
    static String ddmin(String chars, Predicate<String> fails) {
        int n = 2;
        while (chars.length() >= 2) {
            int size = chars.length();
            List<String> subsets = new ArrayList<>();
            List<String> complements = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                int lo = i * size / n, hi = (i + 1) * size / n;
                subsets.add(chars.substring(lo, hi));
                complements.add(chars.substring(0, lo) + chars.substring(hi));
            }
            Optional<String> smaller = subsets.stream().filter(fails).findFirst();
            if (smaller.isPresent()) { // reduce to subset
                chars = smaller.get();
                n = 2;
                System.out.println("subset     " + chars.length());
                continue;
            }
            smaller = complements.stream().filter(fails).findFirst();
            if (smaller.isPresent()) { // reduce to complement
                chars = smaller.get();
                n = Math.max(n - 1, 2);
                System.out.println("complement " + chars.length());
                continue;
            }
            if (n == size) { // each single character was removed
                break;
            }
            n = Math.min(size, 2 * n); // increase granularity
        }
        return chars;
    }

    // Stands for one run of the browser: it crashes on a <SELECT ...> tag.
    static boolean browserCrashes(String text) {
        tests++;
        int start = text.indexOf("<SELECT");
        return start >= 0 && text.indexOf('>', start) >= 0;
    }

    public static void main(String[] args) {
        String page = "<td align=left><SELECT NAME=\"priority\" MULTIPLE SIZE=7>";
        String minimal = ddmin(page, Main::browserCrashes);
        System.out.printf("%d characters reduced to %s in %d tests%n", page.length(), minimal, tests);
    }
}
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests

The program counts the tests in a static field. A lambda cannot change a local variable of the method that creates it, so the counter cannot be a local.

This code does not compile, on purpose.

import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        int tests = 0;
        Predicate<String> crashes = text -> {
            tests++;
            return text.contains("<SELECT");
        };
        System.out.println(crashes.test("<SELECT>") + " after " + tests + " tests");
    }
}
Error output
Main.java:7: error: local variables referenced from a lambda expression must be final or effectively final
            tests++;
            ^
1 error
  • Verdict: idiom. The Java class library has no delta debugging.
  • Predicate<String> is the type of the test. Main::browserCrashes is a method reference that fits it.
  • stream().filter(fails).findFirst() is lazy. It tests the parts in order and stops at the first part that fails.
  • A lambda can read only local variables that are final or effectively final. A counter must be a field, an array element or an AtomicInteger.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

static int tests = 0;

// Stands for one run of the browser: it crashes on a <SELECT ...> tag.
static bool browser_crashes(const char *text) {
    tests++;
    const char *start = strstr(text, "<SELECT");
    return start != NULL && strchr(start, '>') != NULL;
}

// Reduces chars in place to a 1-minimal part on which fails is still true.
static void ddmin(char *chars, bool (*fails)(const char *)) {
    char candidate[256];
    size_t n = 2;
    while (strlen(chars) >= 2) {
        size_t size = strlen(chars);
        bool reduced = false;
        for (size_t i = 0; i < n && !reduced; i++) { // the subsets
            size_t lo = i * size / n, hi = (i + 1) * size / n;
            snprintf(candidate, sizeof candidate, "%.*s", (int)(hi - lo), chars + lo);
            if (fails(candidate)) { // reduce to subset
                strcpy(chars, candidate);
                n = 2;
                printf("subset     %zu\n", strlen(chars));
                reduced = true;
            }
        }
        for (size_t i = 0; i < n && !reduced; i++) { // the complements
            size_t lo = i * size / n, hi = (i + 1) * size / n;
            snprintf(candidate, sizeof candidate, "%.*s%s", (int)lo, chars, chars + hi);
            if (fails(candidate)) { // reduce to complement
                strcpy(chars, candidate);
                n = n - 1 > 2 ? n - 1 : 2;
                printf("complement %zu\n", strlen(chars));
                reduced = true;
            }
        }
        if (reduced) {
            continue;
        }
        if (n == size) { // each single character was removed
            break;
        }
        n = 2 * n < size ? 2 * n : size; // increase granularity
    }
}

int main(void) {
    const char *page = "<td align=left><SELECT NAME=\"priority\" MULTIPLE SIZE=7>";
    char minimal[256];
    snprintf(minimal, sizeof minimal, "%s", page);
    ddmin(minimal, browser_crashes);
    printf("%zu characters reduced to %s in %d tests\n", strlen(page), minimal, tests);
}
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests
  • Verdict: idiom. The C library has no delta debugging.
  • snprintf with %.*s builds each part in a fixed buffer, so the program does not allocate. The buffer limits the input to 255 bytes.
  • ddmin changes the string in place, and a global variable counts the tests, because a C function pointer has no captured state.
int tests = 0;

// Stands for one run of the browser: it crashes on a <SELECT ...> tag.
bool BrowserCrashes(string text)
{
    tests++;
    int start = text.IndexOf("<SELECT", StringComparison.Ordinal);
    return start >= 0 && text.IndexOf('>', start) >= 0;
}

string page = "<td align=left><SELECT NAME=\"priority\" MULTIPLE SIZE=7>";
string minimal = DeltaDebugging.Ddmin(page, BrowserCrashes);
Console.WriteLine($"{page.Length} characters reduced to {minimal} in {tests} tests");

static class DeltaDebugging
{
    // Returns a 1-minimal part of chars on which fails is still true.
    public static string Ddmin(string chars, Func<string, bool> fails)
    {
        int n = 2;
        while (chars.Length >= 2)
        {
            int size = chars.Length;
            var bounds = Enumerable.Range(0, n).Select(i => (Lo: i * size / n, Hi: (i + 1) * size / n)).ToList();
            var subsets = bounds.Select(b => chars[b.Lo..b.Hi]);
            var complements = bounds.Select(b => chars[..b.Lo] + chars[b.Hi..]);
            string? smaller = subsets.FirstOrDefault(fails);
            if (smaller != null) // reduce to subset
            {
                chars = smaller;
                n = 2;
                Console.WriteLine($"subset     {chars.Length}");
                continue;
            }
            smaller = complements.FirstOrDefault(fails);
            if (smaller != null) // reduce to complement
            {
                chars = smaller;
                n = Math.Max(n - 1, 2);
                Console.WriteLine($"complement {chars.Length}");
                continue;
            }
            if (n == size) // each single character was removed
            {
                break;
            }
            n = Math.Min(size, 2 * n); // increase granularity
        }
        return chars;
    }
}
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests
  • Verdict: idiom. .NET has no delta debugging.
  • Ranges such as chars[lo..hi] and chars[..lo] cut the string.
  • Select is lazy, so FirstOrDefault(fails) builds and tests parts only until one fails. It returns null when no part fails.
  • A local function in the top-level statements counts the tests.
JavaScriptGitHub
// Returns a 1-minimal part of chars on which fails() is still true.
function ddmin(chars, fails) {
  let n = 2;
  while (chars.length >= 2) {
    const size = chars.length;
    const bounds = [];
    for (let i = 0; i < n; i++) {
      bounds.push([Math.floor((i * size) / n), Math.floor(((i + 1) * size) / n)]);
    }
    const subsets = bounds.map(([lo, hi]) => chars.slice(lo, hi));
    const complements = bounds.map(([lo, hi]) => chars.slice(0, lo) + chars.slice(hi));
    let smaller = subsets.find((s) => fails(s));
    if (smaller !== undefined) { // reduce to subset
      chars = smaller;
      n = 2;
      console.log("subset    ", chars.length);
      continue;
    }
    smaller = complements.find((c) => fails(c));
    if (smaller !== undefined) { // reduce to complement
      chars = smaller;
      n = Math.max(n - 1, 2);
      console.log("complement", chars.length);
      continue;
    }
    if (n === size) { // each single character was removed
      break;
    }
    n = Math.min(size, 2 * n); // increase granularity
  }
  return chars;
}

let tests = 0;

// Stands for one run of the browser: it crashes on a <SELECT ...> tag.
function browserCrashes(text) {
  tests++;
  const start = text.indexOf("<SELECT");
  return start >= 0 && text.indexOf(">", start) >= 0;
}

const page = '<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>';
const minimal = ddmin(page, browserCrashes);
console.log(`${page.length} characters reduced to ${minimal} in ${tests} tests`);
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests

The loop must stop when each part is one character and no part fails. Without the n === size check, n stays at size and the loop runs the same tests forever.

This code does not stop, on purpose.

function ddmin(chars, fails) {
  let n = 2;
  while (chars.length >= 2) {
    const size = chars.length;
    const bounds = [];
    for (let i = 0; i < n; i++) {
      bounds.push([Math.floor((i * size) / n), Math.floor(((i + 1) * size) / n)]);
    }
    const smaller =
      bounds.map(([lo, hi]) => chars.slice(lo, hi)).find(fails) ??
      bounds.map(([lo, hi]) => chars.slice(0, lo) + chars.slice(hi)).find(fails);
    if (smaller !== undefined) {
      chars = smaller;
      n = 2;
      continue;
    }
    n = Math.min(size, 2 * n); // no check for n === size
  }
  return chars;
}

const crashes = (text) => text.includes("<SELECT") && text.includes(">");
console.log(ddmin('<SELECT NAME="priority">', crashes));
  • Verdict: idiom. No standard library has delta debugging.
  • Array.prototype.find stops at the first part that fails, but map builds all the parts first.
  • slice counts UTF-16 code units. The input here is ASCII, so each unit is one character.
  • The test function is a plain function, so any function that returns a boolean can serve as the test.
TypeScriptGitHub
// Returns a 1-minimal part of chars on which fails() is still true.
function ddmin(chars: string, fails: (text: string) => boolean): string {
  let n = 2;
  while (chars.length >= 2) {
    const size = chars.length;
    const bounds: [number, number][] = [];
    for (let i = 0; i < n; i++) {
      bounds.push([Math.floor((i * size) / n), Math.floor(((i + 1) * size) / n)]);
    }
    const subsets = bounds.map(([lo, hi]) => chars.slice(lo, hi));
    const complements = bounds.map(([lo, hi]) => chars.slice(0, lo) + chars.slice(hi));
    let smaller = subsets.find((s) => fails(s));
    if (smaller !== undefined) { // reduce to subset
      chars = smaller;
      n = 2;
      console.log("subset    ", chars.length);
      continue;
    }
    smaller = complements.find((c) => fails(c));
    if (smaller !== undefined) { // reduce to complement
      chars = smaller;
      n = Math.max(n - 1, 2);
      console.log("complement", chars.length);
      continue;
    }
    if (n === size) { // each single character was removed
      break;
    }
    n = Math.min(size, 2 * n); // increase granularity
  }
  return chars;
}

let tests = 0;

// Stands for one run of the browser: it crashes on a <SELECT ...> tag.
function browserCrashes(text: string): boolean {
  tests++;
  const start = text.indexOf("<SELECT");
  return start >= 0 && text.indexOf(">", start) >= 0;
}

const page = '<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>';
const minimal = ddmin(page, browserCrashes);
console.log(`${page.length} characters reduced to ${minimal} in ${tests} tests`);
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests
  • Verdict: idiom. The program is the JavaScript program with types.
  • The type (text: string) => boolean documents the contract of the test function.
  • find returns string | undefined, and the compiler makes the program check for undefined before it uses the result.
package main

import (
	"fmt"
	"strings"
)

// ddmin returns a 1-minimal part of chars on which fails is still true.
func ddmin(chars string, fails func(string) bool) string {
	n := 2
	for len(chars) >= 2 {
		size := len(chars)
		var subsets, complements []string
		for i := range n {
			lo, hi := i*size/n, (i+1)*size/n
			subsets = append(subsets, chars[lo:hi])
			complements = append(complements, chars[:lo]+chars[hi:])
		}
		if s, ok := first(subsets, fails); ok { // reduce to subset
			chars, n = s, 2
			fmt.Println("subset    ", len(chars))
			continue
		}
		if c, ok := first(complements, fails); ok { // reduce to complement
			chars, n = c, max(n-1, 2)
			fmt.Println("complement", len(chars))
			continue
		}
		if n == size { // each single character was removed
			break
		}
		n = min(size, 2*n) // increase granularity
	}
	return chars
}

// first returns the first candidate on which fails is true.
func first(candidates []string, fails func(string) bool) (string, bool) {
	for _, c := range candidates {
		if fails(c) {
			return c, true
		}
	}
	return "", false
}

func main() {
	tests := 0
	// browserCrashes stands for one run of the browser:
	// it crashes on a <SELECT ...> tag.
	browserCrashes := func(text string) bool {
		tests++
		start := strings.Index(text, "<SELECT")
		return start >= 0 && strings.Contains(text[start:], ">")
	}
	page := `<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>`
	minimal := ddmin(page, browserCrashes)
	fmt.Printf("%d characters reduced to %s in %d tests\n", len(page), minimal, tests)
}
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests
  • Verdict: idiom. The standard library has no delta debugging.
  • The test is a closure that counts its own calls in the variable tests. See Closure.
  • A Go string is a sequence of bytes, and chars[lo:hi] slices bytes. For input that is not ASCII, convert it to []rune first, or a part can hold half of a character.
  • The helper first stops at the first part that fails, so the program runs no extra tests.
RustGitHub
/// Returns a 1-minimal part of `chars` on which `fails` is still true.
fn ddmin(mut chars: Vec<char>, fails: &mut impl FnMut(&[char]) -> bool) -> Vec<char> {
    let mut n = 2;
    while chars.len() >= 2 {
        let size = chars.len();
        let bounds: Vec<(usize, usize)> = (0..n).map(|i| (i * size / n, (i + 1) * size / n)).collect();
        let subset = bounds.iter().map(|&(lo, hi)| chars[lo..hi].to_vec()).find(|s| fails(s));
        if let Some(s) = subset {
            // reduce to subset
            chars = s;
            n = 2;
            println!("subset     {}", chars.len());
            continue;
        }
        let complement = bounds
            .iter()
            .map(|&(lo, hi)| [&chars[..lo], &chars[hi..]].concat())
            .find(|c| fails(c));
        if let Some(c) = complement {
            // reduce to complement
            chars = c;
            n = (n - 1).max(2);
            println!("complement {}", chars.len());
            continue;
        }
        if n == size {
            break; // each single character was removed
        }
        n = size.min(2 * n); // increase granularity
    }
    chars
}

fn main() {
    let mut tests = 0;
    // Stands for one run of the browser: it crashes on a <SELECT ...> tag.
    let mut browser_crashes = |chars: &[char]| {
        tests += 1;
        let text: String = chars.iter().collect();
        match text.find("<SELECT") {
            Some(start) => text[start..].contains('>'),
            None => false,
        }
    };
    let page = r#"<td align=left><SELECT NAME="priority" MULTIPLE SIZE=7>"#;
    let minimal: String = ddmin(page.chars().collect(), &mut browser_crashes).into_iter().collect();
    println!("{} characters reduced to {} in {} tests", page.len(), minimal, tests);
}
Output
complement 42
complement 28
complement 21
complement 17
complement 14
complement 13
complement 12
complement 10
complement 9
complement 8
55 characters reduced to <SELECT> in 147 tests
  • Verdict: idiom. The standard library has no delta debugging.
  • The input is a Vec<char>, so a part never splits a UTF-8 character.
  • map(...).find(...) is lazy. It builds a part and tests it, and it stops at the first part that fails.
  • The test changes the counter tests, so its type is FnMut, and ddmin takes it by &mut.

Isolating a difference

When a passing input is also known, the general algorithm dd isolates the difference between the passing input and the failing one. It grows the passing input and shrinks the failing input until they differ by a 1-minimal set of changes. dd generalizes ddmin.1 Isolation needs fewer tests than minimization. In the examples of the paper, isolation needs 7 tests where minimization needs 26. The cost is that the developer must keep the common context of both inputs in mind.1

Hierarchical reduction

The Mozilla study ran ddmin twice. The first run used lines as changes and reduced 896 lines to one line in 57 tests. The second run used the characters of that line and reduced it to <SELECT>.1 A coarse first run removes large blocks with few tests. A fine second run removes the details.

Fuzzing and property-based testing

A fuzzer or a property-based test finds a failing input at random, and that input is often long and full of noise. These tools shrink the input before they report it, with the same goal as ddmin. See Fuzz testing and Property-based testing.

git bisect

Delta debugging can also search the history of a program. The changes are then commits, not parts of an input. If an old version works and a new version fails, one of the commits between them introduced the failure. git bisect finds that commit with a binary search through the history.3 See Git and commit.

git bisect start <bad> <good> marks the two ends. git bisect run <cmd> then checks out a commit in the middle, runs the command and reads its exit status:3

  • exit 0 means the commit is good;
  • exit 1 to 127, except 125, means the commit is bad;
  • exit 125 means the commit cannot be tested, so Git skips it;
  • any other exit status stops the search.

At the end, Git prints the first bad commit, and the ref refs/bisect/bad points at it.3 git bisect reset returns to the branch where the search started.

The script below makes a history of 8 commits. One commit changes total.sh so that it rounds the total to an even number, and 2 + 3 then gives 4. The test script lives outside the repository, so each checkout leaves it alone.

export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1
export GIT_AUTHOR_NAME=Ada GIT_AUTHOR_EMAIL=ada@example.com GIT_AUTHOR_DATE=2026-01-05T10:00:00Z
export GIT_COMMITTER_NAME=Ada GIT_COMMITTER_EMAIL=ada@example.com GIT_COMMITTER_DATE=2026-01-05T10:00:00Z
exec 2>&1
git -c init.defaultBranch=main init -q shop && cd shop
step() { printf '%s\n' "$2" > "$1"; git add "$1"; git commit -q -m "$3"; }
step total.sh 'echo $(( $1 + $2 ))' "Add the total script"
step README 'Adds two prices.' "Add a README"
step total.sh 'echo $(( ${1:-0} + ${2:-0} ))' "Treat a missing price as 0"
step README 'Adds two prices. A missing price is 0.' "Document missing prices"
step total.sh 'echo $(( (${1:-0} + ${2:-0}) / 2 * 2 ))' "Round the total to an even number"
step README 'Adds two prices and rounds the total.' "Document the rounding"
step NEWS 'Version 2' "Write the news file"
step NEWS 'Version 2, with rounding' "Update the news file"
cat > ../test.sh <<'EOF'
#!/bin/sh
# Exit 0 if the commit is good, 1 if it is bad.
test "$(sh total.sh 2 3)" = 5
EOF
chmod +x ../test.sh
git bisect start HEAD "$(git rev-list --max-parents=0 HEAD)"
git bisect run ../test.sh
git log -1 --format='first bad commit: %s' refs/bisect/bad
git bisect reset
Output
Bisecting: 3 revisions left to test after this (roughly 2 steps)
[516ec22fbcffc6049c6904bf080876f24ab687a5] Document missing prices
running '../test.sh'
Bisecting: 1 revision left to test after this (roughly 1 step)
[e3344e5a8074285075230505583aa388fc81e23c] Document the rounding
running '../test.sh'
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[456c71953887868b48a317631253c6e6a537eff0] Round the total to an even number
running '../test.sh'
456c71953887868b48a317631253c6e6a537eff0 is the first 'bad' commit
commit 456c71953887868b48a317631253c6e6a537eff0
Author: Ada <ada@example.com>
Date:   Mon Jan 5 10:00:00 2026 +0000

    Round the total to an even number

 total.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
bisect found first 'bad' commit
first bad commit: Round the total to an even number
Previous HEAD position was 456c719 Round the total to an even number
Switched to branch 'main'

Git tested 3 of the 6 commits between the two ends. A linear search from the oldest commit would test up to 6. The gain grows with the length of the history, because each test halves the range.

git bisect assumes that the history has one point where the result changes from good to bad. ddmin makes no such assumption about an input, so it needs more tests. When the failure needs two commits together, a bisection finds the later of the two, not the pair.

Pitfalls

The search finds a different failure

The test function decides what counts as the failure. If it returns "fail" for any error, ddmin can move from the failure in the bug report to a different one. A smaller input often has new errors, such as an unclosed tag or a syntax error. The Python example shows this: a test that treats any exception as the failure reduces the page to <, which shows a different bug.

Zeller and Hildebrandt saw this effect. In their first runs, the test returned ✘ for any crash. For the NROFF input t1, the result had 2 characters. Then they made the test more precise: it returned ✘ only if the backtrace of the crash was the same as in the original failure, and unresolved for a crash with a different backtrace. The result then had 60 characters, and only those 60 caused the original failure.1 A test should compare the error type, the message or the location of the failure. Any other error is an unresolved outcome. See Exception.

A test that is not deterministic

ddmin assumes that the same input gives the same outcome each time. A failure that depends on timing, on random numbers or on the state of the machine breaks this assumption. The algorithm can then keep a part that does not matter or remove a part that does. Fix the seed, the clock and the environment before the search, or run each test several times.

The loop does not stop

The third rule applies only while n < |c|. Without this check, n stays at |c| and the loop runs the same tests forever. The JavaScript example has a version with this bug.

Many inputs are not valid

Most subsets of a structured input, such as a C program or a JSON file, are not valid. The test is then unresolved, and ddmin needs more tests. In the GCC case study, each attempt to remove one more character from the 77-character program gave a program that was not valid C.1 A reduction at the level of lines, tokens or syntax tree nodes keeps more inputs valid than a reduction at the level of characters.

The cost of one test

Each test runs the program. If one run takes a minute, 1000 tests take most of a day. Start with a coarse granularity, set a time limit on each run, and make the test start the program as fast as possible.

Cost

Proposition 12 of the paper gives the worst case: ddmin runs at most |c|² + 3|c| tests on an input of |c| changes. The worst case occurs when almost every test is unresolved. Proposition 13 gives the best case: if one change alone causes the failure, and every input with that change fails, ddmin runs at most 2 log₂ |c| tests.1

The case studies of the paper fall between these bounds:1

  • GCC. A C program of 755 characters crashed GCC with optimization on. The first tests cut it to 377 and then 188 characters. 731 more tests reduced it to 77 characters, a 1-minimal program.
  • Mozilla. 95 user actions were reduced to 3 in 82 test runs, which took 21 minutes. 896 lines of HTML were reduced to one line in 57 tests.
  • Total. The abstract gives 139 test runs, or 35 minutes on a 500 MHz PC, for the Mozilla case study.

The example on this page needs 147 tests for 55 characters. The test function returns at once, so the run takes much less than a second. The cost of a real search is the number of tests times the cost of one run of the program.

History

  • 1999. Mozilla's bug database held more than 370 open bug reports that nobody had simplified. Netscape asked volunteers to turn bug reports into minimal test cases in the Mozilla BugAThon. A volunteer who simplified 5 bug reports got an invitation to the launch party, and 20 bug reports earned a T-shirt.1
  • 1999. Zeller presented the first delta debugging algorithm, dd, in "Yesterday, my program worked. Today, it does not. Why?" at ESEC/FSE 1999. It searched for the changes to program code that cause a failure.1
  • 2002. Zeller and Hildebrandt published "Simplifying and Isolating Failure-Inducing Input" in IEEE Transactions on Software Engineering. The paper defines ddmin, 1-minimality and the general dd for inputs, and it applies them to GCC, Mozilla and UNIX utilities.1

References

  1. Andreas Zeller and Ralf Hildebrandt, Simplifying and Isolating Failure-Inducing Input, IEEE Transactions on Software Engineering 28(2), February 2002 (read from the copy at https://www.cs.purdue.edu/homes/xyzhang/fall07/Papers/delta-debugging.pdf), Abstract; I Introduction; III-A Minimal Test Cases (Definition 10); III-B A Minimizing Algorithm (Figure 5, Propositions 11 to 13); IV-A GCC; IV-B Mozilla; IV-D The Precision Effect; V Isolating Failure-Inducing Differences; references [2] and [3]
  2. Andreas Zeller, Introduction to Debugging, in The Debugging Book, the sections From Defect to Failure, From Failure to Defect, The Scientific Method and Keep a Log
  3. Git documentation, git-bisect, Description; Bisect run; Examples

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/8J7Q8Z/text.yaml