diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b0b1f8c..e09e0ce3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ` 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. diff --git a/README.md b/README.md index 02eb8079..2124de54 100644 --- a/README.md +++ b/README.md @@ -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] ` 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 --test []` 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 --test []` 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 ` one item's row and detail; `add …` files an item under the next free ID, `edit …` sets an item's cells or detail, and `move --release ` sets an item's release; `finish ` 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 ...` 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 [] [--timeout ]` 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. diff --git a/bin/mutate_changes/in_diff_tools.py b/bin/mutate_changes/in_diff_tools.py index 68d1d7c1..e8d198f6 100644 --- a/bin/mutate_changes/in_diff_tools.py +++ b/bin/mutate_changes/in_diff_tools.py @@ -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 ` 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.""" diff --git a/bin/task_bench/figures.py b/bin/task_bench/figures.py index 53300c1a..04a01ccb 100644 --- a/bin/task_bench/figures.py +++ b/bin/task_bench/figures.py @@ -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: diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index fc66729b..17579781 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -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 ` "$@"` 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"])) diff --git a/bin/task_bench/plant.py b/bin/task_bench/plant.py index 7595268d..52c0400b 100644 --- a/bin/task_bench/plant.py +++ b/bin/task_bench/plant.py @@ -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), ) diff --git a/bin/task_bench/planted_mutant.py b/bin/task_bench/planted_mutant.py index 6ff0d6ae..ba6f31f8 100644 --- a/bin/task_bench/planted_mutant.py +++ b/bin/task_bench/planted_mutant.py @@ -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 diff --git a/bin/task_bench/rust_bugs.py b/bin/task_bench/rust_bugs.py new file mode 100644 index 00000000..6a1a6cd1 --- /dev/null +++ b/bin/task_bench/rust_bugs.py @@ -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"(? Option { + 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 with None +@@ -1,13 +1,10 @@ + pub fn first(items: &[i32]) -> Option { +- 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 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 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() diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index e7b10f92..c40d6ee7 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -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): diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 3df0d017..f2efc71c 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -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 diff --git a/todo.md b/todo.md index 5819ddde..4bca87e6 100644 --- a/todo.md +++ b/todo.md @@ -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.