Bench questions a script answers from the code against the panel's hardest places
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,130 @@
|
||||
import ast
|
||||
import dataclasses
|
||||
import hashlib
|
||||
|
||||
from failure import Failure
|
||||
from metric_bench.python_units import FUNCTION, Unit
|
||||
|
||||
Key = tuple[str, str]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Code:
|
||||
"""What the questions' answers rest on: for each measured unit, the names its calls end in, and for each test file, the names its code refers to."""
|
||||
calls: list[tuple[Key, set[str]]]
|
||||
tests: dict[str, set[str]]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Question:
|
||||
unit: Key
|
||||
text: str
|
||||
truth: frozenset[str]
|
||||
|
||||
|
||||
# The rules each answer follows, given to the agent as they are applied here.
|
||||
RULES = """A unit is a module-level function, or a method of a module-level class, in a Python file git tracks outside the tests; a nested function belongs to the unit around it. A test file is a tracked `test_*.py` or `*_test.py`, or a `.py` under a `tests/` folder. A unit calls a name when its body holds a call `name(…)` or `anything.name(…)`. Write a unit as `path:name`, the path from the repository's root and the name without its class."""
|
||||
|
||||
|
||||
def calls(path: str, source: str) -> list[tuple[Key, set[str]]] | Failure:
|
||||
"""Each unit in source, with the last name of each call in its body; a method and a function may share a key."""
|
||||
try:
|
||||
tree = ast.parse(source)
|
||||
except (SyntaxError, ValueError) as failure:
|
||||
return Failure(f"{path} does not parse: {failure}")
|
||||
nodes = [node for node in tree.body if isinstance(node, FUNCTION)]
|
||||
nodes += [method for node in tree.body if isinstance(node, ast.ClassDef) for method in node.body if isinstance(method, FUNCTION)]
|
||||
return [((path, node.name), {name for call in ast.walk(node) if (name := called(call))}) for node in nodes]
|
||||
|
||||
|
||||
def called(node: ast.AST) -> str | None:
|
||||
if not isinstance(node, ast.Call):
|
||||
return None
|
||||
if isinstance(node.func, ast.Name):
|
||||
return node.func.id
|
||||
return node.func.attr if isinstance(node.func, ast.Attribute) else None
|
||||
|
||||
|
||||
def referred(path: str, source: str) -> set[str] | Failure:
|
||||
"""The names a test file's code refers to: names, attributes and imported names, not strings or comments."""
|
||||
try:
|
||||
tree = ast.parse(source)
|
||||
except (SyntaxError, ValueError) as failure:
|
||||
return Failure(f"{path} does not parse: {failure}")
|
||||
names = set()
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Name):
|
||||
names.add(node.id)
|
||||
elif isinstance(node, ast.Attribute):
|
||||
names.add(node.attr)
|
||||
elif isinstance(node, ast.alias):
|
||||
names.add(node.name.rpartition(".")[2])
|
||||
return names
|
||||
|
||||
|
||||
def askable(code: Code) -> list[Key]:
|
||||
"""The units whose name no other unit shares, so a call by that name means that unit; dunder methods, which Python calls implicitly, are left out."""
|
||||
names = [name for (_, name), _ in code.calls]
|
||||
return sorted(key for key, _ in code.calls if names.count(key[1]) == 1 and not key[1].startswith("__"))
|
||||
|
||||
|
||||
def sampled(units: list[Key], named: set[Key], commit: str) -> list[Key]:
|
||||
"""Each askable unit the seats named, and as many others, picked by a hash of the commit so a rerun asks the same."""
|
||||
asked = [unit for unit in units if unit in named]
|
||||
others = sorted((unit for unit in units if unit not in named), key=lambda unit: digest(commit, *unit))
|
||||
return asked + others[:len(asked)]
|
||||
|
||||
|
||||
def questions(code: Code, units: list[Key], commit: str) -> list[Question]:
|
||||
"""Three questions on each unit, in an order hashed from the commit, so the named units do not come first."""
|
||||
defined = {name for (_, name), _ in code.calls}
|
||||
called_by = dict(code.calls)
|
||||
asked = []
|
||||
for unit in units:
|
||||
path, name = unit
|
||||
asked += [
|
||||
Question(unit, f"Which units call `{name}`, defined in `{path}`?", frozenset(f"{caller}:{other}" for (caller, other), names in code.calls if name in names)),
|
||||
Question(unit, f"Which unit names does `{path}:{name}` call? Answer each as the bare name.", frozenset(called_by[unit] & defined)),
|
||||
Question(unit, f"Which test files refer to `{name}` in their code, not only in a string or comment?", frozenset(test for test, names in code.tests.items() if name in names)),
|
||||
]
|
||||
return sorted(asked, key=lambda question: digest(commit, question.text))
|
||||
|
||||
|
||||
def digest(*parts: str) -> str:
|
||||
return hashlib.sha256(" ".join(parts).encode()).hexdigest()
|
||||
|
||||
|
||||
def prompt(asked: list[Question]) -> str:
|
||||
listed = "\n".join(f"{number}. {question.text}" for number, question in enumerate(asked, 1))
|
||||
return f"Answer each question about the code in this repository. {RULES} Answer each question with every item it asks for, and an empty list when there is none; answer question n in the nth entry of `answers`.\n\n{listed}"
|
||||
|
||||
|
||||
def answer_schema(count: int) -> dict:
|
||||
answer = {"type": "array", "items": {"type": "string"}}
|
||||
return {"type": "object", "properties": {"answers": {"type": "array", "items": answer, "minItems": count, "maxItems": count}}, "required": ["answers"]}
|
||||
|
||||
|
||||
def agreement(truth: frozenset[str], given: list[str], root: str) -> float:
|
||||
"""The Jaccard index of the answer and the truth, 1.0 when both are empty; a path is read from the repository's root whether given absolute or relative."""
|
||||
answer = {normal(item, root) for item in given}
|
||||
return len(answer & truth) / len(answer | truth) if answer | truth else 1.0
|
||||
|
||||
|
||||
def normal(item: str, root: str) -> str:
|
||||
item = item.strip().strip("`").strip()
|
||||
for prefix in (root.rstrip("/") + "/", "./"):
|
||||
item = item.removeprefix(prefix)
|
||||
return item
|
||||
|
||||
|
||||
def misses(asked: list[Question], given: list[list[str]], root: str) -> dict[Key, float]:
|
||||
"""For each unit asked about, how far its answers fall short: 1 less the mean agreement of its questions."""
|
||||
agreements: dict[Key, list[float]] = {}
|
||||
for question, answer in zip(asked, given):
|
||||
agreements.setdefault(question.unit, []).append(agreement(question.truth, answer, root))
|
||||
return {unit: 1 - sum(values) / len(values) for unit, values in agreements.items()}
|
||||
|
||||
|
||||
def sample_units(units: list[Unit], asked: list[Key]) -> list[Unit]:
|
||||
keys = set(asked)
|
||||
return [unit for unit in units if (unit.path, unit.name) in keys]
|
||||
Reference in New Issue
Block a user