Plant bugs for task-bench in Rust, from the mutants cargo-mutants kills #710

Merged
lilleman merged 9 commits from item-526 into main 2026-11-24 03:21:50 +01:00
14 changed files with 439 additions and 40 deletions
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- `task-bench` plants bugs in Rust files too, from the mutants cargo-mutants catches, and tells Haiku the panic message `cargo test` prints.
- `task-bench --tasks shipped-features` benches rebuilding features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of its plan item, and checks the build with the tests that change holds. `--shipped <n>` sets how many it takes, and a feature whose branch landed by fast-forward is passed over.
- `task-bench` plants a Python mutant in a file whose lines end in CRLF, which it could not re-apply before, and a Go mutant there keeps applying.
- This repo documents its own `task-bench` command in the README → Test, with `task-bench-image/Dockerfile`, an image that holds pytest, git and tmux, so each scoring run in `larv-review` benches claude-config and records its figures.
+2 -2
View File
@@ -228,7 +228,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go and Python files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. It passes over a feature whose branch landed by fast-forward. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go, Python and Rust files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. It passes over a feature whose branch landed by fast-forward. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
@@ -278,7 +278,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go and Python files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, Python and Rust files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
- `test_env.py` serves the tests.
- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
+13 -5
View File
@@ -32,11 +32,10 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git,
return scratch
try:
pathlib.Path(scratch, "branch.diff").write_text(diff, encoding="utf-8")
relative = os.path.relpath(scratch, top)
ran = run(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top)
if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED:
return ran if isinstance(ran, Failure) else failed("cargo mutants", ran)
outcomes = {outcome: outcome_lines(pathlib.Path(scratch, "mutants.out", f"{outcome}.txt")) for outcome in CARGO_OUTCOMES}
out = cargo_mutants_out(top, scratch, ["--in-diff", os.path.join(os.path.relpath(scratch, top), "branch.diff")], run, jobs)
if isinstance(out, Failure):
return out
outcomes = {outcome: outcome_lines(out / f"{outcome}.txt") for outcome in CARGO_OUTCOMES}
except OSError as failure:
return Failure(f"could not hand cargo-mutants the diff or read its outcomes in {scratch}: {failure}")
finally:
@@ -45,6 +44,15 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git,
return [f"cargo-mutants: {sum(map(len, outcomes.values()))} mutants on changed lines, {len(uncaught)} not caught.", *uncaught]
def cargo_mutants_out(top: str, scratch: str, arguments: list[str], run: Run, jobs: int) -> pathlib.Path | Failure:
"""Run `cargo mutants <arguments>` in top, and return the `mutants.out` folder it writes. That folder is in scratch, which is a
folder in top."""
ran = run(["cargo", "mutants", *arguments, "--output", os.path.relpath(scratch, top), "--jobs", str(jobs)], top)
if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED:
return ran if isinstance(ran, Failure) else failed("cargo mutants", ran)
return pathlib.Path(scratch, "mutants.out")
class Mutant(typing.NamedTuple):
"""A mutant in Gremlins' report, in the order the report prints them."""
+3 -1
View File
@@ -108,8 +108,10 @@ def median(column: Column, results: list[Result]) -> float | None:
def row(task: str, side: str, results: list[Result]) -> str:
"""A task's row for one side. A `|` in the task's name is escaped, since cargo-mutants names a mutant by its operator, as in
`replace || with &&`, and a bare one would end the cell."""
passed = f"{sum(result.passed for result in results)}/{len(results)}"
return cells([task, side, passed, *("-" if (found := median(column, results)) is None else number(found) for column in COLUMNS)])
return cells([task.replace("|", "\\|"), side, passed, *("-" if (found := median(column, results)) is None else number(found) for column in COLUMNS)])
def change(bugs: list[tuple[list[Result], list[Result]]]) -> str:
+21 -14
View File
@@ -14,13 +14,14 @@ origin's as last fetched, else main or master. Where --base names the head's own
No model judges anything: the bench runs programs, and reads Haiku's own stream.
- Plant. It copies the tree at the base and runs a mutation tool there, over the files that hold the places `larv-review places`
prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, and mutmut 3 over
the Python files, as `mutmut run`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, mutmut 3 over
the Python files, as `mutmut run`, and cargo-mutants over the Rust files, as `cargo mutants`. No other language is planted
in so far. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
them, 5 by default, have become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where,
planted at each side, a test fails and prints a message that says more than the test's name. The bench reads that message
from `go test`'s output for a Go file and from pytest's for a Python file, so --test must run the tests of each language the
places name, with that runner: pytest as it prints by default, or with --tb=short. Any other mutant is passed over, so a
change to the very lines of a bug is not benched. Go and Python are the languages so far.
from `go test`'s output for a Go file, from pytest's for a Python file and from `cargo test`'s for a Rust file, so --test must
run the tests of each language the places name, with that runner: pytest as it prints by default, or with --tb=short, and
`cargo test` without --nocapture. Any other mutant is passed over, so a change to the very lines of a bug is not benched.
- Run. Haiku fixes each bug --runs times at each side, 5 by default, the sides in turn. A fix starts from a copy of that side's
tree with the bug in it, committed once, so git doesn't show which line the bug is on. In the copy, in a container, `claude -p
--strict-mcp-config --disable-slash-commands --no-session-persistence --model claude-haiku-5-5 --effort low` works with every
@@ -28,23 +29,29 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
Claude home is new and empty, so the project's own CLAUDE.md, or AGENTS.md, in the copy is all the setup that loads. Its network
reaches api.anthropic.com and nothing else. A fix ends after 30 minutes.
- Check. The test command runs over the planted tree with each file that is no test as Haiku left it; a fix passes where it exits 0.
A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder.
A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder. A Rust test that
stands in the file of the code it tests is the exception: the bench takes that file whole, so a change to such a test counts.
--image is the project's development image, such as golang:1.27.4. The bench adds Claude Code to it, as its installer installs it,
so the image needs curl and bash; the result names the version. Haiku works in that image. So does --test: sh runs that text at
the copy's top, with no network, so the image must hold what the tests would otherwise download.
--prefix is shell text that runs the mutation tool, on the host, as mutate-changes' --prefix does: sh runs `<prefix> "$@"` with
the tool's command as "$@", such as `gremlins unleash ...` or `mutmut run ...`. Gremlins runs in the copy of the base, and mutmut
in a copy of the folder there that holds its settings; $PWD is the folder the tool runs in. Without --prefix, the bench runs
the `gremlins` or the `mutmut` on the host's PATH. For example, for Go and then for Python:
the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins and
cargo-mutants run in the copy of the base, and mutmut in a copy of the folder there that holds its settings; $PWD is the folder
the tool runs in. Without --prefix, the bench runs the `gremlins`, the `mutmut` or the `cargo` on the host's PATH. For example,
for Go, for Python and then for Rust:
docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \
sh -c 'shift; exec go run github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0 "$@"' sh
uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"
Where the places name files in both languages, the one prefix gets both tools' commands, Gremlins' first, and a tool it
cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins` or `mutmut`:
docker run --rm --memory 16g --memory-swap 16g --user "$(id -u):$(id -g)" -e CARGO_HOME=/tmp/cargo -v "$PWD:$PWD" -w "$PWD" \
rust:1.100.0 sh -c 'cargo install --quiet --locked cargo-mutants@27.1.0 && exec "$@"' sh
Where the places name files in more than one language, the one prefix gets each tool's command, Gremlins' first and
cargo-mutants' last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`, `mutmut` or `cargo`, as here for Go
and Python:
sh -c 'case "$1" in
gremlins) shift; exec docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \
@@ -136,7 +143,7 @@ not, unless a bench or a gather is using it. So gather a bench before the next o
Exit 1, saying why, on an unknown or repeated argument, a missing --image or --test, a --seed, --bugs or --runs that is no whole
number from 1, a --tasks that is none of bugs, features, data-sources and shipped-features, or no token; and where git, docker or a mutation tool
fails, the seats' places don't name any Go or Python file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
fails, the seats' places don't name any Go, Python or Rust file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
features or data-sources it exits 1 on a --seed, --bugs or --prefix; where no config names the checkout or its config sets no
`bench-tasks`, or the folder holds no task of that kind, one that lacks a part, or a `generate-register` that is no executable
file, each before docker runs; and where the tests fail at a side without the acceptance tests, or no task counts.
@@ -342,11 +349,11 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str])
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure:
"""What plans a bench of bugs: of the mutants the tests kill in the Go and Python files of the tree at base that hold a place
"""What plans a bench of bugs: of the mutants the tests kill in the Go, Python and Rust files of the tree at base that hold a place
in places, those --seed draws first become bugs, until --bugs of them have."""
files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()]
if not files:
return Failure("The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug.")
return Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.")
run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg)
mutants = killed_mutants(base, files, run, CPUS_PER_SLOT)
return mutants if isinstance(mutants, Failure) else functools.partial(planted_tasks, mutants=mutants, seed=int(given["--seed"]), bugs=int(given["--bugs"]))
+2 -1
View File
@@ -6,7 +6,7 @@ import re
import typing
from failure import Failure
from task_bench import go_bugs, python_bugs
from task_bench import go_bugs, python_bugs, rust_bugs
from mutate_changes.changed_lines import is_test
from task_bench.planted_mutant import Mutant
from mutate_changes.tool_process import Run
@@ -29,6 +29,7 @@ class Language(typing.NamedTuple):
LANGUAGES = (
Language("Go", (".go",), go_bugs.killed_mutants, go_bugs.task_text),
Language("Python", (".py",), python_bugs.killed_mutants, python_bugs.task_text),
Language("Rust", (".rs",), rust_bugs.killed_mutants, rust_bugs.task_text),
)
+1 -1
View File
@@ -11,7 +11,7 @@ class Mutant(typing.NamedTuple):
"""A mutant the project's tests killed, as the lines it changes in the tree its tool ran in: the number of the first, from 1,
those lines as the tree has them, and what the mutant has in their place. Where it only adds lines, the number is that of the
line they go in before. name is what the report calls the bug it becomes: the path and line, then what the tool tells the
mutant by, which is Gremlins' column and mutator, or mutmut's name."""
mutant by, which is Gremlins' column and mutator, or mutmut's name. cargo-mutants' own name for a mutant holds all of it."""
path: str
line: int
+95
View File
@@ -0,0 +1,95 @@
"""The bugs task-bench plants in Rust: the mutants cargo-mutants reports as caught, each read from the diff it writes, and the message
cargo test prints when a test panics on one."""
import json
import re
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.planted_mutant import Mutant
from mutate_changes.tool_process import remove, Run, scratch_folder
# What cargo-mutants 27.1.0 writes after the code it put in, as in `sum -= /* ~ changed by cargo-mutants ~ */ item;`. A planted
# bug leaves it out, since it would show Haiku the line.
MARK = b" /* ~ changed by cargo-mutants ~ */"
HUNK = re.compile(rb"@@ -(\d+)")
# The heading of what a failed test printed, in cargo test's output: `---- tests::adds stdout ----`.
SECTION = re.compile(r"^---- (\S+) std(?:out|err) ----$")
# The line before a panic's message: `thread 'tests::adds' (3058) panicked at src/lib.rs:21:9:`. An older Rust prints no
# thread id.
PANICKED = re.compile(r"^thread '.*' (?:\(\d+\) )?panicked at .*:$")
# What follows a panic's message: a hint to ask for a backtrace, or the backtrace.
AFTER_MESSAGE = ("note: run with `RUST_BACKTRACE", "stack backtrace:")
# The heading cargo test prints twice: before the first failed test's section, and before the list of the failed tests' names.
FAILED_TESTS = "failures:"
def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure:
"""The mutants in `files` that the tests of the tree at top kill, as cargo-mutants finds them there, each under the name
cargo-mutants gives it. One whose diff holds no change, or more than one hunk, is left out."""
scratch = scratch_folder(top)
if isinstance(scratch, Failure):
return scratch
try:
out = in_diff_tools.cargo_mutants_out(top, scratch, [argument for path in files for argument in ("--file", path)], run, jobs)
if isinstance(out, Failure):
return out
# cargo-mutants writes no outcomes where it finds no mutant, as in a file that holds only types.
outcomes = json.loads(listed.read_bytes())["outcomes"] if (listed := out / "outcomes.json").is_file() else []
# The run of the unmutated tree is an outcome too. Its scenario is the text `Baseline`, which holds no mutant, so the summary is
# checked first.
caught = [(mutant, outcome["diff_path"]) for outcome in outcomes if outcome["summary"] == "CaughtMutant" and (mutant := outcome["scenario"]["Mutant"])["file"] in files]
lines = [(mutant, changed((out / diff).read_bytes())) for mutant, diff in caught]
return [Mutant(mutant["file"], found[0], mutant["name"], found[1], found[2]) for mutant, found in lines if found]
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"could not read cargo-mutants' outcomes in {scratch}: {failure}")
finally:
remove(scratch)
def changed(diff: bytes) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None:
"""The lines a mutant changes, from the diff cargo-mutants writes for it: the number of the first, from 1, those lines as the
tree has them, and what the mutant has in their place, without MARK. An unchanged line between two changed ones is in both.
None where the diff holds no change, or more than one hunk."""
header, *hunks = HUNK.split(diff)
if len(hunks) != 2:
return None
# A line that starts with a backslash says the file ends without a line end.
body = [line for line in hunks[1].split(b"\n")[1:] if not line.startswith(b"\\")]
at = [index for index, line in enumerate(body) if line[:1] in (b"-", b"+")]
if not at:
return None
# Each line before the first changed one is a line of the tree.
first = int(hunks[0]) + at[0]
span = body[at[0]:at[-1] + 1]
was = tuple(line[1:] for line in span if not line.startswith(b"+"))
now = tuple(line[1:].replace(MARK, b"") for line in span if not line.startswith(b"-"))
return first, was, now
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the message of the first panic in a failed test's section of cargo test's output,
without the test's name or the file and line that panicked, so it says what goes wrong and not where.
None where no failed test's section holds a panic with a message, as on a passing run or a build that broke, or where the
message only names the test."""
test, within = "", False
message: list[str] = []
for line in output.splitlines():
heading = SECTION.match(line)
if message and (heading or line == FAILED_TESTS):
break
if heading:
test, within = heading[1], False
elif line == FAILED_TESTS:
test, within = "", False
elif test and not message and PANICKED.match(line):
within = True
elif within and line.startswith(AFTER_MESSAGE):
within = False
elif within:
message.append(line.strip())
# A test in a module has the module's name before its own, as `tests::adds`; a message may name the whole or the test alone. A Rust test's own
# name is often a plain word, such as `big`, so a longer identifier that holds it, such as `is_big`, doesn't name the test.
names = [re.compile(rf"(?<!\w){re.escape(name)}(?!\w)") for name in {test, test.rpartition("::")[2]}]
kept = [text for text in message if text and not any(name.search(text) for name in names)]
return "\n".join(kept) or None
+5
View File
@@ -85,6 +85,11 @@ def run(task: int, side: str, number: int, passed: bool, input_: int = 100, turn
class TableTest(unittest.TestCase):
def test_escapes_a_bar_in_a_tasks_name_so_its_row_keeps_the_headings_cells(self):
rows = table([run(1, "base", 1, True, input_=100, turns=10, seconds=60, reads=3)], {1: "src/pick.rs:7:20: replace || with && in keep"}, "bug")
self.assertTrue(rows[2].startswith(r"| 1: src/pick.rs:7:20: replace \|\| with && in keep | base | 1/1 |"))
self.assertEqual(rows[2].replace(r"\|", "").count("|"), rows[0].count("|"))
def test_prints_a_row_per_task_and_side_with_the_pass_count_and_each_median_then_all_tasks_and_the_heads_change(self):
results = [
run(1, "base", 1, True, input_=100, turns=10, seconds=60, reads=3),
+3 -2
View File
@@ -84,10 +84,11 @@ class LanguagesTest(unittest.TestCase):
class ShippedLanguagesTest(unittest.TestCase):
def test_go_reads_go_tests_output_and_python_pytests(self):
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("Python", (".py",))])
def test_each_language_reads_its_own_test_runners_output(self):
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("Python", (".py",)), ("Rust", (".rs",))])
self.assertEqual(task_text("calc.go", "--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3, want 4\nFAIL\n"), "got 3, want 4")
self.assertEqual(task_text("calc.py", "==== FAILURES ====\n___ test_pick ___\nE assert 3 == 4\n"), "assert 3 == 4")
self.assertEqual(task_text("calc.rs", "---- picks stdout ----\nthread 'picks' (7) panicked at src/calc.rs:9:5:\ngot 3, want 4\n"), "got 3, want 4")
if __name__ == "__main__":
+269
View File
@@ -0,0 +1,269 @@
"""task-bench's Rust planter: which files cargo-mutants mutates, how its diffs become mutants and what cargo test's output tells Haiku.
PICK's two diffs, ASSERTION and TWO_FAILED are what cargo-mutants 27.1.0 and Rust 1.100.0 wrote for a small project, and OUTCOMES
holds the keys the planter reads of that run's outcomes. The other diffs and outputs are made up in the same form."""
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.rust_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
PICK = b"""pub fn first(items: &[i32]) -> Option<i32> {
if items.is_empty() {
return None;
}
Some(items[0])
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum
}
"""
OPERATOR_DIFF = b"""--- src/pick.rs
+++ replace += with -= in total
@@ -3,12 +3,12 @@
return None;
}
Some(items[0])
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
- sum += item;
+ sum -= /* ~ changed by cargo-mutants ~ */ item;
}
sum
}
"""
BODY_DIFF = b"""--- src/pick.rs
+++ replace first -> Option<i32> with None
@@ -1,13 +1,10 @@
pub fn first(items: &[i32]) -> Option<i32> {
- if items.is_empty() {
- return None;
- }
- Some(items[0])
+ None /* ~ changed by cargo-mutants ~ */
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum
"""
# cargo test's report of a test in the code's own file whose assertion failed.
ASSERTION = """running 2 tests
test tests::adds ... FAILED
test tests::big ... ok
failures:
---- tests::adds stdout ----
thread 'tests::adds' (3058) panicked at src/lib.rs:21:9:
assertion `left == right` failed
left: 0
right: 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::adds
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `-p calc --lib`
"""
# Two failed tests: one that panicked with its own message, and one that unwrapped an error.
TWO_FAILED = """running 3 tests
test first_of_some ... ok
test totals ... FAILED
test unwraps ... FAILED
failures:
---- totals stdout ----
thread 'totals' (5813) panicked at tests/picks.rs:13:9:
total of 1, 2, 3 is -6, want 6
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
---- unwraps stdout ----
thread 'unwraps' (5814) panicked at tests/picks.rs:20:7:
called `Result::unwrap()` on an `Err` value: "bad total"
failures:
totals
unwraps
test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
"""
PASSING = """running 1 test
test totals ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
"""
def section(test: str, *lines: str) -> str:
return "\n".join(["failures:", "", f"---- {test} stdout ----", *lines, "", "", "failures:", f" {test}", ""])
class ChangedTest(unittest.TestCase):
def test_is_the_line_an_operator_mutant_changes_without_cargo_mutants_mark(self):
self.assertEqual(changed(OPERATOR_DIFF), (11, (b" sum += item;",), (b" sum -= item;",)))
def test_is_every_line_a_replaced_body_spans(self):
was = (b" if items.is_empty() {", b" return None;", b" }", b" Some(items[0])")
self.assertEqual(changed(BODY_DIFF), (2, was, (b" None",)))
def test_the_tree_with_the_mutant_applied_is_the_code_cargo_mutants_tested_without_its_mark(self):
for diff, line in ((OPERATOR_DIFF, b" sum -= item;"), (BODY_DIFF, b" None")):
with self.subTest(line=line):
line_number, was, now = changed(diff)
planted = mutated(PICK, Mutant("src/pick.rs", line_number, "a name", was, now))
self.assertIn(line, planted.split(b"\n"))
self.assertNotIn(b"cargo-mutants", planted)
def test_keeps_an_unchanged_line_between_two_changed_ones_on_both_sides(self):
diff = b"--- a.rs\n+++ a name\n@@ -4,5 +4,4 @@\n fn f() {\n- a\n b\n- c\n+ d /* ~ changed by cargo-mutants ~ */\n }\n"
self.assertEqual(changed(diff), (5, (b" a", b" b", b" c"), (b" b", b" d")))
def test_a_mutant_that_only_removes_lines_has_no_line_in_their_place(self):
diff = b"--- a.rs\n+++ a name\n@@ -4,3 +4,2 @@\n fn f() {\n- a\n }\n"
self.assertEqual(changed(diff), (5, (b" a",), ()))
def test_skips_the_line_that_says_the_file_ends_without_a_line_end(self):
diff = b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n fn f() {\n-a }\n\\ No newline at end of file\n+b /* ~ changed by cargo-mutants ~ */ }\n\\ No newline at end of file\n"
self.assertEqual(changed(diff), (2, (b"a }",), (b"b }",)))
def test_is_none_for_a_diff_of_no_change_or_of_more_than_one_hunk(self):
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n"))
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n a\n b\n"))
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n a\n-b\n+c\n@@ -9,2 +9,2 @@\n a\n-b\n+c\n"))
class TaskTextTest(unittest.TestCase):
def test_is_the_failed_tests_panic_message_without_the_tests_name_file_or_line(self):
self.assertEqual(task_text(ASSERTION), "assertion `left == right` failed\nleft: 0\nright: 3")
def test_takes_the_first_failed_test_that_has_a_message(self):
self.assertEqual(task_text(TWO_FAILED), "total of 1, 2, 3 is -6, want 6")
self.assertEqual(task_text(TWO_FAILED.replace("total of 1, 2, 3 is -6, want 6\n", "")), 'called `Result::unwrap()` on an `Err` value: "bad total"')
def test_a_message_ends_at_the_next_tests_section_where_no_note_follows_it(self):
self.assertEqual(task_text(TWO_FAILED.replace("note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n", "")), "total of 1, 2, 3 is -6, want 6")
def test_takes_the_panic_not_what_the_test_printed_before_it(self):
output = section("totals", "summing 3 items", "", "thread 'totals' (7) panicked at tests/picks.rs:13:9:", "got -6, want 6")
self.assertEqual(task_text(output), "got -6, want 6")
def test_tells_a_panic_in_the_code_under_test(self):
output = section("first_of_none", "", "thread 'first_of_none' (7) panicked at src/pick.rs:5:10:", "index out of bounds: the len is 0 but the index is 0")
self.assertEqual(task_text(output), "index out of bounds: the len is 0 but the index is 0")
def test_leaves_out_each_line_that_names_the_test(self):
output = section("tests::adds", "", "thread 'tests::adds' (7) panicked at src/lib.rs:21:9:", "adds: got 0", "want 3")
self.assertEqual(task_text(output), "want 3")
self.assertEqual(task_text(output.replace("adds: got 0", "tests::adds broke")), "want 3")
self.assertEqual(task_text(output.replace("tests::adds", "pick::tests::adds")), "want 3")
def test_a_message_may_hold_the_tests_name_inside_a_longer_identifier(self):
output = section("tests::big", "", "thread 'tests::big' (7) panicked at src/lib.rs:27:9:", "assertion failed: !is_big(10)")
self.assertEqual(task_text(output), "assertion failed: !is_big(10)")
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text(section("totals", "", "thread 'totals' (7) panicked at tests/picks.rs:13:9:", "totals failed")))
def test_is_none_where_no_test_panicked_as_on_a_passing_run_or_a_build_that_broke(self):
self.assertIsNone(task_text(PASSING))
self.assertIsNone(task_text("error[E0308]: mismatched types\n --> src/lib.rs:4:5\nerror: could not compile `calc` (lib) due to 1 previous error\n"))
self.assertIsNone(task_text(""))
def test_a_panic_outside_a_failed_tests_section_is_no_message(self):
after_the_list = section("totals", "summing 3 items") + "thread 'main' (7) panicked at src/main.rs:2:5:\nno arguments\n"
self.assertIsNone(task_text(after_the_list))
self.assertIsNone(task_text("thread 'main' (7) panicked at src/main.rs:2:5:\nno arguments\n"))
class KilledMutantsTest(unittest.TestCase):
OUTCOMES = {"outcomes": [
{"scenario": "Baseline", "summary": "Success"},
{"scenario": {"Mutant": {"name": "src/pick.rs:11:13: replace += with -= in total", "file": "src/pick.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/operator.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:2:5: replace first -> Option<i32> with None", "file": "src/pick.rs"}}, "summary": "MissedMutant", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:9:5: replace total -> i32 with 0", "file": "src/pick.rs"}}, "summary": "Timeout", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/lib.rs:2:5: replace first -> Option<i32> with None", "file": "src/lib.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:1:1: a mutant whose diff holds no change", "file": "src/pick.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/empty.diff"},
]}
DIFFS = {"operator.diff": OPERATOR_DIFF, "body.diff": BODY_DIFF, "empty.diff": b"--- src/pick.rs\n+++ a name\n"}
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = folder.name
self.ran: list[tuple[list[str], str]] = []
def cargo_mutants(self, outcomes: object, code: int = 0, diffs: dict[str, bytes] = DIFFS):
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd))
out = pathlib.Path(cwd, argv[argv.index("--output") + 1], "mutants.out")
(out / "diff").mkdir(parents=True)
for name, diff in diffs.items():
(out / "diff" / name).write_bytes(diff)
if outcomes is not None:
(out / "outcomes.json").write_text(json.dumps(outcomes))
return Ran(code, "cargo-mutants said so")
return run
def test_runs_cargo_mutants_at_the_top_over_the_files_asked_for(self):
killed_mutants(self.top, ["src/pick.rs", "src/lib.rs"], self.cargo_mutants({"outcomes": []}), 3)
argv, cwd = self.ran[0]
self.assertEqual(cwd, self.top)
self.assertEqual(argv[:6], ["cargo", "mutants", "--file", "src/pick.rs", "--file", "src/lib.rs"])
self.assertEqual((argv[6], argv[8:]), ("--output", ["--jobs", "3"]))
def test_keeps_the_caught_mutants_of_the_files_asked_for_as_the_lines_each_changes_under_cargo_mutants_name(self):
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES, code=2), 3)
self.assertEqual(found, [Mutant("src/pick.rs", 11, "src/pick.rs:11:13: replace += with -= in total", (b" sum += item;",), (b" sum -= item;",))])
def test_removes_its_scratch_folder(self):
killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES), 3)
self.assertEqual(list(pathlib.Path(self.top).iterdir()), [])
def test_a_cargo_mutants_that_does_not_finish_is_a_failure_with_what_it_printed(self):
# 4 is its exit code where the tests fail before any mutant.
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES, code=4), 3)
self.assertIsInstance(found, Failure)
self.assertIn("cargo-mutants said so", found.reason)
def test_outcomes_or_a_diff_that_cannot_be_read_are_a_failure_that_names_the_folder(self):
for outcomes, diffs in (({"outcomes": [{"summary": "CaughtMutant"}]}, self.DIFFS), ("no outcomes", self.DIFFS), (self.OUTCOMES, {})):
with self.subTest(outcomes=outcomes, diffs=diffs):
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(outcomes, diffs=diffs), 3)
self.assertIsInstance(found, Failure)
self.assertIn(f"could not read cargo-mutants' outcomes in {self.top}", found.reason)
def test_finds_no_mutant_where_cargo_mutants_wrote_no_outcomes_as_it_does_where_it_finds_none(self):
self.assertEqual(killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(None), 3), [])
self.assertEqual(list(pathlib.Path(self.top).iterdir()), [])
if __name__ == "__main__":
unittest.main()
+3 -3
View File
@@ -236,7 +236,7 @@ class BenchTest(unittest.TestCase):
def test_the_command_line_fails_with_the_reason_where_the_places_or_the_bench_fail(self):
argv = [part for name, value in self.given.items() for part in (name, value)]
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug.\n")):
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.\n")):
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as errors:
self.assertEqual(main.main(argv, self.env, lambda home: places), 1)
self.assertEqual((out.getvalue(), errors.getvalue().splitlines(keepends=True)[-1]), ("", said))
@@ -306,10 +306,10 @@ class BenchTest(unittest.TestCase):
self.assertEqual(report[0], f"task-bench: base {self.head[:12]}, head {self.head[:12]}. 1 bug, each run 1 time at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
self.assertEqual(report[4:6], ["| 1: calc.go:5:11 ARITHMETIC_BASE | base | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |", "| 1: calc.go:5:11 ARITHMETIC_BASE | head | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |"])
def test_fails_where_the_places_name_no_go_or_python_file_of_the_base(self):
def test_fails_where_the_places_name_no_file_of_the_base_in_a_language_the_bench_plants_in(self):
with contextlib.redirect_stderr(io.StringIO()):
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home)
self.assertEqual(found, Failure("The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug."))
self.assertEqual(found, Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug."))
self.assertFalse(self.log.exists())
def test_fails_where_the_tests_fail_without_a_bug(self):
+12
View File
@@ -3558,3 +3558,15 @@ Read most (opens and searches):
- `README.md` 1
- `bin/task_bench/python_bugs.py` 1
- `bin/task_bench/test_planted_mutant.py` 1
## Reading cost, chunk be78ef577b52, finished 2026-11-24T01:07:00Z
102199 new input tokens before the first commit.
Read most (opens and searches):
- `bin/task_bench/feature_tasks.py` 3
- `bin/task_bench/main.py` 2
- `bin/task_bench/registers.py` 1
- `bin/task_bench/runs.py` 1
- `bin/task_bench/tasks.py` 1
+9 -11
View File
@@ -6,7 +6,7 @@
`Bar = 0.1`
`Next ID = 532`
`Next ID = 533`
## Renamed
@@ -18,7 +18,7 @@
|---|---|---|---|---|---|---|---|---|---|---|---|
| 531 | 0.16.0 | | | **Bench the shipped features of a branch that landed by fast-forward: take as the feature the commits from the one after the item finished before it, up to the commit that took its item out of the plan.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 3 | 1.1 |
| 524 | 0.16.0 | | owner | **Write fejkdata's first six bench features, each a spec, acceptance tests in Go and a reference patch that builds it, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 6 | 1.1 by 3 | 0.5 |
| 526 | 0.16.0 | | owner | **Plant bugs for `task-bench` in Rust, from the mutants cargo-mutants kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 532 | 0.16.0 | | | **Leave out of a `task-bench` fix a change Haiku makes to a Rust test that stands in the file of the code it tests.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 1 | 0.4 |
| 527 | 0.16.0 | | owner | **Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 528 | 0.16.0 | | owner | **Plant bugs for `task-bench` in PHP, from the mutants Infection kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 525 | 0.16.0 | | owner | **Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 7 | 1.1 by 3 | 0.3 |
@@ -138,18 +138,16 @@ The second part of item 504, which says what a bench feature is and when a run c
Done when `task-bench` counts a run of each: its acceptance tests fail at fejkdata's base and head and pass with its reference patch. The six land in fejkdata's checkout or its config folder, wherever its `bench-tasks` setting points, so the item changes no file of this repo and carries no `Touches:` list. About 1,000 lines of Go and specs.
### 526. Plant bugs for `task-bench` in Rust, from the mutants cargo-mutants kills.
### 532. Leave out of a `task-bench` fix a change Haiku makes to a Rust test that stands in the file of the code it tests.
cargo-mutants runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from the diffs it writes under `mutants.out`. Tell Haiku the failure `cargo test` prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no Rust.
Today the check takes each file that is no test as Haiku left it, and `is_test` tells a test by its file's path. Rust keeps unit tests in the source file, in a `#[cfg(test)]` module, so a fix that edits or deletes the failing test there passes. The help's Check paragraph says so. It holds at the base and at the head alike, so the head's change against the base still compares like with like; the Passed column of a Rust bench counts such a run as a fix.
Recommended: keep each `#[cfg(test)]` module of a Rust file as the planted tree has it, and take the rest of the file from Haiku's copy; where the module cannot be told apart, pass the mutant over. Passing over every mutant that a test in a source file kills would leave most Rust bugs out, since unit tests are where most Rust tests stand. A product-owner finding on item 526's chunk raised this.
Touches:
- `bin/task_bench/rust_bugs.py`
- `bin/task_bench/test_rust_bugs.py`
- `bin/task_bench/plant.py`: `LANGUAGES`
- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest`
- `bin/mutate_changes/in_diff_tools.py`: `run_cargo_mutants`
- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner`
- `README.md`: lines 231-231, lines 281-281
- `bin/task_bench/runs.py`: `checked_tree`, `of_tests` (small)
- `bin/task_bench/test_task_bench.py`
- `bin/task_bench/main.py`: lines 30-33
### 527. Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills.