Files
claude-config/bin/task_bench/go_bugs.py
T
2026-11-23 21:31:00 +01:00

102 lines
6.1 KiB
Python

"""The bugs task-bench plants in Go: Gremlins' killed mutants, re-applied from its report, and what go test prints of the test
each fails."""
import os
import pathlib
import re
from failure import Failure
from mutate_changes import in_diff_tools
from mutate_changes.changed_lines import is_test
from mutate_changes.tool_process import Run
from task_bench.planted_mutant import Mutant
# What each of Gremlins v0.6.0's mutators writes in place of a token: `tokenMutations` in its internal/engine/mappings.go, under the
# names its report gives the mutators, from internal/mutator/mutator.go.
MUTATIONS: dict[str, dict[bytes, bytes]] = {
"ARITHMETIC_BASE": {b"+": b"-", b"*": b"/", b"/": b"*", b"%": b"*", b"-": b"+"},
"CONDITIONALS_BOUNDARY": {b">=": b">", b">": b">=", b"<=": b"<", b"<": b"<="},
"CONDITIONALS_NEGATION": {b"==": b"!=", b">=": b"<", b">": b"<=", b"<=": b">", b"<": b">=", b"!=": b"=="},
"INCREMENT_DECREMENT": {b"--": b"++", b"++": b"--"},
"INVERT_ASSIGNMENTS": {b"+=": b"-=", b"*=": b"/=", b"/=": b"*=", b"-=": b"+="},
"INVERT_BITWISE": {b"&": b"|", b"|": b"&", b"^": b"&", b"&^": b"&", b"<<": b">>", b">>": b"<<"},
"INVERT_BWASSIGN": {b"&=": b"|=", b"|=": b"&=", b"^=": b"&=", b"&^=": b"&=", b"<<=": b">>=", b">>=": b"<<="},
"INVERT_LOGICAL": {b"&&": b"||", b"||": b"&&"},
"INVERT_LOOPCTRL": {b"break": b"continue", b"continue": b"break"},
"INVERT_NEGATIVES": {b"-": b"+"},
"REMOVE_SELF_ASSIGNMENTS": dict.fromkeys((b"+=", b"&=", b"&^=", b"*=", b"|=", b"/=", b"%=", b"<<=", b">>=", b"-=", b"^="), b"="),
}
# What a test printed, as go test shows it: ` pick_test.go:42: got 3, want 4`. A failed assertion and a log line look the same.
PRINTED = re.compile(r"^( *)\S*_test\.go:\d+:(.*)$")
# The lines that say whose output follows: `=== RUN TestPick` with -v, and `--- FAIL: TestPick (0.00s)` with and without it.
TEST_MARK = re.compile(r"^( *)(?:=== (?:RUN|CONT|NAME)|--- (?:FAIL|PASS|SKIP):)\s+(\S+)")
FAILED_TEST = re.compile(r"^\s*--- FAIL: (\S+)", re.MULTILINE)
def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure:
"""The mutants in `files` that the tests of the tree at top kill, as Gremlins finds them there. One whose line and column hold
no token its mutator changes is left out.
Gremlins takes no list of files to mutate, only patterns to leave out, so it gets one for each other Go file of the tree."""
others = sorted(path for path in go_files(top) if path not in files)
found = in_diff_tools.gremlins_mutants(top, [argument for path in others for argument in ("--exclude-files", f"^{re.escape(path)}$")], run, jobs)
if isinstance(found, Failure):
return found
killed = [mutant for mutant in found if mutant.status == "KILLED" and mutant.path in files]
try:
lines = {path: pathlib.Path(top, path).read_bytes().split(b"\n") for path in {mutant.path for mutant in killed}}
except OSError as failure:
return Failure(f"could not read the files Gremlins mutated in {top}: {failure}")
return [mutant for reported in killed if (mutant := reapplied(reported, lines[reported.path]))]
def go_files(top: str) -> list[str]:
"""Each Go file under top that Gremlins would mutate, by its path from top."""
paths = (os.path.relpath(os.path.join(folder, name), top) for folder, _, names in os.walk(top) for name in names)
return [path for path in paths if path.endswith(".go") and not is_test(path)]
def reapplied(reported: in_diff_tools.Mutant, lines: list[bytes]) -> Mutant | None:
"""The mutant Gremlins reports by its mutator and the token it changed, at a line and a column in bytes, both from 1, as the
line it changes in a file of those lines. None where the place holds no token the mutator changes."""
if not (1 <= reported.line <= len(lines) and reported.column >= 1):
return None
line = lines[reported.line - 1]
rest = line[reported.column - 1:]
# The longest token first: `>=` holds `>`, and Gremlins names the mutant by the whole token.
token = max((token for token in MUTATIONS.get(reported.mutator, {}) if rest.startswith(token)), key=len, default=None)
if token is None:
return None
now = line[:reported.column - 1] + MUTATIONS[reported.mutator][token] + rest[len(token):]
return Mutant(reported.path, reported.line, f"{reported.path}:{reported.line}:{reported.column} {reported.mutator}", (line,), (now,))
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the failing assertion's message in go test's output, without the test's name, file or
line, so it says what goes wrong and not where. That is the last message of the first failed test that printed one, since a
test logs before it asserts; a test with a failed subtest is left out, since it fails with the subtest. None where no failed test printed a message, as on a panic, a build that broke or a passing run,
or where the message only names the test."""
lines = output.splitlines()
failed = set(FAILED_TEST.findall(output))
# A subtest is named `TestPick/empty_input`; a message may name the whole or the test it belongs to.
tests = {part for name in failed for part in (name, name.partition("/")[0])}
marks: list[tuple[int, str]] = []
last: dict[str, tuple[int, re.Match[str]]] = {}
for index, line in enumerate(lines):
if mark := TEST_MARK.match(line):
marks.append((len(mark[1]), mark[2]))
elif printed := PRINTED.match(line):
# A test's output is indented deeper than its mark, so a line after a subtest's may be its parent's.
test = next((name for indent, name in reversed(marks) if indent < len(printed[1])), None)
if test is not None and test in failed and not any(other.startswith(f"{test}/") for other in failed):
last[test] = index, printed
if not last:
return None
index, found = next(iter(last.values()))
indent = len(found[1])
# A message's later lines are indented deeper than its first.
later = lines[index + 1:]
ends = next((at for at, text in enumerate(later) if len(text) - len(text.lstrip(" ")) <= indent), len(later))
message = [text.strip() for text in (found[2], *later[:ends])]
kept = [text for text in message if text and "_test.go" not in text and not any(name in text for name in tests)]
return "\n".join(kept) or None