Answer principles round 1: 0 🔴, 5 🟡 (0 misread); make a move a union with ToStatus, take only parsed events in figures, catch OSError at each file operation, pass progress through the bench, type the sides, and split the README bullet
CI / tests (pull_request) Successful in 5m4s

This commit is contained in:
2026-11-23 01:37:39 +01:00
parent 9fe060575b
commit cfe537b3fd
11 changed files with 186 additions and 123 deletions
+2 -1
View File
@@ -8,6 +8,7 @@ import typing
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
from task_bench.figures import Side
# A trace keeps the first TEXT_LINES lines of the model's text between two calls, and the first TEXT_WIDTH characters of each.
TEXT_LINES = 3
@@ -40,7 +41,7 @@ class Bug(typing.NamedTuple):
runs: list[Run]
def digest(sides: dict[str, str], table: list[str], bugs: list[Bug], is_file: typing.Callable[[str], bool]) -> str:
def digest(sides: dict[Side, str], table: list[str], bugs: list[Bug], is_file: typing.Callable[[str], bool]) -> str:
"""The digest of a bench of the commits sides names: where each side's code is, the table of its figures, then each bug.
is_file says whether a path in the project names a file."""
code = f"Base {sides['base']}, head {sides['head']}. A bug's name gives its line at the base. Each side's code without the bugs is in `trees/base` and `trees/head` in the bench's folder."
+8 -7
View File
@@ -3,7 +3,7 @@ import dataclasses
import statistics
import typing
from claude_code.entries import Entry, json_object, tool_calls, ToolCall
from claude_code.entries import Entry, entry_from, tool_calls, ToolCall
from failure import Failure
from task_bench.runs import HOME, WORK
from reading_cost.measure import reads_of
@@ -11,7 +11,9 @@ from claude_code.tokens import Tokens, tokens_of
# 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")
# A bench's two sides: the commit before the change and the one after it.
Side = typing.Literal["base", "head"]
SIDES: tuple[Side, Side] = ("base", "head")
@dataclasses.dataclass(frozen=True)
@@ -31,7 +33,7 @@ class Result(typing.NamedTuple):
holds what its stream tells, for the digest."""
task: int
side: str
side: Side
run: int
passed: bool
figures: Figures | None
@@ -60,13 +62,12 @@ COLUMNS = (
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
def figures(events: list[dict], bug_file: str) -> Figures | None | Failure:
"""The figures of the run whose claude printed events, its stream's JSON lines, 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."""
events = [event for line in stream.splitlines() if (event := json_object(line))]
result = next((event for event in reversed(events) if event.get("type") == "result"), None)
if result is None:
return None
@@ -75,7 +76,7 @@ def figures(stream: bytes, entries: typing.Sequence[Entry], bug_file: str) -> Fi
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"), {})
calls = [call for _, call in tool_calls(entries)]
calls = [call for _, call in tool_calls([entry_from(event) for event in events])]
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))
+93 -57
View File
@@ -87,10 +87,10 @@ 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 claude_code.entries import entries_of
from claude_code.entries import entry_from, json_objects
from mutate_changes.tool_process import failed, Ran, run_tool
from failure import Failure
from task_bench.figures import figures, Result, SIDES, table
from task_bench.figures import figures, Result, Side, 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
@@ -111,8 +111,8 @@ class Task:
"""A bug to fix: its number from 1, the mutant at the base, and per side the planted tree and what Haiku is told there."""
number: int
mutant: Mutant
trees: dict[str, str]
messages: dict[str, str]
trees: dict[Side, str]
messages: dict[Side, str]
def named(self) -> str:
return f"{self.mutant.path}:{self.mutant.line}:{self.mutant.column} {self.mutant.mutator}"
@@ -128,14 +128,15 @@ class Asked(typing.NamedTuple):
@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."""
containers, the bench's folder, git, and say, which tells the caller each run's outcome as it finishes."""
checkout: str
sides: dict[str, str]
trees: dict[str, str]
sides: dict[Side, str]
trees: dict[Side, str]
asked: Asked
containers: Containers
folder: pathlib.Path
git: Git
say: typing.Callable[[str], None]
class Fixes(typing.NamedTuple):
@@ -190,8 +191,22 @@ def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] |
return given
def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, home: pathlib.Path) -> list[str] | Failure:
"""The report of one bench of the checkout the process runs in, with `places` what `larv-review places` prints there."""
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 on_disk[T](doing: str, act: typing.Callable[[], T]) -> T | Failure:
"""act's answer, or a Failure that says what could not be done where the filesystem refuses act."""
try:
return act()
except OSError as failure:
return Failure(f"could not {doing}: {failure}")
def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, home: pathlib.Path, say: typing.Callable[[str], None] = progress) -> list[str] | Failure:
"""The report of one bench of the checkout the process runs in, with `places` what `larv-review places` prints there; say
tells the caller the bench's progress."""
git = functools.partial(git_repo.git, env=env)
checkout = top(git)
if isinstance(checkout, Failure):
@@ -199,7 +214,7 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, hom
sides = commits(given, checkout, git)
if isinstance(sides, Failure):
return sides
print(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.", file=sys.stderr)
say(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.")
review = made_review_folder(checkout, home)
if isinstance(review, Failure):
return review
@@ -207,37 +222,34 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, hom
if isinstance(folder, Failure):
return folder
clear_left(home / REPORTS)
return bench_in(folder, given, env, places, checkout, sides, git)
return bench_in(folder, given, env, places, checkout, sides, git, say)
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:
def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[str, str], places: str, checkout: str, sides: dict[Side, str], git: Git, say: typing.Callable[[str], None]) -> 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()}")
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
files = [path for path in place_files(places) if pathlib.Path(trees["base"], path).is_file()]
if not files:
return Failure("The places the seats found hard name no Go file that the base holds, so there is nowhere to plant a bug.")
run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg)
mutants = killed_mutants(trees["base"], files, run, CPUS_PER_SLOT)
if isinstance(mutants, Failure):
return mutants
try:
shutil.rmtree(folder, ignore_errors=True)
trees: dict[str, str] = {}
for side, commit in sides.items():
tree = archived(commit, folder / "trees" / side, checkout, git)
if isinstance(tree, Failure):
return tree
trees[side] = tree
files = [path for path in place_files(places) if pathlib.Path(trees["base"], path).is_file()]
if not files:
return Failure("The places the seats found hard name no Go file that the base holds, so there is nowhere to plant a bug.")
run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg)
mutants = killed_mutants(trees["base"], files, run, CPUS_PER_SLOT)
if isinstance(mutants, Failure):
return mutants
try:
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:
return Failure(f"could not write under {folder}: {failure}")
found = opened(containers, given["--image"]) or benched(Bench(checkout, sides, trees, Asked(int(given["--seed"]), int(given["--bugs"]), int(given["--runs"])), containers, folder, git, say), mutants)
finally:
closed(containers)
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:
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)
@@ -252,7 +264,9 @@ def commits(given: dict[str, str], checkout: str, git: Git) -> dict[str, str] |
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`."""
into.mkdir(parents=True)
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):
@@ -260,9 +274,9 @@ def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str |
try:
with tarfile.open(archive) as held:
held.extractall(into, filter="tar")
except tarfile.TarError as failure:
archive.unlink()
except (tarfile.TarError, OSError) as failure:
return Failure(f"could not unpack the tree at {commit}: {failure}")
archive.unlink()
return str(into)
@@ -278,7 +292,8 @@ def benched(bench: Bench, mutants: list[Mutant]) -> list[str] | Failure:
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 failure := kept(bench, tasks, names, fixes.results):
return failure
if fixes.stopped:
return stopped_report(fixes.stopped, fixes.results, total, names, bench.folder)
return report(bench.sides, names, bench.asked, fixes.results)
@@ -316,19 +331,24 @@ def ran_fixes(bench: Bench, tasks: list[Task], total: int) -> Fixes:
if isinstance(result, Failure):
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)
bench.say(f"task-bench: run {len(results)} of {total}, bug {task.number} at the {side}: {'passed' if result.passed else 'not passed'}.")
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}
(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")
def kept(bench: Bench, tasks: list[Task], names: dict[int, str], results: list[Result]) -> Failure | None:
"""Writes results.json and the digest into the bench's folder, with names the bugs' names by number."""
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")
recorded_runs = json.dumps({"sides": bench.sides, "seed": bench.asked.seed, "bugs": names, "runs": [recorded(result) for result in results]}, indent="\t") + "\n"
digest_text = digest(bench.sides, table(results, names), [digested(task, results, bench.folder) for task in tasks], in_a_tree)
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[str, str], names: dict[int, str], asked: Asked, results: list[Result]) -> list[str]:
def report(sides: dict[Side, 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(names) == asked.bugs else [f"Planted {len(names)} of the {asked.bugs} bugs asked for: no other mutant the tests kill becomes one."]
@@ -352,11 +372,14 @@ def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None:
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 = {side: source.read_bytes() if (source := pathlib.Path(tree, mutant.path)).is_file() else None for side, tree in bench.trees.items()}
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)
if bugs is None:
return None
trees, messages = {}, {}
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)
@@ -366,12 +389,15 @@ def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None:
return Task(number, mutant, trees, messages)
def planted_tree(bench: Bench, side: str, tree: pathlib.Path, path: str, changed: bytes) -> str | Failure | None:
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)
shutil.copytree(bench.trees[side], tree, symlinks=True)
(tree / path).write_bytes(changed)
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):
@@ -391,30 +417,40 @@ def planted_tree(bench: Bench, side: str, tree: pathlib.Path, path: str, changed
def tests_in_copy(containers: Containers, tree: str, folder: pathlib.Path) -> Ran | Failure:
"""The test command's run in a copy of tree, removed afterwards, so what the tests write stays out of tree."""
copy = folder / "tested"
shutil.copytree(tree, copy, symlinks=True)
copied = on_disk(f"copy {tree} to test it", lambda: shutil.copytree(tree, copy, symlinks=True))
if isinstance(copied, Failure):
return copied
try:
return ran_tests(containers, str(copy))
finally:
shutil.rmtree(copy, ignore_errors=True)
def fixed(task: Task, side: str, number: int, containers: Containers, folder: pathlib.Path) -> Result | Failure:
def fixed(task: Task, side: Side, 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 = stream_of(Result(task.number, side, number, False, None), folder)
stream.parent.mkdir(exist_ok=True)
copy, check = folder / "copy", folder / "check"
try:
shutil.copytree(task.trees[side], copy, symlinks=True)
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 bug {task.number}'s tree at the {side}: {failure}")
attempted = fix_attempted(containers, str(copy), task.messages[side], stream)
if isinstance(attempted, Failure):
return attempted
raw = stream.read_bytes()
entries = entries_of(raw)
found = figures(raw, entries, os.path.join(WORK, task.mutant.path))
raw = on_disk(f"read {stream}", stream.read_bytes)
if isinstance(raw, Failure):
return raw
events = json_objects(raw)
entries = [entry_from(event) for event in events]
found = figures(events, os.path.join(WORK, task.mutant.path))
if isinstance(found, Failure):
return found
checked_tree(task.trees[side], str(copy), str(check))
checked = on_disk(f"make the tree that checks bug {task.number}'s fix at the {side}", lambda: checked_tree(task.trees[side], str(copy), str(check)))
if isinstance(checked, Failure):
return checked
ran = ran_tests(containers, str(check))
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
return ran
+5 -3
View File
@@ -9,6 +9,7 @@ from failure import Failure
from mutate_changes.in_diff_tools import gremlins_mutants
from mutate_changes.changed_lines import is_test
from mutate_changes.tool_process import Run
from task_bench.figures import Side
# A place as `larv-review places` prints it: `<path>:<line>` in backticks.
PLACE = re.compile(r"`([^`\s:]+):\d+`")
@@ -86,7 +87,7 @@ 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:
def bug_at_sides(mutant: Mutant, diff: str, sources: dict[Side, bytes | None]) -> dict[Side, 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.
@@ -94,8 +95,9 @@ def bug_at_sides(mutant: Mutant, diff: str, sources: dict[str, bytes | None]) ->
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))):
bugs: dict[Side, bytes] = {}
placings: tuple[tuple[Side, Mutant], ...] = (("base", mutant), ("head", mutant._replace(line=at_head)))
for side, placed in placings:
changed = None if (source := sources[side]) is None else mutated(source, placed)
if changed is None:
return None
+2 -2
View File
@@ -7,9 +7,9 @@ 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, Result, table
from claude_code.entries import json_objects
from claude_code.tokens import Tokens
INIT = {"type": "system", "subtype": "init", "cwd": "/work", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330"}
@@ -26,7 +26,7 @@ def stream(*events: dict) -> bytes:
def figures(raw: bytes, bug_file: str) -> Figures | None | Failure:
return bench_figures.figures(raw, entries_of(raw), bug_file)
return bench_figures.figures(json_objects(raw), bug_file)
class FiguresTest(unittest.TestCase):
+13 -1
View File
@@ -450,7 +450,7 @@ class RunOutcomesTest(unittest.TestCase):
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: "")
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: "", lambda line: None)
def test_a_fix_whose_tests_run_out_of_time_does_not_pass(self):
late = TimedOut("docker run still ran after 30 min")
@@ -659,5 +659,17 @@ class ApiProxyTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(await self.answered(request), b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
class OnDisk(unittest.TestCase):
def test_a_refused_file_operation_is_a_failure_that_says_what_could_not_be_done(self):
with tempfile.TemporaryDirectory() as folder:
missing = pathlib.Path(folder, "gone", "file")
found = main.on_disk(f"read {missing}", missing.read_bytes)
self.assertIsInstance(found, Failure)
self.assertTrue(found.reason.startswith(f"could not read {missing}: "), found.reason)
def test_an_operation_that_succeeds_gives_its_answer(self):
self.assertEqual(main.on_disk("count", lambda: 3), 3)
if __name__ == "__main__":
unittest.main()