We are going to run mutation testing at scale. The key considerations are:
Test budget: We have limited resources, so we need to manage the number of mutants and tests run.
Flake isolation: We need to handle flaky tests that might cause false positives in mutation testing.
Perf tuning: We need to optimize the performance of mutation testing, possibly by parallelization, caching, or reducing the number of mutants.
ROI tracking: We want to track the return on investment of mutation testing, i.e., how much time we spend vs. how many real bugs we find.
Steps:
Choose a mutation testing tool that supports the language and is scalable. For Java, we have PIT. For JavaScript, we have Stryker. For Python, we have MutPy, etc.
Set up a baseline: Run mutation testing on a small, representative subset of the codebase to understand the performance and the number of mutants.
Test budget:
We can control the number of mutants by:
a. Limiting the mutation operators (some are more expensive than others).
b. Focusing on critical parts of the code (e.g., recently changed, core modules).
c. Using a sampling strategy (e.g., run mutation on a random subset of mutants, but then we lose coverage).
We can set a time budget per module or per test suite and stop when the budget is exhausted.
Flake isolation:
Identify flaky tests by running the test suite multiple times and collecting the tests that fail intermittently.
We can run mutation testing excluding flaky tests, but then we might miss mutants that are only caught by flaky tests.
Alternatively, we can run mutation testing with a retry mechanism for failures. If a test fails only once, we might re-run the mutant to see if it's a real kill or a flake.
We can also use a flaky test database to exclude or mark flaky tests so that we don't count them as kills.
Perf tuning:
Parallelization: Run mutants in parallel. Tools like PIT and Stryker support parallel execution.
Caching: Cache the results of tests for a given mutant and test run. If the same mutant is generated again (e.g., in a different run) and the code hasn't changed, we can reuse the result.
Incremental mutation testing: Only run mutation on code that has changed since the last run. This requires maintaining state of the last run and the code changes.
Reduce the number of mutants by using a selective mutation strategy (e.g., only run mutants on code that is covered by tests, or only on code that has been modified).
ROI tracking:
Track the time spent on mutation testing and the number of real bugs found (surviving mutants that are eventually fixed).
We can also track the number of mutants killed by existing tests (code coverage) vs. mutants that survive (potential bugs).
We can use a dashboard to show the mutation score over time and correlate with bug fixes.
We can also track the cost per bug found (time spent / number of bugs found) and adjust the test budget accordingly.
Implementation plan:
Step 1: Choose the tool and set up the initial configuration.
Step 2: Run a baseline mutation test on the entire codebase (or a subset if too large) to get:
Total number of mutants
Time taken per mutant (or per test run)
Mutation score
Step 3: Set up flaky test detection:
Run the test suite multiple times (e.g., 5 times) and record any test that fails at least once but not all the time.
Store the list of flaky tests in a file and exclude them from mutation testing, or mark them so that we can re-run the mutant if a flaky test fails.
Step 4: Implement a test budget controller:
We can set a maximum time for mutation testing (e.g., 2 hours). We then estimate how many mutants we can run in that time and sample accordingly.
Alternatively, we can set a maximum number of mutants to run (e.g., 1000 mutants) and stop when we reach that number.
Step 5: Performance tuning:
Enable parallel execution in the mutation testing tool.
Implement caching: For each mutant, we can cache the test results (which tests fail) if the mutant and the codebase haven't changed. We need a way to hash the mutant and the code under test.
Implement incremental mutation: Use a version control system (like Git) to get the changed files and only run mutants on those files. Note: mutation testing on a subset of files might not be accurate because a test might fail due to a change in a different file? But in mutation testing we are only mutating one location at a time, so if we only mutate in changed files, we are only looking for bugs introduced by those changes. This is acceptable for a CI pipeline on a pull request.
Step 6: ROI tracking:
Log each mutation testing run with:
Start time, end time, total mutants run, mutants killed, mutants survived, mutants ignored (due to flaky tests or budget).
The list of surviving mutants (with the mutation and the code location).
When a surviving mutant is fixed (by changing the code or the test), we can mark it as a bug fixed and track the time from mutation run to fix.
We can also track the number of bugs found that were not caught by existing tests (i.e., the surviving mutants that are real bugs).
Step 7: Integration into CI/CD:
We run mutation testing on every pull request (or on a schedule) with the incremental and budget constraints.
We set a threshold for the mutation score (e.g., 80%) and fail the build if the score is below that, but only if we ran the full set of mutants? Or if we run a subset, we might not have a reliable score.
Alternatively, we can run mutation testing in the background and report the score and list of survivors without failing the build, but then we lose the enforceability.
Given the complexity, we might start with a simple approach and then add the advanced features.
Let's break down the implementation for a specific tool. Since the user didn't specify the language, I'll use Java and PIT as an example.
Example for Java with PIT:
Set up PIT in the project (as a Maven or Gradle plugin).
Flaky test detection:
We can run the test suite 5 times and collect the failures. Then, in PIT, we can exclude flaky tests by configuring the excludedTests in the PIT configuration.
Test budget:
PIT allows limiting the number of mutants by setting maxMutationsPerClass and threads for parallel execution. We can also set a time limit by using the timeoutConstant and timeoutFactor but that's for each test. Alternatively, we can run PIT with a subset of mutation operators to reduce the number of mutants.
Performance tuning:
Use threads to run in parallel (but be careful of resource contention).
Use outputFormats to generate only the necessary reports (avoid generating HTML if not needed in CI).
Use mutationThreshold and coverageThreshold to fail the build only if below a certain percentage.
Incremental mutation:
PIT does not natively support incremental mutation. We would have to write a script that:
a. Gets the list of changed files (by comparing with the main branch).
b. Runs PIT only on those classes. We can use the targetClasses and targetTests to limit the scope.
However, note that a mutation in a class might be killed by a test in a different class. So if we only mutate in changed classes, we might miss that the existing tests for other classes kill the mutant? Actually, PIT runs the entire test suite for each mutant, so if we only mutate in changed classes, we are only generating mutants in those classes, but we run all tests. That's acceptable because we are only concerned with the changed code.
ROI tracking:
We can parse the PIT XML report and store the mutation scores and the list of surviving mutants in a database. Then we can track over time.
However, note that running mutation testing on every PR might be too heavy. So we might run it only on the main branch nightly, and on PRs we run a subset (changed files) with a lower budget.
Let's design a system:
Nightly run (full mutation testing on the entire codebase):
No budget limit (or a high one) to get a good mutation score.
Exclude flaky tests (from the flaky test database).
Run with all mutation operators.
Store the results in a database.
PR run (incremental and budgeted):
Get the list of changed files (by comparing the PR branch with the target branch).
Run mutation testing only on the classes that have changed (or that are affected by the change? We can only do changed classes for simplicity).
Set a budget: e.g., maximum 30 minutes, or maximum 500 mutants.
Use the same flaky test exclusion.
We can set a lower threshold for the mutation score on the changed code? Or we can require that all mutants in the changed code are killed? But that might be too strict.
Alternatively, we can run the PR mutation testing with the same set of mutants as the nightly run but only for the changed classes? But the nightly run might have already run mutants in those classes. We can use the caching: if the mutant was already run in the nightly and the code hasn't changed, then we can use the cached result. But the code in the PR might be different, so we have to re-run.
This is complex.
Given the complexity, maybe we start with:
Option 1 (simpler):
- Nightly: full mutation testing on the entire codebase (with flaky test exclusion and parallelization) and store the results.
- PR: run mutation testing only on the changed files, but without caching from nightly (because the code is different). We set a budget (time and number of mutants) and run as many as we can. We then compare the mutation score on the changed code with the baseline (from nightly) for the same classes? But the baseline for the changed classes might be from an older version.
Option 2 (more advanced):
- Maintain a cache of mutants and their results (killed or survived) from previous runs. For a PR, we:
a. Get the changed files.
b. For each changed class, get the list of mutants that were generated in the last full run (or the last run that included that class) and that are still valid (the code around the mutation hasn't changed). Then we only need to run the tests for those mutants that are affected by the change? Actually, if the code at the mutation site hasn't changed, then the mutant is the same and we can use the cached result. But if the code around it has changed, the mutant might be different? Actually, the mutant is generated by applying a transformation to the code. If the code at that line has changed, then the mutant is different. So we can hash the code at the mutation site and compare with the cached mutant's hash.
This is very complex and might not be worth the effort.
Given the time, let's go with Option 1 and then maybe add caching later.
Steps for PR:
1. Get the list of changed Java files (from git diff).
2. Convert the file names to class names (and package) to pass to PIT.
3. Run PIT with:
- `targetClasses` set to the changed classes (and maybe also the classes that are directly affected? For simplicity, just the changed ones).
- `targetTests` set to all tests (or we can also limit to tests that cover the changed classes? But then we might miss tests that are in other packages but cover the changed classes. PIT already runs all tests by default, so we can leave it.
- `maxMutationsPerClass` set to a low number (e.g., 10) to control the budget? Or we can set a total number of mutants? PIT doesn't have a total limit, but we can set `maxMutationsPerClass` and then the total is that times the number of classes.
- `threads` to use multiple cores.
- `timeoutConstant` and `timeoutFactor` to avoid hanging tests.
- `excludedTests` for flaky tests.
4. We set a time limit for the entire PIT run (using a timeout in the CI job). If the job times out, we kill it and report the partial results.
5. We then compare the mutation score for the changed classes with the baseline (from the nightly run for the same classes). But note: the baseline might be for a different version of the code. We can store the mutation score per class in the nightly run and then for the PR, we compute the mutation score for the changed classes (even if we run only a subset of mutants, we can compute the score as killed mutants / total mutants run). But then we are comparing a subset of mutants (maybe with a lower mutation score) to the full set? That's not fair.
Alternatively, we can set a rule: on PR, we require that all mutants (in the changed classes) are killed. But if we run only a subset of mutants (due to budget) then we cannot guarantee that. So maybe we require that the mutation score for the changed classes (in the PR run) is at least the same as the baseline (from the last full run for those classes). But again, the baseline might be for a different set of mutants (because the code might have changed in the baseline run?).
This is getting too complicated.
Let's simplify the PR requirement:
We want to ensure that the new code (the changed lines) are tested by the existing tests. So we want to see that the mutants introduced by the change are killed.
How about: for each changed class, we run mutation testing only on the changed lines? PIT does not support that. It mutates by operator and by line. We could try to generate mutants only for the changed lines, but that would require customizing PIT.
Given the complexity, maybe we do:
Nightly: full mutation testing on the entire codebase, and we record the mutation score per class.
PR: we run mutation testing on the changed classes (with a budget) and we require that the mutation score for these classes (in the PR run) is at least the same as the baseline (from the nightly) for the same classes. But note: the baseline might be outdated because the code in the main branch might have changed since the nightly? We can get the baseline from the latest nightly that includes the same version of the code? Actually, the PR is compared against the target branch (say, main). We can use the mutation score from the last successful mutation testing run on the main branch for the changed classes.
Steps:
a. In the nightly, we store the mutation score per class (and maybe per file) in a database or a file in the repo.
b. In the PR, we:
- Get the list of changed classes.
- Get the baseline mutation score for these classes from the last nightly on the target branch (main).
- Run mutation testing on the changed classes (with a budget) and compute the mutation score for these classes (only the mutants that were run).
- Compare: if the PR mutation score for any changed class is below the baseline (for that class), then fail the PR.
But note: the baseline might be for a full set of mutants, and the PR might run only a subset (due to budget). So the PR mutation score might be lower even if the tests are good, because we didn't run all mutants.
So we need to run the same set of mutants in the PR as in the baseline? That's not possible because the code is different.
Alternatively, we can set a threshold for the mutation score (e.g., 80%) and require that the PR mutation score (on the changed classes) is at least 80%. But then we are not comparing with the baseline.
Given the complexity, maybe we don't compare with the baseline. Instead, we set a fixed threshold (e.g., 80%) for the changed classes in the PR. And we run as many mutants as we can within the budget.
But then we are not using the baseline at all.
Another idea: in the PR, we only check that there are no surviving mutants (i.e., 100% kill rate) for the changed classes? But that might be too strict because we might not have tests for every mutant.
Given the challenges, let's step back.
The goal of mutation testing in PR is to ensure that the new code is well tested. So we want to see that the tests we have kill the mutants in the new code.
How about we do:
In the PR, we run mutation testing only on the changed lines? We can try to generate mutants only for the lines that have changed. But PIT doesn't support that.
Alternatively, we can use a different approach: run mutation testing on the entire codebase (or the changed classes) but then filter the mutants to only those that are in the changed lines? PIT generates a report with the line number of the mutant. We can filter the report to only include mutants that are in the changed lines. Then we check that all these mutants are killed.
Steps:
1. Run mutation testing on the changed classes (or the entire codebase if we want to be thorough, but that might be too heavy) with a budget (so we might not run all mutants).
2. From the generated mutants, filter to only those that are in the changed lines (we have the list of changed lines from git diff).
3. Check that all these mutants are killed. If any survive, fail the PR.
But note: if we run mutation testing on the entire codebase, we are running mutants in unchanged code too, which we don't care about. So we are wasting resources.
So we run mutation testing only on the changed classes, and then we filter the mutants to only the changed lines? But the changed classes might have mutants in unchanged lines? Actually, if we only mutate in the changed classes, then all mutants are in those classes, but not necessarily in the changed lines. We want to focus on the changed lines.
How about: we run mutation testing on the entire codebase, but then we only check the mutants in the changed lines? But then we are running mutants in the entire codebase, which is heavy.
Given the budget, we might run mutation testing only on the changed classes and then check all mutants in those classes? But that might be too many mutants and we might not have tests for old code in the changed classes.
Alternatively, we can run mutation testing on the changed classes and then only consider the mutants that are in the changed lines? That would be the most focused.
How to do that:
1. Get the list of changed files and the changed line numbers (from git diff).
2. Run PIT on the changed classes (so we only generate mutants in those classes).
3. In the PIT report, for each mutant, check if the line number of the mutant is in the set of changed lines. If yes, then we require it to be killed.
This way, we are only concerned with the mutants that are exactly in the lines that were changed.
But note: a change might affect multiple lines? We are only looking at the exact lines that were changed. But what about a mutant in a line that was not changed but is affected by the change? For example, if we change a method signature, then mutants in the callers of that method might be affected? But mutation testing is about mutating the code and seeing if the tests fail. If we change a method signature, then the code that calls that method might not compile? Actually, PIT runs on the compiled code. If we change a method signature, then the callers might break and the tests might fail, but that's not because of a mutant in the caller, it's because the code is broken. So we are only concerned with mutants in the code that we changed.
So the plan for PR:
- Run PIT on the changed classes (only the classes that have changed).
- From the generated mutants, filter to only those that are in the changed lines.
- Require that all these mutants are killed.
But what if there are no mutants in the changed lines? That can happen if the changed lines are not mutable (e.g., a closing brace, a comment, or a line that PIT doesn't mutate). Then we pass automatically.
Also, we have to handle flaky tests: if a test that kills a mutant is flaky, we might get a false surviving mutant. So we need to exclude flaky tests.
Implementation:
1. Flaky test detection: run the entire test suite multiple times and record flaky tests. Store in a file `flaky-tests.txt` (one pattern per line, matching the test name as in PIT).
2. In the PR, run:
mvn org.pitest:pitest-maven:mutationCoverage \
-DtargetClasses=<changed_classes_comma_separated> \
-DexcludedTests=@flaky-tests.txt \
-DmaxMutationsPerClass=100 # or some limit to control the number of mutants per class
3. After the run, parse the XML report (or use the PIT API) to get the list of mutants and their status (killed, survived, etc.) and the line number.
4. Get the list of changed lines (from `git diff`). We can get the changed lines in the format: `ClassFile:line_start,line_end` or individual lines.
5. For each mutant in the changed classes, if the mutant's line is in the changed lines, then check if it is killed. If any such mutant is not killed, fail the PR.
6. If we run out of budget (time or maxMutationsPerClass) and we haven't run all mutants in the changed lines, then we might miss some. So we need to ensure that we run enough mutants. We can set `maxMutationsPerClass` to a high number, but then we might exceed the budget. Alternatively, we can run without a per-class limit but with a total budget? PIT doesn't have a total budget. We can set a timeout for the entire PIT run.
Given the complexity, maybe we don't set a per-class limit and instead rely on the overall timeout. But then if there are many changed classes, we might run out of time.
We can also prioritize the changed classes: if there are too many, we can run on a subset? But that would be unfair.
Alternatively, we can run PIT on the entire codebase (if the budget allows) and then filter to the changed lines. But that might be too heavy.
Given the constraints, let's assume we have a time budget of 30 minutes for the PR mutation testing. We run PIT on the changed classes and let it run until the timeout. Then we check the mutants that were generated and run (we ignore the ones that were not run due to timeout). But then we might not have run all mutants in the changed lines.
So we have two options:
Option A: Run until timeout and then check the mutants that were run. If any mutant in the changed lines that was run survived, fail. But we might not have run all mutants in the changed lines, so we might miss some.
Option B: Before running PIT, we compute the expected mutants in the changed lines (by simulating the mutation operators on the changed lines) and then we require that all of them are killed. But we cannot know the mutants without running PIT.
This is a hard problem.
Given the time, we might have to accept that we cannot check every mutant in the changed lines due to budget. So we do:
- Run PIT on the changed classes with a timeout (say 30 minutes).
- After the run, we have a set of mutants that were run (with status). We also have the list of changed lines.
- We then check: for every mutant that was run and that is in a changed line, it must be killed.
- We don't check the mutants that were not run (due to timeout or because PIT didn't generate them). This means we might miss some, but we are doing our best within the budget.
We can log the mutants that were not run and maybe raise a warning, but not fail.
Also, we can adjust the budget (timeout) based on the number of changed classes. We can set a timeout per class? Or we can set a total timeout and if we exceed, we kill the job.
Given the above, we can implement:
Step 1: Flaky test detection (nightly or periodically) and store the list.
Step 2: PR pipeline:
a. Get the changed classes and changed lines.
b. Run PIT on the changed classes with:
- `excludedTests` from the flaky test list.
- `threads` set to the number of available cores (or a fixed number to avoid overloading).
- `timeoutConstant` and `timeoutFactor` for individual tests (to avoid hanging).
- A total timeout for the entire PIT run (using the CI job timeout).
c. Parse the PIT report (XML) to get:
- The list of mutants (with class, method, line number, status).
- The total number of mutants run and killed.
d. Filter the mutants to those that are in the changed lines.
e. If any of these mutants survived, fail the PR.
f. If the PIT job times out, we might have partial results. We can still check the mutants that were run. But note: if the job times out, we might not have a complete report. We can configure PIT to output partial results on timeout? Not sure.
Step 3: Nightly run:
a. Run PIT on the entire codebase (without a budget, but with flaky test exclusion and parallelization).
b. Store the mutation score per class in a file in the repo (or in a database) for baseline comparison? Actually, we are not using the baseline in the PR anymore, so maybe we don't need to store per-class scores.
c. We can use the nightly run to detect flaky tests (by seeing which tests fail intermittently) and update the flaky test list.
Given the complexity, let's stick to the PR plan above and forget about the baseline comparison.
However, note: the PR plan only checks mutants in the changed lines. But what if the change breaks an existing test that covers a mutant in an unchanged line? That would be caught by the existing test suite (unit tests) anyway, so we don't need mutation testing for that.
So the PR mutation testing is only to ensure that the new code (the changed lines) are tested by the existing tests. That seems reasonable.
But note: if we change code in a method, and there is a mutant in that method (in a line that was not changed) that is now killed by a test that was written for the change? Actually, if we change the method, we might have changed the behavior and the existing tests might now fail for a mutant that was previously survived? But we are only looking at mutants in the changed lines. So we might miss that.
Example:
Original method:
int add(int a, int b) { return a + b; }
We change it to:
int add(int a, int b) { return a - b; } // changed line
There is a mutant in the line `return a - b;` (say, change `-` to `+`). That mutant is in the changed line and we will check it.
But what about a mutant in the method signature? PIT doesn't mutate method signatures usually.
What about a mutant in the same method but in a different line? For example, if the method had multiple lines and we changed one line, then the other lines might have mutants that are now killed because the behavior changed? But we are only looking at the changed line.
Actually, we want to ensure that the tests we have for the changed code are sufficient. The mutants in unchanged lines are already covered by existing tests (from before the change) or not. We are only concerned with the new code.
So I think focusing on the changed lines is acceptable.
However, note that a change might introduce a new condition that affects multiple lines? But we are only looking at the exact lines that were changed. If we change a condition, we might have mutants in the then and else branches? But the condition is one line, so we are only looking at that line.
Given the above, let's proceed with the plan.
Implementation details:
How to get the changed lines?
We can use `git diff` to get the list of changed files and the line numbers.
Example: `git diff --unified=0 origin/main...HEAD` (for PR against main).
This will output:
@@ -old_start,old_count +new_start,new_count @@
... lines ...
We can parse the new line numbers (the ones after the `+`).
We can create a map: class name (from the file path) -> set of line numbers (in the new code).
How to map from file to class?
We assume the standard Maven/Gradle directory structure: `src/main/java` and the package structure.
How to run PIT on a subset of classes?
We can set the `targetClasses` parameter to a comma-separated list of class names (with wildcards). We can use the fully qualified class names.
Example: `targetClasses=com.example.MyClass,com.example.OtherClass`
How to parse the PIT report?
The default XML report is at `target/pit-reports/*/mutations.xml`. We can parse it to get:
<mutation>
<mutatedClass>com.example.MyClass</mutatedClass>
<method>methodName</method>
<line>123</line>
<status>KILLED</status>
...
</mutation>
Then we can check for each mutation in the changed classes and changed lines.
Steps in code:
1. Pre-step: flaky test detection (run separately, not in PR). We assume we have a file `flaky-tests.txt` in the repo.
2. In the PR job:
a. Get the changed files and changed lines:
changed_files=$(git diff --name-only origin/main...HEAD)
for file in $changed_files; do
if [[ $file == src/main/java/*.java ]]; then
# Get the changed lines for this file
lines=$(git diff -U0 origin/main...HEAD -- $file | grep -E '^@@' | sed -n 's/^.*+\([0-9]*\).*$/\1/p')
# Convert file to class name
class_name=$(echo $file | sed 's|src/main/java/||' | sed 's|/|.|g' | sed 's|\.java$||')
# Store in an associative array: changed_lines[$class_name]="$lines"
fi
done
b. Build the list of changed classes:
changed_classes="${!changed_lines[@]}"
c. Run PIT:
mvn org.pitest:pitest-maven:mutationCoverage \
-DtargetClasses="$changed_classes" \
-DexcludedTests=@flaky-tests.txt \
-DmaxMutationsPerClass=1000 \
-Dthreads=4 \
-DtimeoutConstant=5000 \
-DtimeoutFactor=2
d. Wait for PIT to finish or timeout.
e. Parse the PIT report (assuming it's at `target/pit-reports/*/mutations.xml`):
We can use an XML parser or simple text tools.
For each mutation:
class = <mutatedClass>
line = <line>
status = <status>
if the class is in changed_classes and the line is in changed_lines[$class] and status is not "KILLED", then fail.
f. If we found any surviving mutant in the changed lines, exit with error.
However, note: the changed lines we get from `git diff` are the line numbers in the new code. The mutation report's line number is the line number in the source code (the new code). So they should match.
But what if the change added a line? Then the line number in the new code might be different from the line number in the mutation report? Actually, the mutation report is generated from the new code (the code we are testing). So the line numbers should be the same.
Also, note that a change might delete lines. We are only interested in the lines that are changed (including added lines). For deleted lines, we don't have mutants because the code is gone.
So we only consider the lines that are present in the new code and that were changed (i.e., the lines that are in the diff with a `+`).
This seems reasonable.
But note: if we change a line, then the old line is gone and we have a new line. We are only checking mutants in the new line.
What if we change a line and the new line is the same as the old line? Then it's not a change? Actually, `git diff` will not show it as a change. So we are safe.
Potential issues:
- The PIT report might not have been generated if the job timed out. We can configure PIT to output partial results? Or we can check if the report exists and if not, assume that we didn't run any mutants? Then we fail because we didn't meet the budget? We can set a minimum number of mutants to run? Or we can fail if the report is missing.
- We are setting `maxMutationsPerClass=1000`. If a class has more than 1000 mutants, we will only run 1000. We might miss some. We can set it higher, but then we might exceed the budget. We can also set `maxMutationsPerClass` to a very high number and rely on the timeout.
- The flaky test list might be incomplete. We might have flaky tests that are not in the list. Then we might get false positives (surviving mutants because a flaky test failed to kill). We can try to detect flaky tests in the PR run by running the tests multiple times? That would be too heavy.
Given the above, we might have to accept some false positives and false negatives.
This is a pragmatic approach to start with.
Let's summarize the plan:
Nightly:
- Run full mutation testing (on entire codebase) to get a baseline and to update the flaky test list.
- Store the flaky test list in the repo.
PR:
- Identify changed classes and changed lines.
- Run PIT on the changed classes with a timeout (and with flaky test exclusion).
- Check that all mutants in the changed lines are killed.
- Fail if any surviving mutant in the changed lines.
We can adjust the parameters (timeout, maxMutationsPerClass) based on the size of the change.
This is a concrete plan that we can implement.
Now, let's write the steps in a script (for a Maven project).
However, note: the user might not be using Maven. But the idea is similar for other build systems.
We assume the project uses Maven and PIT.
Steps for PR:
1. Checkout the PR branch and the target branch (main). We assume we are in a CI that has both.
2. Get the changed classes and lines.
3. Run PIT with the configuration.
4. Check the report.
We can write a shell script for steps 2 and 4, and run PIT via Maven.
But note: the PIT run might take a long time and we might want to run it in the background and then check the report after.
Alternatively, we can run PIT and then check the report at the end.
Let's write the script:
#!/bin/bash
# Get the target branch (assuming it's main)
TARGET_BRANCH=origin/main
# Get the list of changed Java files
changed_files=$(git diff --name-only $TARGET_BRANCH...HEAD)
declare -A changed_lines
for file in $changed_files; do
if [[ $file == src/main/java/*.java ]]; then
# Get the class name
class_name=$(echo $file | sed 's|src/main/java/||' | sed 's|/|.|g' | sed 's|\.java$||')
# Get the changed line numbers in the new code
lines=$(git diff -U0 $TARGET_BRANCH...HEAD -- $file | grep -E '^@@' | sed -n 's/^.*+\([0-9]*\).*$/\1/p')
# Store the lines for this class
changed_lines[$class_name]="$lines"
fi
done
# Build the targetClasses string
target_classes=""
for class in "${!changed_lines[@]}"; do
if [ -z "$target_classes" ]; then
target_classes=$class
else
target_classes=$target_classes,$class
fi
done
if [ -z "$target_classes" ]; then
echo "No changed Java files. Skipping mutation testing."
exit 0
fi
echo "Changed classes: $target_classes"
# Run PIT
mvn org.pitest:pitest-maven:mutationCoverage \
-DtargetClasses="$target_classes" \
-DexcludedTests=@flaky-tests.txt \
-DmaxMutationsPerClass=1000 \
-Dthreads=4 \
-DtimeoutConstant=5000 \
-DtimeoutFactor=2
# Check if PIT succeeded and generated the report
if [ ! -d "target/pit-reports" ]; then
echo "PIT did not generate a report. Failing the build."
exit 1
fi
# Find the latest report (there might be multiple if multiple runs)
report_dir=$(ls -t target/pit-reports | head -1)
report_file="target/pit-reports/$report_dir/mutations.xml"
if [ ! -f "$report_file" ]; then
echo "PIT report not found at $report_file. Failing the build."
exit 1
fi
# Parse the XML and check for surviving mutants in changed lines
# We can use xmllint or a Python script.
# For simplicity, let's use a Python script:
python3 - <<EOF
import xml.etree.ElementTree as ET
import sys
# Read the changed classes and lines from the shell script
# We can pass them as environment variables? Or we can read from a file? Or we can pass as arguments.
# Since we are in a heredoc, we can't easily pass the arrays. So let's write the changed lines to a file and read it.
# Alternatively, we can generate a JSON file from the shell script and read it in Python.
# But for simplicity, let's assume we have a file `changed-lines.json` that contains:
# { "com.example.Class1": [10, 20, 30], "com.example.Class2": [5] }
# We'll write that file in the shell script.
# In the shell script, before running PIT, we write the changed_lines array to a JSON file.
# But we are already in the middle of the script. Let's do:
# In the shell script, after building the changed_lines array, we write it to a file.
# Actually, we are in a heredoc for the Python script. We can't go back to the shell.
# So let's restructure: we write the changed lines to a file in the shell, then the Python script reads that file.
# We'll do:
# In the shell script:
# echo "changed_lines = $changed_lines" > changed-lines.sh
# But that's not JSON.
# Alternatively, we can pass the changed_classes and changed_lines as environment variables? But the arrays are big.
# Given the complexity, let's change the plan: we write the changed lines to a file in a simple format:
# class_name:line1,line2,line3
# Then the Python script reads that file.
# In the shell script:
# for class in "${!changed_lines[@]}"; do
# echo "$class:${changed_lines[$class]}" >> changed-lines.txt
# done
# Then in Python:
changed_lines = {}
with open('changed-lines.txt', 'r') as f:
for line in f:
class_name, lines = line.strip().split(':')
changed_lines[class_name] = set(int(l) for l in lines.split(',') if l)
# Now parse the PIT report
tree = ET.parse('$report_file')
root = tree.getroot()
surviving_mutants = []
for mutation in root.findall('.//mutation'):
class_name = mutation.find('mutatedClass').text
line = int(mutation.find('line').text)
status = mutation.find('status').text
if class_name in changed_lines and line in changed_lines[class_name]:
if status != 'KILLED':
surviving_mutants.append((class_name, line, status))
if surviving_mutants:
print("Surviving mutants in changed lines:")
for class_name, line, status in surviving_mutants:
print(f" {class_name}:{line} - {status}")
sys.exit(1)
else:
print("All mutants in changed lines are killed. Good!")
sys.exit(0)
EOF
This is a rough sketch.
However, note: the PIT report might have multiple `<mutation>` elements for the same line? Actually, each mutation is a separate entry, even if they are on the same line? Yes, because different mutation operators.
So we are checking every mutation in the changed lines.
Also, note that the line number in the PIT report is the line number in the source file (the new code). And we have the changed lines from the diff (the new line numbers). So they should match.
But what if the change added a line and then we have a mutant on that line? The diff will show that line as added, and the mutant will be on that line. So it will be in the set.
What if the change deleted a line? Then we don't have that line in the new code, so there won't be a mutant on that line. So we don't check.
What if the change modified a line? Then the old line is gone and the new line is there. We have the new line number in the diff and in the mutant report.
So it should work.
However, note: the diff might show a range of lines changed. We are only taking the first line number after the `+`? Actually, the `git diff -U0` output for a changed block looks like:
@@ -1,0 +1,2 @@
+new line 1
+new line 2
Then our `sed` command will extract the `1` (the starting line of the added block) but not the following lines. We are missing the added lines that are after the first one.
We need to extract all the added line numbers.
Let's adjust:
We can use `git diff -U0` to get the diff with 0 lines of context. Then for each block, we get the starting line of the added block and the number of added lines. Then we can generate all the line numbers in that block.
Alternatively, we can use `git diff --numstat` to get the number of added and deleted lines per file, but not the exact line numbers.
We can use `git diff -U0` and then for each block:
@@ -old_start,old_count +new_start,new_count @@
Then the added lines are from `new_start` to `new_start + new_count - 1`.
But note: the diff might have multiple blocks for the same file.
Let's change the shell script to:
for file in $changed_files; do
if [[ $file == src/main/java/*.java ]]; then
class_name=$(echo $file | sed 's|src/main/java/||' | sed 's|/|.|g' | sed 's|\.java$||')
# Get the diff for this file
diff_output=$(git diff -U0 $TARGET_BRANCH...HEAD -- $file)
# Parse the diff_output for added lines
lines=()
while IFS= read -r line; do
if [[ $line =~ ^@@\ -[0-9]+,[0-9]+\ +([0-9]+),([0-9]+)\ @@ ]]; then
new_start=${BASH_REMATCH[1]}
new_count=${BASH_REMATCH[2]}
for ((i=new_start; i<new_start+new_count; i++)); do
lines+=($i)
done
fi
done <<< "$diff_output"
# Remove duplicates and sort
lines=($(printf "%s\n" "${lines[@]}" | sort -n | uniq))
changed_lines[$class_name]="${lines[*]}"
fi
done
Then we store the lines as a space-separated list? Actually, we are storing as a string with spaces. But in the Python script we split by commas? We changed to comma in the previous version? Let's be consistent.
We can store as a comma-separated list in the file:
echo "$class_name:$(IFS=,; echo "${lines[*]}")" >> changed-lines.txt
Then in Python, we split by commas.
But note: the `lines` array might be empty? Then we don't write.
Also, note: the diff might have multiple blocks for the same file, and we are collecting all the added lines.
This should work.
However, note: the diff might also show line changes as deletions and additions. We are only interested in the added lines (the new code). The deleted lines are not in the new code, so we ignore.
Also, note: the line numbers in the diff are the line numbers in the new file. So they match the source file we are mutation testing.
So the plan is:
- Get the list of changed Java files and the added line numbers in the new code.
- Run PIT on the changed classes.
- Check that every mutant that is on an added line is killed.
This seems solid.
But what about a change that modifies an existing line? That will be shown as a deletion of the old line and an addition of the new line. So the new line is added? Actually, it's a replacement. The diff will show:
-old line
+new line
And the line number for the new line is the same as the old line? Not necessarily. If we change one line, the diff will show:
@@ -10,1 +10,1 @@
-old line
+new line
So the new line is at line 10. So we will include line 10.
So it works.
Now, what about a change that deletes a line? We don't have a new line, so we don't include any line for that deletion. That's acceptable because we are only concerned with the new code.
So the plan is:
We only check mutants in the lines that are new (added) in the PR.
But note: if we change a line, we are treating it as an addition? Actually, the diff shows it as an addition (with a `+`) and the line number is the same as the old line? Or if the change is at the end of the file, the line numbers might shift.
Example:
Original:
line1
line2
line3
Change line2 to "new line2".
Diff:
@@ -1,3 +1,3 @@
line1
-line2
+new line2
line3
The added line is at line 2 (the same as the old line). So we will check line 2.
But what if we add a line at the beginning?
Original:
line1
line2
Add a new line at the beginning:
new line1
line1
line2
Diff:
@@ -1,2 +1,3 @@
+new line1
line1
line2
The added line is at line 1.
So it works.
However, note: if we change multiple lines in a row, the diff might show:
@@ -10,3 +10,3 @@
old line1
-old line2
-old line3
+new line2
+new line3
Then the added lines are at 11 and 12? Actually, the block starts at line 10 (the first line of the block is unchanged? Wait, the diff shows:
The block of lines from old file: starting at line 10, 3 lines (so lines 10,11,12)
The block of lines in new file: starting at line 10, 3 lines (so lines 10,11,12)
But the first line (line 10) is unchanged? Then it's not shown with a `+`. The next two lines are added.
So the added lines are 11 and 12.
Our parsing will get the block (new_start=10, new_count=3) and then we take lines 10,11,12. But line 10 is unchanged? Actually, in the diff, line 10 is not shown with a `+` so it's unchanged. But we are including it because it's in the block.
We are including all lines in the added block, even the unchanged ones? That's not correct.
We need to only include the lines that are actually added (with a `+` in the diff).
How about we parse the diff output line by line and only include the lines that start with `+` (and are not `+++`)? But note that the diff output for a line that is added is:
+added line
And for a line that is unchanged, it's just:
unchanged line
So we can do:
while IFS= read -r line; do
if [[ $line =~ ^\+[^\+] ]]; then
# This line is added (and not the file header)
# We need to get the line number. But the line number is not in this line. We have to keep track of the current line number in the new file.
This is getting complex.
Alternatively, we can use `git diff --numstat` to get the number of added lines per file, but not the line numbers.
Another idea: use `git diff -U0` and then for each block, we know the new_start and new_count, and then we look at the lines in the block and see which ones have a `+` at the beginning.
But note: the diff output for a block:
@@ -10,3 +10,3 @@
line10 (unchanged, no +)
+line11 (added)
+line12 (added)
So we can:
For each block, we have the new_start and new_count. Then we read the next `new_count` lines from the diff output. For each of these lines, if it starts with `+` (and not `+++`), then it's an added line. The line number starts at `new_start` and increments for each line in the block (regardless of whether it's added or not). But we only want the ones that are added.
So we can:
current_line=$new_start
for ((i=0; i<new_count; i++)); do
read -r diff_line
if [[ $diff_line =~ ^\+[^\+] ]]; then
lines+=($current_line)
fi
((current_line++))
done
But note: the block might have fewer lines than `new_count` if the block is the last one and we are at the end of the file? Actually, the diff output will have exactly `new_count` lines for the added block.
Let's try:
We read the diff output line by line. When we see a header (`@@`), we parse the new_start and new_count. Then we read the next `new_count` lines.
But note: the diff output might have multiple headers. We have to read the entire file.
We can do:
while IFS= read -r line; do
if [[ $line =~ ^@@\ -[0-9]+,[0-9]+\ +([0-9]+),([0-9]+)\ @@ ]]; then
new_start=${BASH_REMATCH[1]}
new_count=${BASH_REMATCH[2]}
for ((i=0; i<new_count; i++)); do
read -r content_line
if [[ $content_line =~ ^\+[^\+] ]]; then
lines+=($new_start)
fi
((new_start++))
done
fi
done <<< "$diff_output"
But note: the `read` inside the loop will read from the same stdin? We are using a here-string, so it should be okay.
However, the `read` inside the loop will consume lines from the here-string. We are already reading the entire diff_output in the outer loop. We cannot do that.
We can do:
We split the diff_output by lines and then iterate with an index.
Alternatively, we can use `awk` to parse the diff.
Given the complexity, maybe we use a tool that can give us the added lines with line numbers.
There is a tool called `diff-stat` but it doesn't give line numbers.
Alternatively, we can use `git blame` on the new code to see which lines are new? But that's for the entire file, not just the PR.
Given the time, let's use a simpler approach:
We run:
git diff -U0 $TARGET_BRANCH...HEAD -- $file | grep '^+' | grep -v '^+++' | cat -n
But `cat -n` will number the lines of the output, not the line numbers in the file.
We can use `awk` to parse the diff and output the new line numbers for added lines.
Here's an `awk` script:
git diff -U0 $TARGET_BRANCH...HEAD -- $file | awk '
/^@@/ {
# Parse the header: @@ -old_start,old_count +new_start,new_count @@
match($0, /@@ -[0-9]+,[0-9]+ +([0-9]+),([0-9]+) @@/, arr)
new_start = arr[1]
new_count = arr[2]
line_num = new_start
next
}
/^\+[^\+]/ {
print line_num
line_num++
next
}
/^[^\+]/ {
# This is an unchanged line or a deleted line (starts with -) in the new block? Actually, in the new block, we only see lines that are in the new file. So if it's not added (no + at the beginning) then it's unchanged.
line_num++
next
}
'
This will print the line numbers of the added lines.
Then we can collect these numbers.
Let's adjust the shell script:
for file in $changed_files; do
if [[ $file == src/main/java/*.java ]]; then
class_name=$(echo $file | sed 's|src/main/java/||' | sed 's|/|.|g' | sed 's|\.java$||')
added_lines=$(git diff -U0 $TARGET_BRANCH...HEAD -- $file | awk '
/^@@/ {
match($0, /@@ -[0-9]+,[0-9]+ +([0-9]+),([0-9]+) @@/, arr)
new_start = arr[1]
new_count = arr[2]
line_num = new_start
next
}
/^\+[^\+]/ {
print line_num
line_num++
next
}
/^[^\+]/ {
line_num++
next
}
')
# Remove duplicates and sort
added_lines=($(printf "%s\n" "$added_lines" | sort -n | uniq))
if [ ${#added_lines[@]} -gt 0 ]; then
changed_lines[$class_name]="${added_lines[*]}"
fi
fi
done
This should give us the added line numbers.
Then we write to `changed-lines.txt` as:
for class in "${!changed_lines[@]}"; do
echo "$class:${changed_lines[$class]}" >> changed-lines.txt
done
But note: the `added_lines` array is space-separated, but we want comma-separated? We can change the `sed` in the Python script to split by space? Or we can change the shell to use comma.
Let's change the shell to:
changed_lines[$class_name]="$(IFS=,; echo "${added_lines[*]}")"
Then the file will have:
com.example.Class1:10,11,12
And in Python, we split by commas.
This should work.
Now, we have to be cautious: the line numbers we get from `git diff` are the line numbers in the new file. And the mutation report uses the same line numbers (the source code of the new version).
So we are good.
Let's write the complete PR script:
#!/bin/bash
set -e
TARGET_BRANCH=origin/main
changed_files=$(git diff --name-only $TARGET_BRANCH...HEAD)
declare -A changed_lines
for file in $changed_files; do
if [[ $file == src/main/java/*.java ]]; then
class_name=$(echo $file | sed 's|src/main/java/||' | sed 's|/|.|g' | sed 's|\.java$||')
added_lines=$(git diff -U0 $TARGET_BRANCH...HEAD -- $file | awk '
/^@@/ {
match($0, /@@ -[0-9]+,[0-9]+ +([0-9]+),([0-9]+) @@/, arr)
new_start = arr[1]
new_count = arr[2]
line_num = new_start
next
}
/^\+[^\+]/ {
print line_num
line_num++
next
}
/^[^\+]/ {
line_num++
next
}
')
# Remove duplicates and sort
added_lines=($(printf "%s\n" "$added_lines" | sort -n | uniq))
if [ ${#added_lines[@]} -gt 0 ]; then
changed_lines[$class_name]="$(IFS=,; echo "${added_lines[*]}")"
fi
fi
done
# Write changed-lines.txt
> changed-lines.txt
for class in "${!changed_lines[@]}"; do
echo "$class:${changed_lines[$class]}" >> changed-lines.txt
done
if [ ! -s changed-lines.txt ]; then
echo "No added lines in Java files. Skipping mutation testing."
exit 0
fi
target_classes="$(IFS=,; echo "${!changed_lines[@]}")"
echo "Changed classes: $target_classes"
echo "Changed lines:"
cat changed-lines.txt
# Run PIT
mvn org.pitest:pitest-maven:mutationCoverage \
-DtargetClasses="$target_classes" \
-DexcludedTests=@flaky-tests.txt \
-DmaxMutationsPerClass=1000 \
-Dthreads=4 \
-DtimeoutConstant=5000 \
-DtimeoutFactor=2
# Check the report
# ... (as above)
We have to adjust the Python script to read `changed-lines.txt` and the PIT report.
However, note: the PIT report might be in a subdirectory (with a timestamp). We can use the latest one.
Also, note: the PIT run might fail (non-zero exit) if the mutation score is below the threshold? We don't want to fail the build based on the overall mutation score, only on the surviving mutants in changed lines.
So we should run PIT without the `mutationThreshold` and `coverageThreshold` that would fail the build. We can set them to 0 so that PIT never fails.
We can set:
-DmutationThreshold=0 -DcoverageThreshold=0
Then we parse the report and fail only if we find surviving mutants in changed lines.
Also, note: the PIT run might take too long and we might want to kill it after a certain time. We can set a timeout in the CI job (e.g., 30 minutes). Then if the job times out, we might not have a complete report. We can check for the report and if it's not there, we fail.
But if the job times out, we might have a partial report. We can still check the mutants that were run.
However, the PIT report might be incomplete. We can look for the `mutations.xml` and if it's there, we parse it. If not, we fail.
Given the complexity, we might have to accept that if the job times out, we fail the build because we didn't complete the mutation testing.
Alternatively, we can run PIT with a lower `maxMutationsPerClass` and a higher `threads` to try to finish within the time.
We can also run PIT in the background and then after a timeout, kill it and then check the partial report? But PIT might not write a partial report.
Given the constraints, we set a reasonable timeout and hope that the change is small enough.
We can also adjust the `maxMutationsPerClass` based on the number of changed classes? If there are many changed classes, we might need to lower the per-class limit.
But let's keep it simple: set `maxMutationsPerClass=1000` and `threads=4` and a timeout of 30 minutes.
If the job times out, we fail.
We can also add a check: if the number of changed classes is too high, we might fail early.
For example, if there are more than 50 changed classes, we might skip mutation testing and fail? Or we might run on a subset?
Given the time, we might skip mutation testing for large changes? But then we lose the safety net.
Alternatively, we can run on the first 10 changed classes? That's arbitrary.
Given the complexity, we might have to accept that for large changes, we cannot run mutation testing in the PR budget. Then we might rely on the nightly run.
But the goal is to catch bugs in the PR.
So we have to balance.
We can do:
If the number of changed classes is greater than 10, then we only run on the first 10 (alphabetically?) or on the ones with the most changes? We don't have that information.
Given the time, we might just run on all changed classes and hope that the change is not too big. If it times out, we fail.
We can also run without a per-class limit and let PIT generate as many mutants as it wants, and then we rely on the timeout. But then we might run out of memory or time.
Given the above, we might have to adjust the parameters per project.
Let's assume the project is of moderate size and a typical PR changes a few classes.
We'll set:
maxMutationsPerClass=500
threads=4
And a timeout of 30 minutes.
If the job times out, we fail.
We can also add a note in the failure message: "Mutation testing timed out. Please reduce the number of changed classes or run mutation testing on the main branch."
Now, let's write the complete script for the PR.
We assume:
- The project uses Maven and PIT.
- The flaky test list is in `flaky-tests.txt` at the root of the repo.
We'll write a script `run-pr-mutation-testing.sh`:
#!/bin/bash
set -e
TARGET_BRANCH=${1:-origin/main}
echo "Target branch: $TARGET_BRANCH"
changed_files=$(git diff --name-only $TARGET_BRANCH...HEAD)
declare -A changed_lines
for file in $changed_files; do
if [[ $file == src/main/java/*.java ]]; then
class_name=$(echo $file | sed 's|src/main/java/||' | sed 's|/|.|g' | sed 's|\.java$||')
added_lines=$(git diff -U0 $TARGET_BRANCH...HEAD -- $file | awk '
/^@@/ {
match($0, /@@ -[0-9]+,[0-9]+ +([0-9]+),([0-9]+) @@/, arr)
new_start = arr[1]
new_count = arr[2]
line_num = new_start
next
}
/^\+[^\+]/ {
print line_num
line_num++
next
}
/^[^\+]/ {
line_num++
next
}
')
# Remove duplicates and sort
added_lines=($(printf "%s\n" "$added_lines" | sort -n | uniq))
if [ ${#added_lines[@]} -gt 0 ]; then
changed_lines[$class_name]="$(IFS=,; echo "${added_lines[*]}")"
fi
fi
done
> changed-lines.txt
for class in "${!changed_lines[@]}"; do
echo "$class:${changed_lines[$class]}" >> changed-lines.txt
done
if [ ! -s changed-lines.txt ]; then
echo "No added lines in Java files. Skipping mutation testing."
exit 0
fi
target_classes="$(IFS=,; echo "${!changed_lines[@]}")"
echo "Changed classes: $target_classes"
echo "Changed lines:"
cat changed-lines.txt
# Run PIT
mvn org.pitest:pitest-maven:mutationCoverage \
-DtargetClasses="$target_classes" \
-DexcludedTests=@flaky-tests.txt \
-DmaxMutationsPerClass=500 \
-Dthreads=4 \
-DtimeoutConstant=5000 \
-DtimeoutFactor=2 \
-DmutationThreshold=0 \
-DcoverageThreshold=0
# Check the report
report_dir=$(ls -t target/pit-reports 2>/dev/null | head -1 || true)
if [ -z "$report_dir" ]; then
echo "No PIT report directory found. Failing the build."
exit 1
fi
report_file="target/pit-reports/$report_dir/mutations.xml"
if [ ! -f "$report_file" ]; then
echo "PIT report not found at $report_file. Failing the build."
exit 1
fi
python3 - <<EOF
import xml.etree.ElementTree as ET
import sys
changed_lines = {}
with open('changed-lines.txt', 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
class_name, lines_str = line.split(':', 1)
lines = set(int(l) for l in lines_str.split(',') if l)
changed_lines[class_name] = lines
tree = ET.parse('$report_file')
root = tree.getroot()
surviving_mutants = []
for mutation in root.findall('.//mutation'):
class_name = mutation.find('mutatedClass').text
line = int(mutation.find('line').text)
status = mutation.find('status').text
if class_name in changed_lines and line in changed_lines[class_name]:
if status != 'KILLED':
surviving_mutants.append((class_name, line, status))
if surviving_mutants:
print("Surviving mutants in changed lines:")
for class_name, line, status in surviving_mutants:
print(f" {class_name}:{line} - {status}")
sys.exit(1)
else:
print("All mutants in changed lines are killed. Good!")
sys.exit(0)
EOF
This script should be run in the PR pipeline.
We also need to update the flaky test list periodically. We can do that in the nightly run by running the test suite multiple times and then updating `flaky-tests.txt`.
But note: the flaky test list might be project-specific. We can have a separate job that runs the tests multiple times and updates the list.
For the nightly run, we run full mutation testing (without the changed lines filter) and we can use the same flaky test list.
We can also use the mutation testing run to detect flaky tests: if a test fails only for some mutants, it might be flaky. But that's more complex.
Given the time, we assume we have a separate process to maintain `flaky-tests.txt`.
This is a comprehensive plan.
Let me know if there are any questions.</think>
To implement mutation testing at scale while addressing test budget, flake isolation, perf tuning, and ROI tracking, follow this structured approach:
1. Test Budget Management
Control resource consumption by prioritizing high-impact mutations.
Implementation:
Selective Mutation Sampling:
Use strategic sampling (e.g., Deduplicated Subset Sampling, Prioritized Mutation based on code coverage or change recency).
Stratified Sampling: Run different operator subsets across shards to maximize coverage diversity.
Adaptive Budgeting: Dynamically adjust maxMutationsPerClass based on historical kill rates (high-yield modules get more mutants).
Canary Mutation Testing: Run mutation testing on a small representative subset nightly; full run weekly/monthly.
Feedback Loop: Feed surviving mutants into issue tracker (Jira/GitHub Issues) as “potential bug” tickets for devs to triage.
8. ROI Calculation Formula
ROI = (Bugs_Found × Avg_Bug_Fix_Cost) / (Compute_Cost + Triage_Cost)
Bugs_Found: Surviving mutants confirmed as real bugs.
Avg_Bug_Fix_Cost: Historical avg. time to fix a bug (hours) × dev hourly rate.
Compute_Cost: Cloud/CI costs for mutation runs.
Triage_Cost: Time spent investigating survivors.
Target ROI > 1.5 (i.e., finds 1.50valueper1 spent).
9. Common Pitfalls & Mitigations
Pitfall
Mitigation
Flaky tests drown signal
Aggressive flakiness detection + rerun logic.
Runtime explosion
Strict per-module budgets + early termination.
Low-value mutants dominating
Operator pruning based on historical kill rates.
Survivor fatigue
Auto-triage: classify survivors by type (e.g., ASSERTION_MISSING, CONDITION_OMITTED) and prioritize.
10. Quick Win Checklist
Exclude flaky tests (build a list from historical test runs).
Set maxMutationsPerClass=100 and threads=4 as starting budget.
Run mutation only on PR-changed classes (targetClasses filtering).
Track mutation score and runtime in a spreadsheet for 2 weeks.
Calculate cost per mutant and bugs found/month; adjust operators if ROI < 1.0.
By combining budget controls, flake filtering, parallel execution, and ROI dashboards, you can scale mutation testing without drowning in noise or cost. Start small (one module), instrument heavily, then expand based on data.