Answer architecture round 1: 0 🔴, 6 🟡 (0 misread); count a release review only where it names the next release, split task_bench into bugs, features and figures, group README's packages
CI / tests (pull_request) Successful in 4m55s

This commit is contained in:
2026-11-27 11:23:08 +01:00
parent d1b01c76c8
commit b563a597f1
55 changed files with 293 additions and 198 deletions
View File
+185
View File
@@ -0,0 +1,185 @@
"""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.
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.features.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, DATA_SOURCE, FEATURE, Kind, on_disk, Planned, Task
from project_config.settings import BENCH_TASKS, CONFIG
from failure import Failure
from task_bench.features.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
from task_bench.figures.figures import Side, SIDES
SPEC = "spec.md"
PATCH = "reference.patch"
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. 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):
"""The reference patch doesn't apply to the tree."""
class Features(typing.NamedTuple):
"""A project's features, found in the folder that keeps them."""
folder: pathlib.Path
found: list[Feature]
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, kind)
return found if isinstance(found, Failure) else Features(folder, found)
def features_folder(home: pathlib.Path) -> pathlib.Path | Failure:
"""The folder the config of the current directory's project names as `bench-tasks`."""
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 tasks to bench, as `project-config --help` describes it")
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 {kind.noun}s in {folder}: it is no folder")
try:
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 {kind.noun}s in {folder}: {failure}")
if not found:
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, 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 {noun} in {folder} lacks {part.name}")
told = spec.read_text(encoding="utf-8").strip()
if not told:
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 {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."""
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:
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, trees))
bench.say(f"task-bench: passed over the {noun} {feature.name}: {trees}.")
if not tasks:
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:
"""A copy of each side's tree, committed once. Every feature starts from it, since a feature doesn't add anything to the tree Haiku
works in."""
trees: dict[Side, str] = {}
for side in SIDES:
tree = bench.folder / "features" / 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
if failure := committed(bench.git, str(tree)):
return failure
trees[side] = str(tree)
return trees
def why_passed_over(bench: Bench, trees: dict[Side, str], feature: Feature) -> str | Failure | None:
"""Why feature doesn't count at the first side where it doesn't, in the committed trees; None where it counts at both. A
Failure where the tests could not run."""
for side, is_built in itertools.product(SIDES, (False, True)):
ran = checked_run(bench, trees[side], feature, is_built)
if isinstance(ran, NotApplied):
return f"its reference patch doesn't apply at the {side}"
if isinstance(ran, TimedOut):
return f"the tests run out of time at the {side}"
if isinstance(ran, Failure):
return ran
if not is_built and ran.code == 0:
return f"its acceptance tests pass at the {side} before it is built"
if is_built and ran.code:
return f"the tests fail with its reference patch at the {side}"
return None
def checked_run(bench: Bench, tree: str, feature: Feature, is_built: bool) -> Ran | Failure:
"""The test command's run over the tree that checks a copy of tree, with the reference patch applied to the copy where
is_built. It is checked as a run of Haiku's is, so a patch that leans on a test or `testdata` file of its own fails, as a
build would. Both trees are removed afterwards."""
copy, check = bench.folder / "copy", bench.folder / "check"
try:
copied = on_disk(f"copy {tree} to check {feature.name} in it", lambda: shutil.copytree(tree, copy, symlinks=True))
if isinstance(copied, Failure):
return copied
# git has run in this bench already, so a failure here is the patch's.
applied = bench.git("apply", feature.patch, cwd=str(copy)) if is_built else None
if isinstance(applied, Failure):
return NotApplied(applied.reason)
made = on_disk(f"make the tree that checks {feature.name}", lambda: check_made(tree, str(copy), str(check), feature.acceptance))
return made or ran_tests(bench.containers, str(check))
finally:
shutil.rmtree(copy, ignore_errors=True)
shutil.rmtree(check, ignore_errors=True)
+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.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")
+173
View File
@@ -0,0 +1,173 @@
"""The features task-bench has Haiku rebuild: those the project shipped, read from its history. A shipped feature is a chunk on
the base's first-parent line that took an item out of the plan, as branch_chunks cuts that line. Once its change is out of each
side's tree, it is a feature as task_bench.features.feature_tasks has it. `task-bench --help` says what Haiku is told and how a rebuild
is checked."""
import functools
import os
import pathlib
import re
import shutil
import typing
from task_bench.features.feature_tasks import ACCEPTANCE, Feature, PATCH, why_passed_over
from task_bench.tasks import Bench, committed, on_disk, Planned, Task
from branch_chunks.read import cut_with_shipped, unsupported
from failure import Failure
from git_cli.git_repo import Git
from plan.todo_table import Item, tagline_text
from project_config.main import located
from task_bench.runs import of_tests
from project_config.settings import RECORDS
from task_bench.figures.figures import Side, SIDES
# Why a feature that landed by fast-forward is passed over: no earlier chunk says where its commits start, or its branch merged
# the default branch into itself, so its commits hold what other features built.
NO_START = "its branch landed by fast-forward, and nothing earlier marks where its commits start"
MERGED_IN = "its branch landed by fast-forward after merging the default branch into itself, so its commits hold other features' changes"
# What git titles a merge of the default branch into a feature branch, other than into main or master, which git leaves out of
# the title. A person's merge of a branch into another default branch has the same title; its feature is then passed over.
SYNC_MERGE = re.compile(r"Merge (?:remote-tracking )?branch '[^']+' into (?!main$|master$)\S+")
# The options that keep the checkout's diff config out of a patch. --no-renames writes a renamed file as one file removed and
# one added, so `git apply` doesn't have to detect the rename again.
PLAIN_DIFF = ("--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--src-prefix=a/", "--dst-prefix=b/")
class Shipped(typing.NamedTuple):
"""A feature the project shipped: the name the report gives it, such as `item 7`, the tagline of each item its chunk took out
of the plan, a paragraph each, and the commits its change runs between. before is None where the history doesn't say where
the change starts, and passed_over then says why."""
name: str
told: str
before: str | None
tip: str
passed_over: str = ""
class ShippedFeatures(typing.NamedTuple):
"""The features a project shipped, newest first, and the paths of its plan and its records, each from the checkout's top. A
chunk's change to those paths is no part of its feature."""
found: list[Shipped]
records: list[str]
def read_shipped(home: pathlib.Path, checkout: str, base: str, git: Git) -> ShippedFeatures | Failure:
"""The features that the project in checkout shipped on the first-parent line of the commit base. A Failure where no config
names the checkout, where its config puts the plan or a record at a path branch_chunks doesn't read, where git fails, and
where that line shipped no item."""
in_checkout = functools.partial(git, cwd=checkout)
config = located(checkout, home, in_checkout)
if isinstance(config, Failure):
return config
if why := unsupported(checkout, home, in_checkout):
return Failure(f"task-bench cannot tell what the project shipped: {why}")
cut = cut_with_shipped(base, in_checkout, config.titles)
if isinstance(cut, Failure):
return cut
branch, shipped = cut
found: list[Shipped] = []
# The oldest chunk first, so each feature knows the commit that ends the chunk before it.
marked = None
merged_in = False
for chunk, items in reversed(list(zip(branch.chunks, shipped))):
if items:
# A fast-forwarded feature's commits are a chunk each, and this chunk holds only the last. The earlier ones follow the
# commit that ends the latest earlier chunk of another feature.
starts, why = chunk.before, ""
if chunk.landing == "push":
starts, why = (None, NO_START) if marked is None else (None, MERGED_IN) if merged_in else (marked, "")
told = "\n\n".join(tagline_text(item.tagline) for item in items)
found.append(Shipped(named(items), told, starts, chunk.tip, why))
if SYNC_MERGE.fullmatch(branch.commits[chunk.tip].title):
merged_in = True
elif items or chunk.landing != "push":
marked, merged_in = chunk.tip, False
found.reverse()
if not found:
return Failure("No chunk on the base's history took an item out of todo.md, so that history holds no shipped feature to rebuild.")
return ShippedFeatures(found, [path for path in map(config.tracked, ("plan", *RECORDS)) if path])
def named(items: tuple[Item, ...]) -> str:
"""What the report calls the feature that shipped items: `item 7`, or `items 7, 8`."""
return f"item{'s' * (len(items) > 1)} {', '.join(str(item.id) for item in items)}"
def shipped_tasks(bench: Bench, shipped: ShippedFeatures, count: int) -> Planned | Failure:
"""The task of rebuilding each feature of shipped that counts at the bench's commits, newest first, until there are count
tasks. The tasks are numbered from 1, and a line says why each feature on the way was passed over. A Failure where none
counts."""
noun = bench.asked.kind.noun
tasks: list[Task] = []
passed_over: list[str] = []
for feature in shipped.found:
if len(tasks) == count:
break
# A feature passed over leaves no folder, so the next one tried takes the same number.
folder = bench.folder / "shipped-features" / str(len(tasks) + 1)
taken_out = feature.passed_over if feature.before is None else on_disk(f"take {feature.name} out of the trees in {folder}", functools.partial(without, bench, feature, feature.before, shipped.records, folder))
why = taken_out if not isinstance(taken_out, TakenOut) else why_passed_over(bench, taken_out.trees, taken_out.feature)
if isinstance(why, Failure):
return why
if isinstance(taken_out, TakenOut) and why is None:
tasks.append(Task(len(tasks) + 1, feature.name, taken_out.trees, dict.fromkeys(SIDES, feature.told), acceptance=taken_out.feature.acceptance))
continue
shutil.rmtree(folder, ignore_errors=True)
passed_over.append(f"the {noun} {feature.name}: {why}.")
bench.say(f"task-bench: passed over {passed_over[-1]}")
if not tasks:
return Failure(f"No {noun} on the base's history counts; the lines above say why.")
return Planned(tasks, [f"Passed over {line}" for line in passed_over], {})
def held(path: str) -> bool:
"""Whether path is a file or a link, which copies as a test does; a folder doesn't."""
return os.path.islink(path) or os.path.isfile(path)
class TakenOut(typing.NamedTuple):
"""A shipped feature taken out of the bench's trees: each side's tree without it, committed once, and the feature that
builds it there again."""
trees: dict[Side, str]
feature: Feature
def without(bench: Bench, shipped: Shipped, before: str, records: list[str], folder: pathlib.Path) -> TakenOut | str | Failure:
"""shipped, as the commits from before to its tip, taken out of a copy of each side's tree, under folder, where its patch and its acceptance tests go too; or why it
cannot be, which ends a sentence that opens with its name. A Failure where git fails.
Raises OSError where a file cannot be copied."""
change = (before, shipped.tip, "--", ".", *(f":(exclude,literal){path}" for path in records))
# A name that is not UTF-8 is read with U+FFFD in it. The head's tree holds no file of that name, so the file is left out.
names = bench.git("diff", "--name-only", "-z", *change, cwd=bench.checkout, errors="replace")
if isinstance(names, Failure):
return names
tests = [path for path in names.split("\x00") if path and of_tests(path) and held(os.path.join(bench.trees["head"], path))]
if not tests:
return "its change holds no test that the head holds"
patch, acceptance = folder / PATCH, folder / ACCEPTANCE
for path in tests:
os.makedirs(os.path.dirname(acceptance / path), exist_ok=True)
shutil.copy2(os.path.join(bench.trees["head"], path), acceptance / path, follow_symlinks=False)
# --binary writes a binary file's bytes, which `git apply` needs. --output has git write them to the file, since bench.git
# would read them from its output as text.
diffed = bench.git("diff", "--binary", f"--output={patch}", *PLAIN_DIFF, *change, cwd=bench.checkout)
if isinstance(diffed, Failure):
return diffed
trees: dict[Side, str] = {}
for side in SIDES:
tree = str(folder / side)
shutil.copytree(bench.trees[side], tree, symlinks=True)
# In a repository of its own, the tree is where `git apply` reads the patch's paths from, whatever repository holds the
# bench's folder. git has run in this bench already, so a failure of the second command is the patch's.
if isinstance(made := bench.git("init", "--quiet", cwd=tree), Failure):
return made
if isinstance(bench.git("apply", "-R", str(patch), cwd=tree), Failure):
return f"its revert doesn't apply at the {side}"
if failure := committed(bench.git, tree):
return failure
trees[side] = tree
return TakenOut(trees, Feature(shipped.name, shipped.told, str(patch), str(acceptance)))
@@ -0,0 +1,304 @@
"""`task-bench --tasks features` from its command line down: a whole bench of the features in a project's `bench-tasks` folder,
with docker and claude faked, and the folder's faults."""
import contextlib
import io
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import textwrap
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.tasks import Asked, Bench, FEATURE
from task_bench.test_task_bench import BASE_CODE, DOCKER, HEAD_CODE, InTurn, TESTS
from task_bench.runs import Containers, TimedOut
from failure import Failure
from task_bench.features.feature_tasks import Feature, features, why_passed_over
from test_env import isolated_env
from task_bench import main
from mutate_changes.tool_process import Ran
CONFIG = "".join(f'{name} = "checkout:{name}.md"\n' for name in ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles", "standards"))
# Stands in for `go test ./...`: each test of the tree, a shell text in a file named as a Go test.
TEST = 'for file in *_test.go; do sh "$file" || exit 1; done'
ACCEPTANCE = "grep -q 'a / 2' halve.go 2>/dev/null && exit 0\necho 'Halve is missing or wrong'\nexit 1\n"
REFERENCE = textwrap.dedent("""\
diff --git a/halve.go b/halve.go
new file mode 100644
--- /dev/null
+++ b/halve.go
@@ -0,0 +1,5 @@
+package calc
+
+func Halve(a int) int {
+ return a / 2
+}
""")
# Changes the line of Twice that the head rewrote, so it applies at the base alone.
BASE_ONLY = textwrap.dedent("""\
diff --git a/calc.go b/calc.go
--- a/calc.go
+++ b/calc.go
@@ -6,4 +6,4 @@
func Twice(a int) int {
- return a * 2
+ return a * 2 // twice
}
""")
# Builds Halve right at the head. At the base it builds it wrong, and adds a test of its own that would pass. It logs its prompt
# and the files it was handed.
CLAUDE = textwrap.dedent("""\
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("."))}))
print(json.dumps({"type": "system", "subtype": "init", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330"}))
print(json.dumps({"type": "assistant", "message": {"id": "msg_1", "content": [{"type": "tool_use", "id": "toolu_1", "name": "Read", "input": {"file_path": "/work/calc.go"}}], "usage": {}}}))
at_head = "// Add adds." in pathlib.Path("calc.go").read_text()
pathlib.Path("halve.go").write_text("package calc\\n\\nfunc Halve(a int) int {\\n\\treturn a " + ("/ 2" if at_head else "- 2") + "\\n}\\n")
pathlib.Path("halve_test.go").write_text("exit 0\\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": "Built."}))
""")
def feature(folder: pathlib.Path, spec: str = "Add `Halve(a int) int`, which halves a.\n", patch: str = REFERENCE, acceptance: str = ACCEPTANCE, test: str = "halve_test.go") -> None:
"""Writes a feature into folder."""
(folder / "acceptance").mkdir(parents=True)
(folder / "spec.md").write_text(spec)
(folder / "reference.patch").write_text(patch)
(folder / "acceptance" / test).write_text(acceptance)
def added(path: str) -> str:
"""The part of a patch that adds the file path, which holds `exit 0`."""
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 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)
self.root = pathlib.Path(folder.name).resolve()
self.home, self.repo, fakes = self.root / "home", self.root / "repo", self.root / "fakes"
for made in (self.home / ".claude-projects/calc", self.repo, fakes):
made.mkdir(parents=True)
(fakes / "docker").write_text(DOCKER)
(fakes / "docker").chmod(0o755)
(fakes / "claude.py").write_text(CLAUDE)
self.log = self.root / "docker.log"
self.env = {**isolated_env(), "HOME": str(self.home), "PATH": f"{fakes}{os.pathsep}{os.environ['PATH']}", "FAKE_LOG": str(self.log), "FAKE_CLAUDE": str(fakes / "claude.py"), "CLAUDE_CODE_OAUTH_TOKEN": "sk-secret-token"}
self.given = {"--image": "golang:1.27.4", "--test": TEST, "--tasks": "features", "--runs": "2", "--base": "main"}
self.config = self.home / ".claude-projects/calc/config.toml"
self.config.write_text(f'checkout = "{self.repo}"\n{CONFIG}bench-tasks = "checkout:bench-tasks"\n')
self.tasks = self.repo / "bench-tasks"
self.git("init", "--quiet", "--initial-branch", "main")
for name, text in (("calc.go", BASE_CODE), ("calc_test.go", TESTS), ("README.md", "# Calc\n")):
(self.repo / name).write_text(text)
# A link is copied as a link, never followed, and a dangling one doesn't stop the bench.
os.symlink("missing", self.repo / "dangling")
feature(self.tasks / "halve")
self.base = self.commit("Base")
self.git("checkout", "--quiet", "-b", "item-1")
(self.repo / "calc.go").write_text(HEAD_CODE)
self.head = self.commit("Head")
self.enterContext(contextlib.chdir(self.repo))
def git(self, *args: str) -> str:
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@localhost", "-c", "commit.gpgsign=false", *args], cwd=self.repo, env=self.env, check=True, capture_output=True, text=True).stdout.strip()
def commit(self, title: str) -> str:
self.git("add", "--all")
self.git("commit", "--quiet", "--message", title)
return self.git("rev-parse", "HEAD")
def bench(self, **given: str):
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")
feature(self.tasks / "unbuildable", patch=BASE_ONLY, acceptance="grep -q '// twice' calc.go\n", test="twice_test.go")
report = self.bench()
self.assertNotIsInstance(report, Failure, report)
folder = pathlib.Path(report[-1].removeprefix(main.KEPT))
self.assertEqual(report[:-1], [
f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 feature, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.",
"Passed over the feature stale: its acceptance tests pass at the base before it is built.",
"Passed over the feature unbuildable: its reference patch doesn't apply at the head.",
"",
"| Feature | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |",
"|---|---|---|---|---|---|---|---|---|---|",
"| 1: halve | base | 0/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |",
"| 1: halve | 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"], "Build the feature below in this project.\n\nAdd `Halve(a int) int`, which halves a.")
# Haiku's copy holds the code and git's own folder: not the features' folder, with its acceptance tests and reference patches.
self.assertEqual(handed["handed"], [".git", "README.md", "calc.go", "calc_test.go", "dangling"])
results = json.loads((folder / "results.json").read_text())
self.assertEqual((results["features"], len(results["runs"])), ({"1": "halve"}, 4))
self.assertEqual((results["runs"][0]["feature"], results["runs"][0]["passed"], results["runs"][0]["reads"]), (1, False, None))
self.assertNotIn("seed", results)
self.assertEqual(sorted(path.name for path in (folder / "runs").iterdir() if path.suffix == ".jsonl"), ["feature-1-base-1.jsonl", "feature-1-base-2.jsonl", "feature-1-head-1.jsonl", "feature-1-head-2.jsonl"])
self.assertEqual(self.progress.getvalue().splitlines()[1:], [
"task-bench: passed over the feature stale: its acceptance tests pass at the base before it is built.",
"task-bench: passed over the feature unbuildable: its reference patch doesn't apply at the head.",
"task-bench: run 1 of 4, feature 1 at the base: not passed.",
"task-bench: run 2 of 4, feature 1 at the head: passed.",
"task-bench: run 3 of 4, feature 1 at the base: not passed.",
"task-bench: run 4 of 4, feature 1 at the head: passed.",
])
self.assertFalse((folder / "trees/base/bench-tasks").exists() or (folder / "trees/head/bench-tasks").exists())
def test_writes_a_digest_that_quotes_each_features_spec_and_traces_without_decoys(self):
folder = pathlib.Path(self.bench()[-1].removeprefix(main.KEPT))
digest = (folder / "digest.md").read_text().splitlines()
self.assertEqual(digest[2], f"Base {self.base}, head {self.head}. Each side's code without the features is in `trees/base` and `trees/head` in the bench's folder.")
self.assertEqual(digest[12:], [
"## Feature 1: halve",
"",
"The spec Haiku was told:",
"",
" Add `Halve(a int) int`, which halves a.",
"",
"2 of the 4 runs passed.",
"",
"### feature-1-base-1, the failing run that spent the most tokens, 61840 tokens",
"",
"Read calc.go",
"",
"### feature-1-head-1, the passing run with the median tokens, 61840 tokens",
"",
"Read calc.go",
])
def test_reads_the_features_from_a_folder_outside_the_checkout(self):
outside = self.home / ".claude-projects/calc/bench-tasks"
self.tasks.rename(outside)
self.config.write_text(self.config.read_text().replace("checkout:bench-tasks", "folder:bench-tasks"))
self.head = self.commit("Move the features out")
report = self.bench(**{"--base": self.head})
self.assertNotIsInstance(report, Failure, report)
self.assertIn("| 1: halve | head | 2/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |", report)
def test_benches_a_base_whose_tree_lacks_the_features_folder(self):
# A project's first bench of features: the folder came with the head.
self.git("rm", "-r", "--quiet", "--cached", "bench-tasks")
self.git("commit", "--quiet", "--message", "Base without the features")
base = self.git("rev-parse", "HEAD")
self.head = self.commit("Add the features")
report = self.bench(**{"--base": base})
self.assertNotIsInstance(report, Failure, report)
self.assertEqual([line for line in report if line.startswith("| 1: halve |")], [
"| 1: halve | base | 2/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |",
"| 1: halve | head | 2/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |",
])
def test_passes_over_a_feature_whose_reference_patch_leans_on_a_test_or_testdata_file_it_adds(self):
# A build's tests and testdata files don't count, so the reference patch's don't either.
for path in ("halve_cases_test.go", "testdata/halved"):
with self.subTest(path=path):
shutil.rmtree(self.tasks / "leaning", ignore_errors=True)
feature(self.tasks / "leaning", patch=REFERENCE + added(path), acceptance=f"grep -q 'a / 2' halve.go && test -f {path} && exit 0\necho 'Halve or its cases are missing'\nexit 1\n", test="leaning_test.go")
report = self.bench()
self.assertNotIsInstance(report, Failure, report)
self.assertIn("Passed over the feature leaning: the tests fail with its reference patch at the base.", report)
def test_fails_where_no_feature_counts_saying_why_each_does_not(self):
(self.tasks / "halve/acceptance/halve_test.go").write_text("echo 'never passes'\nexit 1\n")
feature(self.tasks / "stale", acceptance="exit 0\n", test="stale_test.go")
self.assertEqual(self.bench().reason, f"None of the 2 features in {self.tasks} counts. halve: the tests fail with its reference patch at the base. stale: its acceptance tests pass at the base before it is built.")
self.assertNotIn(["claude"], [call[-2:-1] for call in map(json.loads, self.log.read_text().splitlines())])
def test_fails_before_any_container_starts_where_the_config_or_the_folder_is_at_fault(self):
for fault, reason in (
(lambda: (self.tasks / "halve/spec.md").unlink(), f"the feature in {self.tasks / 'halve'} lacks spec.md"),
(lambda: (self.tasks / "halve/spec.md").write_text(" \n"), f"the feature in {self.tasks / 'halve'} has an empty spec.md"),
(lambda: (self.tasks / "halve/reference.patch").unlink(), f"the feature in {self.tasks / 'halve'} lacks reference.patch"),
(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 tasks to bench, as `project-config --help` describes it"),
):
with self.subTest(reason=reason):
shutil.rmtree(self.tasks, ignore_errors=True)
feature(self.tasks / "halve")
fault()
found = self.bench()
self.assertIsInstance(found, Failure)
self.assertEqual(found.reason, reason)
self.assertFalse(self.log.exists())
def test_reads_no_places_of_the_seats_since_no_bug_is_planted_at_them(self):
argv = [part for name, value in self.given.items() if name != "--runs" for part in (name, value)]
with contextlib.redirect_stderr(io.StringIO()) as told, contextlib.redirect_stdout(io.StringIO()) as report:
code = main.main(argv, self.env, read=lambda home: Failure("the history cannot be read"))
self.assertNotIn("the history cannot be read", told.getvalue())
self.assertEqual((code, report.getvalue()[:12]), (0, "task-bench: "))
def test_a_file_beside_the_features_folders_is_no_feature(self):
(self.tasks / "README.md").write_text("# Features\n")
self.assertEqual([found.name for found in features(self.tasks)], ["halve"])
class PassedOverTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.folder = pathlib.Path(folder.name)
self.trees = {"base": str(self.folder / "base"), "head": str(self.folder / "head")}
for tree in self.trees.values():
pathlib.Path(tree).mkdir()
feature(self.folder / "halve")
self.feature = Feature("halve", "Add Halve.", str(self.folder / "halve/reference.patch"), str(self.folder / "halve/acceptance"))
def test_passes_a_feature_over_where_it_breaks_the_rule_at_the_head_alone(self):
late = TimedOut("docker run still ran after 30 min")
# The test command's runs in turn: before the build and with the reference patch at the base, then the same at the head.
for runs, why in (
((Ran(1, ""), Ran(0, ""), Ran(0, ""), Ran(0, "")), "its acceptance tests pass at the head before it is built"),
((Ran(1, ""), Ran(0, ""), Ran(1, ""), Ran(1, "")), "the tests fail with its reference patch at the head"),
((Ran(1, ""), Ran(0, ""), late), "the tests run out of time at the head"),
):
with self.subTest(why=why):
containers = Containers(InTurn(*runs), "bench", "go test ./...", 512, "1000:1000")
bench = Bench("", {"base": "b", "head": "h"}, self.trees, Asked(FEATURE, 1), containers, self.folder, lambda *args, **given: "", lambda line: None)
self.assertEqual(why_passed_over(bench, self.trees, self.feature), why)
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": "sk"})
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, features, data-sources or shipped-features, not chores")
def test_features_run_5_times_at_each_side_by_default(self):
self.assertEqual(self.options("--tasks", "features")["--runs"], "5")
def test_the_options_that_choose_bugs_are_refused_with_features(self):
for option in ("--seed", "--bugs", "--prefix"):
with self.subTest(option=option):
self.assertEqual(self.options("--tasks", "features", option, "2").reason, f"{option} is for a bench of bugs, so it doesn't go with --tasks features")
self.assertNotIn("--seed", self.options("--tasks", "features"))
if __name__ == "__main__":
unittest.main()
+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[2]))
from task_bench.features.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.features.feature_tasks import features
from task_bench.features.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, data-sources or shipped-features, 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()
@@ -0,0 +1,349 @@
"""`task-bench --tasks shipped-features` from its command line down: a whole bench of the features a project's history shipped,
with docker and claude faked, and the histories it passes over."""
import contextlib
import functools
import json
import os
import pathlib
import re
import subprocess
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.features.test_feature_tasks import ACCEPTANCE, BenchOfTasksCase
from task_bench.test_task_bench import BASE_CODE, HEAD_CODE
from failure import Failure
from git_cli.git_repo import git
from task_bench import main
from task_bench.features.shipped_features import MERGED_IN, read_shipped
from branch_chunks.read import READ_AT
HEADER = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
ROWS = {
7: "| 7 | 0.1.0 | | | **Add `Halve`, which halves a whole number.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 3 |\n",
8: "| 8 | 0.1.0 | | | **Multiply in `Twice`.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 3 |\n",
9: "| 9 | 0.1.0 | | | **Say in the README what Calc is.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 3 |\n",
10: "| 10 | 0.1.0 | | | **Keep `Twice` whole, as `a \\| b` is.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 3 |\n",
11: "| 11 | 0.1.0 | | | **Add `Third`.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 3 |\n",
}
HALVE = "package calc\n\nfunc Halve(a int) int {\n\treturn a / 2\n}\n"
class ShippedFeaturesCase(BenchOfTasksCase):
"""BenchOfTasksCase's checkout, whose default branch then shipped four items, each in a chunk rebased onto it. Oldest first:
- item 8 wrote the line of Twice that the head rewrites;
- item 7 added Halve, with a binary file, a file whose name is not UTF-8, a test, and a link to that test;
- item 9 changed the README alone;
- item 10 added only a test, which passes without it.
The head branches off after them. The checkout's config writes a diff without the `a/` and `b/` that `git apply` strips."""
def setUp(self):
super().setUp()
self.given.update({"--tasks": "shipped-features", "--shipped": "5"})
# branch_chunks reads the plan and two records at these paths alone.
self.config.write_text(re.sub(r'"checkout:(plan|comprehension-history|reading-cost)\.md"', lambda found: f'"checkout:{READ_AT[found[1]]}"', self.config.read_text()))
self.git("checkout", "--quiet", "main")
self.git("config", "diff.noprefix", "true")
self.git("rm", "--quiet", "-r", "bench-tasks")
(self.repo / "calc.go").write_text(BASE_CODE.replace("a * 2", "a + a"))
self.plan(7, 8, 9, 10)
self.landed(1, "Plan four items")
(self.repo / "calc.go").write_text(BASE_CODE)
(self.repo / "twice_test.go").write_text("grep -q 'a \\* 2\\|2 \\* a' calc.go\n")
self.plan(7, 9, 10)
self.landed(2, "Multiply in Twice", "Finish item 8 in the plan")
(self.repo / "halve_test.go").write_text(ACCEPTANCE)
self.landed(3, "Test Halve")
(self.repo / "halve.go").write_text(HALVE)
(self.repo / "halve.bin").write_bytes(b"\x00\xff")
(self.repo / os.fsdecode(b"halv\xe9.txt")).write_text("A name that is not UTF-8.\n")
os.symlink("halve_test.go", self.repo / "linked_test.go")
self.plan(9, 10)
self.landed(3, "Add Halve", "Finish item 7 in the plan")
(self.repo / "README.md").write_text("# Calc\n\nIt adds.\n")
self.plan(10)
self.landed(4, "Say what Calc is")
(self.repo / "whole_test.go").write_text("exit 0\n")
self.plan()
self.landed(5, "Keep Twice whole", "Finish item 10 in the plan")
self.base = self.git("rev-parse", "HEAD")
self.git("checkout", "--quiet", "-B", "item-1")
(self.repo / "calc.go").write_text(HEAD_CODE)
self.head = self.commit("Head")
def plan(self, *ids: int) -> None:
"""Writes a plan that holds the items ids."""
(self.repo / "todo.md").write_text("# Plan\n\n" + HEADER + "".join(ROWS[id_] for id_ in ids))
def landed(self, hour: int, *titles: str, written_then: bool = False) -> None:
"""Commits what the checkout holds under the first of titles, and an empty commit under each other one, all at the commit
time a rebase at that hour would give them: branch_chunks reads the commits that share a commit time as one chunk.
With written_then the commits were written at that time too, as a fast-forward leaves them."""
times = {"GIT_COMMITTER_DATE": f"2026-11-01T0{hour}:00:00+00:00"}
self.env.update(times | {"GIT_AUTHOR_DATE": times["GIT_COMMITTER_DATE"]} if written_then else times)
self.git("add", "--all")
for title in titles:
self.git("commit", "--quiet", "--allow-empty", "--message", title)
for name in ("GIT_COMMITTER_DATE", "GIT_AUTHOR_DATE"):
self.env.pop(name, None)
def fast_forwarded_item_11(self):
"""Item 11 lands as a fast-forward leaves a branch: a plan commit, the feature and the commit that takes the item out, each
with the time it was written at, so each is a chunk of its own to branch_chunks. The head branches off after them."""
self.git("checkout", "--quiet", "main")
self.plan(11)
self.landed(6, "Plan an item", written_then=True)
(self.repo / "third.go").write_text("package calc\n")
(self.repo / "third_test.go").write_text("test -e third.go\n")
self.landed(7, "Add Third", written_then=True)
self.plan()
self.landed(8, "Finish item 11 in the plan", written_then=True)
self.git("checkout", "--quiet", "-B", "item-1")
(self.repo / "calc.go").write_text(HEAD_CODE)
self.commit("Head")
def fast_forwarded_item_11_alone(self):
"""Makes the default branch a history of its own, where item 11 is the one item shipped, and it landed by fast-forward."""
self.git("checkout", "--quiet", "--orphan", "fresh")
self.git("rm", "--quiet", "-r", "-f", ".")
self.plan(11)
(self.repo / "calc_test.go").write_text("exit 0\n")
self.landed(1, "Plan an item", written_then=True)
(self.repo / "third.go").write_text("package calc\n")
self.landed(2, "Add Third", written_then=True)
self.plan()
self.landed(3, "Finish item 11 in the plan", written_then=True)
self.git("branch", "--quiet", "--force", "main", "fresh")
class ShippedFeatureBenchTest(ShippedFeaturesCase):
def test_has_haiku_rebuild_each_shipped_feature_from_its_tagline_and_checks_it_with_the_tests_its_change_added(self):
report = self.bench()
self.assertNotIsInstance(report, Failure, report)
folder = pathlib.Path(report[-1].removeprefix(main.KEPT))
self.assertEqual(report[:-1], [
f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 shipped feature, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.",
"Passed over the shipped feature item 10: its acceptance tests pass at the base before it is built.",
"Passed over the shipped feature item 9: its change holds no test that the head holds.",
"Passed over the shipped feature item 8: its revert doesn't apply at the head.",
"",
"| Shipped feature | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |",
"|---|---|---|---|---|---|---|---|---|---|",
"| 1: item 7 | base | 0/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |",
"| 1: item 7 | 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"], "Build the feature below in this project.\n\nAdd `Halve`, which halves a whole number.")
# Haiku's copy holds the tree without Halve, its binary file and its tests; the plan and the later items' files stay as the side holds them.
self.assertEqual(handed["handed"], [".git", "README.md", "calc.go", "calc_test.go", "dangling", "todo.md", "twice_test.go", "whole_test.go"])
results = json.loads((folder / "results.json").read_text())
self.assertEqual((results["shipped-features"], len(results["runs"])), ({"1": "item 7"}, 4))
self.assertEqual(sorted(path.name for path in (folder / "runs").iterdir() if path.suffix == ".jsonl"), [f"shipped-feature-1-{side}-{run}.jsonl" for side in ("base", "head") for run in (1, 2)])
def test_stops_looking_once_as_many_features_count_as_shipped_asks_for(self):
report = self.bench(**{"--shipped": "1"})
self.assertNotIsInstance(report, Failure, report)
# Item 8 shipped before item 7, which filled the bench, so nothing is said of it.
self.assertEqual(report[1:4], [
"Passed over the shipped feature item 10: its acceptance tests pass at the base before it is built.",
"Passed over the shipped feature item 9: its change holds no test that the head holds.",
"",
])
def test_gives_haiku_a_tree_whose_one_commit_holds_it_without_the_feature(self):
report = self.bench()
tree = pathlib.Path(report[-1].removeprefix(main.KEPT)) / "shipped-features" / "1" / "head"
self.assertEqual(sorted(path.name for path in tree.iterdir()), [".git", "README.md", "calc.go", "calc_test.go", "dangling", "todo.md", "twice_test.go", "whole_test.go"])
self.assertEqual(subprocess.run(["git", "log", "--format=%s"], cwd=tree, env=self.env, check=True, capture_output=True, text=True).stdout, "Import\n")
self.assertEqual(subprocess.run(["git", "status", "--porcelain"], cwd=tree, env=self.env, check=True, capture_output=True, text=True).stdout, "")
def test_writes_a_digest_that_says_where_the_tree_without_each_feature_is(self):
report = self.bench()
digest = (pathlib.Path(report[-1].removeprefix(main.KEPT)) / "digest.md").read_text().splitlines()
self.assertEqual(digest[2], f"Base {self.base}, head {self.head}. Each side's code without shipped feature <n> is in `shipped-features/<n>/base` and `shipped-features/<n>/head` in the bench's folder.")
self.assertIn("## Shipped feature 1: item 7", digest)
def test_keeps_a_test_that_is_a_link_as_a_link(self):
report = self.bench()
acceptance = pathlib.Path(report[-1].removeprefix(main.KEPT)) / "shipped-features" / "1" / "acceptance"
self.assertEqual(sorted(path.name for path in acceptance.iterdir()), ["halve_test.go", "linked_test.go"])
self.assertEqual(os.readlink(acceptance / "linked_test.go"), "halve_test.go")
def test_benches_the_whole_checkout_from_a_folder_inside_it(self):
(self.repo / "inside").mkdir()
self.enterContext(contextlib.chdir(self.repo / "inside"))
report = self.bench()
self.assertNotIsInstance(report, Failure, report)
self.assertIn("| 1: item 7 | head | 2/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | - |", report)
def test_passes_over_a_feature_whose_tests_the_head_removed_or_made_a_folder(self):
# The checkout the process runs in still holds both tests.
self.git("checkout", "--quiet", "-b", "without-test")
self.git("rm", "--quiet", "halve_test.go", "linked_test.go")
(self.repo / "halve_test.go").mkdir()
(self.repo / "halve_test.go" / "notes").write_text("Halve's test was here.\n")
self.commit("Remove Halve's tests")
self.git("checkout", "--quiet", "item-1")
report = self.bench(**{"--head": "without-test"})
self.assertEqual(report.reason, "No shipped feature on the base's history counts; the lines above say why.")
self.assertIn("task-bench: passed over the shipped feature item 7: its change holds no test that the head holds.", self.progress.getvalue().splitlines())
def test_fails_where_no_shipped_feature_counts(self):
# The default branch as it was when item 8 had shipped and no other; the head rewrites the line item 8 wrote.
self.git("branch", "--quiet", "--force", "main", "main~6")
report = self.bench()
self.assertEqual(report.reason, "No shipped feature on the base's history counts; the lines above say why.")
self.assertIn("task-bench: passed over the shipped feature item 8: its revert doesn't apply at the head.", self.progress.getvalue().splitlines())
def test_rebuilds_a_feature_whose_branch_landed_by_fast_forward_from_the_commits_after_the_item_shipped_before_it(self):
self.fast_forwarded_item_11()
report = self.bench(**{"--shipped": "1"})
self.assertNotIsInstance(report, Failure, report)
# Nothing is passed over, and the feature has a row at each side.
self.assertEqual(report[1], "")
self.assertEqual([line[:23] for line in report if line.startswith("| 1: item 11")], ["| 1: item 11 | base | 0", "| 1: item 11 | head | 0"])
def test_passes_over_a_fast_forwarded_feature_where_no_item_shipped_before_it(self):
self.fast_forwarded_item_11_alone()
self.git("checkout", "--quiet", "-B", "item-1")
(self.repo / "calc.go").write_text(HEAD_CODE)
self.commit("Head")
report = self.bench(**{"--shipped": "1"})
self.assertEqual(report.reason, "No shipped feature on the base's history counts; the lines above say why.")
self.assertIn("task-bench: passed over the shipped feature item 11: its branch landed by fast-forward, and nothing earlier marks where its commits start.", self.progress.getvalue().splitlines())
def test_fails_before_docker_runs_where_the_history_shipped_no_item(self):
self.git("branch", "--quiet", "--force", "main", "main~8")
report = self.bench()
self.assertEqual(report.reason, "No chunk on the base's history took an item out of todo.md, so that history holds no shipped feature to rebuild.")
self.assertFalse(self.log.exists(), "docker ran")
def test_fails_before_docker_runs_where_the_plan_is_kept_outside_the_checkout(self):
self.config.write_text(self.config.read_text().replace('plan = "checkout:todo.md"', 'plan = "folder:todo.md"'))
report = self.bench()
self.assertEqual(report.reason, f"task-bench cannot tell what the project shipped: the project's config puts {self.config.parent / 'todo.md'} elsewhere than todo.md, docs/comprehension-history.md, docs/reading-cost.md in the checkout, the only paths whose commits are read so far")
self.assertFalse(self.log.exists(), "docker ran")
class ReadShippedTest(ShippedFeaturesCase):
def read(self, run=git):
return read_shipped(self.home, str(self.repo), "main", functools.partial(run, env=self.env))
def test_reads_the_features_newest_first_with_the_paths_a_revert_leaves_alone(self):
shipped = self.read()
self.assertEqual([(feature.name, feature.told) for feature in shipped.found], [
# The table writes a | as \\|.
("item 10", "Keep `Twice` whole, as `a | b` is."),
("item 9", "Say in the README what Calc is."),
("item 7", "Add `Halve`, which halves a whole number."),
("item 8", "Multiply in `Twice`."),
])
self.assertEqual(shipped.records, ["todo.md", "decisions.md", "score-anchors.md", "docs/comprehension-history.md", "docs/reading-cost.md", "changelog.md"])
def test_a_fast_forwarded_feature_starts_after_the_chunk_that_shipped_the_item_before_it(self):
self.fast_forwarded_item_11()
newest = self.read().found[0]
self.assertEqual((newest.name, newest.before, newest.tip), ("item 11", self.git("rev-parse", "main~3"), self.git("rev-parse", "main")))
def test_a_fast_forwarded_feature_with_no_item_shipped_before_it_has_no_start(self):
self.fast_forwarded_item_11_alone()
self.assertEqual([(feature.name, feature.before) for feature in self.read().found], [("item 11", None)])
def fast_forwarded_item_11_around_a_merge(self, title):
"""Item 11's commits, fast-forwarded, with a merge of a commit from a side branch between them under title. Returns the merge's hash."""
self.git("checkout", "--quiet", "main")
self.git("branch", "--quiet", "side")
self.git("checkout", "--quiet", "side")
(self.repo / "other.go").write_text("package calc\n")
self.landed(5, "Other work")
self.git("checkout", "--quiet", "main")
self.plan(11)
self.landed(6, "Plan an item", written_then=True)
(self.repo / "third.go").write_text("package calc\n")
self.landed(7, "Add Third", written_then=True)
self.git("merge", "--quiet", "--no-ff", "--message", title, "side")
self.plan()
self.landed(9, "Finish item 11 in the plan", written_then=True)
return self.git("rev-parse", "main~1")
def test_passes_over_a_fast_forwarded_feature_whose_branch_merged_the_default_branch_into_itself(self):
self.fast_forwarded_item_11_around_a_merge("Merge remote-tracking branch 'origin/main' into item-11")
newest = self.read().found[0]
self.assertEqual((newest.name, newest.before, newest.passed_over), ("item 11", None, MERGED_IN))
def test_a_fast_forwarded_feature_starts_after_a_chunk_that_landed_by_a_merge_and_shipped_no_item(self):
merge = self.fast_forwarded_item_11_around_a_merge("Merge pull request 'Release review' (#7) from release-review into main")
self.assertEqual(self.read().found[0].before, merge)
def test_a_chunk_that_shipped_two_items_is_one_feature_told_by_both_taglines(self):
self.git("checkout", "--quiet", "main")
self.plan(7, 8)
self.landed(5, "Plan two items again")
self.plan()
self.landed(6, "Build both", "Finish item 7 in the plan", "Finish item 8 in the plan")
newest = self.read().found[0]
self.assertEqual((newest.name, newest.told), ("items 7, 8", "Add `Halve`, which halves a whole number.\n\nMultiply in `Twice`."))
self.assertEqual((newest.before, newest.tip), (self.git("rev-parse", "main~3"), self.git("rev-parse", "main")))
def test_a_feature_that_landed_by_a_rebase_starts_at_its_own_chunk_whatever_was_fast_forwarded_before_it(self):
self.git("checkout", "--quiet", "main")
self.plan(11)
self.landed(6, "Plan an item", written_then=True)
self.plan()
self.landed(7, "Build it", "Finish item 11 in the plan")
self.assertEqual(self.read().found[0].before, self.git("rev-parse", "main~2"))
def test_an_item_a_commit_title_drops_is_not_shipped(self):
self.git("checkout", "--quiet", "main")
self.plan(8)
self.landed(5, "Plan an item again")
self.plan()
self.landed(6, "Drop item 8: nobody asked for it")
self.assertEqual(self.read().found[0].name, "item 10")
def test_reads_the_checkout_it_is_given_wherever_the_process_runs(self):
self.enterContext(contextlib.chdir(self.root))
self.assertEqual(len(self.read().found), 4)
def test_refuses_a_plan_outside_the_checkout_wherever_the_process_runs(self):
self.config.write_text(self.config.read_text().replace('plan = "checkout:todo.md"', 'plan = "folder:todo.md"'))
self.enterContext(contextlib.chdir(self.root))
self.assertTrue(self.read().reason.startswith("task-bench cannot tell what the project shipped: "))
def test_fails_where_git_cannot_read_a_plan(self):
def run(*args, **named):
return Failure("git broke") if "show" in args[:1] or "cat-file" in args[:1] else git(*args, **named)
self.assertEqual(self.read(run).reason, "git broke")
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": "sk-secret-token"})
def test_shipped_says_how_many_shipped_features_to_take_and_is_5_by_default(self):
self.assertEqual(self.options("--tasks", "shipped-features")["--shipped"], "5")
self.assertEqual(self.options("--tasks", "shipped-features", "--shipped", "2")["--shipped"], "2")
self.assertEqual(self.options("--tasks", "shipped-features", "--shipped", "0").reason, "--shipped takes a whole number from 1, not 0")
def test_shipped_goes_with_no_other_kind_of_task(self):
for tasks in ("bugs", "features", "data-sources"):
with self.subTest(tasks=tasks):
self.assertEqual(self.options("--tasks", tasks, "--shipped", "2").reason, f"--shipped is for a bench of shipped features, so it doesn't go with --tasks {tasks}")
self.assertNotIn("--shipped", self.options())
def test_a_bench_of_shipped_features_takes_no_option_of_a_bench_of_bugs(self):
self.assertEqual(self.options("--tasks", "shipped-features", "--seed", "2").reason, "--seed is for a bench of bugs, so it doesn't go with --tasks shipped-features")
if __name__ == "__main__":
unittest.main()