Bench adding a data source in task-bench, from a register a seeded script generates #702

Merged
lilleman merged 16 commits from item-505 into main 2026-11-23 21:07:06 +01:00
17 changed files with 496 additions and 100 deletions
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- `task-bench --tasks data-sources` benches adding a data source: Haiku gets a made-up register that the task's seeded `generate-register` writes, and acceptance tests check the importer, the data and whatever else the spec asks.
- `task-bench --tasks features` has Haiku build features instead of fixing planted bugs: each folder in the folder the project's config names as the new optional `bench-tasks` holds a `spec.md`, a `reference.patch` and acceptance tests Haiku never sees. A feature counts only where those tests fail before it is built and pass with the reference patch, at the base and at the head; the report names each feature passed over and why.
- A bench started with `task-bench --record-figures` appends its figures over every bug to the comprehension history once it finishes, and a scoring run in `larv-review` starts the project's bench that way where its README documents a `task-bench` command. The figures are a report beside the panel's scores: none blocks a merge.
- `task-bench`'s table prints the mean of the bugs' own head/base changes as its All change, in place of the change of the two All rows' medians, which swung up to three times as far in tokens. The All rows per side stay, so the change row is no longer their difference, and a change from before 0.15.1 can't be compared with one from after it.
+3 -3
View File
@@ -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] <model> <L>` 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 <image> --test <shell text> [<options>]` 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 <image> --test <shell text> [<options>]` 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 <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` 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 <ID>...` 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 <file> [<pattern>] [--timeout <seconds>]` 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.
+3 -2
View File
@@ -82,8 +82,9 @@ where `touch-predictions record` appends what each chunk was predicted to touch
Left out, the project keeps no such record. It is printed with the others only where it is set.
`bench-tasks` is an optional setting, a path spelt as the others are: the folder of the features that
`task-bench --tasks features` has Haiku build, such as `bench-tasks = "checkout:testdata/bench-tasks"`. `task-bench
--help` says what the folder holds. Left out, the project has no features to bench. It is printed with
`task-bench --tasks features` has Haiku build, and of the data sources `--tasks data-sources` has it add, such as
`bench-tasks = "checkout:testdata/bench-tasks"`. `task-bench --help` says what the folder holds. Left out, the project
has neither to bench. It is printed with
the others only where it is set.
`coding-conventions` is an optional setting, a list of paths spelt as the others are: the files in
+5 -4
View File
@@ -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, under a heading that calls the task by noun. A task with a file is a bug; any other is a
feature or a data source."""
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:",
"",
+57 -32
View File
@@ -1,14 +1,19 @@
"""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 task_bench.registers import GENERATE, NotGenerated, registered_trees
from project_config.main import located
from mutate_changes.tool_process import Ran
from task_bench.runs import ran_tests, TimedOut
@@ -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)
@@ -54,57 +62,74 @@ def features_folder(home: pathlib.Path) -> pathlib.Path | Failure:
config = located(None, home)
if isinstance(config, Failure):
return config
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")
return config.paths.get(BENCH_TASKS) or Failure(f"{config.folder / CONFIG} sets no `{BENCH_TASKS}`, the folder of the tasks 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 kind in folder, in the order of their names. A folder there with a `generate-register` holds a data source,
and any other holds a feature. A Failure where folder holds no such task, 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")
return Failure(f"could not read the {kind.noun}s 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}")
return Failure(f"could not read the {kind.noun}s 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:
+2
View File
@@ -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 the digest's headings read `## Data source`, the bench had Haiku add data sources instead. Each data source is a spec, which the digest quotes, and a register: a made-up dataset as a publisher would release it. Haiku wrote the importer, the data and whatever else the spec asks. Read every data source as a feature, with two differences. Its runs are named as `data-source-1-base-2`. And the tree Haiku started in, register included, is `data-sources/<name>/base` or `data-sources/<name>/head` in the bench's folder, `<name>` being the name in the heading; `trees/base` and `trees/head` lack the register.
Each run's whole stream is in the `runs` folder of the bench's folder, named below, as `<run id>.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:
+46 -30
View File
@@ -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 <image> --test <shell text> [--base <ref>] [--head <ref>] [--prefix <shell text>] [--seed <n>] [--bugs <n>] [--runs <n>] [--record-figures]
task-bench --tasks features --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--runs <n>] [--record-figures]
task-bench --tasks features|data-sources --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--runs <n>] [--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,20 @@ 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 script; --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 container
holds that tree and the script alone, so the script can't read another file of the task's folder. Seed the script, so that it
writes the same bytes at both sides. The bench passes over a task whose script doesn't exit 0, as where the image lacks its
interpreter, runs for 30 minutes, adds no file, adds a link or anything else that is no regular file, writes a `.git`, or
writes one register at the base and another at the head; the report says which, with the last line a failing script printed.
`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. Name the made-up publisher's country by a code no real data could carry: one 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,8 +85,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 <branch>: head
<commit> against base <commit>`, where <branch> is the branch checked out, whatever --head names. For a bench of
features the heading reads `task-bench features of <branch>: ...` instead. 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.
features the heading reads `task-bench features of <branch>: ...` instead, and for one of data sources `task-bench data-sources
of <branch>: ...`. 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
cheapest rung of the model loop-claude runs the project on, with the digest and the prompt in gather-prompt.md beside this file.
@@ -83,11 +97,12 @@ Each bench empties its own folder first, and removes the folder every earlier be
not, unless a bench or a gather is using it. So gather a bench before the next one starts.
Exit 1, saying why, on an unknown or repeated argument, a missing --image or --test, a --seed, --bugs or --runs that is no whole
number from 1, a --tasks that is neither bugs nor features, or no token; and where git, docker or Gremlins fails, the seats' places
don't name any Go file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks features it exits 1 on a
--seed, --bugs or --prefix; where no config names the checkout or its config sets no `bench-tasks`, or the folder holds no feature or one that lacks a part,
each before docker runs; and where the tests fail at a side without the acceptance tests, or no feature counts. Where the API refuses a run, the bench stops there and exits 1 too, after the table of
the runs that finished.
number from 1, a --tasks that is none of bugs, features and data-sources, or no token; and where git, docker or Gremlins fails,
the seats' places don't name any Go file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
features or data-sources it exits 1 on a --seed, --bugs or --prefix; where no config names the checkout or its config sets no
`bench-tasks`, or the folder holds no task of that kind, one that lacks a part, or a `generate-register` that is no executable
file, each before docker runs; and where the tests fail at a side without the acceptance tests, or no task counts. Where the
API refuses a run, the bench stops there and exits 1 too, after the table of the runs that finished.
With --record-figures it also exits 1, saying why: before it plants a bug, where no config names the checkout or the history
cannot be read; and after the bench, where the history already holds that branch's bench of those two commits or cannot be
written. The folder then still holds the bench's results.
@@ -107,7 +122,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
@@ -127,7 +142,7 @@ from larv_review.history_commands import read_places
from task_bench.record_figures import recorded_bench
from run_heavy.capped_docker import SHARE_VARIABLE
USAGE = "usage: task-bench --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--prefix <shell text>] [--seed <n>] [--bugs <n>] [--runs <n>] [--record-figures], or task-bench --tasks features --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--runs <n>] [--record-figures], or task-bench gather"
USAGE = "usage: task-bench --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--prefix <shell text>] [--seed <n>] [--bugs <n>] [--runs <n>] [--record-figures], or task-bench --tasks features|data-sources --image <image> --test <shell text> [--base <ref>] [--head <ref>] [--runs <n>] [--record-figures], or task-bench gather"
# A panel of three readers, seated as the README's audience, picked these options on 2026-11-21, each 3 to 0.
OPTIONS = ("--base", "--bugs", "--head", "--image", "--prefix", "--record-figures", "--runs", "--seed", "--tasks", "--test")
# The one option that takes no value.
@@ -189,11 +204,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 +227,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 +253,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 +265,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):
@@ -373,9 +389,9 @@ def ran_fixes(bench: Bench, tasks: list[Task], total: int) -> Fixes:
def kept(bench: Bench, plan: Planned, names: dict[int, str], results: list[Result]) -> Failure | None:
"""Writes results.json and the digest of the plan's tasks into the bench's folder. names holds each task's name by its number."""
in_a_tree = lambda path: any(pathlib.Path(tree, path).is_file() for tree in bench.trees.values())
noun = bench.asked.kind.noun
recorded_runs = json.dumps({"sides": bench.sides, **plan.drawn_by, f"{noun}s": names, "runs": [recorded(result, noun) for result in results]}, indent="\t") + "\n"
digest_text = digest(bench.sides, table(results, names, noun), [digested(task, results, bench.folder, noun) for task in plan.tasks], in_a_tree, noun)
noun, key = bench.asked.kind.noun, bench.asked.kind.key
recorded_runs = json.dumps({"sides": bench.sides, **plan.drawn_by, f"{key}s": names, "runs": [recorded(result, key) for result in results]}, indent="\t") + "\n"
digest_text = digest(bench.sides, table(results, names, noun), [digested(task, results, bench.folder, key) for task in plan.tasks], in_a_tree, noun)
try:
(bench.folder / "results.json").write_text(recorded_runs, encoding="utf-8")
(bench.folder / DIGEST).write_text(digest_text, encoding="utf-8", errors="replace")
@@ -449,7 +465,7 @@ def planted_tree(bench: Bench, side: Side, tree: pathlib.Path, path: str, change
def fixed(task: Task, side: Side, number: int, containers: Containers, folder: pathlib.Path, kind: Kind) -> Result | Failure:
"""One run: Haiku's work on task at side in a copy of its tree, then the tests over what it changed, with a feature's
acceptance tests among them. 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, kind.noun)
stream = stream_of(Result(task.number, side, number, False, None), folder, kind.key)
copy, check = folder / "copy", folder / "check"
try:
try:
@@ -480,21 +496,21 @@ def fixed(task: Task, side: Side, number: int, containers: Containers, folder: p
shutil.rmtree(check, ignore_errors=True)
def stream_of(result: Result, folder: pathlib.Path, noun: str) -> pathlib.Path:
"""The file that holds the stream of the run result names, of a task the bench calls by noun. Its name without the suffix is
def stream_of(result: Result, folder: pathlib.Path, key: str) -> pathlib.Path:
"""The file that holds the stream of the run result names, of a task whose kind has that key. Its name without the suffix is
the run's id in the digest."""
return folder / "runs" / f"{noun}-{result.task}-{result.side}-{result.run}.jsonl"
return folder / "runs" / f"{key}-{result.task}-{result.side}-{result.run}.jsonl"
def digested(task: Task, results: list[Result], folder: pathlib.Path, noun: str) -> TaskRuns:
def digested(task: Task, results: list[Result], folder: pathlib.Path, key: str) -> TaskRuns:
"""The task as the digest tells it, with each of its runs in results. A run that didn't finish has no tokens."""
runs = [Run(stream_of(result, folder, noun).stem, result.passed, found.tokens.context() + found.tokens.output if (found := result.figures) else None, result.entries) for result in results if result.task == task.number]
runs = [Run(stream_of(result, folder, key).stem, result.passed, found.tokens.context() + found.tokens.output if (found := result.figures) else None, result.entries) for result in results if result.task == task.number]
return TaskRuns(f"{task.number}: {task.name}", task.file, task.told["base"], runs)
def recorded(result: Result, noun: str) -> dict:
"""A run as results.json holds it, of a task the bench calls by noun."""
run = {noun: result.task, "side": result.side, "run": result.run, "passed": result.passed, "finished": result.figures is not None}
def recorded(result: Result, key: str) -> dict:
"""A run as results.json holds it, of a task whose kind has that key."""
run = {key: result.task, "side": result.side, "run": result.run, "passed": result.passed, "finished": result.figures is not None}
if not (found := result.figures):
return run
return {**run, "claude_code": found.version, "model": found.model, "tokens": dataclasses.asdict(found.tokens), "turns": found.turns, "seconds": found.seconds, "reads": found.reads}
+6 -4
View File
@@ -4,6 +4,7 @@ import re
import typing
from review_rules.comprehension_history import appended
from task_bench.tasks import BUG, KINDS
from task_bench.gather import DIGEST
from failure import Failure
from git_cli.git_repo import Git
@@ -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 |"
# What a bench's name says its tasks are, by how its table's header opens, as task_bench.figures.table writes it. 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"
+74
View File
@@ -0,0 +1,74 @@
"""The register a data-source task hands Haiku: the files the task's `generate-register` writes into the tree Haiku starts in.
A task counts only where its script writes the same register at the base and at the head, byte for byte, which a seeded script
does."""
import os
import pathlib
import shutil
from task_bench.tasks import Bench, committed, on_disk
from task_bench.runs import Containers, entries, in_tree, NotStarted, run_in_image, TimedOut
from failure import Failure
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}"
# What `docker run` exits with where docker itself failed, before any container started.
DOCKER_FAILED = 125
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, writes a `.git`, writes no new file, or
writes one that is no regular 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")
# With 126 or 127 the container started and the image could not run the script, as the task's fault as any other exit.
if isinstance(ran, NotStarted) and ran.ran.code != DOCKER_FAILED:
ran = ran.ran
if isinstance(ran, Failure):
return ran
if ran.code:
said = ran.output.strip().splitlines()[-1:]
return NotGenerated(f"its {GENERATE} exits {ran.code}" + "".join(f" after printing `{line[:200]}`" for line in said))
# git runs on the host in this tree next, and would run what a `.git/config` there names, outside the container.
if os.path.lexists(os.path.join(tree, ".git")):
return NotGenerated(f"its {GENERATE} writes a `.git`")
new = [path for path in entries(tree) if path not in before]
# The host reads each next: it would follow a link into its own files, and never finish reading a pipe.
if odd := [path for path in new if os.path.islink(os.path.join(tree, path)) or not os.path.isfile(os.path.join(tree, path))]:
return NotGenerated(f"its {GENERATE} writes `{odd[0]}`, which is no regular file")
register = on_disk(f"read the register in {tree}", lambda: {path: pathlib.Path(tree, path).read_bytes() for path in new})
return register or NotGenerated(f"its {GENERATE} doesn't write any new file")
+7 -1
View File
@@ -41,6 +41,12 @@ class TimedOut(Failure):
"""docker still ran when its time was up."""
@dataclasses.dataclass(frozen=True)
class NotStarted(Failure):
"""`docker run` exited with one of NOT_STARTED, as ran holds it."""
ran: Ran
class Docker(typing.Protocol):
"""Runs `docker <args>` and waits for it, at most `seconds`, and is TimedOut after that. Its output goes to `stdout` and its
errors to `stderr` where the call gives them, and into the Ran otherwise."""
@@ -148,7 +154,7 @@ def run_in_image(containers: Containers, args: list[str], stdout: typing.IO[byte
containers.docker(["rm", "--force", containers.running], seconds=120)
return ran
if ran.code in NOT_STARTED:
return Failure(f"docker run could not start its command, and exited {ran.code}: {ran.output.strip()}".removesuffix(": "))
return NotStarted(f"docker run could not start its command, and exited {ran.code}: {ran.output.strip()}".removesuffix(": "), ran)
return ran
+12 -3
View File
@@ -1,4 +1,4 @@
"""What task-bench's two kinds of task share. One kind is a planted bug, the other a feature to build. They share the task itself, the bench it runs in, and the
"""What task-bench's three kinds of task share: a planted bug, a feature to build and a data source to add. They share the task itself, the bench it runs in, and the
steps that commit a task's tree and run the tests over a copy of one."""
import dataclasses
import pathlib
@@ -23,18 +23,27 @@ class Kind(typing.NamedTuple):
prompt: str
without: str
@property
def key(self) -> str:
"""The noun as results.json and a run's file name spell it, without a space."""
return self.noun.replace(" ", "-")
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]
+7 -3
View File
@@ -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 called `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")
@@ -229,7 +233,7 @@ class FeatureBenchTest(unittest.TestCase):
(lambda: (self.tasks / "halve/acceptance/halve_test.go").unlink(), f"the feature in {self.tasks / 'halve'} holds no file under acceptance"),
(lambda: (self.tasks / "halve").rename(self.root / "moved"), f"{self.tasks} holds no feature: a folder for each, with spec.md, reference.patch and the acceptance tests under acceptance"),
(lambda: shutil.rmtree(self.tasks), f"could not read the features in {self.tasks}: it is no folder"),
(lambda: self.config.write_text(self.config.read_text().replace('bench-tasks = "checkout:bench-tasks"\n', "")), f"{self.config} sets no `bench-tasks`, the folder of the features to bench, as `project-config --help` describes it"),
(lambda: self.config.write_text(self.config.read_text().replace('bench-tasks = "checkout:bench-tasks"\n', "")), f"{self.config} sets no `bench-tasks`, the folder of the tasks to bench, as `project-config --help` describes it"),
):
with self.subTest(reason=reason):
shutil.rmtree(self.tasks, ignore_errors=True)
@@ -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")
+4
View File
@@ -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):
+229
View File
@@ -0,0 +1,229 @@
"""`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 os
import pathlib
import sys
import tempfile
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 task_bench.tasks import Asked, Bench, DATA_SOURCE
from task_bench.runs import Containers, TimedOut
from failure import Failure
from task_bench.feature_tasks import features
from task_bench.registers import generated, NotGenerated, registered_trees
from task_bench import main
from mutate_changes.tool_process import Ran
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 correctly 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.assertTrue((folder / "results.json").read_text().startswith('{\n\t"sides": {\n\t\t"base"'))
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\necho made half\necho no seed given >&2\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 after printing `no seed given` 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_passes_over_a_data_source_whose_script_writes_a_git_folder_before_git_runs_in_its_tree(self):
# git on the host would run the filter as it adds the files, outside the container and with the token.
marker = self.root / "ran-on-the-host"
planted = f"#!/bin/sh\necho x > register.csv\nmkdir .git\nprintf '[filter \"x\"]\\n\\tclean = touch {marker}; cat\\n' > .git/config\necho '* filter=x' > .gitattributes\n"
data_source(self.tasks / "names-qz", generate=planted)
report = self.bench()
self.assertEqual(report.reason, f"None of the 1 data sources in {self.tasks} counts. names-qz: its generate-register writes a `.git` at the base.")
self.assertFalse(marker.exists())
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_says_which_folder_holds_a_data_source_it_could_not_read(self):
data_source(self.tasks / "names-qz")
(self.tasks / "names-qz/spec.md").write_bytes(b"\xff")
unread = self.bench()
self.assertTrue(unread.reason.startswith(f"could not read the data sources in {self.tasks}: 'utf-8' codec can't decode"), unread.reason)
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 GeneratedTest(unittest.TestCase):
"""What a run of the script leaves, with docker faked as a function."""
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.tree = pathlib.Path(folder.name, "tree")
self.tree.mkdir()
def containers(self, docker) -> Containers:
return Containers(docker, "task-bench-test", "true", 512, "1000:1000")
def test_a_script_that_runs_out_of_time_generates_no_register(self):
ran = generated(self.containers(lambda args, **_: TimedOut("docker run still ran after 30 min")), str(self.tree), "/tasks/generate-register")
self.assertIsInstance(ran, NotGenerated)
self.assertEqual(ran.reason, "its generate-register runs out of time")
def test_says_which_register_it_could_not_read(self):
def docker(args, **_):
(self.tree / "register.csv").write_text("x")
(self.tree / "register.csv").chmod(0)
return Ran(0, "")
ran = generated(self.containers(docker), str(self.tree), "/tasks/generate-register")
self.assertNotIsInstance(ran, NotGenerated)
self.assertTrue(ran.reason.startswith(f"could not read the register in {self.tree}: "), ran.reason)
def test_a_link_or_a_pipe_is_no_register_and_the_host_reads_neither(self):
for name, write in (("register.csv", lambda path: os.symlink("/etc/hostname", path)), ("made/pipe", lambda path: (path.parent.mkdir(), os.mkfifo(path)))):
with self.subTest(name):
def docker(args, **_):
(self.tree / "plain.csv").write_text("x")
write(self.tree / name)
return Ran(0, "")
ran = generated(self.containers(docker), str(self.tree), "/tasks/generate-register")
self.assertIsInstance(ran, NotGenerated)
self.assertEqual(ran.reason, f"its generate-register writes `{name}`, which is no regular file")
def test_a_failing_script_is_quoted_by_the_first_200_characters_of_its_last_line_alone(self):
ran = generated(self.containers(lambda args, **_: Ran(3, f"first\nsecond\n{'x' * 201}\n")), str(self.tree), "/tasks/generate-register")
self.assertEqual(ran.reason, f"its generate-register exits 3 after printing `{'x' * 200}`")
def test_a_script_the_image_cannot_run_is_the_tasks_fault_and_a_docker_that_fails_is_not(self):
docker = lambda code: lambda args, **_: Ran(code, "exec /generate-register: no such file or directory\n")
for code in (126, 127):
ran = generated(self.containers(docker(code)), str(self.tree), "/tasks/generate-register")
self.assertIsInstance(ran, NotGenerated)
self.assertEqual(ran.reason, f"its generate-register exits {code} after printing `exec /generate-register: no such file or directory`")
ran = generated(self.containers(docker(125)), str(self.tree), "/tasks/generate-register")
self.assertNotIsInstance(ran, NotGenerated)
self.assertEqual(ran.reason, "docker run could not start its command, and exited 125: exec /generate-register: no such file or directory")
def test_a_script_that_fails_without_a_word_is_named_by_its_exit_code_alone(self):
ran = generated(self.containers(lambda args, **_: Ran(2, "\n")), str(self.tree), "/tasks/generate-register")
self.assertEqual(ran.reason, "its generate-register exits 2")
def test_says_which_tree_it_could_not_copy(self):
bench = Bench("/checkout", {}, {"base": str(self.tree / "missing")}, Asked(DATA_SOURCE, 1), self.containers(None), self.tree, None, print)
trees = registered_trees(bench, "names-qz", "/tasks/generate-register")
self.assertTrue(trees.reason.startswith(f"could not copy the base's tree to {self.tree / 'data-sources/names-qz/base'}: "), trees.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")
self.assertIn(", or task-bench --tasks features|data-sources --image <image>", main.USAGE)
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()
+7 -2
View File
@@ -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.
@@ -629,7 +632,9 @@ class ContainersTest(unittest.TestCase):
def test_a_run_whose_command_never_started_is_a_failure_that_says_what_docker_printed(self):
for code in (125, 126, 127):
self.assertEqual(ran_tests(self.containers(run=Ran(code, "sh: gotestsum: not found\n")), "/tree"), Failure(f"docker run could not start its command, and exited {code}: sh: gotestsum: not found"))
ran = ran_tests(self.containers(run=Ran(code, "sh: gotestsum: not found\n")), "/tree")
self.assertIsInstance(ran, Failure)
self.assertEqual(ran.reason, f"docker run could not start its command, and exited {code}: sh: gotestsum: not found")
self.assertEqual(ran_tests(self.containers(run=Ran(124, "late")), "/tree"), Ran(124, "late"))
self.assertEqual(ran_tests(self.containers(run=Ran(128, "killed")), "/tree"), Ran(128, "killed"))
self.assertEqual(fix_attempted(self.containers(run=Ran(125, "")), "/tree", "got 3", self.stream), Failure(f"docker run could not start its command, and exited 125; its errors are in {self.stream.with_suffix('.stderr')}"))
+17
View File
@@ -3460,3 +3460,20 @@ Read most (opens and searches):
## Reading cost, chunk 5c33cc8bf84f, finished 2026-11-23T13:17:23Z
41140 new input tokens before the first commit.
## Reading cost, chunk 0a5c0968dbc6, finished 2026-11-23T17:38:22Z
100034 new input tokens before the first commit.
Read most (opens and searches):
- `bin/project_config/settings.py` 6
- `bin/task_bench/main.py` 6
- `README.md` 4
- `rules/todo-items.md` 4
- `bin/task_bench/plant.py` 2
- `bin/project_config/main.py` 1
- `bin/task_bench/digest.py` 1
- `bin/task_bench/gather.py` 1
- `bin/task_bench/runs.py` 1
- `docs/score-anchors.md` 1
+16 -16
View File
@@ -6,7 +6,7 @@
`Bar = 0.1`
`Next ID = 525`
`Next ID = 526`
## Renamed
@@ -16,12 +16,12 @@
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 505 | 0.16.0 | | owner | **Bench adding source data in `task-bench`: hand Haiku a fake register that a seeded script generates for a made-up country, and check the importer, the data and the licence entry it adds, starting with five tasks for fejkdata.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 3, code health by 2 | 2.6 |
| 508 | 0.16.0 | | owner | **Plant bugs for `task-bench` in Python, Rust, TypeScript and PHP, from the mutants `mutate-changes` runs for each, so this repo benches itself.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 3, code health by 2 | 2.6 |
| 506 | 0.16.0 | | owner | **Go over the bench features in each release review: reapply each reference patch, drop a feature that no longer breaks a goal, and add features until they cover the places the seats find hardest.** | 2 | 2 | 2 | 4 | 3 | 1.1 by 3 | 1.1 |
| 512 | 0.16.0 | | | **Make stability-reviewer check that keys built from path segments, or matched by prefix, cannot collide.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 507 | 0.16.0 | | owner | **Bench rebuilding a feature the project shipped: revert its commit at the head, hand Haiku its item tagline, and check with the tests that commit added.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 3 | 0.7 |
| 524 | 0.16.0 | | owner | **Write fejkdata's first six bench features, each a spec, acceptance tests in Go and a reference patch that builds it, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 6 | 1.1 by 3 | 0.5 |
| 525 | 0.16.0 | | owner | **Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 7 | 1.1 by 3 | 0.3 |
| 477 | 0.17.0 | | question | **Rewrite `## Goals` and `## Audience` for a setup others install and run apart from their own `~/.claude`.** | 1 | 1 | 2 | 2 | 2 | | 0.0 |
| 478 | 0.17.0 | | question | **Name the project, its repo and its two commands, today proposed as `do-release` and `do-epic`.** | 1 | 1 | 2 | 2 | 1 | | 0.0 |
| 523 | 0.17.0 | | | **Make the security pass and stability-reviewer check that a new secret's docs name its scope and its reach, such as the other repositories its account can use.** | 1 | 1 | 2 | 2 | 1 | 1.1 by 2 | 0.9 |
@@ -112,20 +112,6 @@
## Details
### 505. Bench adding source data in `task-bench`: hand Haiku a fake register that a seeded script generates for a made-up country, and check the importer, the data and the licence entry it adds, starting with five tasks for fejkdata.
Adding a source is fejkdata's recurring work, so it stays easy only while the bench shows it does. The country code comes from ISO 3166-1's user-assigned range (AA, QM–QZ, XA–XZ, ZZ), leaving out XK, which the EU and others use for Kosovo, so no task meets real data. Each register has the quirks real ones publish, and its script regenerates it byte for byte.
The checker runs a template such as `{/person[QZ]}` with a fixed seed, fejkdata's full test suite with the data-licence tests, and the importer again, which must reproduce the committed data.
fejkdata's five:
- D1: names weighted by frequency, from a semicolon CSV in Latin-1.
- D2: addresses, with postcodes mapped to towns, from nested JSON; values that belong together come from one pick.
- D3: a valid national id, from a spec page giving the checksum; the checker validates every id the template prints.
- D4: companies with legal-form suffixes, from an XML register.
- D5: D1's register in its next edition, with a renamed column and a new code list, so Haiku updates an importer that exists.
### 508. Plant bugs for `task-bench` in Python, Rust, TypeScript and PHP, from the mutants `mutate-changes` runs for each, so this repo benches itself.
Each tool reports a killed mutant by file and line, and some by column; the planter re-applies it from that report, as it does Gremlins'.
@@ -158,6 +144,20 @@ The second part of item 504, which says what a bench feature is and when a run c
Done when `task-bench` counts a run of each: its acceptance tests fail at fejkdata's base and head and pass with its reference patch. The six land in fejkdata's checkout or its config folder, wherever its `bench-tasks` setting points, so the item changes no file of this repo and carries no `Touches:` list. About 1,000 lines of Go and specs.
### 525. Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.
The second part of item 505, which says what a source-data task is and when a run counts. The country code of each comes from ISO 3166-1's user-assigned range (AA, QM–QZ, XA–XZ, ZZ), leaving out XK, which the EU and others use for Kosovo, so no task meets real data. Each register has the quirks real ones publish.
Each checker runs a template such as `{/person[QZ]}` with a fixed seed, fejkdata's full test suite with the data-licence tests, and the importer again, which must reproduce the committed data.
- D1: names weighted by frequency, from a semicolon CSV in Latin-1.
- D2: addresses, with postcodes mapped to towns, from nested JSON; values that belong together come from one pick.
- D3: a valid national id, from a spec page giving the checksum; the checker validates every id the template prints.
- D4: companies with legal-form suffixes, from an XML register.
- D5: D1's register in its next edition, with a renamed column and a new code list, so Haiku updates an importer that exists.
Done when `task-bench` counts a run of each. The five land wherever fejkdata's `bench-tasks` setting points, which its config must first set, so the item changes no file of this repo and carries no `Touches:` list. About 1,500 lines of Python, Go, data and specs.
### 477. Rewrite `## Goals` and `## Audience` for a setup others install and run apart from their own `~/.claude`.
Part of the standalone-install plan lilleman approved on 2026-11-20. `do-release` and `do-epic` stand for the names item 478 picks. Goal 2, "Make my claude setup shareable between computers", and an audience of lilleman, with client teams as readers of what the loop writes, no longer fit. The goals and the audience are the human's to write; propose a wording and ask.