diff --git a/README.md b/README.md index 70c5c165..145b579f 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,8 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`). - `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. - `loop_claude` runs `chunk-preflight` as a process of its own. -- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. +- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it. +- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read. - `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`. diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index 337b2f88..43d21637 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -84,9 +84,14 @@ def parse_entry(raw: str | bytes) -> Entry | None: return None if found is None else entry_from(found) +def json_objects(raw: bytes) -> list[dict]: + """The lines of a transcript or a stream-json stream that are JSON objects, parsed.""" + return [found for line in raw.splitlines() if (found := json_object(line))] + + def entries_of(raw: bytes) -> list[Entry]: """The entries of a transcript or a stream-json stream, one per line that is a JSON object.""" - return [entry for line in raw.splitlines() if (entry := parse_entry(line))] + return [entry_from(found) for found in json_objects(raw)] def entry_from(found: dict) -> Entry: diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index bb479885..52fd6900 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -353,24 +353,26 @@ class Landed(enum.Enum): class How(enum.Enum): - """How a finished chunk's issue moves.""" + """How a finished chunk's issue moves, where it moves to no status the config names.""" # do-epic neither moves nor awaits it. LEFT = enum.auto() - # do-epic moves it to the status the Move names. - TO_STATUS = enum.auto() # Nobody would move it, so the loop stops. STUCK = enum.auto() # The team's automation moves it, and do-epic waits for that. AWAITED = enum.auto() + # do-epic moves it to done. TO_DONE = enum.auto() @dataclasses.dataclass(frozen=True) -class Move: - """The move of a finished chunk's issue. For How.TO_STATUS, status is where it moves, and through a status a failed move is tried again by way of, None where there is none.""" - how: How - status: str | None = None - through: str | None = None +class ToStatus: + """do-epic moves a finished chunk's issue to status, trying a failed move again by way of through, None where there is none.""" + status: str + through: str | None + + +# The move of a finished chunk's issue. +Move = How | ToStatus def issue_move(landed: Landed, automated: bool, merged: str | None, opened: str | None, finishing: bool) -> Move: @@ -380,49 +382,50 @@ def issue_move(landed: Landed, automated: bool, merged: str | None, opened: str |---|---|---|---| | the epic's finishing, which has no issue | either | either | LEFT | | a human's task | yes | either | LEFT: the human moves it | - | landed on the epic's working branch | either | yes | TO_STATUS merged, through opened | + | landed on the epic's working branch | either | yes | ToStatus merged, through opened | | landed on the epic's working branch | yes | no | STUCK: the automation doesn't see that merge | | landed on the default branch | yes | either | AWAITED | | any other | either | either | TO_DONE | A chunk that never parked left its issue before the open status, from which a workflow may offer no way to the merged one: hence through.""" if finishing or (landed is Landed.WITH_A_HUMAN and automated): - return Move(How.LEFT) + return How.LEFT if landed is Landed.ON_EPIC_BRANCH and merged: - return Move(How.TO_STATUS, merged, opened or None) + return ToStatus(merged, opened or None) if landed is Landed.ON_EPIC_BRANCH and automated: - return Move(How.STUCK) + return How.STUCK if landed is Landed.ON_DEFAULT_BRANCH and automated: - return Move(How.AWAITED) - return Move(How.TO_DONE) + return How.AWAITED + return How.TO_DONE def handed_on(key: str, epic: EpicRun, landed: Landed = Landed.NOWHERE) -> Stop: """The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its parent too where the parent's sub-tasks now let it move (`parents_settled`), so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Where the team's automation moves issues, others move two kinds of issue. The automation moves the issue of a chunk whose work landed on the default branch, from its pull request: the stop waits for that move (`moved_by_automation`). The human moves their own task: the stop doesn't move or await anything. A chunk without a repo has no pull request, so its issue moves to done as ever, and so does a split item, once Jira counts each of its sub-tasks done. The automation doesn't see a pull request that merged into an epic's working branch: the stop moves that chunk's issue to the status `jira-pull-request-merged-status` names. Where none is named, it moves the issue to done, or stops where the automation moves issues, since then nobody would move it. do-epic's window closes as it exits.""" move = issue_move(landed, epic.config.automation_moves, epic.config.pull_merged_status, epic.config.pull_open_status, finishing=key == epic.key) issues: list[EpicIssue] | Failure - if move.how is How.LEFT: - issues = epic.store.read() - elif move.how is How.TO_STATUS and (status := move.status): - moved = epic.store.move_issue(key, status) - if isinstance(moved, Failure) and move.through and not isinstance(epic.store.move_issue(key, move.through), Failure): + match move: + case How.LEFT: + issues = epic.store.read() + case ToStatus(status, through): moved = epic.store.move_issue(key, status) - if isinstance(moved, Failure): - return Stop(1, f"the chunk finished, but its issue could not move to {status!r}: {moved.reason}; once it has that status in Jira, run `do-epic {epic.key}` to start the chunks it blocks") - issues = epic.store.read() - # A search may not show the move yet, so the issue counts as moved here whatever the read says. - issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, status=status) if each.key == key else each for each in issues] - elif move.how is How.STUCK: - return Stop(1, f"the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `{PULL_MERGED_STATUS}` to move it to. Move {key} in Jira, then run `do-epic {epic.key}` to start the chunks it blocks") - elif move.how is How.AWAITED: - issues = moved_by_automation(key, epic) - else: - moved = epic.store.finish_issue(key) - if isinstance(moved, Failure): - return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") - issues = epic.store.read() - # A search may not show the move yet, so the issue counts as done here whatever the read says. - issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, done=True) if each.key == key else each for each in issues] + if isinstance(moved, Failure) and through and not isinstance(epic.store.move_issue(key, through), Failure): + moved = epic.store.move_issue(key, status) + if isinstance(moved, Failure): + return Stop(1, f"the chunk finished, but its issue could not move to {status!r}: {moved.reason}; once it has that status in Jira, run `do-epic {epic.key}` to start the chunks it blocks") + issues = epic.store.read() + # A search may not show the move yet, so the issue counts as moved here whatever the read says. + issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, status=status) if each.key == key else each for each in issues] + case How.STUCK: + return Stop(1, f"the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `{PULL_MERGED_STATUS}` to move it to. Move {key} in Jira, then run `do-epic {epic.key}` to start the chunks it blocks") + case How.AWAITED: + issues = moved_by_automation(key, epic) + case How.TO_DONE: + moved = epic.store.finish_issue(key) + if isinstance(moved, Failure): + return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") + issues = epic.store.read() + # A search may not show the move yet, so the issue counts as done here whatever the read says. + issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, done=True) if each.key == key else each for each in issues] if isinstance(issues, Failure): return Stop(1, f"the chunk finished, but the next could not start: {issues.reason}") closed = parents_settled(epic, issues) diff --git a/bin/do_epic/parking.py b/bin/do_epic/parking.py index 55df9e6f..ec7eef0b 100644 --- a/bin/do_epic/parking.py +++ b/bin/do_epic/parking.py @@ -11,6 +11,9 @@ from loop_effects.effects import say from agent_cycle.stop import Stop from agent_cycle import tmux +# How the news for a chunk that was parked opens. +DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while" + def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool, based: str | None) -> str | Stop: """Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. based is the epic's working branch that `epic_based` recorded as the chunk's base when the window started, None where it recorded none. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh. @@ -124,10 +127,6 @@ def resumed_news(poll: Poll, on: str, shown: str | None) -> str | Stop: poll.epic.effects.sleep(POLL_SECONDS) -# How the news for a chunk that was parked opens. -DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while" - - def resumed(repo: str, loop: Loop, epic: EpicRun) -> str | None: """scheduler.resume for the parked chunk in loop's window, whose work is in the repo called repo, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked.""" # A chunk that resumes starts no other, so it needs no start order. diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index df62b4b8..b814070a 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -1243,29 +1243,32 @@ class TheMoveOfAFinishedChunksIssue(unittest.TestCase): def test_the_epics_finishing_has_no_issue_to_move(self) -> None: for automated in (False, True): - self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review", finishing=True), main.Move(main.How.LEFT)) + with self.subTest(automated=automated): + self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review", finishing=True), main.How.LEFT) def test_a_humans_task_is_left_where_the_automation_moves_issues_and_done_otherwise(self) -> None: - self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, True, "Release Ready"), main.Move(main.How.LEFT)) - self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, False, "Release Ready"), main.Move(main.How.TO_DONE)) + self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, True, "Release Ready"), main.How.LEFT) + self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, False, "Release Ready"), main.How.TO_DONE) def test_a_chunk_without_a_repo_moves_to_done(self) -> None: for automated in (False, True): - self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review"), main.Move(main.How.TO_DONE)) + with self.subTest(automated=automated): + self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review"), main.How.TO_DONE) def test_work_on_the_default_branch_awaits_the_automation_or_moves_to_done(self) -> None: - self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, True, "Release Ready", "In Review"), main.Move(main.How.AWAITED)) - self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, False, "Release Ready", "In Review"), main.Move(main.How.TO_DONE)) + self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, True, "Release Ready", "In Review"), main.How.AWAITED) + self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, False, "Release Ready", "In Review"), main.How.TO_DONE) def test_work_on_the_epics_branch_moves_to_the_merged_status_through_the_open_one_where_named(self) -> None: for automated in (False, True): - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready", "In Review"), main.Move(main.How.TO_STATUS, "Release Ready", "In Review")) - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready"), main.Move(main.How.TO_STATUS, "Release Ready")) + with self.subTest(automated=automated): + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready", "In Review"), main.ToStatus("Release Ready", "In Review")) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready"), main.ToStatus("Release Ready", None)) def test_work_on_the_epics_branch_with_no_merged_status_is_stuck_under_automation_and_done_otherwise(self) -> None: - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, None, "In Review"), main.Move(main.How.STUCK)) - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, "", "In Review"), main.Move(main.How.STUCK)) - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, False, None, "In Review"), main.Move(main.How.TO_DONE)) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, None, "In Review"), main.How.STUCK) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, "", "In Review"), main.How.STUCK) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, False, None, "In Review"), main.How.TO_DONE) class TheStatus(DoEpicTest): diff --git a/bin/task_bench/digest.py b/bin/task_bench/digest.py index 24f7b26c..197dc04b 100644 --- a/bin/task_bench/digest.py +++ b/bin/task_bench/digest.py @@ -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." diff --git a/bin/task_bench/figures.py b/bin/task_bench/figures.py index 1a65f1c5..2988c56d 100644 --- a/bin/task_bench/figures.py +++ b/bin/task_bench/figures.py @@ -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)) diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index 52d353a7..14a01955 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -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 diff --git a/bin/task_bench/plant.py b/bin/task_bench/plant.py index 65e46017..ebd2ba24 100644 --- a/bin/task_bench/plant.py +++ b/bin/task_bench/plant.py @@ -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: `:` 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 diff --git a/bin/task_bench/test_figures.py b/bin/task_bench/test_figures.py index 29f68dd8..789236b7 100644 --- a/bin/task_bench/test_figures.py +++ b/bin/task_bench/test_figures.py @@ -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): diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 9df98188..dacae2e9 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -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()