Keep a Rust test in a file of its own as planted in a task-bench fix

This commit is contained in:
2026-11-27 16:05:56 +01:00
parent 4a4a8526af
commit 86edf81d28
5 changed files with 195 additions and 23 deletions
+12 -3
View File
@@ -42,8 +42,10 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
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.
is never closed, is passed over. A Rust file that a `#[cfg(test)] mod name;` in another file of the planted tree names, as
`src/name.rs` or `src/name/mod.rs` beside a `lib.rs`, `main.rs` or `mod.rs`, or in the folder of any other file's name, is a
test: it stands as the planted tree has it, and no mutant is planted in it. A Rust mutant in a tree where such a declaration
names no file there, as one that `#[path]` moves does, is passed over.
--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
@@ -200,7 +202,7 @@ from task_bench.tasks import Asked, Bench, BUG, check_made, committed, DATA_SOUR
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.runs import closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, rust_test_files, 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
@@ -588,6 +590,13 @@ def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None:
# 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
# ... and a Rust test in a file of its own, which it can only keep where it finds each such file.
if mutant.path.endswith(".rs"):
standing = on_disk(f"find the Rust test files beside {mutant.path}", lambda: [rust_test_files(tree) for tree in bench.trees.values()])
if isinstance(standing, Failure):
return standing
if any(tests is None or mutant.path in tests for tests in standing):
return None
trees: dict[Side, str] = {}
messages: dict[Side, str] = {}
for side, changed in bugs.items():
+30 -6
View File
@@ -12,7 +12,7 @@ from mutate_changes.tool_process import failed, Ran
from failure import Failure
from mutate_changes.changed_lines import is_test
from task_bench.api_proxy import PORT
from task_bench.rust_test_modules import with_tests_of
from task_bench.rust_test_modules import declared, homes, with_tests_of
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.
@@ -168,19 +168,21 @@ def checked_tree(planted: str, copy: str, into: str, rust_tests_planted: bool =
"""Makes at `into` the tree the tests check a fix in: `planted`, the code with the bug as Haiku got it, with each file that is no
test as `copy` holds it after the fix. So a test Haiku changed, removed or added doesn't count, and neither does a file under
a `testdata` folder, where Go's tests keep the output they expect. Where rust_tests_planted, a Rust file's inline `#[cfg(test)]`
modules stand as the planted file has them too, as `with_tests_of` says.
modules stand as the planted file has them too, as `with_tests_of` says, and so does each Rust file that `rust_test_files` finds.
Raises OSError where a file cannot be copied."""
shutil.copytree(planted, into, symlinks=True)
# `rust_test_files` is None for a tree whose declarations it cannot resolve, which the bench passes over where it plants the bug.
rust_tests = (rust_test_files(planted) or set()) if rust_tests_planted else set()
before, after = set(entries(planted)), set(entries(copy))
for path in before - after:
if not of_tests(path):
if not of_tests(path, rust_tests):
with contextlib.suppress(FileNotFoundError):
os.unlink(os.path.join(into, path))
for path in sorted(after):
target = os.path.join(into, path)
# A link is copied as a link, never followed; and one that would stand in for a folder of the planted tree is left out.
if of_tests(path) or (os.path.isdir(target) and not os.path.islink(target)):
if of_tests(path, rust_tests) or (os.path.isdir(target) and not os.path.islink(target)):
continue
os.makedirs(os.path.dirname(target), exist_ok=True)
with contextlib.suppress(FileNotFoundError):
@@ -201,8 +203,30 @@ def keep_rust_tests(planted_file: str, target: str) -> None:
pathlib.Path(target).write_bytes(with_tests_of(planted, pathlib.Path(target).read_bytes()))
def of_tests(path: str) -> bool:
return is_test(path) or "testdata" in pathlib.PurePath(path).parts
def of_tests(path: str, rust_tests: typing.AbstractSet[str] = frozenset()) -> bool:
"""Whether path is a test by its path alone, or one of rust_tests."""
return is_test(path) or "testdata" in pathlib.PurePath(path).parts or path in rust_tests
def rust_test_files(tree: str) -> set[str] | None:
"""The Rust files under tree that a `#[cfg(test)] mod name;` declaration names, by their paths from tree. None where a
declaration names no file there, or `declared` cannot tell a file's declarations.
Raises OSError where a file cannot be read."""
files = set(entries(tree))
found = set()
for path in sorted(files):
if not path.endswith(".rs") or os.path.islink(os.path.join(tree, path)):
continue
names = declared(pathlib.Path(tree, path).read_bytes())
if names is None:
return None
for name in names:
standing = [home for home in homes(path, name) if home in files]
if not standing:
return None
found.add(standing[0])
return found
def entries(top: str) -> list[str]:
+51 -13
View File
@@ -1,5 +1,7 @@
"""The `#[cfg(test)]` modules of a Rust file, which stand in the file of the code they test. Here are where each is, and a file with
the modules of another file put in place of its own. A file is bytes: a Rust file is UTF-8, and a module is found by ASCII text alone."""
"""The `#[cfg(test)]` modules of a Rust file, which stand in the file of the code they test or, as `mod name;` declares, in a file of
their own. Here are where each inline one is, which files hold the others, and a file with the modules of another file put in place
of its own. A file is bytes: a Rust file is UTF-8, and a module is found by ASCII text alone."""
import pathlib
import re
# What the scan steps over or stops at. A string, a char and a comment may hold a brace.
@@ -17,6 +19,10 @@ STRING_BODY = re.compile(rb'(?:[^"\\]|\\.)*"', re.DOTALL)
COMMENT_EDGE = re.compile(rb"/\*|\*/")
# What follows the attribute that starts an inline module: any other attributes, an optional visibility, then `mod name {`.
MODULE = re.compile(rb"\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+(?P<name>\w+)\s*\{")
# What follows the attribute that starts a module kept in a file of its own: any other attributes, an optional visibility, then `mod name;`.
DECLARATION = re.compile(rb"\s*(?P<attributes>(?:#\[[^\]]*\]\s*)*)(?:pub(?:\([^)]*\))?\s+)?mod\s+(?P<name>\w+)\s*;")
PATH_ATTRIBUTE = re.compile(rb"#\[\s*path\b")
KEEP_BESIDE = ("lib.rs", "main.rs", "mod.rs")
def tells_apart(path: str, source: bytes) -> bool:
@@ -32,16 +38,13 @@ def modules(source: bytes) -> dict[bytes, tuple[int, int]] | None:
depth = 0
# The module being read: its name, the offset of its attribute and the depth outside it.
inside: tuple[bytes, int, int] | None = None
position: int | None = 0
while position is not None and (match := SCAN.search(source, position)):
token, position = match.group(), match.end()
if token == b"/*":
position = after_comment(source, position)
elif token == b'"':
position = after_string(source, position)
elif match.group("hashes") is not None:
position = after_raw_string(source, position, match.group("hashes"))
elif token == b"{":
position = 0
while match := SCAN.search(source, position):
token = match.group()
if (after := after_token(source, match)) is None:
return None
position = after
if token == b"{":
depth += 1
elif token == b"}":
depth -= 1
@@ -52,7 +55,42 @@ def modules(source: bytes) -> dict[bytes, tuple[int, int]] | None:
elif token.startswith(b"#[") and inside is None and (module := MODULE.match(source, position)):
inside, position = (module.group("name"), match.start(), depth), module.end()
depth += 1
return found if position is not None and depth == 0 and inside is None else None
return found if depth == 0 and inside is None else None
def declared(source: bytes) -> list[str] | None:
"""The name of each `#[cfg(test)] mod name;` of source, a test module kept in a file of its own, in the order they stand.
None where a `#[path]` attribute moves such a file, or a string or comment is never closed."""
names = []
position = 0
while match := SCAN.search(source, position):
if (after := after_token(source, match)) is None:
return None
position = after
if match.group() == b"#[cfg(test)]" and (declaration := DECLARATION.match(source, position)):
if PATH_ATTRIBUTE.search(declaration.group("attributes")):
return None
names.append(declaration.group("name").decode())
return names
def homes(path: str, name: str) -> list[str]:
"""Where the file of the module `name`, declared in the Rust file at path, may stand, by its path from the same top. A crate root
(`lib.rs`, `main.rs`) and a `mod.rs` keep their modules beside them; any other file keeps them in a folder of its own name."""
declaring = pathlib.PurePosixPath(path)
folder = declaring.parent if declaring.name in KEEP_BESIDE else declaring.parent / declaring.stem
return [str(folder / f"{name}.rs"), str(folder / name / "mod.rs")]
def after_token(source: bytes, match: re.Match[bytes]) -> int | None:
"""The offset after match, or after the comment, string or raw string that match opens; None where that is never closed."""
if match.group() == b"/*":
return after_comment(source, match.end())
if match.group() == b'"':
return after_string(source, match.end())
if match.group("hashes") is not None:
return after_raw_string(source, match.end(), match.group("hashes"))
return match.end()
def after_comment(source: bytes, position: int) -> int | None:
+24
View File
@@ -103,6 +103,30 @@ class ModulesTest(unittest.TestCase):
self.assertIsNone(modules(source))
def declared(source: str) -> list[str] | None:
return rust_test_modules.declared(source.encode())
class DeclaredTest(unittest.TestCase):
def test_lists_each_test_module_the_file_declares_without_a_body(self):
self.assertEqual(declared("#[cfg(test)]\nmod tests;\n#[cfg(test)]\n#[allow(dead_code)]\npub(crate) mod checks;\n"), ["tests", "checks"])
def test_leaves_out_an_inline_module_and_a_declaration_that_is_no_test_module(self):
self.assertEqual(declared(LIB + "mod util;\n#[cfg(feature = \"x\")]\nmod extra;\n"), [])
def test_leaves_out_a_declaration_in_a_comment_or_a_string(self):
source = '// #[cfg(test)]\n// mod a;\n/* #[cfg(test)] mod b; */\nconst C: &str = "#[cfg(test)] mod c;";\nconst D: &str = r#"#[cfg(test)] mod d;"#;\n'
self.assertEqual(declared(source), [])
def test_cannot_tell_where_a_declaration_moves_its_file_with_a_path_attribute(self):
self.assertIsNone(declared('#[cfg(test)]\n#[path = "elsewhere.rs"]\nmod tests;\n'))
def test_cannot_tell_where_a_string_or_comment_is_never_closed(self):
for source in ("#[cfg(test)]\nmod tests;\nconst A: &str = \"\n", "/* open\n#[cfg(test)]\nmod tests;\n"):
with self.subTest(source=source):
self.assertIsNone(declared(source))
class TellsApartTest(unittest.TestCase):
def test_tells_the_modules_of_a_rust_file_apart_where_they_can_be(self):
self.assertEqual([tells_apart("lib.rs", b"fn a() {}"), tells_apart("lib.rs", b"fn a() {")], [True, False])
+78 -1
View File
@@ -17,7 +17,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench import api_proxy, bench_folder, main, runs
from test_env import assert_not_root, isolated_env
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests, TimedOut
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests, rust_test_files, TimedOut
from task_bench.bugs.plant import drawn
from claude_code.entries import Entry, entry_from
from failure import Failure
@@ -613,6 +613,34 @@ class RunOutcomesTest(unittest.TestCase):
mutant = Mutant("lib.rs", 2, "lib.rs:2:7 replace + with -", (b" a + b",), (b" a - b",))
self.assertIsNone(main.planted(self.bench(), 1, mutant))
def rust_bench(self, files: dict[str, str], *runs: Ran | Failure) -> main.Bench:
for path, text in files.items():
(self.tree / path).parent.mkdir(parents=True, exist_ok=True)
(self.tree / path).write_text(text)
return self.bench(*runs)
ADD = "pub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n#[cfg(test)]\nmod tests;\n"
ADDING = Mutant("src/lib.rs", 2, "src/lib.rs:2:7 replace + with -", (b" a + b",), (b" a - b",))
def test_a_rust_mutant_in_a_test_file_of_its_own_is_passed_over(self):
bench = self.rust_bench({"src/lib.rs": self.ADD, "src/tests.rs": "fn t() { assert!(1 + 1 == 2); }\n"})
mutant = Mutant("src/tests.rs", 1, "src/tests.rs:1:20 replace + with -", (b"fn t() { assert!(1 + 1 == 2); }",), (b"fn t() { assert!(1 - 1 == 2); }",))
self.assertIsNone(main.planted(bench, 1, mutant))
def test_a_rust_mutant_in_a_tree_whose_declared_test_file_is_not_found_is_passed_over(self):
self.assertIsNone(main.planted(self.rust_bench({"src/lib.rs": self.ADD}), 1, self.ADDING))
def test_a_rust_mutant_in_code_beside_a_test_file_goes_on_to_the_tests(self):
broke = Failure("docker could not start: No such file or directory")
self.assertEqual(main.planted(self.rust_bench({"src/lib.rs": self.ADD, "src/tests.rs": ""}, broke), 1, self.ADDING), broke)
def test_a_rust_mutant_in_a_tree_whose_rust_file_cannot_be_read_fails_the_bench_naming_the_file(self):
assert_not_root(self)
bench = self.rust_bench({"src/lib.rs": self.ADD, "src/tests.rs": "", "src/other.rs": ""})
(self.tree / "src/other.rs").chmod(0)
self.addCleanup((self.tree / "src/other.rs").chmod, 0o644)
self.assertFailsWith(main.planted(bench, 1, self.ADDING), "could not find the Rust test files beside src/lib.rs: ")
class ContainersTest(unittest.TestCase):
IN_TREE = ["--memory", "512m", "--memory-swap", "512m", "--user", "1000:1000", "--env", "HOME=/tmp", "--volume", "/tree:/work", "--workdir", "/work"]
@@ -772,6 +800,55 @@ class CheckedTreeTest(unittest.TestCase):
checked_tree(planted, copy, str(self.root / "check"))
self.assertEqual(self.held("check")["src/new.rs"], added)
DECLARING = "fn a() { 1 }\n#[cfg(test)]\nmod tests;\n"
def test_takes_a_rust_test_in_a_file_of_its_own_as_planted_and_the_rest_as_fixed(self):
planted = self.tree("planted", {"src/lib.rs": self.DECLARING, "src/tests.rs": "old tests", "src/other.rs": "bug"})
copy = self.tree("copy", {"src/lib.rs": "fn a() { 2 }\n#[cfg(test)]\nmod tests;\n", "src/tests.rs": "rewritten", "src/other.rs": "fixed"})
checked_tree(planted, copy, str(self.root / "check"))
self.assertEqual(self.held("check"), {"src/lib.rs": "fn a() { 2 }\n#[cfg(test)]\nmod tests;\n", "src/tests.rs": "old tests", "src/other.rs": "fixed"})
def test_takes_a_rust_test_file_the_fix_deleted_as_planted(self):
planted = self.tree("planted", {"src/lib.rs": self.DECLARING, "src/tests.rs": "old tests"})
copy = self.tree("copy", {"src/lib.rs": "fn a() { 2 }\n#[cfg(test)]\nmod tests;\n"})
checked_tree(planted, copy, str(self.root / "check"))
self.assertEqual(self.held("check")["src/tests.rs"], "old tests")
def test_takes_a_rust_test_file_the_fix_added_as_fixed_since_the_planted_tree_declares_none(self):
planted = self.tree("planted", {"src/lib.rs": "fn a() { 1 }\n"})
copy = self.tree("copy", {"src/lib.rs": "fn a() { 2 }\n", "src/tests.rs": "mine"})
checked_tree(planted, copy, str(self.root / "check"))
self.assertEqual(self.held("check")["src/tests.rs"], "mine")
def test_a_task_with_acceptance_tests_takes_a_rust_test_file_as_fixed(self):
planted = self.tree("planted", {"src/lib.rs": self.DECLARING, "src/tests.rs": "old tests"})
copy = self.tree("copy", {"src/lib.rs": self.DECLARING, "src/tests.rs": "new tests"})
checked_tree(planted, copy, str(self.root / "check"), rust_tests_planted=False)
self.assertEqual(self.held("check")["src/tests.rs"], "new tests")
def test_finds_a_rust_test_file_where_the_module_system_puts_it(self):
cases = {
"beside a crate root": ({"src/lib.rs": self.DECLARING, "src/tests.rs": ""}, {"src/tests.rs"}),
"as a folder with a mod.rs": ({"src/main.rs": self.DECLARING, "src/tests/mod.rs": ""}, {"src/tests/mod.rs"}),
"in the folder of a module file": ({"src/pick.rs": self.DECLARING, "src/pick/tests.rs": ""}, {"src/pick/tests.rs"}),
"beside a mod.rs": ({"src/pick/mod.rs": self.DECLARING, "src/pick/tests.rs": ""}, {"src/pick/tests.rs"}),
"declared by no file": ({"src/lib.rs": "fn a() {}\n", "src/tests.rs": ""}, set()),
}
for name, (files, found) in cases.items():
with self.subTest(name):
self.assertEqual(rust_test_files(self.tree(name.replace(" ", "-"), files)), found)
def test_cannot_find_a_rust_test_file_that_is_not_where_its_declaration_puts_it_or_cannot_be_read_from_it(self):
cases = {
"missing": {"src/lib.rs": self.DECLARING},
"beside a module file, where only a crate root has its modules": {"src/pick.rs": self.DECLARING, "src/tests.rs": ""},
"moved by a path attribute": {"src/lib.rs": '#[cfg(test)]\n#[path = "t.rs"]\nmod tests;\n', "src/t.rs": ""},
"in a declaring file whose string is never closed": {"src/lib.rs": '#[cfg(test)]\nmod tests;\nconst A: &str = "\n', "src/tests.rs": ""},
}
for name, files in cases.items():
with self.subTest(name):
self.assertIsNone(rust_test_files(self.tree(name.replace(" ", "-"), files)))
def test_leaves_a_rust_link_as_a_link_whatever_it_points_at(self):
planted = self.tree("planted", {"z.rs": "fn a() {}\n#[cfg(test)]\nmod tests {}\n", "a.txt": "text"})
copy = self.tree("copy", {"a.txt": "text"})