Files
claude-config/bin/task_bench/main.py
T

689 lines
43 KiB
Python

r"""Measure how hard a project's code is to fix a bug in, or to build a feature in, at a base commit and at a head: plant bugs its
tests catch, have Haiku fix each several times at both, and print how often the fix passes and what it took. With --tasks features,
Haiku builds the project's bench features instead, with --tasks data-sources it adds made-up data sources, and with --tasks
shipped-features it rebuilds features the project shipped.
usage: task-bench --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--prefix <shell text>] [--seed <n>] [--bugs <n>] [--runs <n>] [--record-figures]
task-bench --tasks features|data-sources --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--runs <n>] [--record-figures]
task-bench --tasks shipped-features --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--shipped <n>] [--runs <n>] [--record-figures]
task-bench gather
Run it in a checkout, under ~/.claude/bin/run-heavy, with a long-lived token in CLAUDE_CODE_OAUTH_TOKEN, which `claude setup-token`
prints. The head is --head, by default HEAD. The base is the merge base of the head and --base, by default the default branch:
origin's as last fetched, else main or master. Where --base names the head's own commit, the bench runs the head against itself.
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`, Infection over the
PHP files, as `vendor/bin/infection`, mutmut 3 over the Python files, as `mutmut run`, cargo-mutants over the Rust files, as
`cargo mutants`, and Stryker over the TypeScript and JavaScript files, as `npx --no --package=@stryker-mutator/core stryker
run`, which runs the Stryker the project installs and downloads none. No other language is planted in so far. Infection and
Stryker each run at the top of a copy of that tree, with the project's config for the tool there, and the copy is removed
with all the tool wrote. Stryker's json reporter must write where it does by default, `reports/mutation/mutation.json`.
The bench 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, from PHPUnit's for a PHP file, from pytest's for a Python file, from `cargo test`'s for a Rust file and from
`node --test`'s for a TypeScript or JavaScript file. So --test must run the tests of each language the places name, with
that runner: PHPUnit as it prints by default, pytest as it prints by default or with --tb=short, `cargo test` without
--nocapture, and `node --test --test-reporter=spec`. 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
tool. It is told the message the failing test printed at that side, without the test's name, file or line. The container's
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. The bench
tells a test by its path: a folder named `test`, `tests` or `__tests__`, or a file named `test_*.py`, `*_test.py`,
`*_test.go`, `*.test.*` or `*.spec.*`. A test of any other name counts as code, such as `src/PickTest.php` or
`src/pick-test.js`, so Haiku's change to it stands. In a Rust file, each
inline `#[cfg(test)]` module stands as the planted file has it, and the rest is as Haiku left it. Where the planted file has such
modules and Haiku's file lacks one of them, or its modules cannot be told apart, the planted file stands whole; where the planted
file has none, or its modules cannot be told apart, Haiku's stands. A Rust mutant whose file's modules cannot be told apart, as where two share a name or a brace, string or comment
is never closed, is passed over. A Rust test in a file of its own, as `#[cfg(test)] mod tests;` names, counts, since the bench
tells no such file from code.
--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 ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins and cargo-mutants
run in the copy of the base, Infection and Stryker in a copy of that copy, and mutmut in a copy of the folder there that holds
its settings; $PWD is the folder the tool runs in. That folder holds the files git tracks and no others, so for Infection and
Stryker the prefix first installs the project's dependencies there, as `composer install` and `npm ci` do. Infection also
needs PHP with a coverage driver, pcov or Xdebug. Without --prefix, the bench runs the `gremlins`, the `mutmut`, the `cargo`
or the `npx` on the host's PATH, or the tree's own `vendor/bin/infection`, which only a project that tracks `vendor` has.
For example, for Go, for Python, for Rust and then for TypeScript:
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"
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
docker run --rm --memory 16g --memory-swap 16g --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD:$PWD" -w "$PWD" \
node:24.19.0-alpine3.24 sh -c 'npm ci --silent && exec "$@"' sh
Where the places name files in more than one language, the one prefix gets each tool's command, Gremlins' first and
Stryker's last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`,
`vendor/bin/infection`, `mutmut`, `cargo` or `npx`, 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 \
go run github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0 "$@" ;;
*) exec uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4" "$@" ;;
esac' sh
--tasks features benches features instead of bugs; --tasks bugs is the default. The features are the folders in the folder the
project's config names as `bench-tasks`, in the order of their names. Each holds:
- `spec.md`, all that Haiku is told of the feature;
- `reference.patch`, a patch `git apply` takes at the tree's top, which builds the feature;
- `acceptance`, a folder of tests Haiku never sees, each at the path it takes from the tree's top. The test command must run them.
A feature counts where, at the base and at the head, the test command fails with the acceptance tests in the tree, and passes
once the reference patch is applied too. The bench passes over any other feature, and the report says which and why. Haiku
works in a copy of the side's tree without the `bench-tasks` folder. A build passes where the test command exits 0 over the
side's tree with each file that is no test as Haiku left it, a Rust file's test modules included, and the acceptance tests put
over that. The reference patch is
checked the same way, so a test or a `testdata` file it adds doesn't count either. Keep the folder where the project's own test
command doesn't find the acceptance tests, which fail by design: outside the checkout, or in a folder the test runner skips, as Go
skips `testdata`. The table then has a row per feature and side, and `-` for the reads. No mutation tool
runs, so --seed, --bugs and --prefix don't go with it.
--tasks data-sources benches adding a data source, for a project that imports what others publish. Each task is a folder in
`bench-tasks` that holds a feature's three parts and `generate-register`, an executable script; --tasks features leaves such
a folder out. Before Haiku starts, the bench runs the script at the top of a copy of each side's tree, in the image with no
network, and the files it adds are the register: a made-up dataset in the format a real publisher would use. The container
holds that tree and the script alone, so the script can't read another file of the task's folder. Seed the script, so that it
writes the same bytes at both sides. The bench passes over a task whose script doesn't exit 0, as where the image lacks its
interpreter, runs for 30 minutes, adds no file, adds a link or anything else that is no regular file, writes a `.git`, or
writes one register at the base and another at the head; the report says which, with the last line a failing script printed.
`spec.md` tells Haiku where the register is and what to add: say, the importer, the data it imports and the licence entry. The
reference patch adds them, and the acceptance tests check them, as by running the importer again and comparing what it writes
with the committed data. A task counts, and a run passes, as for a feature; the tree that is checked holds the register as
Haiku left it. Name the made-up publisher's country by a code no real data could carry: one ISO 3166-1 leaves to its users,
such as QZ, and never XK, which is Kosovo's in practice. The table has a row per data source and side.
--tasks shipped-features benches rebuilding features the project shipped, so nobody writes a task. A shipped feature is a chunk
on the base's first-parent history that took an item out of `todo.md`. A chunk is a merge commit with what it merged, or the
commits a rebase landed together, which share a commit time. A chunk with a commit whose title opens `Drop item <ID>:` took
that item out unbuilt, so it didn't ship it. Commits fast-forwarded onto the branch keep a commit time each, so each is a chunk
of its own, and the chunk that took the item out holds only the feature's last commit. The feature then starts after the latest
earlier chunk that took an item out or landed by a merge or a rebase. A commit between two features that belongs to neither
joins the later one; it counts only where its tests fail after the revert and pass with the reference patch, as for any feature.
A fast-forwarded feature is passed over where no such chunk comes before it, and where its branch merged the default branch into
itself, since its commits then hold the changes of the features that merge brought in. A merge titled
`Merge remote-tracking branch '...' into <branch>` is read as that, whatever the branch. The bench goes through the shipped
features newest first, until --shipped of them, 5 by default, count. For each:
- it takes the feature's change out of a copy of each side's tree, as `git apply -R` does. The plan and the project's records stay
as the side holds them, since later chunks added to them. The records are the changelog, the comprehension history, the
decisions, the reading cost and the score anchors. So Haiku can read there what the changelog says of the feature;
- Haiku is told the tagline of the item, or of each item the chunk shipped;
- the acceptance tests are the test files the change touched, and its files under a `testdata` folder, each as the head holds it;
- the reference patch is the change itself.
With those, a shipped feature counts, and a build passes, as for a feature. The bench also passes over two kinds:
- one whose change doesn't come out of both trees cleanly, as where a later chunk rewrote its lines;
- one whose change touched no test the head still holds.
The report says which and why. The table has a row per shipped feature and side, named by its items, as `item 7`.
The project's config must name the checkout, with the plan at `todo.md`, the comprehension history at
`docs/comprehension-history.md` and the reading cost at `docs/reading-cost.md`. --seed, --bugs and --prefix don't go with
--tasks shipped-features, and --shipped goes with no other kind.
It prints the base and the head, then a table: a row per bug and side with how many fixes passed and the medians, over the runs
that finished, of the input, cache-write, cache-read and output tokens, the turns, the wall time, and the reads and searches before
the run first opened the file the bug is in. The median of the reads leaves out a run that never opened that file. Then come a row
per side over every bug, and the head's change against the base. That last row holds the pass count's difference and, for each other
column, the mean over the bugs of each bug's own change, so it isn't the difference of the two rows above it. The last line names
the bench's folder: `task-bench` in the chunk's review folder.
That folder holds each run's result and stream, and digest.md, which says why runs failed in a few kilobytes per bug:
- the table;
- per bug its decoys, the files more than half of its failing runs read that the bug isn't in; per feature its spec instead;
- per bug up to two traces: of a failing run, one that didn't finish or else the one that spent the most tokens, and of the
passing run with the median tokens. A trace has a line per tool call, such as `Read pick.go:120-180` or `Grep "readName" → 4
hits`, and the first 3 lines of what Haiku wrote between calls.
Read a change against the noise. Measured on `fejkdata`, a Go project, with the defaults, a bench of a commit against itself shows,
in 19 cases of 20, an All change under 12% in output tokens, 16% in cache-read tokens and 10% in wall time. On its bugs every run
passed, so the pass rate's noise is unmeasured.
`docs/decisions.md` → `task-bench: a bench takes` has the figures.
With --record-figures, a bench that finishes appends its figures to the project's comprehension history: an entry with the
table's header and its three All rows. The entry's heading gives the current UTC time, then `task-bench of <branch>: head
<commit> against base <commit>`, where <branch> is the branch checked out, whatever --head names. For a bench of
features the heading reads `task-bench features of <branch>: ...` instead, for one of data sources `task-bench data-sources
of <branch>: ...`, and for one of shipped features `task-bench shipped-features of <branch>: ...`. No tool reads the entry as a ruling or a scoring run. The bench's last line says where the entry went. A bench that fails or stops doesn't record anything.
`task-bench gather`, run in the same checkout, turns the digest into plan items. It starts a claude on the project's rung, the
cheapest rung of the model loop-claude runs the project on, with the digest and the prompt in bin/task_bench/figures/gather-prompt.md.
That claude files an item with `todo-item add` for each place the runs show to be hard, and leaves the plan's file uncommitted.
gather prints that claude's answer and removes the bench's folder. Where claude fails, the folder stays, for another try.
Each bench empties its own folder first, and removes the folder every earlier bench left under any review folder, gathered or
not, unless a bench or a gather is using it. So gather a bench before the next one starts.
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 file in a language the bench plants bugs in, 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.
With --tasks shipped-features it exits 1 on a --seed, --bugs or --prefix, and on a --shipped that is no whole number from 1;
where no config names the checkout, its config keeps the plan, the comprehension history or the reading cost at another path
than the one above, or the base's history shipped no item, each before docker runs; and where the tests fail at a side with every feature in, or no shipped feature
counts. A --shipped with another kind of task exits 1 too.
Where the API refuses a run, the bench stops there and exits 1 too, after the table of the runs that finished.
With --record-figures it also exits 1, saying why: before it plants a bug, where no config names the checkout or the history
cannot be read; and after the bench, where the history already holds that branch's bench of those two commits or cannot be
written. The folder then still holds the bench's results.
gather exits 1, saying why, outside a checkout, without a digest, where loop-claude has saved no model for the project or the
model is not on its routing ladder, and where its claude fails or hits a usage limit.
"""
import dataclasses
import functools
import itertools
import json
import os
import pathlib
import shutil
import sys
import tarfile
import time
import typing
import uuid
from task_bench.tasks import Asked, Bench, BUG, check_made, committed, DATA_SOURCE, FEATURE, Kind, KINDS, on_disk, Planned, SHIPPED, Side, SIDES, Task, tests_in_copy
from task_bench.bugs.planted_mutant import bug_at_sides, Mutant
from claude_code.reply import Claude
from task_bench.bench_folder import clear_left, held
from task_bench.runs import closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN, WORK
from task_bench.figures.digest import counted, digest, Run, TaskRuns
from machine_load.slots import CPUS_PER_SLOT
from git_cli.git_repo import default_ref, Git, top
from task_bench.figures.gather import DIGEST, gather, run_claude
from task_bench.bugs.plant import drawn, killed_mutants, place_files, task_text
from claude_code.entries import Entry, entry_from, json_objects
from mutate_changes.tool_process import failed, Ran, run_tool
from failure import Failure
from task_bench.features.feature_tasks import feature_tasks, Features, read_features
from task_bench.figures.run_figures import Figures, figures, Result, table
from git_cli import git_repo
from review_rules.review_folder import made_review_folder, REPORTS
from larv_review.history_commands import read_places
from task_bench.features.shipped_features import read_shipped, shipped_tasks
from task_bench.figures.record_figures import recorded_bench
from run_heavy.capped_docker import SHARE_VARIABLE
from task_bench.rust_test_modules import tells_apart
USAGE = "usage: task-bench --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--prefix <shell text>] [--seed <n>] [--bugs <n>] [--runs <n>] [--record-figures], or task-bench --tasks features|data-sources --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--runs <n>] [--record-figures], or task-bench --tasks shipped-features --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--shipped <n>] [--runs <n>] [--record-figures], or task-bench gather"
# A panel of three readers, seated as the README's audience, picked these options on 2026-11-21, each 3 to 0.
# Such a panel picked --shipped on 2026-11-24, first for two of its three and second for the third, who would spell it out as
# --shipped-features: it names its kind as --bugs does, where --features would read as counting the bench features.
OPTIONS = ("--base", "--bugs", "--head", "--image", "--prefix", "--record-figures", "--runs", "--seed", "--shipped", "--tasks", "--test")
# The one option that takes no value.
RECORD = "--record-figures"
COUNTS = {"--bugs": "5", "--runs": "5", "--seed": "1", "--shipped": "5"}
TASKS = "--tasks"
# Opens the report's last line, which names the bench's folder.
KEPT = "The digest, and each run's result and stream, until `task-bench gather` files plan items from them or the next bench starts: "
# The options only a bench of one kind takes. For bugs, two choose the bugs to plant, and --prefix runs the mutation tool.
ONLY_FOR = {"--seed": BUG, "--bugs": BUG, "--prefix": BUG, "--shipped": SHIPPED}
# What plans a bench's tasks, once the bench has opened its containers.
Planner = typing.Callable[[Bench], Planned | Failure]
# What makes a kind's planner from each side's tree, once the trees stand.
Planning = typing.Callable[[dict[Side, str]], Planner | Failure]
# What reads a kind's tasks once the bench knows its checkout and its sides' commits, with git to read them by.
Source = typing.Callable[[str, dict[Side, str], Git], Planning | Failure]
class Fixes(typing.NamedTuple):
"""The runs that finished, in the order they ran, and the failure that stopped the bench before the rest, if one did."""
results: list[Result]
stopped: Failure | None
class Call(typing.NamedTuple):
"""What a bench was called with: its options, the environment its tools run in, what reads what `larv-review places` prints,
and the home folder."""
given: dict[str, str]
env: typing.Mapping[str, str]
read: typing.Callable[[pathlib.Path], str | Failure]
home: pathlib.Path
def new_name() -> str:
"""A name no other bench's containers have."""
return f"task-bench-{uuid.uuid4().hex[:12]}"
def host_user() -> str:
"""The user and group this process runs as, as docker's --user takes them."""
return f"{os.getuid()}:{os.getgid()}"
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude, name: typing.Callable[[], str] = new_name, user: typing.Callable[[], str] = host_user) -> int:
"""Runs task-bench with the arguments argv; git, docker and the mutation tool run in the environment env, `read` reads what
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers. `name` names a bench's containers,
and `user` is the user they run as."""
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
home = pathlib.Path(env.get("HOME") or pathlib.Path.home())
if argv[:1] == ["gather"]:
report = gather(env, home, claude) if argv == ["gather"] else Failure(f"gather takes no arguments; {USAGE}")
else:
given = options(argv, env)
if isinstance(given, Failure):
print(f"{given.reason}; {USAGE}", file=sys.stderr)
return 1
report = bench(given, env, read, home, name(), user())
if isinstance(report, Failure):
print(report.reason, file=sys.stderr)
return 1
print("\n".join(report))
return 0
def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] | Failure:
"""The options argv gives, with each default filled in; a Failure where argv cannot be read, or asks what no bench does."""
given = parsed(argv)
return given if isinstance(given, Failure) else checked(given, env)
def parsed(argv: list[str]) -> dict[str, str] | Failure:
"""Each option argv names, with its value, given as `--name value` or `--name=value`."""
given: dict[str, str] = {}
rest = list(argv)
while rest:
name, equals, value = rest.pop(0).partition("=")
if name not in OPTIONS:
return Failure(f"unknown argument {name}")
if name in given:
return Failure(f"{name} is given twice")
if name == RECORD:
if equals:
return Failure(f"{name} takes no value")
given[name] = ""
continue
if not equals and not rest:
return Failure(f"{name} needs a value")
given[name] = value if equals else rest.pop(0)
return given
def checked(given: dict[str, str], env: typing.Mapping[str, str]) -> dict[str, str] | Failure:
"""given with each default filled in, where it holds what a bench of its kind needs and env holds the token."""
for name in ("--image", "--test"):
if not given.get(name):
return Failure(f"{name} is missing")
tasks = given.get(TASKS, "bugs")
if tasks not in KINDS:
return Failure(f"{TASKS} takes {', '.join(list(KINDS)[:-1])} or {list(KINDS)[-1]}, not {tasks}")
kind = KINDS[tasks]
for name, only in ONLY_FOR.items():
if only is not kind and name in given:
return Failure(f"{name} is for a bench of {only.noun}s, so it doesn't go with {TASKS} {tasks}")
filled = {TASKS: tasks, **count_defaults(kind), **given}
return counts_failure(filled) or (filled if env.get(TOKEN) else Failure(f"{TOKEN} holds no token"))
def count_defaults(kind: Kind) -> dict[str, str]:
"""The default of each count a bench of kind takes."""
return {name: default for name, default in COUNTS.items() if ONLY_FOR.get(name, kind) is kind}
def counts_failure(filled: dict[str, str]) -> Failure | None:
"""A Failure where a count filled holds is no whole number from 1."""
for name in COUNTS:
if name in filled and (not filled[name].isdecimal() or int(filled[name]) < 1):
return Failure(f"{name} takes a whole number from 1, not {filled[name]}")
return None
def progress(line: str) -> None:
"""Prints a line of a bench's progress to stderr, apart from its report on stdout."""
print(line, file=sys.stderr)
def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path, name: str, user: str) -> list[str] | Failure:
"""The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. Its
containers are named name and run as user. It tells its progress on stderr."""
kind = KINDS[given[TASKS]]
# Each kind reads what it makes its tasks from before anything is copied or built, so a fault there stops the bench at once.
source = SOURCES[kind](Call(given, env, read, home), kind)
if isinstance(source, Failure):
return source
git = functools.partial(git_repo.git, env=env)
checkout = top(git)
if isinstance(checkout, Failure):
return checkout
sides = commits(given, checkout, git)
if isinstance(sides, Failure):
return sides
planning = source(checkout, sides, git)
if isinstance(planning, Failure):
return planning
progress(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.")
review = made_review_folder(checkout, home)
if isinstance(review, Failure):
return review
with held(review) as folder:
if isinstance(folder, Failure):
return folder
clear_left(home / REPORTS)
containers = Containers(docker_cli(env), name, given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), user)
run = functools.partial(bench_in, folder, given["--image"], containers, Asked(kind, int(given["--runs"])), planning, checkout, sides, git)
return recorded_bench(run, folder, git, home, time.time) if RECORD in given else run()
def bench_in(folder: pathlib.Path, image: str, containers: Containers, asked: Asked, planning: Planning, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure:
"""The report of a bench of the commits sides names, in containers of image, which empties folder and keeps its runs there.
planning makes what plans the tasks of the kind asked."""
shutil.rmtree(folder, ignore_errors=True)
trees: dict[Side, str] = {}
for side, commit in sides.items():
tree = archived(commit, folder / "trees" / side, checkout, git)
if isinstance(tree, Failure):
return tree
trees[side] = tree
planned = planning(trees)
if isinstance(planned, Failure):
return planned
try:
found = opened(containers, image) or benched(Bench(checkout, sides, trees, asked, containers, folder, git, progress), planned)
finally:
closed(containers)
return found if isinstance(found, Failure) else [*found, f"{KEPT}{folder}"]
def bugs_source(call: Call, kind: Kind) -> Source | Failure:
"""Reads the seats' places, the only places bugs are planted."""
places = call.read(call.home)
if isinstance(places, Failure):
return places
return lambda checkout, sides, git: functools.partial(bugs_planner, call.given, call.env, places)
def features_source(call: Call, kind: Kind) -> Source | Failure:
"""Reads the features, or the data sources where kind is DATA_SOURCE, from the project's folder."""
features = read_features(call.home, kind)
if isinstance(features, Failure):
return features
return lambda checkout, sides, git: functools.partial(features_planner, features, checkout)
def shipped_source(call: Call, kind: Kind) -> Source:
"""Shipped features are read from the base's history, so only once the base is known."""
def source(checkout: str, sides: dict[Side, str], git: Git) -> Planning | Failure:
shipped = read_shipped(call.home, checkout, sides["base"], git)
if isinstance(shipped, Failure):
return shipped
return lambda trees: functools.partial(shipped_tasks, shipped=shipped, count=int(call.given["--shipped"]))
return source
# What reads each kind's tasks. A kind without an entry stops the bench before it reads anything.
SOURCES: dict[Kind, typing.Callable[[Call, Kind], Source | Failure]] = {BUG: bugs_source, FEATURE: features_source, DATA_SOURCE: features_source, SHIPPED: shipped_source}
def features_planner(features: Features, checkout: str, trees: dict[Side, str]) -> Planner:
"""What plans a bench of features in trees, each side's. It takes the features' folder, with its acceptance tests and
reference patches, out of trees first, so Haiku's copy leaves it out."""
if features.folder.is_relative_to(checkout):
for tree in trees.values():
# A side older than the folder, or a folder not yet committed, leaves none to take out.
shutil.rmtree(pathlib.Path(tree, features.folder.relative_to(checkout)), ignore_errors=True)
return functools.partial(feature_tasks, found=features.found, folder=features.folder)
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, trees: dict[Side, str]) -> Planner | Failure:
"""What plans a bench of bugs. The bugs' files are those of the base's tree in trees that hold a place in places and are in a
language of plant's LANGUAGES. Of the mutants the tests kill in those files, the ones --seed draws first become bugs, until
--bugs of them have."""
base = trees["base"]
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 file at the base in a language the bench plants bugs in, 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"]))
def commits(given: dict[str, str], checkout: str, git: Git) -> dict[Side, str] | Failure:
"""The base's commit and the head's."""
head = git("rev-parse", "--verify", f"{given.get('--head', 'HEAD')}^{{commit}}", cwd=checkout)
against = given.get("--base") or default_ref(cwd=checkout, run=git)
if isinstance(head, Failure):
return head
if isinstance(against, Failure):
return against
base = git("merge-base", against, head.strip(), cwd=checkout)
return base if isinstance(base, Failure) else {"base": base.strip(), "head": head.strip()}
def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str | Failure:
"""Makes `into` the tree at commit, as `git archive` holds it, and returns its path: without git's own data, and without a
path the project marks `export-ignore`."""
made = on_disk(f"make {into}", lambda: into.mkdir(parents=True))
if isinstance(made, Failure):
return made
archive = into.with_suffix(".tar")
wrote = git("archive", "--format=tar", "--output", str(archive), commit, cwd=checkout)
if isinstance(wrote, Failure):
return wrote
try:
with tarfile.open(archive) as held:
held.extractall(into, filter="tar")
except (tarfile.TarError, OSError) as failure:
return Failure(f"could not unpack the tree at {commit}: {failure}")
removed = on_disk(f"remove {archive}", archive.unlink)
return removed if isinstance(removed, Failure) else str(into)
def benched(bench: Bench, planned: Planner) -> list[str] | Failure:
"""Makes the tasks that planned plans, runs each, writes the results into the bench's folder and returns the report."""
if failure := baseline_failure(bench):
return failure
plan = planned(bench)
if isinstance(plan, Failure):
return plan
tasks = plan.tasks
total = bench.asked.runs * len(tasks) * len(SIDES)
fixes = ran_fixes(bench, tasks, total)
if fixes.stopped and not fixes.results:
return fixes.stopped
names = {task.number: task.name for task in tasks}
if failure := kept(bench, plan, names, fixes.results):
return failure
if fixes.stopped:
return stopped_report(fixes.stopped, fixes.results, total, names, bench.folder, bench.asked.kind)
return report(bench.sides, names, bench.asked, fixes.results, plan.left_out)
def baseline_failure(bench: Bench) -> Failure | None:
"""Why a side's tests don't pass without a task; None where they pass at both sides."""
for side, tree in bench.trees.items():
ran = tests_in_copy(bench.containers, tree, bench.folder)
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else failed(f"The tests fail at the {side} without {bench.asked.kind.without}: the test command", ran)
return None
def planted_tasks(bench: Bench, mutants: list[Mutant], seed: int, bugs: int) -> Planned | Failure:
"""The mutants that become bugs, in the order seed draws them, until the bench has as many as bugs; with a line that says so
where it has fewer."""
tasks: list[Task] = []
for mutant in drawn(mutants, seed):
if len(tasks) == bugs:
break
task = planted(bench, len(tasks) + 1, mutant)
if isinstance(task, Failure):
return task
tasks += [task] if task else []
if not tasks:
return Failure(f"None of the {len(mutants)} mutants the tests kill becomes a bug: each is on a line the head changed, or the test it fails doesn't print a message.")
return Planned(tasks, [] if len(tasks) == bugs else [f"Planted {len(tasks)} of the {bugs} bugs asked for: no other mutant the tests kill becomes one."], {"seed": seed})
def ran_fixes(bench: Bench, tasks: list[Task], total: int) -> Fixes:
"""Each task's fix at each side, as many times as asked for, the sides in turn, until a run stops the bench."""
results: list[Result] = []
for number, task, side in itertools.product(range(1, bench.asked.runs + 1), tasks, SIDES):
result = fixed(task, side, number, bench.containers, bench.folder, bench.asked.kind)
if isinstance(result, Failure):
return Fixes(results, result)
results.append(result)
bench.say(f"task-bench: run {len(results)} of {total}, {bench.asked.kind.noun} {task.number} at the {side}: {'passed' if result.passed else 'not passed'}.")
return Fixes(results, None)
def kept(bench: Bench, plan: Planned, names: dict[int, str], results: list[Result]) -> Failure | None:
"""Writes results.json and the digest of the plan's tasks into the bench's folder. names holds each task's name by its number."""
in_a_tree = lambda path: any(pathlib.Path(tree, path).is_file() for tree in bench.trees.values())
noun, key = bench.asked.kind.noun, bench.asked.kind.key
recorded_runs = json.dumps({"sides": bench.sides, **plan.drawn_by, f"{key}s": names, "runs": [recorded(result, key) for result in results]}, indent="\t") + "\n"
digest_text = digest(bench.sides, table(results, names, noun), [digested(task, results, bench.folder, key) for task in plan.tasks], in_a_tree, noun)
try:
(bench.folder / "results.json").write_text(recorded_runs, encoding="utf-8")
(bench.folder / DIGEST).write_text(digest_text, encoding="utf-8", errors="replace")
except OSError as failure:
return Failure(f"could not write the results under {bench.folder}: {failure}")
return None
def report(sides: dict[Side, str], names: dict[int, str], asked: Asked, results: list[Result], left_out: list[str]) -> list[str]:
"""What a finished bench prints: the commits, the tasks named in names, what ran them, a line of left_out on each thing the
bench left out, and the table."""
ran_on = sorted({f"{found.model} in Claude Code {found.version}" for result in results if (found := result.figures)})
return [
f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}. {counted(len(names), asked.kind.noun)}, each run {counted(asked.runs, 'time')} at each side by {' and '.join(ran_on) or 'no run that finished'}.",
*left_out,
"",
*table(results, names, asked.kind.noun),
"",
]
def stopped_report(stopped: Failure, results: list[Result], total: int, names: dict[int, str], folder: pathlib.Path, kind: Kind) -> Failure:
"""Why the bench stopped, then the table of the runs that finished: they took hours and tokens, so the bench shows them
before it fails."""
return Failure("\n".join([stopped.reason, f"task-bench stopped after {len(results)} of {total} runs, which results.json holds in {folder}:", "", *table(results, names, kind.noun)]))
def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None:
"""The task of fixing mutant, with its planted tree at each side; None where the mutant doesn't become a bug at one side or the other."""
diff = bench.git("diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", bench.sides["base"], bench.sides["head"], "--", mutant.path, cwd=bench.checkout, errors="replace")
if isinstance(diff, Failure):
return diff
sources = on_disk(f"read {mutant.path}", lambda: {side: source.read_bytes() if (source := pathlib.Path(tree, mutant.path)).is_file() else None for side, tree in bench.trees.items()})
if isinstance(sources, Failure):
return sources
bugs = bug_at_sides(mutant, diff, sources)
# The check keeps a Rust file's test modules as planted, which it can only do where it tells them apart.
if bugs is None or not all(tells_apart(mutant.path, source) for source in bugs.values()):
return None
trees: dict[Side, str] = {}
messages: dict[Side, str] = {}
for side, changed in bugs.items():
tree = bench.folder / "bugs" / str(number) / side
message = planted_tree(bench, side, tree, mutant.path, changed)
if message is None or isinstance(message, Failure):
return message
trees[side], messages[side] = str(tree), message
return Task(number, mutant.name, trees, messages, file=mutant.path)
def planted_tree(bench: Bench, side: Side, tree: pathlib.Path, path: str, changed: bytes) -> str | Failure | None:
"""Makes tree a copy of the side's with the file at path holding changed, committed once, and returns what the failing test
prints there; None where it prints no message to tell Haiku."""
shutil.rmtree(tree, ignore_errors=True)
try:
shutil.copytree(bench.trees[side], tree, symlinks=True)
(tree / path).write_bytes(changed)
except OSError as failure:
return Failure(f"could not plant the bug in {tree}: {failure}")
ran = tests_in_copy(bench.containers, str(tree), bench.folder)
# Tests that never end under the bug have no message.
if isinstance(ran, TimedOut):
return None
if isinstance(ran, Failure):
return ran
message = task_text(path, ran.output)
if message is None:
return None
return committed(bench.git, str(tree)) or message
def fixed(task: Task, side: Side, number: int, containers: Containers, folder: pathlib.Path, kind: Kind) -> Result | Failure:
"""One run: Haiku's work on task at side in a copy of its tree, then the tests over what it changed, with a feature's
acceptance tests among them. The stream stays in folder; the copy is removed. Tests that run out of time don't pass."""
stream = stream_of(Result(task.number, side, number, False, None), folder, kind.key)
copy, check = folder / "copy", folder / "check"
try:
worked = attempt(task, side, containers, copy, stream, kind)
if isinstance(worked, Failure):
return worked
passed = verdict(task, side, containers, copy, check, kind)
if isinstance(passed, Failure):
return passed
return Result(task.number, side, number, passed, *worked)
finally:
shutil.rmtree(copy, ignore_errors=True)
shutil.rmtree(check, ignore_errors=True)
def attempt(task: Task, side: Side, containers: Containers, copy: pathlib.Path, stream: pathlib.Path, kind: Kind) -> tuple[Figures | None, tuple[Entry, ...]] | Failure:
"""Haiku's work on task in copy, made a copy of the side's tree: the figures of its run, None where it didn't finish, and
the entries of its stream, which it writes to the file stream."""
try:
stream.parent.mkdir(exist_ok=True)
shutil.copytree(task.trees[side], copy, symlinks=True)
except OSError as failure:
return Failure(f"could not copy {kind.noun} {task.number}'s tree at the {side}: {failure}")
attempted = fix_attempted(containers, str(copy), kind.prompt.format(told=task.told[side]), stream)
if isinstance(attempted, Failure):
return attempted
raw = on_disk(f"read {stream}", stream.read_bytes)
if isinstance(raw, Failure):
return raw
events = json_objects(raw)
found = figures(events, task.file and os.path.join(WORK, task.file))
return found if isinstance(found, Failure) else (found, tuple(entry_from(event) for event in events))
def verdict(task: Task, side: Side, containers: Containers, copy: pathlib.Path, check: pathlib.Path, kind: Kind) -> bool | Failure:
"""Whether the tests pass over check, made the side's tree with what Haiku changed in copy. Tests that run out of time don't."""
checked = on_disk(f"make the tree that checks {kind.noun} {task.number}'s fix at the {side}", lambda: check_made(task.trees[side], str(copy), str(check), task.acceptance))
if isinstance(checked, Failure):
return checked
ran = ran_tests(containers, str(check))
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
return ran
return isinstance(ran, Ran) and ran.code == 0
def stream_of(result: Result, folder: pathlib.Path, key: str) -> pathlib.Path:
"""The file that holds the stream of the run result names, of a task whose kind has that key. Its name without the suffix is
the run's id in the digest."""
return folder / "runs" / f"{key}-{result.task}-{result.side}-{result.run}.jsonl"
def digested(task: Task, results: list[Result], folder: pathlib.Path, key: str) -> TaskRuns:
"""The task as the digest tells it, with each of its runs in results. A run that didn't finish has no tokens."""
runs = [Run(stream_of(result, folder, key).stem, result.passed, found.tokens.context() + found.tokens.output if (found := result.figures) else None, result.entries) for result in results if result.task == task.number]
return TaskRuns(f"{task.number}: {task.name}", task.file, task.told["base"], runs)
def recorded(result: Result, key: str) -> dict:
"""A run as results.json holds it, of a task whose kind has that key."""
run = {key: result.task, "side": result.side, "run": result.run, "passed": result.passed, "finished": result.figures is not None}
if not (found := result.figures):
return run
return {**run, "claude_code": found.version, "model": found.model, "tokens": dataclasses.asdict(found.tokens), "turns": found.turns, "seconds": found.seconds, "reads": found.reads}