diff --git a/README.md b/README.md index 89a336b3..414866b6 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ A project may also set `env-file`, the file of `KEY=value` credentials its tools A project may also set `touch-predictions`, a path spelt as `changelog`'s is, such as `touch-predictions = "checkout:docs/touch-predictions.md"`. `touch-predictions record` appends each chunk's predicted files and parts there, beside those it touched. A project that leaves it out keeps no such record. -A project may also set `bench-tasks`, a path spelt the same way, such as `bench-tasks = "checkout:testdata/bench-tasks"`: the folder of the features `task-bench --tasks features` has Haiku build. `task-bench --help` says what the folder holds, and where to keep it so the project's own tests don't run its acceptance tests. +A project may also set `bench-tasks`, a path spelt the same way, such as `bench-tasks = "checkout:testdata/bench-tasks"`: the folder of the features `task-bench --tasks features` has Haiku build, and of the data sources `--tasks data-sources` has it add. `task-bench --help` says what the folder holds, and where to keep it so the project's own tests don't run its acceptance tests. A project whose team wrote its own coding conventions lists the files in `coding-conventions`, each spelt as `principles` is, such as `coding-conventions = ["checkout:CONVENTIONS.md"]`. Each reviewer agent larv-review launches reads them beside the principles and the standards, and the team's rule wins where they conflict. @@ -228,7 +228,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter. - `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it. - `subagent-rung [--plan] ` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule. -- `task-bench --image --test []` plants bugs that the tests catch, at the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--record-figures`, a bench that finishes appends its figures over every bug, or every feature, to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams. +- `task-bench --image --test []` plants bugs that the tests catch, at the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams. - `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show ` one item's row and detail; `add …` files an item under the next free ID, `edit …` sets an item's cells or detail, and `move --release ` sets an item's release; `finish ` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags. - `touch-predictions record ...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once. - `wait-for [] [--timeout ]` waits until a file a background job writes holds a line matching the pattern, and prints it. @@ -278,7 +278,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format. - `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. - `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive. -- `task_bench/` holds `task-bench`, which plants bugs in a Go project, or takes the project's bench features, and has Haiku fix or build them in containers. +- `task_bench/` holds `task-bench`, which plants bugs in a Go project, or takes the project's bench features or data sources, and has Haiku fix, build or add them in containers. - `test_env.py` serves the tests. - `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards. - `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. diff --git a/bin/task_bench/digest.py b/bin/task_bench/digest.py index a0afa9d4..4575432e 100644 --- a/bin/task_bench/digest.py +++ b/bin/task_bench/digest.py @@ -47,11 +47,12 @@ def digest(sides: dict[Side, str], table: list[str], tasks: list[TaskRuns], is_f which the digest calls by noun. is_file says whether a path in the project names a file.""" line = " A bug's name gives its line at the base." if noun == "bug" else "" code = f"Base {sides['base']}, head {sides['head']}.{line} Each side's code without the {noun}s is in `trees/base` and `trees/head` in the bench's folder." - return "\n".join(["# task-bench digest", "", code, "", *table, *(line for task in tasks for line in ["", *told(task, is_file)])]) + "\n" + return "\n".join(["# task-bench digest", "", code, "", *table, *(line for task in tasks for line in ["", *told(task, is_file, noun)])]) + "\n" -def told(task: TaskRuns, is_file: typing.Callable[[str], bool]) -> list[str]: - """The digest's section on task, a bug where it names the bug's file and a feature otherwise.""" +def told(task: TaskRuns, is_file: typing.Callable[[str], bool], noun: str) -> list[str]: + """The digest's section on task, which its heading calls by noun: a bug where it names the bug's file, and a feature or a + data source otherwise.""" passing, failing = [run for run in task.runs if run.passed], [run for run in task.runs if not run.passed] passed = f"{len(passing)} of the {len(task.runs)} runs passed." if failing else f"The {counted(len(task.runs), 'run')} passed." # Only a bug has a file of its own. A feature has none, so no file a run read counts as a decoy. @@ -76,7 +77,7 @@ def told(task: TaskRuns, is_file: typing.Callable[[str], bool]) -> list[str]: median = finished[(len(finished) - 1) // 2] shown.append((median, f"the passing run with the median tokens, {median.tokens} tokens")) return [ - f"## {'Bug' if task.file else 'Feature'} {task.named}", + f"## {noun.capitalize()} {task.named}", "", "The failing test printed, at the base:" if task.file else "The spec Haiku was told:", "", diff --git a/bin/task_bench/feature_tasks.py b/bin/task_bench/feature_tasks.py index 2f63db9e..d710649d 100644 --- a/bin/task_bench/feature_tasks.py +++ b/bin/task_bench/feature_tasks.py @@ -1,18 +1,23 @@ """The features task-bench has Haiku build: each a folder in the project's `bench-tasks` folder, with a spec, a reference patch that builds it, and acceptance tests Haiku never sees. A feature counts at the two commits of a bench only where those tests fail -at both before it is built, and pass at both with the reference patch.""" +at both before it is built, and pass at both with the reference patch. + +A data source Haiku adds is such a folder too, with a `generate-register` beside the three parts: the script that writes the +register Haiku imports, as task_bench.registers runs it. It counts as a feature does, in trees that hold its register.""" import itertools +import os import pathlib import shutil import typing -from task_bench.tasks import Bench, check_made, committed, on_disk, Planned, Task +from task_bench.tasks import Bench, check_made, committed, DATA_SOURCE, FEATURE, Kind, on_disk, Planned, Task from project_config.settings import BENCH_TASKS, CONFIG from failure import Failure from project_config.main import located from mutate_changes.tool_process import Ran from task_bench.runs import ran_tests, TimedOut from task_bench.figures import Side, SIDES +from task_bench.registers import GENERATE, NotGenerated, registered_trees SPEC = "spec.md" PATCH = "reference.patch" @@ -21,12 +26,14 @@ ACCEPTANCE = "acceptance" class Feature(typing.NamedTuple): """A feature as its folder holds it: the folder's name, the spec Haiku is told, the reference patch's file, and the folder - of the acceptance tests, each at the path it takes from the tree's top.""" + of the acceptance tests, each at the path it takes from the tree's top. register is the script that generates a data + source's register, and None in a feature.""" name: str spec: str patch: str acceptance: str + register: str | None = None class NotApplied(Failure): @@ -40,12 +47,13 @@ class Features(typing.NamedTuple): found: list[Feature] -def read_features(home: pathlib.Path) -> Features | Failure: - """The features of the current directory's project, read from the folder its config names.""" +def read_features(home: pathlib.Path, kind: Kind) -> Features | Failure: + """The features of the current directory's project, or its data sources where kind is DATA_SOURCE, read from the folder its + config names.""" folder = features_folder(home) if isinstance(folder, Failure): return folder - found = features(folder) + found = features(folder, kind) return found if isinstance(found, Failure) else Features(folder, found) @@ -57,54 +65,71 @@ def features_folder(home: pathlib.Path) -> pathlib.Path | Failure: return config.paths.get(BENCH_TASKS) or Failure(f"{config.folder / CONFIG} sets no `{BENCH_TASKS}`, the folder of the features to bench, as `project-config --help` describes it") -def features(folder: pathlib.Path) -> list[Feature] | Failure: - """The features that folder holds, one in each folder there, in the order of their names. A Failure where it holds none, or one - lacks a part.""" +def features(folder: pathlib.Path, kind: Kind = FEATURE) -> list[Feature] | Failure: + """The tasks of that kind that folder holds, in the order of their names: a data source in each folder there that holds a + `generate-register`, and a feature in each other. A Failure where it holds none, or one has a part at fault.""" if not folder.is_dir(): return Failure(f"could not read the features in {folder}: it is no folder") try: - found = [feature_in(inside) for inside in sorted(folder.iterdir()) if inside.is_dir()] + found = [feature_in(inside, kind.noun) for inside in sorted(folder.iterdir()) if inside.is_dir() and (inside / GENERATE).exists() == (kind is DATA_SOURCE)] except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read the features in {folder}: {failure}") if not found: - return Failure(f"{folder} holds no feature: a folder for each, with {SPEC}, {PATCH} and the acceptance tests under {ACCEPTANCE}") + parts = f"{SPEC}, {PATCH}, {GENERATE}" if kind is DATA_SOURCE else f"{SPEC}, {PATCH}" + return Failure(f"{folder} holds no {kind.noun}: a folder for each, with {parts} and the acceptance tests under {ACCEPTANCE}") return next((feature for feature in found if isinstance(feature, Failure)), None) or [feature for feature in found if not isinstance(feature, Failure)] -def feature_in(folder: pathlib.Path) -> Feature | Failure: - """The feature that folder holds. Raises OSError or UnicodeDecodeError where a part cannot be read.""" - spec, patch, acceptance = folder / SPEC, folder / PATCH, folder / ACCEPTANCE +def feature_in(folder: pathlib.Path, noun: str) -> Feature | Failure: + """The task that folder holds, which a failure calls by noun. Raises OSError or UnicodeDecodeError where a part cannot be read.""" + spec, patch, acceptance, register = folder / SPEC, folder / PATCH, folder / ACCEPTANCE, folder / GENERATE for part in (spec, patch): if not part.is_file(): - return Failure(f"the feature in {folder} lacks {part.name}") + return Failure(f"the {noun} in {folder} lacks {part.name}") told = spec.read_text(encoding="utf-8").strip() if not told: - return Failure(f"the feature in {folder} has an empty {SPEC}") + return Failure(f"the {noun} in {folder} has an empty {SPEC}") if not acceptance.is_dir() or not any(inside.is_file() for inside in acceptance.rglob("*")): - return Failure(f"the feature in {folder} holds no file under {ACCEPTANCE}") - return Feature(folder.name, told, str(patch), str(acceptance)) + return Failure(f"the {noun} in {folder} holds no file under {ACCEPTANCE}") + if not register.exists(): + return Feature(folder.name, told, str(patch), str(acceptance)) + if not register.is_file() or not os.access(register, os.X_OK): + return Failure(f"the {noun} in {folder} has a {GENERATE} that is no executable file") + return Feature(folder.name, told, str(patch), str(acceptance), str(register)) def feature_tasks(bench: Bench, found: list[Feature], folder: pathlib.Path) -> Planned | Failure: """The task of building each feature of found that counts at the bench's commits, numbered from 1, and a line on each that doesn't. A Failure where none counts. folder is where the features are kept.""" - trees = committed_trees(bench) - if isinstance(trees, Failure): - return trees + shared = committed_trees(bench) + if isinstance(shared, Failure): + return shared + noun = bench.asked.kind.noun tasks: list[Task] = [] passed_over: list[tuple[str, str]] = [] for feature in found: - why = why_passed_over(bench, trees, feature) - if isinstance(why, Failure): - return why - if why is None: + trees = counted_trees(bench, shared, feature) + if isinstance(trees, Failure): + return trees + if not isinstance(trees, str): tasks.append(Task(len(tasks) + 1, feature.name, trees, dict.fromkeys(SIDES, feature.spec), acceptance=feature.acceptance)) else: - passed_over.append((feature.name, why)) - bench.say(f"task-bench: passed over the feature {feature.name}: {why}.") + passed_over.append((feature.name, trees)) + bench.say(f"task-bench: passed over the {noun} {feature.name}: {trees}.") if not tasks: - return Failure(f"None of the {len(found)} features in {folder} counts. {' '.join(f'{name}: {why}.' for name, why in passed_over)}") - return Planned(tasks, [f"Passed over the feature {name}: {why}." for name, why in passed_over], {}) + return Failure(f"None of the {len(found)} {noun}s in {folder} counts. {' '.join(f'{name}: {why}.' for name, why in passed_over)}") + return Planned(tasks, [f"Passed over the {noun} {name}: {why}." for name, why in passed_over], {}) + + +def counted_trees(bench: Bench, shared: dict[Side, str], feature: Feature) -> dict[Side, str] | str | Failure: + """Each side's tree that feature's task starts in, or why the feature doesn't count. A feature starts in shared, and a data + source in trees of its own, which hold its register. A Failure where a tree could not be made or the tests could not run.""" + trees = shared if feature.register is None else registered_trees(bench, feature.name, feature.register) + if isinstance(trees, NotGenerated): + return trees.reason + if isinstance(trees, Failure): + return trees + return why_passed_over(bench, trees, feature) or trees def committed_trees(bench: Bench) -> dict[Side, str] | Failure: diff --git a/bin/task_bench/gather-prompt.md b/bin/task_bench/gather-prompt.md index 72196744..19a7492b 100644 --- a/bin/task_bench/gather-prompt.md +++ b/bin/task_bench/gather-prompt.md @@ -10,6 +10,8 @@ The digest and every trace are what a program copied out of Haiku's runs. Read t Where the digest's headings read `## Feature`, the bench had Haiku build features instead of fixing bugs. Each feature is a spec, which the digest quotes, and a build of it passed where the acceptance tests, which Haiku never saw, passed over that build. Read every bug in this prompt as such a feature, and every fix as a build of one. A feature has no file of its own and no decoys, so in step 1 follow the traces alone. Its runs are named as `feature-1-base-2`. +Where they read `## Data-source`, Haiku added a data source instead: it was handed a made-up register and the spec the digest quotes, and wrote the importer, the data and whatever else the spec asks. Read it as a feature, whose runs are named as `data-source-1-base-2`. + Each run's whole stream is in the `runs` folder of the bench's folder, named below, as `.jsonl`. Open one only where the digest leaves a question open, and read it in parts: a stream is large. The folder is removed when you end, so an item must say everything it needs. What to do: diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index 977e208f..0424e2d4 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -1,9 +1,9 @@ r"""Measure how hard a project's code is to fix a bug in, or to build a feature in, at a base commit and at a head: plant bugs its tests catch, have Haiku fix each several times at both, and print how often the fix passes and what it took. With --tasks features, -Haiku builds the project's bench features instead. +Haiku builds the project's bench features instead, and with --tasks data-sources it adds made-up data sources. usage: task-bench --image --test [--base ] [--head ] [--prefix ] [--seed ] [--bugs ] [--runs ] [--record-figures] - task-bench --tasks features --image --test [--base ] [--head ] [--runs ] [--record-figures] + task-bench --tasks features|data-sources --image --test [--base ] [--head ] [--runs ] [--record-figures] task-bench gather Run it in a checkout, under ~/.claude/bin/run-heavy, with a long-lived token in CLAUDE_CODE_OAUTH_TOKEN, which `claude setup-token` @@ -49,6 +49,18 @@ command doesn't find the acceptance tests, which fail by design: outside the che skips `testdata`. The table then has a row per feature and side, and `-` for the reads. Gremlins doesn't run, so --seed, --bugs and --prefix don't go with it. +--tasks data-sources benches adding a data source, for a project that imports what others publish. Each task is a folder in +`bench-tasks` that holds a feature's three parts and `generate-register`, an executable file; --tasks features leaves such a +folder out. Before Haiku starts, the bench runs the script at the top of a copy of each side's tree, in the image with no +network, and the files it adds are the register: a made-up dataset in the format a real publisher would use. The script is +seeded, so it writes the same bytes at both sides; the bench passes over a task whose script fails, adds no file, or writes one +register at the base and another at the head. `spec.md` tells Haiku where the register is and what to add: say, the importer, +the data it imports and the licence entry. The reference patch adds them, and the acceptance tests check them, as by running +the importer again and comparing what it writes with the committed data. A task counts, and a run passes, as for a feature; the +tree that is checked holds the register as Haiku left it. Make up a publisher no real data could come from: a country code +ISO 3166-1 leaves to its users, such as QZ, and never XK, which is Kosovo's in practice. The table has a row per data source +and side. + It prints the base and the head, then a table: a row per bug and side with how many fixes passed and the medians, over the runs that finished, of the input, cache-write, cache-read and output tokens, the turns, the wall time, and the reads and searches before the run first opened the file the bug is in. The median of the reads leaves out a run that never opened that file. Then come a row @@ -71,7 +83,8 @@ passed, so the pass rate's noise is unmeasured. With --record-figures, a bench that finishes appends its figures to the project's comprehension history: an entry with the table's header and its three All rows. The entry's heading gives the current UTC time, then `task-bench of : head against base `, where is the branch checked out, whatever --head names. For a bench of -features the heading reads `task-bench features of : ...` instead. No tool reads the entry as a +features the heading reads `task-bench features of : ...` instead, and for one of data sources `task-bench data-sources +of : ...`. No tool reads the entry as a ruling or a scoring run. The bench's last line says where the entry went. A bench that fails or stops doesn't record anything. `task-bench gather`, run in the same checkout, turns the digest into plan items. It starts a claude on the project's rung, the @@ -107,7 +120,7 @@ import time import typing import uuid -from task_bench.tasks import Asked, Bench, BUG, check_made, committed, FEATURE, Kind, KINDS, on_disk, Planned, Task, tests_in_copy +from task_bench.tasks import Asked, Bench, BUG, check_made, committed, Kind, KINDS, on_disk, Planned, Task, tests_in_copy from task_bench.plant import bug_at_sides, drawn, killed_mutants, Mutant, place_files, task_text from claude_code.reply import Claude from task_bench.bench_folder import clear_left, held @@ -189,11 +202,11 @@ def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] | if not given.get(name): return Failure(f"{name} is missing") if given.setdefault(TASKS, "bugs") not in KINDS: - return Failure(f"{TASKS} takes {' or '.join(KINDS)}, not {given[TASKS]}") - of_features = KINDS[given[TASKS]] is FEATURE + return Failure(f"{TASKS} takes {', '.join(list(KINDS)[:-1])} or {list(KINDS)[-1]}, not {given[TASKS]}") + of_features = KINDS[given[TASKS]] is not BUG for name in OF_BUGS: if of_features and name in given: - return Failure(f"{name} is for a bench of bugs, so it doesn't go with {TASKS} features") + return Failure(f"{name} is for a bench of bugs, so it doesn't go with {TASKS} {given[TASKS]}") for name, default in COUNTS.items(): if of_features and name in OF_BUGS: continue @@ -212,9 +225,9 @@ def progress(line: str) -> None: def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path) -> list[str] | Failure: """The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. It tells its progress on stderr.""" - # Only bugs are planted at the seats' places. Each kind reads what it makes its tasks from before anything is copied or built, + # Only bugs are planted at the seats' places; features and data sources come from the project's folder. Each kind reads what it makes its tasks from before anything is copied or built, # so a fault there stops the bench at once. - tasks_from = read(home) if KINDS[given[TASKS]] is BUG else read_features(home) + tasks_from = read(home) if KINDS[given[TASKS]] is BUG else read_features(home, KINDS[given[TASKS]]) if isinstance(tasks_from, Failure): return tasks_from git = functools.partial(git_repo.git, env=env) @@ -238,7 +251,8 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Cal def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[str, str], tasks_from: str | Features, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure: """The report of a bench of the commits sides names, which empties folder and keeps its runs there. The bench plants bugs at - the places tasks_from names, where it is what `larv-review places` prints, and has Haiku build the features it holds otherwise.""" + the places tasks_from names, where it is what `larv-review places` prints, and has Haiku build the features, or add the data + sources, it holds otherwise.""" 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] = {} @@ -249,7 +263,7 @@ def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[st trees[side] = tree planned: typing.Callable[[Bench], Planned | Failure] | Failure if isinstance(tasks_from, Features): - asked, planned = Asked(FEATURE, int(given["--runs"])), features_planner(tasks_from, checkout, trees) + asked, planned = Asked(KINDS[given[TASKS]], int(given["--runs"])), features_planner(tasks_from, checkout, trees) else: asked, planned = Asked(BUG, int(given["--runs"])), bugs_planner(given, env, tasks_from, trees["base"]) if isinstance(planned, Failure): diff --git a/bin/task_bench/record_figures.py b/bin/task_bench/record_figures.py index d867c8b6..643eca7c 100644 --- a/bin/task_bench/record_figures.py +++ b/bin/task_bench/record_figures.py @@ -5,6 +5,7 @@ import typing from review_rules.comprehension_history import appended from task_bench.gather import DIGEST +from task_bench.tasks import BUG, KINDS from failure import Failure from git_cli.git_repo import Git from record_store.held import Held @@ -17,8 +18,9 @@ SIDES = re.compile(r"^Base ([0-9a-f]{7,40}), head ([0-9a-f]{7,40})\.", re.M) # How the table's three rows over every task open, as task_bench.figures.table writes them: the base, the head and the head's change. OVER_ALL = "| All |" COMMIT_LENGTH = 8 -# How the table's header opens in a bench of features, as task_bench.figures.table writes it. -OF_FEATURES = "| Feature |" +# By how the table's header opens, as task_bench.figures.table writes it, what a bench's name says its tasks are. A bench of bugs +# has the bare name. +TASKS_NAMED = {f"| {kind.noun.capitalize()} |": f" {tasks}" for tasks, kind in KINDS.items() if kind is not BUG} def recorded_bench(run: typing.Callable[[], list[str] | Failure], folder: pathlib.Path, git: Git, home: pathlib.Path, now: typing.Callable[[], float]) -> list[str] | Failure: @@ -59,7 +61,7 @@ def bench_appended(history: RecordStore, held: Held, name: str, entry: str) -> s def bench_entry(digest: str, branch: str, now: float) -> tuple[str, str] | None: - """A bench's name in the history and its entry there, stamped with now: the digest's table header and its three rows over every task. The name says where the bench built features, so the history holds it beside a bench of bugs at the same commits. branch is the branch the bench ran on. None where digest is no task-bench digest.""" + """A bench's name in the history and its entry there, stamped with now: the digest's table header and its three rows over every task. The name says where the bench built features or added data sources, so the history holds it beside a bench of bugs at the same commits. branch is the branch the bench ran on. None where digest is no task-bench digest.""" sides = SIDES.search(digest) table = [line for line in digest.splitlines() if line.startswith("|")] rows = [line for line in table if line.startswith(OVER_ALL)] @@ -67,5 +69,5 @@ def bench_entry(digest: str, branch: str, now: float) -> tuple[str, str] | None: return None base, head = (commit[:COMMIT_LENGTH] for commit in sides.groups()) # A panel of three readers, seated as the README's audience, picked this wording on 2026-11-23. Two of the three wanted the bench's name before the commits. - name = f"task-bench{' features' if table[0].startswith(OF_FEATURES) else ''} of {branch}: head {head} against base {base}" + name = f"task-bench{next((named for opening, named in TASKS_NAMED.items() if table[0].startswith(opening)), '')} of {branch}: head {head} against base {base}" return name, "\n".join([f"## {utc(now)}, {name}", "", *table[:2], *rows]) + "\n" diff --git a/bin/task_bench/registers.py b/bin/task_bench/registers.py new file mode 100644 index 00000000..6208ef12 --- /dev/null +++ b/bin/task_bench/registers.py @@ -0,0 +1,59 @@ +"""The register a data-source task hands Haiku: the files the task's `generate-register` writes into the tree Haiku starts in. +The script is seeded, so it writes the same register at the base and at the head, byte for byte; a task whose script doesn't is +passed over.""" +import pathlib +import shutil + +from task_bench.tasks import Bench, committed, on_disk +from failure import Failure +from task_bench.runs import Containers, entries, in_tree, run_in_image, TimedOut +from task_bench.figures import Side, SIDES + +# A panel of three readers, seated as the README's audience, picked the name on 2026-11-23: each had it first or second, over +# `register`, which reads as a data file, and `generate-source`, which two read as generating source code. +GENERATE = "generate-register" +# Where a container finds the script, outside the tree, so the tree never holds it. +MOUNTED = f"/{GENERATE}" + + +class NotGenerated(Failure): + """The script gave no register a task can start from. The reason ends a sentence that opens with the task's name, as in + `its generate-register exits 3 at the base`.""" + + +def registered_trees(bench: Bench, name: str, script: str) -> dict[Side, str] | Failure: + """A copy of each side's tree with the register that script generates in it, committed once, for the data source called name. + NotGenerated where the script fails at a side, or writes one register at the base and another at the head.""" + trees: dict[Side, str] = {} + registers: dict[Side, dict[str, bytes]] = {} + for side in SIDES: + tree = bench.folder / "data-sources" / name / side + copied = on_disk(f"copy the {side}'s tree to {tree}", lambda: shutil.copytree(bench.trees[side], tree, symlinks=True)) + if isinstance(copied, Failure): + return copied + register = generated(bench.containers, str(tree), script) + if isinstance(register, NotGenerated): + return NotGenerated(f"{register.reason} at the {side}") + if isinstance(register, Failure): + return register + if failure := committed(bench.git, str(tree)): + return failure + trees[side], registers[side] = str(tree), register + if registers["base"] != registers["head"]: + return NotGenerated(f"its {GENERATE} writes one register at the base and another at the head") + return trees + + +def generated(containers: Containers, tree: str, script: str) -> dict[str, bytes] | Failure: + """The register script writes when run at the top of tree, in the bench's image with no network: each file new to the tree, + by its path from the top. NotGenerated where the script runs out of time, fails or writes no new file.""" + before = set(entries(tree)) + ran = run_in_image(containers, ["--network", "none", *in_tree(containers, tree), "--volume", f"{script}:{MOUNTED}:ro", containers.image, MOUNTED]) + if isinstance(ran, TimedOut): + return NotGenerated(f"its {GENERATE} runs out of time") + if isinstance(ran, Failure): + return ran + if ran.code: + return NotGenerated(f"its {GENERATE} exits {ran.code}") + register = on_disk(f"read the register in {tree}", lambda: {path: pathlib.Path(tree, path).read_bytes() for path in entries(tree) if path not in before}) + return register or NotGenerated(f"its {GENERATE} doesn't write any new file") diff --git a/bin/task_bench/tasks.py b/bin/task_bench/tasks.py index 0d460785..a5d8f54d 100644 --- a/bin/task_bench/tasks.py +++ b/bin/task_bench/tasks.py @@ -26,15 +26,19 @@ class Kind(typing.NamedTuple): BUG = Kind("bug", "A test of this project fails with the message below. Find the bug in the code and fix it. Change no test.\n\n{told}", "a planted bug") FEATURE = Kind("feature", "Build the feature below in this project.\n\n{told}", "a feature's acceptance tests") +DATA_SOURCE = Kind("data-source", "Add the data source below to this project.\n\n{told}", "a data source's acceptance tests") # By the value --tasks takes. A panel of three readers, seated as the README's audience, picked `--tasks features` on 2026-11-23, # 3 to 0, over a bare `--features` and a `features` subcommand: it names what the bench runs, and the bugs as its other value. -KINDS = {"bugs": BUG, "features": FEATURE} +# Such a panel picked `data-sources` the same day, 3 to 0, over `sources` and `imports`, which read as source code and as import +# statements. +KINDS = {"bugs": BUG, "features": FEATURE, "data-sources": DATA_SOURCE} @dataclasses.dataclass(frozen=True) class Task: """A task for Haiku: its number from 1, its name, and per side the tree it starts in and what Haiku is told there. file is the - file a bug is in, and acceptance the folder of a feature's acceptance tests; each is None in a task of the other kind.""" + file a bug is in, and acceptance the folder of the acceptance tests of a feature or a data source; each is None in a task + of another kind.""" number: int name: str trees: dict[Side, str] diff --git a/bin/task_bench/test_feature_tasks.py b/bin/task_bench/test_feature_tasks.py index 549335f6..3394f778 100644 --- a/bin/task_bench/test_feature_tasks.py +++ b/bin/task_bench/test_feature_tasks.py @@ -80,7 +80,9 @@ def added(path: str) -> str: return f"diff --git a/{path} b/{path}\nnew file mode 100644\n--- /dev/null\n+++ b/{path}\n@@ -0,0 +1 @@\n+exit 0\n" -class FeatureBenchTest(unittest.TestCase): +class BenchOfTasksCase(unittest.TestCase): + """A checkout whose config names `bench-tasks`, with the feature halve in it, a base and a head, and docker and claude faked.""" + def setUp(self): folder = tempfile.TemporaryDirectory() self.addCleanup(folder.cleanup) @@ -121,6 +123,8 @@ class FeatureBenchTest(unittest.TestCase): with contextlib.redirect_stderr(io.StringIO()) as self.progress: return main.bench({**self.given, **given}, self.env, lambda home: "", self.home) + +class FeatureBenchTest(BenchOfTasksCase): def test_has_haiku_build_each_feature_at_both_sides_and_checks_it_with_the_acceptance_tests_it_never_saw(self): # Neither counts: one's acceptance tests pass before it is built, and the other's reference patch doesn't apply at the head. feature(self.tasks / "stale", acceptance="exit 0\n", test="stale_test.go") @@ -284,7 +288,7 @@ class OptionsTest(unittest.TestCase): def test_tasks_names_the_kind_of_task_and_bugs_is_the_default(self): self.assertEqual(self.options()["--tasks"], "bugs") self.assertEqual(self.options("--tasks", "features")["--tasks"], "features") - self.assertEqual(self.options("--tasks=chores").reason, "--tasks takes bugs or features, not chores") + self.assertEqual(self.options("--tasks=chores").reason, "--tasks takes bugs, features or data-sources, not chores") def test_features_run_5_times_at_each_side_by_default(self): self.assertEqual(self.options("--tasks", "features")["--runs"], "5") diff --git a/bin/task_bench/test_record_figures.py b/bin/task_bench/test_record_figures.py index 6b1f9953..092a7e0c 100644 --- a/bin/task_bench/test_record_figures.py +++ b/bin/task_bench/test_record_figures.py @@ -110,6 +110,10 @@ class RecordFiguresTest(unittest.TestCase): self.assertEqual(name, "task-bench features of item-7: head bbbbbbbb against base aaaaaaaa") self.assertTrue(entry.startswith(f"## 1970-01-01T00:00:00Z, {name}\n\n| Feature | Side |")) + def test_names_a_bench_of_data_sources_as_one(self): + name, _ = bench_entry(DIGEST.replace("| Bug |", "| Data-source |"), "item-7", 0) + self.assertEqual(name, "task-bench data-sources of item-7: head bbbbbbbb against base aaaaaaaa") + def test_refuses_a_digest_without_its_commits_or_without_its_three_rows_over_every_bug(self): for digest in (DIGEST.replace("Base ", "From "), DIGEST.replace("| All | change | +1 | -22% |\n", "")): with self.subTest(digest=digest): diff --git a/bin/task_bench/test_registers.py b/bin/task_bench/test_registers.py new file mode 100644 index 00000000..53d98bf7 --- /dev/null +++ b/bin/task_bench/test_registers.py @@ -0,0 +1,146 @@ +"""`task-bench --tasks data-sources` from its command line down: a whole bench of the data sources in a project's `bench-tasks` +folder, with docker and claude faked, and the faults of a `generate-register`.""" +import json +import pathlib +import sys +import textwrap +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from task_bench.test_feature_tasks import added, BenchOfTasksCase, feature +from failure import Failure +from task_bench.feature_tasks import features +from task_bench.tasks import DATA_SOURCE +from task_bench import main + +SPEC = "Import `register.csv`, a register of first names, into `names.txt`, with `import.sh`.\n" +# Writes the same register wherever it runs. +GENERATE = "#!/bin/sh\nprintf 'name;count\\nAda;3\\nBo;1\\n' > register.csv\n" +IMPORTER = "tail -n +2 register.csv | cut -d ';' -f 1 > names.txt" +# The importer must exist, and reproduce the committed data from the register Haiku was handed. +ACCEPTANCE = "cp names.txt committed 2>/dev/null && sh import.sh 2>/dev/null && cmp -s names.txt committed && grep -q Ada names.txt && exit 0\necho 'names.txt is not what import.sh makes of register.csv'\nexit 1\n" +REFERENCE = textwrap.dedent(f"""\ + diff --git a/import.sh b/import.sh + new file mode 100644 + --- /dev/null + +++ b/import.sh + @@ -0,0 +1 @@ + +{IMPORTER} + diff --git a/names.txt b/names.txt + new file mode 100644 + --- /dev/null + +++ b/names.txt + @@ -0,0 +1,2 @@ + +Ada + +Bo +""") +# Imports the register right at the head. At the base it commits data its importer doesn't make. It logs its prompt and the files +# it was handed. +CLAUDE = textwrap.dedent(f"""\ + import json, os, pathlib, sys + log = pathlib.Path(os.environ["FAKE_LOG"] + ".claude") + log.write_text(json.dumps({{"prompt": sys.argv[1], "handed": sorted(os.listdir(".")), "register": pathlib.Path("register.csv").read_text()}})) + print(json.dumps({{"type": "system", "subtype": "init", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330"}})) + at_head = "// Add adds." in pathlib.Path("calc.go").read_text() + pathlib.Path("import.sh").write_text({IMPORTER!r} + "\\n") + pathlib.Path("names.txt").write_text("Ada\\nBo\\n" if at_head else "Ada\\n") + usage = {{"input_tokens": 40, "cache_creation_input_tokens": 9000, "cache_read_input_tokens": 52000, "output_tokens": 800}} + print(json.dumps({{"type": "result", "subtype": "success", "is_error": False, "num_turns": 3, "duration_ms": 61500, "usage": usage, "result": "Imported."}})) +""") + + +def data_source(folder: pathlib.Path, generate: str = GENERATE, mode: int = 0o755) -> None: + """Writes a data-source task into folder.""" + feature(folder, spec=SPEC, patch=REFERENCE, acceptance=ACCEPTANCE, test="names_test.go") + (folder / "generate-register").write_text(generate) + (folder / "generate-register").chmod(mode) + + +class DataSourceBenchTest(BenchOfTasksCase): + def setUp(self): + super().setUp() + self.given["--tasks"] = "data-sources" + (self.root / "fakes/claude.py").write_text(CLAUDE) + + def test_hands_haiku_the_register_the_script_generates_and_checks_the_importer_and_the_data_it_adds(self): + data_source(self.tasks / "names-qz") + report = self.bench() + self.assertNotIsInstance(report, Failure, report) + folder = pathlib.Path(report[-1].removeprefix(main.KEPT)) + # halve, which has no generate-register, is a feature: no task of this bench. + self.assertEqual(report[:-1], [ + f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 data-source, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.", + "", + "| Data-source | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |", + "|---|---|---|---|---|---|---|---|---|---|", + "| 1: names-qz | base | 0/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |", + "| 1: names-qz | head | 2/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |", + "| All | base | 0/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |", + "| All | head | 2/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |", + "| All | change | +2 | 0 % | 0 % | 0 % | 0 % | 0 | 0 % | - |", + "", + ]) + handed = json.loads(pathlib.Path(f"{self.log}.claude").read_text()) + self.assertEqual(handed["prompt"], f"Add the data source below to this project.\n\n{SPEC.strip()}") + # Haiku's copy holds the code and the register: neither the script that made it nor the task's other parts. + self.assertEqual(handed["handed"], [".git", "README.md", "calc.go", "calc_test.go", "dangling", "register.csv"]) + self.assertEqual(handed["register"], "name;count\nAda;3\nBo;1\n") + results = json.loads((folder / "results.json").read_text()) + self.assertEqual((results["data-sources"], results["runs"][0]["data-source"]), ({"1": "names-qz"}, 1)) + self.assertTrue((folder / "runs/data-source-1-base-1.jsonl").is_file()) + self.assertIn(f"\n## Data-source 1: names-qz\n\nThe spec Haiku was told:\n\n {SPEC}", (folder / "digest.md").read_text()) + # The script ran without a network, and git doesn't show Haiku that the register is new. + runs = [json.loads(line) for line in self.log.read_text().splitlines()] + generated = [args for args in runs if args[-1] == "/generate-register"] + self.assertEqual(len(generated), 2) + self.assertEqual(generated[0][generated[0].index("--network") + 1], "none") + self.assertIn(f"{self.tasks / 'names-qz/generate-register'}:/generate-register:ro", generated[0]) + status = self.git("-C", str(folder / "data-sources/names-qz/head"), "status", "--porcelain") + self.assertEqual(status, "") + + def test_a_bench_of_features_takes_no_data_source(self): + data_source(self.tasks / "names-qz") + report = self.bench(**{"--tasks": "features"}) + self.assertNotIsInstance(report, Failure, report) + self.assertIn("1 feature,", report[0]) + self.assertEqual([found.name for found in features(self.tasks, DATA_SOURCE)], ["names-qz"]) + + def test_passes_over_a_data_source_whose_script_fails_writes_no_file_or_writes_another_register_at_the_head(self): + data_source(self.tasks / "a-fails", generate="#!/bin/sh\nexit 3\n") + data_source(self.tasks / "b-empty", generate="#!/bin/sh\ntrue\n") + # The register follows the tree it is generated in, so a seed doesn't regenerate it byte for byte. + data_source(self.tasks / "c-unseeded", generate="#!/bin/sh\nwc -c < calc.go > register.csv\n") + report = self.bench() + self.assertIsInstance(report, Failure) + self.assertEqual(report.reason, f"None of the 3 data-sources in {self.tasks} counts. a-fails: its generate-register exits 3 at the base. b-empty: its generate-register doesn't write any new file at the base. c-unseeded: its generate-register writes one register at the base and another at the head.") + + def test_fails_before_any_container_starts_where_a_part_is_at_fault_or_the_folder_holds_no_data_source(self): + empty = self.bench() + self.assertEqual(empty.reason, f"{self.tasks} holds no data-source: a folder for each, with spec.md, reference.patch, generate-register and the acceptance tests under acceptance") + data_source(self.tasks / "names-qz", mode=0o644) + unrunnable = self.bench() + self.assertEqual(unrunnable.reason, f"the data-source in {self.tasks / 'names-qz'} has a generate-register that is no executable file") + self.assertFalse(self.log.exists()) + + def test_passes_over_a_data_source_whose_reference_patch_leans_on_a_test_file_it_adds(self): + data_source(self.tasks / "names-qz") + (self.tasks / "names-qz/reference.patch").write_text(added("import_test.go")) + report = self.bench() + self.assertIn("names-qz: the tests fail with its reference patch at the base.", report.reason) + + +class OptionsTest(unittest.TestCase): + def options(self, *argv: str): + return main.options(["--image", "golang:1.27.4", "--test", "go test ./...", *argv], {"CLAUDE_CODE_OAUTH_TOKEN": "t"}) + + def test_data_sources_is_a_kind_of_task_that_runs_5_times_at_each_side_by_default(self): + self.assertEqual(self.options("--tasks", "data-sources")["--runs"], "5") + self.assertEqual(self.options("--tasks", "sources").reason, "--tasks takes bugs, features or data-sources, not sources") + + def test_the_options_that_choose_bugs_are_refused_with_data_sources(self): + self.assertEqual(self.options("--tasks", "data-sources", "--seed", "2").reason, "--seed is for a bench of bugs, so it doesn't go with --tasks data-sources") + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 95b4d0d6..0180209e 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -44,7 +44,8 @@ GREMLINS = textwrap.dedent("""\ if os.environ.get("FAKE_GREMLINS_LOG"): json.dump([os.getcwd(), *sys.argv[1:]], open(os.environ["FAKE_GREMLINS_LOG"], "w")) """) -# Logs each call. A `run` of the bench's image runs its command in the mounted tree: sh as it is, and claude as the fake below. +# Logs each call. A `run` of the bench's image runs its command in the mounted tree: sh as it is, claude as the fake below, and a +# file mounted beside the tree from where the host keeps it. DOCKER = textwrap.dedent("""\ #!/usr/bin/env python3 import json, os, subprocess, sys @@ -61,6 +62,8 @@ DOCKER = textwrap.dedent("""\ command = args[next(at for at, arg in enumerate(args) if arg.endswith(":throwaway")) + 1:] if command[0] == "claude": command = [sys.executable, os.environ["FAKE_CLAUDE"], command[-1]] + mounted = {inside: host for host, inside, *_ in (arg.split(":") for at, arg in enumerate(args) if args[at - 1] == "--volume")} + command[0] = mounted.get(command[0], command[0]) 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.