Answer stability round 1: 0 🔴, 10 🟡 (0 misread); take the failed test's last message, fail on a docker run that never started, keep testdata as planted, show finished runs when the API refuses one, and test five survivors

This commit is contained in:
2026-11-21 02:41:36 +01:00
parent 1e96a397af
commit 8c1edf552a
9 changed files with 275 additions and 112 deletions
+112 -17
View File
@@ -15,7 +15,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench import api_proxy, main, runs
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests
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 failure import Failure
from test_env import isolated_env
from mutate_changes.tool_process import Ran
@@ -60,11 +61,14 @@ DOCKER = textwrap.dedent("""\
sys.exit(subprocess.run(command, cwd=tree).returncode)
""")
# Reads the README, then the file with the bug. At the head it fixes the bug; at the base it rewrites the test to pass instead.
# From its FAKE_REFUSED_FROM-th run on, the API refuses it.
CLAUDE = textwrap.dedent("""\
import json, os, pathlib, sys
def call(name, path):
return {"type": "assistant", "message": {"id": "msg_" + path, "content": [{"type": "tool_use", "id": "toolu_" + path, "name": name, "input": {"file_path": path}}], "usage": {}}}
if os.environ.get("FAKE_REFUSED"):
count = pathlib.Path(os.environ["FAKE_LOG"] + ".fixes")
count.write_text(count.read_text() + "." if count.exists() else ".")
if len(count.read_text()) >= int(os.environ.get("FAKE_REFUSED_FROM") or 10 ** 9):
print(json.dumps({"type": "result", "is_error": True, "api_error_status": 401, "result": "API Error: 401"}))
sys.exit(1)
print(json.dumps({"type": "system", "subtype": "init", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330"}))
@@ -130,10 +134,10 @@ class BenchTest(unittest.TestCase):
self.assertNotIsInstance(report, Failure, report)
folder = pathlib.Path(report[-1].removeprefix("Each run's result and stream: "))
self.assertEqual(report[:-1], [
f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 bug, fixed 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.",
f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 bug, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.",
"Planted 1 of the 2 bugs asked for: no other mutant the tests kill becomes one.",
"",
"| Task | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |",
"| Bug | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |",
"|---|---|---|---|---|---|---|---|---|---|",
"| 1: calc.go:4:11 ARITHMETIC_BASE | base | 0/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |",
"| 1: calc.go:4:11 ARITHMETIC_BASE | head | 2/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |",
@@ -166,8 +170,8 @@ class BenchTest(unittest.TestCase):
self.assertEqual(main.main(argv, self.env, lambda home: homes.append(home) or PLACES), 0)
self.assertEqual(homes, [self.home])
# Without --base, the base is the merge base with the default branch.
self.assertEqual(out.getvalue().splitlines()[0], f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 bug, fixed 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
self.assertEqual(out.getvalue().splitlines()[3], "| Task | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |")
self.assertEqual(out.getvalue().splitlines()[0], f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 bug, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
self.assertEqual(out.getvalue().splitlines()[3], "| Bug | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |")
self.assertTrue(out.getvalue().endswith("task-bench\n"), out.getvalue()[-80:])
def test_the_command_line_fails_with_the_reason_where_the_places_or_the_bench_fail(self):
@@ -179,7 +183,7 @@ class BenchTest(unittest.TestCase):
def test_the_head_is_the_commit_asked_for(self):
report = self.bench(**{"--head": "main", "--runs": "1"})
self.assertEqual(report[0], f"task-bench: base {self.base[:12]}, head {self.base[:12]}. 1 bug, fixed 1 time at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
self.assertEqual(report[0], f"task-bench: base {self.base[:12]}, head {self.base[:12]}. 1 bug, each run 1 time at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
def test_fails_on_a_head_or_a_base_git_does_not_know(self):
for name in ("--head", "--base"):
@@ -236,7 +240,7 @@ class BenchTest(unittest.TestCase):
def test_benches_the_head_against_itself_where_the_base_is_the_head(self):
report = self.bench(**{"--base": "HEAD", "--runs": "1", "--bugs": "1"})
self.assertEqual(report[0], f"task-bench: base {self.head[:12]}, head {self.head[:12]}. 1 bug, fixed 1 time at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
self.assertEqual(report[0], f"task-bench: base {self.head[:12]}, head {self.head[:12]}. 1 bug, each run 1 time at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
self.assertEqual(report[4:6], ["| 1: calc.go:5:11 ARITHMETIC_BASE | base | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |", "| 1: calc.go:5:11 ARITHMETIC_BASE | head | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |"])
def test_fails_where_the_places_name_no_go_file_of_the_base(self):
@@ -255,13 +259,41 @@ class BenchTest(unittest.TestCase):
# Passing tests with the bug planted: nothing to tell Haiku.
(self.repo / "calc_test.go").write_text("exit 0\n")
self.commit("Tests that catch nothing")
self.assertEqual(self.bench(), Failure("None of the 2 mutants the tests kill becomes a bug: each is on a line the head changed, or fails no assertion with a message."))
self.assertEqual(self.bench(), Failure("None of the 2 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."))
def test_a_run_the_api_refuses_fails_the_bench_and_still_removes_what_it_made(self):
self.env["FAKE_REFUSED"] = "1"
self.env["FAKE_REFUSED_FROM"] = "1"
self.assertEqual(self.bench(), Failure("claude could not use the API: API Error: 401"))
self.assertEqual(self.calls()[-1][:2], ["image", "rm"])
def test_a_run_the_api_refuses_later_fails_the_bench_after_the_table_of_the_runs_that_finished(self):
self.env["FAKE_REFUSED_FROM"] = "3"
found = self.bench()
self.assertIsInstance(found, Failure)
lines = found.reason.splitlines()
folder = next(self.home.glob(".local/state/larv-review/**/task-bench"))
self.assertEqual(lines[:3], ["claude could not use the API: API Error: 401", f"task-bench stopped after 2 of 4 runs, which results.json holds in {folder}:", ""])
self.assertEqual(lines[-3:-1], ["| All | base | 0/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |", "| All | head | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |"])
self.assertEqual([(run["side"], run["run"]) for run in json.loads((folder / "results.json").read_text())["runs"]], [("base", 1), ("head", 1)])
def test_a_change_to_another_file_neither_moves_nor_drops_the_bug(self):
(self.repo / "notes.txt").write_text("one\ntwo\nthree\nfour\nfive\nsix\n")
self.commit("Notes")
report = self.bench(**{"--bugs": "1", "--runs": "1"})
self.assertNotIsInstance(report, Failure, report)
self.assertEqual(report[4].partition(" | ")[0], "| 1: calc.go:4:11 ARITHMETIC_BASE")
def test_the_seed_sets_which_mutant_becomes_the_first_bug(self):
# Tests that catch both mutants, at a head benched against itself, where each mutant's line stands.
(self.repo / "calc_test.go").write_text(TESTS.replace("calc.go &&", "calc.go && grep -q '2 \\* a' calc.go &&"))
self.commit("Tests that catch Twice")
mutants = [Mutant("calc.go", 5, 11, "ARITHMETIC_BASE"), Mutant("calc.go", 9, 11, "ARITHMETIC_BASE")]
for seed in (1, 2, 3, 4):
report = self.bench(**{"--base": "HEAD", "--bugs": "1", "--runs": "1", "--seed": str(seed)})
self.assertNotIsInstance(report, Failure, report)
first = drawn(mutants, seed)[0]
self.assertEqual(report[4].partition(" | ")[0], f"| 1: calc.go:{first.line}:11 ARITHMETIC_BASE", seed)
def test_a_docker_that_fails_to_build_fails_the_bench(self):
self.env["FAKE_FAILS"] = "build"
found = self.bench()
@@ -275,7 +307,7 @@ class MainTest(unittest.TestCase):
return main.main(list(argv), {"CLAUDE_CODE_OAUTH_TOKEN": token, "HOME": "/nonexistent"}), errors.getvalue()
def test_refuses_an_unknown_repeated_or_valueless_argument(self):
for argv, said in ((["--imgae", "x"], "unknown or repeated argument --imgae"), (["--image", "x", "--image=y"], "unknown or repeated argument --image"), (["--image"], "--image needs a value")):
for argv, said in ((["--imgae", "x"], "unknown argument --imgae"), (["--image", "x", "--image=y"], "--image is given twice"), (["--image"], "--image needs a value")):
code, errors = self.run_main(*argv)
self.assertEqual((code, errors.startswith(f"{said}; usage: task-bench --image")), (1, True), errors)
@@ -320,6 +352,55 @@ class Recorded:
return self.answers.get(args[0], Ran(0, "ran"))
class InTurn(Recorded):
"""A docker that answers each `run` with the next of `runs`."""
def __init__(self, *runs: Ran | Failure):
super().__init__()
self.runs = list(runs)
def __call__(self, args, *, seconds, stdin=None, stdout=None, stderr=None):
answer = super().__call__(args, seconds=seconds, stdin=stdin, stdout=stdout, stderr=stderr)
return self.runs.pop(0) if args[0] == "run" else answer
class RunOutcomesTest(unittest.TestCase):
MUTANT = Mutant("calc.go", 4, 11, "ARITHMETIC_BASE")
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.folder = pathlib.Path(folder.name)
self.tree = self.folder / "tree"
self.tree.mkdir()
(self.tree / "calc.go").write_text(BASE_CODE)
self.trees = {"base": str(self.tree), "head": str(self.tree)}
self.task = main.Task(1, self.MUTANT, self.trees, {"base": "got 3", "head": "got 3"})
def containers(self, *runs: Ran | Failure) -> Containers:
return Containers(InTurn(*runs), "bench", "go test ./...", 512, "1000:1000")
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))
def test_a_fix_whose_tests_docker_could_not_run_fails_the_bench(self):
broke = Failure("docker could not start: No such file or directory")
self.assertEqual(main.fixed(self.task, "base", 1, self.containers(Ran(0, ""), broke), self.folder), broke)
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)
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: ""))
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)
class ContainersTest(unittest.TestCase):
IN_TREE = ["--memory", "512m", "--memory-swap", "512m", "--user", "1000:1000", "--env", "HOME=/tmp", "--volume", "/tree:/work", "--workdir", "/work"]
REMOVED = (["rm", "--force", "bench-run"], 120, None)
@@ -357,7 +438,7 @@ class ContainersTest(unittest.TestCase):
self.assertEqual(self.docker.calls, [(["run", "--rm", "--name", "bench-run", "--network", "none", *self.IN_TREE, "bench:throwaway", "sh", "-c", "go test ./..."], 1800, None)])
def test_tests_that_run_out_of_time_are_a_failure_and_their_container_goes(self):
late = Failure("docker run still ran after 30 min")
late = TimedOut("docker run still ran after 30 min")
self.assertEqual(ran_tests(self.containers(run=late), "/tree"), late)
self.assertEqual(self.docker.calls[1:], [self.REMOVED])
@@ -370,12 +451,19 @@ class ContainersTest(unittest.TestCase):
self.assertEqual(args[18:25], ["--env", "CLAUDE_CODE_OAUTH_TOKEN", "--env", "HTTPS_PROXY=http://bench-proxy:8080", "--env", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "bench:throwaway"])
def test_a_fix_that_runs_out_of_time_is_no_failure_and_its_container_goes(self):
self.assertIsNone(fix_attempted(self.containers(run=Failure("docker run still ran after 30 min")), "/tree", "got 3", self.stream))
self.assertIsNone(fix_attempted(self.containers(run=TimedOut("docker run still ran after 30 min")), "/tree", "got 3", self.stream))
self.assertEqual(self.docker.calls[1:], [self.REMOVED])
def test_a_run_whose_command_never_started_is_a_failure_that_says_what_docker_printed(self):
for code in (125, 126, 127):
self.assertEqual(ran_tests(self.containers(run=Ran(code, "sh: gotestsum: not found\n")), "/tree"), Failure(f"docker run could not start its command, and exited {code}: sh: gotestsum: not found"))
self.assertEqual(ran_tests(self.containers(run=Ran(124, "late")), "/tree"), Ran(124, "late"))
self.assertEqual(ran_tests(self.containers(run=Ran(128, "killed")), "/tree"), Ran(128, "killed"))
self.assertEqual(fix_attempted(self.containers(run=Ran(125, "")), "/tree", "got 3", self.stream), Failure(f"docker run could not start its command, and exited 125; its errors are in {self.stream.with_suffix('.stderr')}"))
def test_a_fix_docker_could_not_start_is_a_failure(self):
broke = Failure("docker could not start: No such file or directory")
self.assertEqual(fix_attempted(self.containers(run=broke), "/tree", "got 3", self.stream), broke)
self.assertEqual(fix_attempted(self.containers(run=broke), "/tree", "got 3", self.stream), Failure(f"{broke.reason}; its errors are in {self.stream.with_suffix('.stderr')}"))
self.assertEqual(self.docker.calls[1:], [self.REMOVED])
def test_a_stream_that_cannot_be_written_is_a_failure(self):
@@ -418,7 +506,7 @@ class DockerCliTest(unittest.TestCase):
waited.append(timeout)
raise subprocess.TimeoutExpired(argv, timeout)
self.assertEqual(docker_cli({}, late)(["run", "--rm"], seconds=90), Failure("docker run still ran after 2 min"))
self.assertEqual(docker_cli({}, late)(["run", "--rm"], seconds=90), TimedOut("docker run still ran after 2 min"))
self.assertEqual(waited, [90])
@@ -444,6 +532,12 @@ class CheckedTreeTest(unittest.TestCase):
checked_tree(planted, copy, str(self.root / "check"))
self.assertEqual(self.held("check"), {".git/HEAD": "ref", "calc.go": "fixed", "calc_test.go": "tests", "sub/new.go": "new", "sub/old_test.go": "old tests"})
def test_takes_the_files_under_testdata_as_planted_since_a_test_reads_what_it_expects_there(self):
planted = self.tree("planted", {"calc.go": "bug", "testdata/want.golden": "3", "sub/testdata/gone.golden": "4", "testdata.go": "code"})
copy = self.tree("copy", {"calc.go": "fixed", "testdata/want.golden": "-1", "testdata/added.golden": "5", "testdata.go": "fixed"})
checked_tree(planted, copy, str(self.root / "check"))
self.assertEqual(self.held("check"), {"calc.go": "fixed", "sub/testdata/gone.golden": "4", "testdata.go": "fixed", "testdata/want.golden": "3"})
def test_copies_a_link_as_a_link(self):
planted = self.tree("planted", {"calc.go": "bug"})
copy = self.tree("copy", {"calc.go": "fixed"})
@@ -469,8 +563,9 @@ class ApiProxyTest(unittest.IsolatedAsyncioTestCase):
await writer.drain()
writer.close()
api = await asyncio.start_server(echoed, "127.0.0.1", 0)
self.allowed = f"127.0.0.1:{api.sockets[0].getsockname()[1]}"
# On an address of its own, so a tunnel to any other host finds nothing listening.
api = await asyncio.start_server(echoed, "127.0.0.2", 0)
self.allowed = f"127.0.0.2:{api.sockets[0].getsockname()[1]}"
proxy = await asyncio.start_server(lambda reader, writer: api_proxy.served(self.allowed, reader, writer), "127.0.0.1", 0)
self.port = proxy.sockets[0].getsockname()[1]
for server in (api, proxy):