Distil each task-bench run into a digest and gather plan items from it
CI / tests (pull_request) Failing after 4m49s

This commit is contained in:
2026-11-21 03:56:18 +01:00
parent d813fdad5a
commit ad11c72016
11 changed files with 686 additions and 23 deletions
+64 -16
View File
@@ -2,6 +2,7 @@ r"""Measure how hard a project's code is to fix a bug in, at a base commit and a
each several times at both, and print how often the fix passes and what it took.
usage: task-bench --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--prefix <shell text>] [--seed <n>] [--bugs <n>] [--runs <n>]
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:
@@ -35,13 +36,30 @@ example:
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. The last line names the folder that holds each run's result and
stream: `task-bench` in the chunk's review folder. Each bench empties that `task-bench` folder first.
per side over every bug, and the head's change against the base. 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 fix doesn't change;
- per bug two traces, of the failing run 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.
`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 gather-prompt.md beside this file.
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 what it answered 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, or no token; and where git, docker or Gremlins fails, the seats' places name no Go file, the tests fail at a side
without a bug, or no mutant becomes a bug. Where the API refuses a run, the bench stops there and exits 1 too, after the table of
the runs that finished.
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
@@ -55,22 +73,28 @@ import tarfile
import typing
import uuid
from task_bench.digest import Bug, digest, Run
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN
from claude_code.reply import Claude
from task_bench.bench_folder import clear_left, held
from machine_load.slots import CPUS_PER_SLOT
from git_cli.git_repo import default_ref, Git, top
from task_bench.gather import DIGEST, gather, run_claude
from task_bench.plant import drawn, killed_mutants, line_at_head, Mutant, mutated, place_files, task_text
from mutate_changes.tool_process import failed, Ran, run_tool
from failure import Failure
from task_bench.figures import figures, Result, SIDES, table, WORK
from git_cli import git_repo
from review_rules.review_folder import made_review_folder
from review_rules.review_folder import made_review_folder, REPORTS
from larv_review.history_commands import read_places
from run_heavy.capped_docker import SHARE_VARIABLE
USAGE = "usage: task-bench --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--prefix <shell text>] [--seed <n>] [--bugs <n>] [--runs <n>]"
USAGE = "usage: task-bench --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--prefix <shell text>] [--seed <n>] [--bugs <n>] [--runs <n>], 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.
OPTIONS = ("--base", "--bugs", "--head", "--image", "--prefix", "--runs", "--seed", "--test")
COUNTS = {"--bugs": "5", "--runs": "5", "--seed": "1"}
# 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: "
# The planted commit doesn't name anyone, and neither a hook nor a signing key of the caller's reaches it.
COMMIT = ["-c", "user.name=task-bench", "-c", "user.email=task-bench@localhost", "-c", "commit.gpgsign=false", "-c", "core.hooksPath=/dev/null", "commit", "--quiet", "--message", "Import"]
@@ -87,19 +111,22 @@ class Task:
return f"{self.mutant.path}:{self.mutant.line}:{self.mutant.column} {self.mutant.mutator}"
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places) -> int:
"""Runs task-bench with the arguments argv; git, docker and Gremlins run in the environment env, and `read` reads what
`larv-review places` prints for the checkout."""
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude) -> int:
"""Runs task-bench with the arguments argv; git, docker and Gremlins run in the environment env, `read` reads what
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers."""
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
given = options(argv, env)
if isinstance(given, Failure):
print(f"{given.reason}; {USAGE}", file=sys.stderr)
return 1
home = pathlib.Path(env.get("HOME") or pathlib.Path.home())
places = read(home)
report = places if isinstance(places, Failure) else bench(given, env, places, home)
if argv == ["gather"]:
report = gather(env, home, claude)
else:
given = options(argv, env)
if isinstance(given, Failure):
print(f"{given.reason}; {USAGE}", file=sys.stderr)
return 1
places = read(home)
report = places if isinstance(places, Failure) else bench(given, env, places, home)
if isinstance(report, Failure):
print(report.reason, file=sys.stderr)
return 1
@@ -143,7 +170,15 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, hom
review = made_review_folder(checkout, home)
if isinstance(review, Failure):
return review
folder = review / "task-bench"
with held(review) as folder:
if isinstance(folder, Failure):
return folder
clear_left(home / REPORTS)
return bench_in(folder, given, env, places, checkout, sides, git)
def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[str, str], places: str, checkout: str, sides: dict[str, str], git: Git) -> list[str] | Failure:
"""The report of a bench of the commits sides names, which empties folder and keeps its runs there."""
containers = Containers(docker_cli(env), f"task-bench-{uuid.uuid4().hex[:12]}", given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), f"{os.getuid()}:{os.getgid()}")
try:
shutil.rmtree(folder, ignore_errors=True)
@@ -166,7 +201,7 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, hom
closed(containers)
except OSError as failure:
return Failure(f"could not write under {folder}: {failure}")
return found if isinstance(found, Failure) else [*found, f"Each run's result and stream: {folder}"]
return found if isinstance(found, Failure) else [*found, f"{KEPT}{folder}"]
def commits(given: dict[str, str], checkout: str, git: Git) -> dict[str, str] | Failure:
@@ -228,6 +263,8 @@ def benched(given: dict[str, str], checkout: str, sides: dict[str, str], trees:
return stopped
names = {task.number: task.named() for task in tasks}
(folder / "results.json").write_text(json.dumps({"sides": sides, "seed": int(given["--seed"]), "bugs": names, "runs": [recorded(result) for result in results]}, indent="\t") + "\n", encoding="utf-8")
in_a_tree = lambda path: any(pathlib.Path(tree, path).is_file() for tree in trees.values())
(folder / DIGEST).write_text(digest(table(results, names), [digested(task, results, folder) for task in tasks], in_a_tree), encoding="utf-8")
if stopped:
# The runs that finished 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)]))
@@ -290,7 +327,7 @@ def tests_in_copy(containers: Containers, tree: str, folder: pathlib.Path) -> Ra
def fixed(task: Task, side: str, number: int, containers: Containers, folder: pathlib.Path) -> Result | Failure:
"""One run: Haiku's fix of task at side in a copy of its planted tree, then the tests over what it changed. The stream stays in
folder; the copy is removed. Tests that run out of time don't pass."""
stream = folder / "runs" / f"bug-{task.number}-{side}-{number}.jsonl"
stream = stream_of(Result(task.number, side, number, False, None), folder)
stream.parent.mkdir(exist_ok=True)
copy, check = folder / "copy", folder / "check"
try:
@@ -311,6 +348,17 @@ def fixed(task: Task, side: str, number: int, containers: Containers, folder: pa
shutil.rmtree(check, ignore_errors=True)
def stream_of(result: Result, folder: pathlib.Path) -> pathlib.Path:
"""The file that holds the stream of the run result names. Its name without the suffix is the run's id in the digest."""
return folder / "runs" / f"bug-{result.task}-{result.side}-{result.run}.jsonl"
def digested(task: Task, results: list[Result], folder: pathlib.Path) -> Bug:
"""The bug as the digest tells it, with each of its runs in results. A run that didn't finish counts as spending no tokens."""
runs = [Run(stream_of(result, folder).stem, result.passed, found.tokens.context() + found.tokens.output if (found := result.figures) else 0, stream_of(result, folder).read_bytes()) for result in results if result.task == task.number]
return Bug(f"{task.number}: {task.named()}", task.mutant.path, task.messages["base"], runs)
def recorded(result: Result) -> dict:
"""A run as results.json holds it."""
run = {"bug": result.task, "side": result.side, "run": result.run, "passed": result.passed, "finished": result.figures is not None}