305 lines
17 KiB
Python
305 lines
17 KiB
Python
"""`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[1]))
|
|
|
|
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.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()
|