Files
claude-config/bin/task_bench/test_shipped_features.py
T

241 lines
13 KiB
Python

"""`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[1]))
from task_bench.test_feature_tasks import ACCEPTANCE, BenchOfTasksCase
from task_bench.test_task_bench import BASE_CODE, HEAD_CODE
from failure import Failure
from task_bench.shipped_features import folder_name, read_shipped
from git_cli.git_repo import git
from task_bench import main
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.** | 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, its test and a link to that
test, item 9 changed the README alone, and item 10 added only a test that 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")
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) -> 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."""
self.env["GIT_COMMITTER_DATE"] = f"2026-11-01T0{hour}:00:00+00:00"
self.git("add", "--all")
for title in titles:
self.git("commit", "--quiet", "--allow-empty", "--message", title)
del self.env["GIT_COMMITTER_DATE"]
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" / "item-7" / "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_keeps_a_test_that_is_a_link_as_a_link(self):
report = self.bench()
acceptance = pathlib.Path(report[-1].removeprefix(main.KEPT)) / "shipped-features" / "item-7" / "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_test_the_head_removed(self):
# The checkout the process runs in still holds the test.
self.git("checkout", "--quiet", "-b", "without-test")
self.git("rm", "--quiet", "halve_test.go", "linked_test.go")
self.commit("Remove Halve's tests")
self.git("checkout", "--quiet", "item-1")
report = self.bench(**{"--head": "without-test"})
self.assertEqual(report.reason, "None of the 4 shipped features 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, "None of the 1 shipped features 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_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 it 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], [
("item 10", "Keep `Twice` whole."),
("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_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_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_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")
def test_names_a_features_folder_by_its_items(self):
self.assertEqual((folder_name("item 7"), folder_name("items 7, 8")), ("item-7", "items-7-8"))
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()