Answer architecture round 1: 2 🔴, 8 🟡 (0 misread); split task-bench's benched into phases and its table into one column list, parse each stream once, move do-epic's parking out with pure move and news decisions, share the round summaries, rename scoring_due, and file the version question as item 517
CI / tests (pull_request) Successful in 5m2s

This commit is contained in:
2026-11-23 01:20:55 +01:00
parent 21200cb698
commit 0bf87b736e
29 changed files with 678 additions and 368 deletions
+11 -13
View File
@@ -5,8 +5,8 @@ import collections
import re
import typing
from claude_code.entries import AssistantTurn, parse_entry, Text, tool_calls, ToolCall, ToolResult, ToolResults
from task_bench.figures import HOME, WORK
from claude_code.entries import AssistantTurn, Entry, Text, tool_calls, ToolCall, ToolResult, ToolResults
from task_bench.runs import HOME, WORK
from reading_cost.measure import reads_of
# A trace keeps the first TEXT_LINES lines of the model's text between two calls, and the first TEXT_WIDTH characters of each.
@@ -22,12 +22,12 @@ AROUND_HITS = re.compile(r"Found \d+ .*|No \w+ found.*|No entries at this offset
class Run(typing.NamedTuple):
"""One run of a bug: the name of its stream's file without the suffix, whether its fix passed, the tokens it spent, None where
it didn't finish, and its stream."""
it didn't finish, and its stream's entries."""
id: str
passed: bool
tokens: int | None
stream: bytes
entries: typing.Sequence[Entry]
class Bug(typing.NamedTuple):
@@ -50,7 +50,7 @@ def digest(sides: dict[str, str], table: list[str], bugs: list[Bug], is_file: ty
def told(bug: Bug, is_file: typing.Callable[[str], bool]) -> list[str]:
passing, failing = [run for run in bug.runs if run.passed], [run for run in bug.runs if not run.passed]
passed = f"{len(passing)} of the {len(bug.runs)} runs passed." if failing else f"The {counted(len(bug.runs), 'run')} passed."
misled = decoys([run.stream for run in failing], bug.file, is_file)
misled = decoys([run.entries for run in failing], bug.file, is_file)
if not failing:
found = "No run failed, so the bug has no decoys."
elif not misled:
@@ -77,27 +77,25 @@ def told(bug: Bug, is_file: typing.Callable[[str], bool]) -> list[str]:
"",
f"{passed} {found}",
*(["", *(f"- {decoy}" for decoy in misled)] if misled else []),
*(line for run, why in shown for line in ["", f"### {run.id}, {why}", "", *trace(run.stream)]),
*(line for run, why in shown for line in ["", f"### {run.id}, {why}", "", *trace(run.entries)]),
]
def decoys(failing: list[bytes], fixed: str, is_file: typing.Callable[[str], bool]) -> list[str]:
"""The files of the project that more than half of the failing runs' streams read, but for fixed, the file the bug is in:
def decoys(failing: list[typing.Sequence[Entry]], fixed: str, is_file: typing.Callable[[str], bool]) -> list[str]:
"""The files of the project that more than half of the failing runs read, but for fixed, the file the bug is in:
each with how many runs read it, sorted by name."""
read_by = collections.Counter(path for stream in failing for path in files_read(stream))
read_by = collections.Counter(path for entries in failing for path in files_read(entries))
by = lambda count: "the one failing run" if len(failing) == 1 else f"{count} of the {len(failing)} failing runs"
return [f"`{path}`, read by {by(count)}" for path, count in sorted(read_by.items()) if count * 2 > len(failing) and path != fixed and is_file(path)]
def files_read(stream: bytes) -> set[str]:
def files_read(entries: typing.Sequence[Entry]) -> set[str]:
"""The paths in the project that the run opened or searched, a folder it searched among them."""
entries = [entry for line in stream.splitlines() if (entry := parse_entry(line))]
return {path.removeprefix(WORK + "/") for _, call in tool_calls(entries) for path in reads_of(call, WORK, HOME).read if path.startswith(WORK + "/")}
def trace(stream: bytes) -> list[str]:
def trace(entries: typing.Sequence[Entry]) -> list[str]:
"""The run in short: a line per tool call, and between calls the first TEXT_LINES lines of what the model wrote, each after `> `."""
entries = [entry for line in stream.splitlines() if (entry := parse_entry(line))]
results = {result.tool_use_id: result for entry in entries if isinstance(entry, ToolResults) for result in entry.results}
return [line for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts for line in (written(part.text) if isinstance(part, Text) else [called(part, results.get(part.id))])]
+38 -27
View File
@@ -3,18 +3,15 @@ import dataclasses
import statistics
import typing
from claude_code.entries import Entry, json_object, tool_calls, ToolCall
from failure import Failure
from claude_code.entries import json_object, parse_entry, tool_calls, ToolCall
from task_bench.runs import HOME, WORK
from reading_cost.measure import reads_of
from claude_code.tokens import Tokens, tokens_of
# Where each run's container mounts its copy of the code, and its home folder: the paths in a run's stream start there.
WORK = "/work"
HOME = "/tmp"
# The tools that read or search without a shell. A Bash call counts where `reads_of` finds a file it reads.
READING_TOOLS = frozenset({"Glob", "Grep", "Read"})
SIDES = ("base", "head")
HEADER = ["| Bug | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |", "|---|---|---|---|---|---|---|---|---|---|"]
@dataclasses.dataclass(frozen=True)
@@ -30,17 +27,42 @@ class Figures:
class Result(typing.NamedTuple):
"""One run of a task at a side. figures is None where its claude ended without a result, as when it ran out of time."""
"""One run of a task at a side. figures is None where its claude ended without a result, as when it ran out of time. entries
holds what its stream tells, for the digest."""
task: int
side: str
run: int
passed: bool
figures: Figures | None
entries: typing.Sequence[Entry] = ()
def figures(stream: bytes, bug_file: str) -> Figures | None | Failure:
"""The figures of the run whose claude printed stream, with bug_file the bug's file as the run's container names it.
class Column(typing.NamedTuple):
"""A figure the table shows: its heading, its value in one run, None where the run has none, and whether the head's change
in it is a share of the base or a count."""
heading: str
value: typing.Callable[[Figures], float | None]
change: typing.Literal["share", "count"]
# Turns and reads are small counts, where a share misleads.
COLUMNS = (
Column("Input", lambda found: found.tokens.input, "share"),
Column("Cache write", lambda found: found.tokens.write_5m + found.tokens.write_1h, "share"),
Column("Cache read", lambda found: found.tokens.read, "share"),
Column("Output", lambda found: found.tokens.output, "share"),
Column("Turns", lambda found: found.turns, "count"),
Column("Wall, s", lambda found: found.seconds, "share"),
Column("Reads", lambda found: found.reads, "count"),
)
HEADINGS = ["Bug", "Side", "Passed", *(column.heading for column in COLUMNS)]
def figures(stream: bytes, entries: typing.Sequence[Entry], bug_file: str) -> Figures | None | Failure:
"""The figures of the run whose claude printed stream, which parses into entries, with bug_file the bug's file as the run's
container names it.
None where the stream holds no result. A Failure where the API refused the run, as on a token it doesn't take: such a run
doesn't measure anything, and every later run would end the same."""
@@ -48,11 +70,11 @@ def figures(stream: bytes, bug_file: str) -> Figures | None | Failure:
result = next((event for event in reversed(events) if event.get("type") == "result"), None)
if result is None:
return None
# Claude Code retries a failed API call itself, on 429, 529 and 5xx, up to CLAUDE_CODE_MAX_RETRIES times, so its retries didn't clear this one.
if result.get("api_error_status") or result.get("terminal_reason") == "api_error":
return Failure(f"claude could not use the API: {result.get('result')}")
# {"type": "system", "subtype": "init", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330", ...}
init = next((event for event in events if event.get("subtype") == "init"), {})
entries = [entry for line in stream.splitlines() if (entry := parse_entry(line))]
calls = [call for _, call in tool_calls(entries)]
return Figures(str(init.get("claude_code_version", "")), str(init.get("model", "")), tokens_of(result.get("usage")), int(result.get("num_turns") or 0), (result.get("duration_ms") or 0) / 1000, reads_before(calls, bug_file))
@@ -73,27 +95,18 @@ def table(results: list[Result], tasks: dict[int, str]) -> list[str]:
sides = {(task, side): [result for result in results if (result.task, result.side) == (task, side)] for task in tasks for side in SIDES}
rows = [row(f"{task}: {tasks[task]}", side, sides[task, side]) for task in sorted(tasks) for side in SIDES]
base, head = ([result for result in results if result.side == side] for side in SIDES)
return [*HEADER, *rows, row("All", "base", base), row("All", "head", head), change([(sides[task, "base"], sides[task, "head"]) for task in sorted(tasks)])]
return [cells(HEADINGS), cells(["---"] * len(HEADINGS)).replace(" ", ""), *rows, row("All", "base", base), row("All", "head", head), change([(sides[task, "base"], sides[task, "head"]) for task in sorted(tasks)])]
def medians(results: list[Result]) -> list[float | None]:
"""Input, cache write, cache read, output, turns, wall time and reads."""
measured = [result.figures for result in results if result.figures]
columns: list[list[float]] = [
[found.tokens.input for found in measured],
[found.tokens.write_5m + found.tokens.write_1h for found in measured],
[found.tokens.read for found in measured],
[found.tokens.output for found in measured],
[found.turns for found in measured],
[found.seconds for found in measured],
[found.reads for found in measured if found.reads is not None],
]
return [statistics.median(column) if column else None for column in columns]
def median(column: Column, results: list[Result]) -> float | None:
"""The column's median over the runs that have a value in it."""
values = [value for result in results if result.figures and (value := column.value(result.figures)) is not None]
return statistics.median(values) if values else None
def row(task: str, side: str, results: list[Result]) -> str:
passed = f"{sum(result.passed for result in results)}/{len(results)}"
return cells([task, side, passed, *("-" if median is None else number(median) for median in medians(results))])
return cells([task, 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:
@@ -102,9 +115,7 @@ def change(bugs: list[tuple[list[Result], list[Result]]]) -> str:
as a share of the base median for tokens and wall time, and as a count for turns and reads. This isn't the change from the All
base row to the All head row: those medians land in whichever bug's runs sit in the middle of the pooled costs."""
passed = sum(result.passed for _, head in bugs for result in head) - sum(result.passed for base, _ in bugs for result in base)
pairs = [list(zip(medians(base), medians(head))) for base, head in bugs]
# Turns and reads are small counts, where a share misleads.
means = [mean_change([pair[column] for pair in pairs], share=column not in (4, 6)) for column in range(7)]
means = [mean_change([(median(column, base), median(column, head)) for base, head in bugs], share=column.change == "share") for column in COLUMNS]
return cells(["All", "change", number(passed, signed=True), *(found or "-" for found in means)])
+134 -68
View File
@@ -37,15 +37,15 @@ It prints the base and the head, then a table: a row per bug and side with how m
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.
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 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.
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
@@ -79,17 +79,18 @@ 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 task_bench.digest import Bug, counted, digest, Run
from task_bench.plant import bug_at_sides, drawn, killed_mutants, Mutant, place_files, task_text
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN, WORK
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 claude_code.entries import entries_of
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 task_bench.figures import figures, Result, SIDES, 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
@@ -117,6 +118,32 @@ class Task:
return f"{self.mutant.path}:{self.mutant.line}:{self.mutant.column} {self.mutant.mutator}"
class Asked(typing.NamedTuple):
"""What the caller asked of a bench: the seed that orders the mutants, how many bugs to plant and how often to run each fix."""
seed: int
bugs: int
runs: int
@dataclasses.dataclass(frozen=True)
class Bench:
"""What a bench's phases share: the checkout, per side its commit and its tree without a bug, what the caller asked, the
containers, the bench's folder and git."""
checkout: str
sides: dict[str, str]
trees: dict[str, str]
asked: Asked
containers: Containers
folder: pathlib.Path
git: Git
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
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."""
@@ -202,7 +229,7 @@ def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[st
if isinstance(mutants, Failure):
return mutants
try:
found = opened(containers, given["--image"]) or benched(given, checkout, sides, trees, mutants, containers, folder, git)
found = opened(containers, given["--image"]) or benched(Bench(checkout, sides, trees, Asked(int(given["--seed"]), int(given["--bugs"]), int(given["--runs"])), containers, folder, git), mutants)
finally:
closed(containers)
except OSError as failure:
@@ -239,45 +266,74 @@ def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str |
return str(into)
def benched(given: dict[str, str], checkout: str, sides: dict[str, str], trees: dict[str, str], mutants: list[Mutant], containers: Containers, folder: pathlib.Path, git: Git) -> list[str] | Failure:
"""Plants the bugs, runs each fix, writes the results into folder and returns the report."""
for side, tree in trees.items():
ran = tests_in_copy(containers, tree, folder)
def benched(bench: Bench, mutants: list[Mutant]) -> list[str] | Failure:
"""Plants the bugs, runs each fix, writes the results into the bench's folder and returns the report."""
if failure := baseline_failure(bench):
return failure
tasks = planted_tasks(bench, mutants)
if isinstance(tasks, Failure):
return 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.named() for task in tasks}
kept(bench, tasks, fixes.results)
if fixes.stopped:
return stopped_report(fixes.stopped, fixes.results, total, names, bench.folder)
return report(bench.sides, names, bench.asked, fixes.results)
def baseline_failure(bench: Bench) -> Failure | None:
"""Why a side's tests don't pass without a planted bug; None where both sides' pass."""
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 a planted bug: the test command", ran)
return None
def planted_tasks(bench: Bench, mutants: list[Mutant]) -> list[Task] | Failure:
"""The mutants that become bugs, in the order the seed draws them, until the bench has as many as asked for."""
tasks: list[Task] = []
for mutant in drawn(mutants, int(given["--seed"])):
if len(tasks) == int(given["--bugs"]):
for mutant in drawn(mutants, bench.asked.seed):
if len(tasks) == bench.asked.bugs:
break
task = planted(len(tasks) + 1, mutant, checkout, sides, trees, containers, folder, git)
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 tasks
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] = []
stopped = None
total = int(given["--runs"]) * len(tasks) * len(SIDES)
for number, task, side in itertools.product(range(1, int(given["--runs"]) + 1), tasks, SIDES):
result = fixed(task, side, number, containers, folder)
for number, task, side in itertools.product(range(1, bench.asked.runs + 1), tasks, SIDES):
result = fixed(task, side, number, bench.containers, bench.folder)
if isinstance(result, Failure):
stopped = result
break
return Fixes(results, result)
results.append(result)
print(f"task-bench: run {len(results)} of {total}, bug {task.number} at the {side}: {'passed' if result.passed else 'not passed'}.", file=sys.stderr)
if stopped and not results:
return stopped
return Fixes(results, None)
def kept(bench: Bench, tasks: list[Task], results: list[Result]) -> None:
"""Writes results.json and the digest into the bench's folder."""
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(sides, table(results, names), [digested(task, results, folder) for task in tasks], in_a_tree), encoding="utf-8", errors="replace")
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)]))
(bench.folder / "results.json").write_text(json.dumps({"sides": bench.sides, "seed": bench.asked.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 bench.trees.values())
(bench.folder / DIGEST).write_text(digest(bench.sides, table(results, names), [digested(task, results, bench.folder) for task in tasks], in_a_tree), encoding="utf-8", errors="replace")
def report(sides: dict[str, str], names: dict[int, str], asked: Asked, results: list[Result]) -> list[str]:
"""What a finished bench prints: the commits, the bugs named in names, what ran them, and the table."""
ran_on = sorted({f"{found.model} in Claude Code {found.version}" for result in results if (found := result.figures)})
short = [] if len(tasks) == int(given["--bugs"]) else [f"Planted {len(tasks)} of the {given['--bugs']} bugs asked for: no other mutant the tests kill becomes one."]
short = [] if len(names) == asked.bugs else [f"Planted {len(names)} of the {asked.bugs} bugs asked for: no other mutant the tests kill becomes one."]
return [
f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}. {counted(len(tasks), 'bug')}, each run {counted(int(given['--runs']), 'time')} at each side by {' and '.join(ran_on) or 'no run that finished'}.",
f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}. {counted(len(names), 'bug')}, each run {counted(asked.runs, 'time')} at each side by {' and '.join(ran_on) or 'no run that finished'}.",
*short,
"",
*table(results, names),
@@ -285,39 +341,51 @@ def benched(given: dict[str, str], checkout: str, sides: dict[str, str], trees:
]
def planted(number: int, mutant: Mutant, checkout: str, sides: dict[str, str], trees: dict[str, str], containers: Containers, folder: pathlib.Path, git: Git) -> 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.
def stopped_report(stopped: Failure, results: list[Result], total: int, names: dict[int, str], folder: pathlib.Path) -> 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)]))
The bug is the same change to the same line at both sides, so only the code around it differs between them."""
diff = git("diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", sides["base"], sides["head"], "--", mutant.path, cwd=checkout, errors="replace")
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
at_head = line_at_head(diff, mutant.line)
if at_head is None:
sources = {side: source.read_bytes() if (source := pathlib.Path(tree, mutant.path)).is_file() else None for side, tree in bench.trees.items()}
bugs = bug_at_sides(mutant, diff, sources)
if bugs is None:
return None
planted_trees, messages = {}, {}
for side, placed in (("base", mutant), ("head", mutant._replace(line=at_head))):
source = pathlib.Path(trees[side], mutant.path)
changed = mutated(source.read_bytes(), placed) if source.is_file() else None
if changed is None:
return None
tree = folder / "bugs" / str(number) / side
shutil.rmtree(tree, ignore_errors=True)
shutil.copytree(trees[side], tree, symlinks=True)
(tree / mutant.path).write_bytes(changed)
ran = tests_in_copy(containers, str(tree), folder)
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
return ran
# Tests that never end under the bug have no message to tell Haiku.
message = None if isinstance(ran, TimedOut) else task_text(ran.output)
if message is None:
return None
for args in (["init", "--quiet"], ["add", "--all", "--force"], COMMIT):
done = git(*args, cwd=str(tree))
if isinstance(done, Failure):
return done
planted_trees[side], messages[side] = str(tree), message
return Task(number, mutant, planted_trees, messages)
trees, messages = {}, {}
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, trees, messages)
def planted_tree(bench: Bench, side: str, 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)
shutil.copytree(bench.trees[side], tree, symlinks=True)
(tree / path).write_bytes(changed)
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(ran.output)
if message is None:
return None
for args in (["init", "--quiet"], ["add", "--all", "--force"], COMMIT):
done = bench.git(*args, cwd=str(tree))
if isinstance(done, Failure):
return done
return message
def tests_in_copy(containers: Containers, tree: str, folder: pathlib.Path) -> Ran | Failure:
@@ -341,14 +409,16 @@ def fixed(task: Task, side: str, number: int, containers: Containers, folder: pa
attempted = fix_attempted(containers, str(copy), task.messages[side], stream)
if isinstance(attempted, Failure):
return attempted
found = figures(stream.read_bytes(), os.path.join(WORK, task.mutant.path))
raw = stream.read_bytes()
entries = entries_of(raw)
found = figures(raw, entries, os.path.join(WORK, task.mutant.path))
if isinstance(found, Failure):
return found
checked_tree(task.trees[side], str(copy), str(check))
ran = ran_tests(containers, str(check))
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
return ran
return Result(task.number, side, number, isinstance(ran, Ran) and ran.code == 0, found)
return Result(task.number, side, number, isinstance(ran, Ran) and ran.code == 0, found, tuple(entries))
finally:
shutil.rmtree(copy, ignore_errors=True)
shutil.rmtree(check, ignore_errors=True)
@@ -361,7 +431,7 @@ def stream_of(result: Result, folder: pathlib.Path) -> pathlib.Path:
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 has no tokens."""
runs = [Run(stream_of(result, folder).stem, result.passed, found.tokens.context() + found.tokens.output if (found := result.figures) else None, stream_of(result, folder).read_bytes()) for result in results if result.task == task.number]
runs = [Run(stream_of(result, folder).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 Bug(f"{task.number}: {task.named()}", task.mutant.path, task.messages["base"], runs)
@@ -371,7 +441,3 @@ def recorded(result: Result) -> dict:
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}
def counted(count: int, noun: str) -> str:
return f"{count} {noun}{'' if count == 1 else 's'}"
+17
View File
@@ -86,6 +86,23 @@ def mutated(source: bytes, mutant: Mutant) -> bytes | None:
return b"\n".join(lines)
def bug_at_sides(mutant: Mutant, diff: str, sources: dict[str, bytes | None]) -> dict[str, bytes] | None:
"""The file of mutant with the bug in it, at the base and at the head, from the file at each side, None where the side has
none, and the diff of it from base to head. None where the mutant doesn't become a bug at one side or the other.
The bug is the same change to the same line at both sides, so only the code around it differs between them."""
at_head = line_at_head(diff, mutant.line)
if at_head is None:
return None
bugs = {}
for side, placed in (("base", mutant), ("head", mutant._replace(line=at_head))):
changed = None if (source := sources[side]) is None else mutated(source, placed)
if changed is None:
return None
bugs[side] = changed
return bugs
def line_at_head(diff: str, line: int) -> int | None:
"""The number at the head of a file's line `line` at the base, or None where the head changed or removed that line.
+3 -1
View File
@@ -10,11 +10,13 @@ import typing
from mutate_changes.tool_process import failed, Ran
from failure import Failure
from task_bench.figures import HOME, WORK
from mutate_changes.changed_lines import is_test
from task_bench.api_proxy import PORT
MODEL = "claude-haiku-5-5"
# Where each run's container mounts its copy of the code, and its home folder: the paths in a run's stream start there.
WORK = "/work"
HOME = "/tmp"
# No MCP server, skill, command or stored session, so a run starts from the code alone; -p needs --verbose with stream-json, and no
# one answers a permission prompt. Not --bare, which can't sign in by a long-lived token: docs/decisions.md → `Claude Code in a home
# of its own`.
+6 -5
View File
@@ -7,6 +7,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.digest import Bug, decoys, digest, Run, trace
from claude_code.entries import entries_of, Entry
def said(text: str) -> dict:
@@ -21,11 +22,11 @@ def result(at: str, text: str, failed: bool = False) -> dict:
return {"type": "user", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": f"toolu_{at}", "content": text, "is_error": failed}]}}
def stream(*events: dict) -> bytes:
return "\n".join(map(json.dumps, events)).encode()
def stream(*events: dict) -> list[Entry]:
return entries_of("\n".join(map(json.dumps, events)).encode())
def reading(*paths: str) -> bytes:
def reading(*paths: str) -> list[Entry]:
return stream(*(call("Read", str(at), file_path=f"/work/{path}") for at, path in enumerate(paths)))
@@ -145,11 +146,11 @@ class DigestTest(unittest.TestCase):
self.assertIn("### bug-2-base-1, the passing run with the median tokens, 10 tokens", held.splitlines())
def test_the_median_is_by_tokens_whatever_the_order_the_runs_ran_in(self):
runs = [Run("bug-2-base-1", True, 20, b""), Run("bug-2-head-1", True, 10, b""), Run("bug-2-base-2", True, 30, b"")]
runs = [Run("bug-2-base-1", True, 20, []), Run("bug-2-head-1", True, 10, []), Run("bug-2-base-2", True, 30, [])]
self.assertEqual(digest(SIDES, [], [Bug("2: a.go:1:1 X", "a.go", "boom", runs)], lambda path: True).splitlines()[-2:], ["### bug-2-base-1, the passing run with the median tokens, 20 tokens", ""])
def test_a_run_that_did_not_finish_is_the_failing_trace_and_is_left_out_of_the_median(self):
runs = [Run("bug-4-base-1", False, 900, b""), Run("bug-4-head-1", False, None, b""), Run("bug-4-base-2", True, None, b""), Run("bug-4-head-2", True, 60, b"")]
runs = [Run("bug-4-base-1", False, 900, []), Run("bug-4-head-1", False, None, []), Run("bug-4-base-2", True, None, []), Run("bug-4-head-2", True, 60, [])]
held = digest(SIDES, [], [Bug("4: a.go:1:1 X", "a.go", "boom", runs)], lambda path: True).splitlines()
self.assertEqual([line for line in held if line.startswith("###")], ["### bug-4-head-1, a failing run that didn't finish", "### bug-4-head-2, the passing run with the median tokens, 60 tokens"])
+7 -1
View File
@@ -6,8 +6,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench import figures as bench_figures
from claude_code.entries import entries_of
from failure import Failure
from task_bench.figures import Figures, figures, Result, table
from task_bench.figures import Figures, Result, table
from claude_code.tokens import Tokens
INIT = {"type": "system", "subtype": "init", "cwd": "/work", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330"}
@@ -23,6 +25,10 @@ def stream(*events: dict) -> bytes:
return "\n".join(map(json.dumps, events)).encode() + b"\n"
def figures(raw: bytes, bug_file: str) -> Figures | None | Failure:
return bench_figures.figures(raw, entries_of(raw), bug_file)
class FiguresTest(unittest.TestCase):
def test_reads_the_version_model_tokens_turns_and_wall_time_from_the_streams_first_and_last_events(self):
found = figures(stream(INIT, RESULT), "/work/calc.go")
+20 -1
View File
@@ -7,7 +7,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.plant import drawn, go_files, killed_mutants, line_at_head, Mutant, mutated, place_files, task_text
from task_bench.plant import bug_at_sides, drawn, go_files, killed_mutants, line_at_head, Mutant, mutated, place_files, task_text
from failure import Failure
from mutate_changes.tool_process import Ran
@@ -156,6 +156,25 @@ class LineAtHeadTest(unittest.TestCase):
self.assertEqual(line_at_head("", 12), 12)
class BugAtSidesTest(unittest.TestCase):
MUTANT = Mutant("calc.go", 3, 11, "ARITHMETIC_BASE")
BASE = b"package calc\n\n\treturn a + b\n"
# The head adds a line above the bug's.
HEAD = b"package calc\n// Add adds.\n\n\treturn a + b\n"
DIFF = "@@ -1,0 +2 @@\n+// Add adds.\n"
def test_the_bug_is_the_same_change_at_each_side_on_the_line_as_that_side_numbers_it(self):
found = bug_at_sides(self.MUTANT, self.DIFF, {"base": self.BASE, "head": self.HEAD})
self.assertEqual(found, {"base": self.BASE.replace(b"+", b"-"), "head": self.HEAD.replace(b"+", b"-")})
def test_a_line_the_head_changed_holds_no_bug(self):
self.assertIsNone(bug_at_sides(self.MUTANT, "@@ -3 +3 @@\n-\treturn a + b\n+\treturn b + a\n", {"base": self.BASE, "head": self.BASE}))
def test_a_side_without_the_file_or_without_the_token_holds_no_bug(self):
self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": None}))
self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": b"package calc\n\n\treturn sum(a, b)\n"}))
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
+31 -10
View File
@@ -17,10 +17,12 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench import api_proxy, bench_folder, main, runs
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests, TimedOut
from task_bench.plant import drawn, Mutant
from claude_code.entries import Entry
from failure import Failure
from task_bench.figures import Figures, Result, table
from test_env import isolated_env
from mutate_changes.tool_process import Ran
from task_bench.figures import Result
from claude_code.tokens import Tokens
BASE_CODE = "package calc\n\nfunc Add(a, b int) int {\n\treturn a + b\n}\n\nfunc Twice(a int) int {\n\treturn a * 2\n}\n"
# The head adds a line right above Add, which moves it down, and rewrites Twice's line.
@@ -344,6 +346,24 @@ class BenchTest(unittest.TestCase):
self.assertIn("docker build", found.reason)
class ReportTest(unittest.TestCase):
SIDES = {"base": "b" * 40, "head": "h" * 40}
NAMES = {1: "calc.go:4:11 ARITHMETIC_BASE"}
RESULTS = [Result(1, "base", 1, True, Figures("2.1.330", "claude-haiku-5-5", Tokens(40, 0, 9000, 52000, 800), 7, 61.5, 2)), Result(1, "head", 1, False, None)]
def test_names_the_commits_the_bugs_the_runs_and_what_ran_them_above_the_table(self):
told = main.report(self.SIDES, self.NAMES, main.Asked(seed=1, bugs=1, runs=2), self.RESULTS)
self.assertEqual(told, ["task-bench: base bbbbbbbbbbbb, head hhhhhhhhhhhh. 1 bug, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.", "", *table(self.RESULTS, self.NAMES), ""])
def test_says_where_fewer_bugs_were_planted_than_asked_for_and_where_no_run_finished(self):
told = main.report(self.SIDES, self.NAMES, main.Asked(seed=1, bugs=3, runs=1), self.RESULTS[1:])
self.assertEqual(told[:3], ["task-bench: base bbbbbbbbbbbb, head hhhhhhhhhhhh. 1 bug, each run 1 time at each side by no run that finished.", "Planted 1 of the 3 bugs asked for: no other mutant the tests kill becomes one.", ""])
def test_a_stopped_bench_tells_why_then_how_far_it_came_then_the_table(self):
told = main.stopped_report(Failure("claude could not use the API: Invalid bearer token"), self.RESULTS, 10, self.NAMES, pathlib.Path("/reviews/task-bench"))
self.assertEqual(told, Failure("\n".join(["claude could not use the API: Invalid bearer token", "task-bench stopped after 2 of 10 runs, which results.json holds in /reviews/task-bench:", "", *table(self.RESULTS, self.NAMES)])))
class MainTest(unittest.TestCase):
def run_main(self, *argv: str, token: str = "t") -> tuple[int, str]:
with contextlib.redirect_stderr(io.StringIO()) as errors, contextlib.redirect_stdout(io.StringIO()):
@@ -377,12 +397,10 @@ class MainTest(unittest.TestCase):
def test_a_run_that_did_not_finish_has_no_tokens_in_the_digest(self):
with tempfile.TemporaryDirectory() as folder:
pathlib.Path(folder, "runs").mkdir()
pathlib.Path(folder, "runs/bug-1-base-2.jsonl").write_bytes(b"{}")
task = main.Task(1, Mutant("calc.go", 4, 11, "ARITHMETIC_BASE"), {}, {"base": "boom", "head": "bang"})
bug = main.digested(task, [Result(1, "base", 2, False, None), Result(2, "base", 1, True, None)], pathlib.Path(folder))
self.assertEqual(bug, ("1: calc.go:4:11 ARITHMETIC_BASE", "calc.go", "boom", [("bug-1-base-2", False, None, b"{}")]))
task = main.Task(1, Mutant("calc.go", 4, 11, "ARITHMETIC_BASE"), {}, {"base": "boom", "head": "bang"})
entries = (Entry(),)
bug = main.digested(task, [Result(1, "base", 2, False, None, entries), Result(2, "base", 1, True, None)], pathlib.Path("/bench"))
self.assertEqual(bug, ("1: calc.go:4:11 ARITHMETIC_BASE", "calc.go", "boom", [("bug-1-base-2", False, None, entries)]))
def test_records_a_run_that_did_not_finish_without_figures(self):
self.assertEqual(main.recorded(Result(1, "base", 2, False, None)), {"bug": 1, "side": "base", "run": 2, "passed": False, "finished": False})
@@ -431,6 +449,9 @@ class RunOutcomesTest(unittest.TestCase):
def containers(self, *runs: Ran | Failure) -> Containers:
return Containers(InTurn(*runs), "bench", "go test ./...", 512, "1000:1000")
def bench(self, *runs: Ran | Failure) -> main.Bench:
return main.Bench("", {"base": "b", "head": "h"}, self.trees, main.Asked(seed=1, bugs=1, runs=1), self.containers(*runs), self.folder, lambda *args, **given: "")
def test_a_fix_whose_tests_run_out_of_time_does_not_pass(self):
late = TimedOut("docker run still ran after 30 min")
self.assertEqual(main.fixed(self.task, "base", 1, self.containers(Ran(0, ""), late), self.folder), Result(1, "base", 1, False, None))
@@ -441,15 +462,15 @@ class RunOutcomesTest(unittest.TestCase):
def test_tests_docker_could_not_run_without_a_bug_fail_the_bench(self):
broke = Failure("docker could not start: No such file or directory")
self.assertEqual(main.benched({}, "", {}, self.trees, [], self.containers(broke), self.folder, None), broke)
self.assertEqual(main.benched(self.bench(broke), []), broke)
def test_a_mutant_whose_tests_run_out_of_time_is_passed_over(self):
late = TimedOut("docker run still ran after 30 min")
self.assertIsNone(main.planted(1, self.MUTANT, "", {"base": "b", "head": "h"}, self.trees, self.containers(late), self.folder, lambda *args, **given: ""))
self.assertIsNone(main.planted(self.bench(late), 1, self.MUTANT))
def test_a_mutant_whose_tests_docker_could_not_run_fails_the_bench(self):
broke = Failure("docker could not start: No such file or directory")
self.assertEqual(main.planted(1, self.MUTANT, "", {"base": "b", "head": "h"}, self.trees, self.containers(broke), self.folder, lambda *args, **given: ""), broke)
self.assertEqual(main.planted(self.bench(broke), 1, self.MUTANT), broke)
class ContainersTest(unittest.TestCase):