Files
claude-config/bin/question_bench/main.py
T

192 lines
9.4 KiB
Python

"""Bench questions a script asks about a project's Python against the places its comprehension panel named as hardest.
usage: question-bench [--model <model>] [history]
history defaults to docs/comprehension-history.md in the checkout it runs in, and the bench reads
the checkout that holds the history. For each scoring run in it, at the commit the panel read, it
asks a headless claude, given only Read, Grep and Glob, three questions about each unit the panel
named and about as many units picked by a hash of the commit: which units call it, which unit names
it calls, and which test files refer to it. The answers come from the code's syntax tree, so a
script checks them. Units are as in metric-bench, and a unit whose name another unit shares is not
asked about. --model picks claude's model; claude's default answers otherwise.
Each answer scores the Jaccard index of what claude named and the truth. A unit misses by 1 less
its answers' mean score. The bench prints, for each run: the units asked about, how many the panel
named, the panel's mean overall score, claude's mean answer score, the new input tokens claude
took in (uncached and cache-written, as reading-cost counts them) and its cost in USD, then how
well the misses rank the named units above the rest, beside each metric-bench metric on the same
units: AUC (0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share of the k highest
units the panel named, k being how many it named). A last row gives the medians.
Below the table it names each run skipped because its commit is not in the checkout, each run not
asked because no unit it names can be asked about or no other unit can, each file left out because
it does not parse, and each run claude did not answer, with why.
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the history
cannot be read, or no run could be scored.
"""
import dataclasses
import json
import pathlib
import statistics
import subprocess
import sys
import tempfile
from question_bench.questions import answer_schema, askable, calls, Code, misses, prompt, Question, questions, referred, sample_units, sampled
from metric_bench.bench import auc, bench, co_changed, METRICS, Score, top_k
from metric_bench.main import cell, failed, git, noted, read_history
from failure import Failure
from metric_bench.python_units import measured, python_units, Unit
from metric_bench.places import resolved, scoring_runs, ScoringRun
USAGE = "usage: question-bench [--model <model>] [history]"
@dataclasses.dataclass(frozen=True)
class Answered:
units: int
named: int
overall: float | None
answer_score: float
tokens: int
cost: float
scores: dict[str, Score]
def main(argv: list[str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
model = None
if argv[:1] == ["--model"] and len(argv) > 1:
model, argv = argv[1], argv[2:]
if len(argv) > 1 or argv[:1] and argv[0].startswith("-"):
print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr)
return 1
read = read_history(pathlib.Path(argv[0]).resolve() if argv else None)
if isinstance(read, Failure):
return failed(read)
top, history, text = read
rows = []
notes = []
for run in scoring_runs(text):
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})")
continue
answered = answer_run(run, top, model, notes)
if isinstance(answered, Failure):
notes.append(f"Not answered: {run.heading}: {answered.reason}")
elif answered:
rows.append((run.heading, answered))
if not rows:
return failed(Failure(f"no scoring run in {history} could be scored{noted(notes)}"))
print(table(rows) + noted(notes))
return 0
def answer_run(run: ScoringRun, top: str, model: str | None, notes: list[str]) -> Answered | None | Failure:
"""The run's answers scored and benched; None, with a note, when it has nothing to ask."""
listed = git(["ls-tree", "-r", "-z", "--name-only", run.commit], top)
if isinstance(listed, Failure):
return listed
tracked = list(filter(None, listed.split("\0")))
read = read_code(run, top, tracked, notes)
if isinstance(read, Failure):
return read
units, code = read
places, _ = resolved(run.places, tracked)
named = {(place.path, place.name) for place in places if place.name}
asked_units = sampled(askable(code), named, run.commit)
if not asked_units or not set(asked_units) - named:
notes.append(f"Not asked, no unit it names can be asked about, or no other unit can: {run.heading}")
return None
asked = questions(code, asked_units, run.commit)
reply = ask(top, run.commit, asked, model)
if isinstance(reply, Failure):
return reply
given, tokens, cost, root = reply
missed = misses(asked, given, root)
log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=tformat:@@", "--name-only", run.commit], top)
if isinstance(log, Failure):
return log
static = bench(sample_units(units, asked_units), places, 0, co_changed(log))
assert static, "sampled() asks about named units and others alike"
named_misses = [missed[unit] for unit in asked_units if unit in named]
rest_misses = [missed[unit] for unit in asked_units if unit not in named]
scores = {"question misses": Score(auc(named_misses, rest_misses), top_k(named_misses, rest_misses), len(set(missed.values())) == 1), **static.scores}
answer_score = 1 - statistics.mean(missed.values())
return Answered(len(asked_units), len(named_misses), run.overall, answer_score, tokens, cost, scores)
def read_code(run: ScoringRun, top: str, tracked: list[str], notes: list[str]) -> tuple[list[Unit], Code] | Failure:
"""The run's units with their metrics, and the code its answers rest on; a file that does not parse is noted and left out."""
units: list[Unit] = []
code = Code([], {})
for path in (path for path in tracked if path.endswith(".py")):
source = git(["show", f"{run.commit}:{path}"], top)
if isinstance(source, Failure):
return source
if not measured(path):
names = referred(path, source)
if isinstance(names, Failure):
notes.append(f"Left out of {run.heading}: {names.reason}")
else:
code.tests[path] = names
continue
found, called = python_units(path, source), calls(path, source)
if isinstance(found, Failure):
notes.append(f"Left out of {run.heading}: {found.reason}")
elif not isinstance(called, Failure):
units += found
code.calls.extend(called)
return units, code
def ask(top: str, commit: str, asked: list[Question], model: str | None) -> tuple[list[list[str]], int, float, str] | Failure:
"""claude's answers in a worktree of the commit, the new input tokens it took in, its cost and the worktree's path."""
with tempfile.TemporaryDirectory() as parent:
root = str(pathlib.Path(parent, "checkout"))
added = git(["worktree", "add", "--detach", root, commit], top)
if isinstance(added, Failure):
return added
try:
return run_claude(root, asked, model)
finally:
git(["worktree", "remove", "--force", root], top)
def run_claude(root: str, asked: list[Question], model: str | None) -> tuple[list[list[str]], int, float, str] | Failure:
# --safe-mode keeps the user's CLAUDE.md, skills and plugins out of the answers; --restricted keeps the tools to the worktree.
args = ["-p", "--safe-mode", "--restricted", "--strict-mcp-config", "--tools", "Read,Grep,Glob", "--no-session-persistence", "--output-format", "json", "--json-schema", json.dumps(answer_schema(len(asked)))]
try:
ran = subprocess.run(["claude", *args, *(["--model", model] if model else [])], capture_output=True, cwd=root, encoding="utf-8", errors="replace", input=prompt(asked))
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
try:
reply = json.loads(ran.stdout)
answers = reply["structured_output"]["answers"]
usage = reply["usage"]
tokens = usage["input_tokens"] + usage["cache_creation_input_tokens"]
cost = float(reply["total_cost_usd"])
except (json.JSONDecodeError, KeyError, TypeError, ValueError):
return Failure(f"claude exited {ran.returncode} without answers: {(ran.stderr or ran.stdout).strip()[-500:]}")
if len(answers) != len(asked) or not all(isinstance(answer, list) and all(isinstance(item, str) for item in answer) for answer in answers):
return Failure(f"claude gave {len(answers)} answers to {len(asked)} questions, or an answer that is not a list of strings")
return answers, tokens, cost, root
COLUMNS = ["question misses", *METRICS]
def table(rows: list[tuple[str, Answered]]) -> str:
head = ["Scoring run", "Units", "Named", "Panel overall", "Answer score", "New input tokens", "Cost USD", *COLUMNS]
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
for heading, run in rows:
overall = "" if run.overall is None else f"{run.overall:.2f}"
lines.append("| " + " | ".join([heading, str(run.units), str(run.named), overall, f"{run.answer_score:.2f}", str(run.tokens), f"{run.cost:.2f}", *(cell(run.scores[column]) for column in COLUMNS)]) + " |")
runs = [run for _, run in rows]
medianed = [cell(Score(statistics.median(run.scores[column].auc for run in runs), statistics.median(run.scores[column].top_k for run in runs), all(run.scores[column].constant for run in runs))) for column in COLUMNS]
lines.append("| " + " | ".join(["Median", "", "", "", f"{statistics.median(run.answer_score for run in runs):.2f}", str(int(statistics.median(run.tokens for run in runs))), f"{statistics.median(run.cost for run in runs):.2f}", *medianed]) + " |")
return "\n".join(lines)