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
CI / tests (pull_request) Successful in 5m4s
This commit is contained in:
+93
-57
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user