143 lines
7.3 KiB
Python
143 lines
7.3 KiB
Python
"""What task-bench measures: the figures of one run, read from the stream its claude printed, and the table of a bench's runs."""
|
|
import dataclasses
|
|
import statistics
|
|
import typing
|
|
|
|
from claude_code.entries import Entry, entry_from, tool_calls, ToolCall
|
|
from failure import Failure
|
|
from task_bench.runs import HOME, WORK
|
|
from reading_cost.measure import reads_of
|
|
from claude_code.tokens import Tokens, tokens_of
|
|
|
|
# The tools that read or search without a shell. A Bash call counts where `reads_of` finds a file it reads.
|
|
READING_TOOLS = frozenset({"Glob", "Grep", "Read"})
|
|
# A bench's two sides: the commit before the change and the one after it.
|
|
Side = typing.Literal["base", "head"]
|
|
SIDES: tuple[Side, Side] = ("base", "head")
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Figures:
|
|
"""One finished run, as its stream tells it. reads counts the reads and searches before the first open of the file the bug is
|
|
in, and is None where the run never opened it, and in a run that built a feature, which has no such file."""
|
|
version: str
|
|
model: str
|
|
tokens: Tokens
|
|
turns: int
|
|
seconds: float
|
|
reads: int | None
|
|
|
|
|
|
class Result(typing.NamedTuple):
|
|
"""One run of a task at a side. figures is None where its claude ended without a result, as when it ran out of time. entries
|
|
holds the entries of its stream, which the digest quotes."""
|
|
|
|
task: int
|
|
side: Side
|
|
run: int
|
|
passed: bool
|
|
figures: Figures | None
|
|
entries: typing.Sequence[Entry] = ()
|
|
|
|
|
|
class Column(typing.NamedTuple):
|
|
"""A figure the table shows: its heading, its value in one run, None where the run has none, and whether the head's change
|
|
in it is a share of the base or a count."""
|
|
|
|
heading: str
|
|
value: typing.Callable[[Figures], float | None]
|
|
change: typing.Literal["share", "count"]
|
|
|
|
|
|
# Turns and reads are small counts, where a share misleads.
|
|
COLUMNS = (
|
|
Column("Input", lambda found: found.tokens.input, "share"),
|
|
Column("Cache write", lambda found: found.tokens.write_5m + found.tokens.write_1h, "share"),
|
|
Column("Cache read", lambda found: found.tokens.read, "share"),
|
|
Column("Output", lambda found: found.tokens.output, "share"),
|
|
Column("Turns", lambda found: found.turns, "count"),
|
|
Column("Wall, s", lambda found: found.seconds, "share"),
|
|
Column("Reads", lambda found: found.reads, "count"),
|
|
)
|
|
|
|
|
|
def figures(events: list[dict], bug_file: str | None) -> Figures | None | Failure:
|
|
"""The figures of the run whose claude printed events, the objects parsed from its stream's lines, with bug_file the bug's file as the run's
|
|
container names it, None where the run built a feature.
|
|
|
|
None where the stream holds no result. A Failure where the API refused the run, as on a token it doesn't take: such a run
|
|
doesn't measure anything, and every later run would end the same."""
|
|
result = next((event for event in reversed(events) if event.get("type") == "result"), None)
|
|
if result is None:
|
|
return None
|
|
# Claude Code retries a failed API call itself, on 429, 529 and 5xx, up to CLAUDE_CODE_MAX_RETRIES times, so its retries didn't clear this one.
|
|
if result.get("api_error_status") or result.get("terminal_reason") == "api_error":
|
|
return Failure(f"claude could not use the API: {result.get('result')}")
|
|
# {"type": "system", "subtype": "init", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330", ...}
|
|
init = next((event for event in events if event.get("subtype") == "init"), {})
|
|
calls = [call for _, call in tool_calls([entry_from(event) for event in events])]
|
|
return Figures(str(init.get("claude_code_version", "")), str(init.get("model", "")), tokens_of(result.get("usage")), int(result.get("num_turns") or 0), (result.get("duration_ms") or 0) / 1000, reads_before(calls, bug_file))
|
|
|
|
|
|
def reads_before(calls: list[ToolCall], bug_file: str | None) -> int | None:
|
|
if bug_file is None:
|
|
return None
|
|
count = 0
|
|
for call in calls:
|
|
read = reads_of(call, WORK, HOME).read
|
|
if bug_file in read:
|
|
return count
|
|
count += call.name in READING_TOOLS or bool(read)
|
|
return None
|
|
|
|
|
|
def table(results: list[Result], tasks: dict[int, str], noun: str = "bug") -> list[str]:
|
|
"""A row per task and side, under a heading that calls a task by noun, then one per side over every task, then the head's change against the base, as `change` says. Each
|
|
figure is the median over the side's runs that have figures, and Reads over those that opened the bug's file."""
|
|
sides = {(task, side): [result for result in results if (result.task, result.side) == (task, side)] for task in tasks for side in SIDES}
|
|
rows = [row(f"{task}: {tasks[task]}", side, sides[task, side]) for task in sorted(tasks) for side in SIDES]
|
|
base, head = ([result for result in results if result.side == side] for side in SIDES)
|
|
headings = [noun.capitalize(), "Side", "Passed", *(column.heading for column in COLUMNS)]
|
|
return [cells(headings), cells(["---"] * len(headings)).replace(" ", ""), *rows, row("All", "base", base), row("All", "head", head), change([(sides[task, "base"], sides[task, "head"]) for task in sorted(tasks)])]
|
|
|
|
|
|
def median(column: Column, results: list[Result]) -> float | None:
|
|
"""The column's median over the runs that have a value in it."""
|
|
values = [value for result in results if result.figures and (value := column.value(result.figures)) is not None]
|
|
return statistics.median(values) if values else None
|
|
|
|
|
|
def row(task: str, side: str, results: list[Result]) -> str:
|
|
passed = f"{sum(result.passed for result in results)}/{len(results)}"
|
|
return cells([task, side, passed, *("-" if (found := median(column, results)) is None else number(found) for column in COLUMNS)])
|
|
|
|
|
|
def change(bugs: list[tuple[list[Result], list[Result]]]) -> str:
|
|
"""The head's change against the base, from each bug's base runs and head runs. The pass count is the difference over every
|
|
run. Each other figure is the mean, over the bugs, of the bug's own change: its head median less its base median, shown
|
|
as a share of the base median for tokens and wall time, and as a count for turns and reads. This isn't the change from the All
|
|
base row to the All head row: those medians land in whichever bug's runs sit in the middle of the pooled costs."""
|
|
passed = sum(result.passed for _, head in bugs for result in head) - sum(result.passed for base, _ in bugs for result in base)
|
|
means = [mean_change([(median(column, base), median(column, head)) for base, head in bugs], share=column.change == "share") for column in COLUMNS]
|
|
return cells(["All", "change", number(passed, signed=True), *(found or "-" for found in means)])
|
|
|
|
|
|
def mean_change(pairs: list[tuple[float | None, float | None]], share: bool) -> str | None:
|
|
"""The mean of the bugs' changes in one figure, from each bug's (base median, head median). A bug counts only where both
|
|
medians exist and, for a share, the base median isn't zero; None where no bug counts."""
|
|
changes = [(now - was) * (100 / was if share else 1) for was, now in pairs if was is not None and now is not None and (was or not share)]
|
|
if not changes:
|
|
return None
|
|
mean = statistics.mean(changes)
|
|
return f"{number(round(mean), signed=True)} %" if share else number(mean, signed=True)
|
|
|
|
|
|
def number(value: float, signed: bool = False) -> str:
|
|
"""A whole number as it is, another with one decimal; signed, with a + before a rise."""
|
|
text = str(int(value)) if value == int(value) else f"{value:.1f}"
|
|
return f"+{text}" if signed and value > 0 else text
|
|
|
|
|
|
def cells(found: list[str]) -> str:
|
|
return f"| {' | '.join(found)} |"
|