Count each finished chunk's later fixes in score-outcomes and the routing figures

This commit is contained in:
2026-10-28 19:27:09 +01:00
parent f2149adc46
commit 1a81b55925
15 changed files with 630 additions and 101 deletions
+40 -14
View File
@@ -8,6 +8,7 @@ import typing
from claude_code.entries import assistant_parts, parts, tool_call, tool_result
from git_command import commits
from model_routing.route import ESCALATION_MARKER, route_from
from score_outcomes.later_fixes import Landed
from routing_figures.prices import listed
from model_routing.ladder import position, Rung
from round_titles import round_counts
@@ -56,7 +57,7 @@ class Reports:
@dataclasses.dataclass(frozen=True)
class ChunkFigures:
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive."""
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive; fixed_later counts the later chunks that fixed code it shipped, None where no chunk on its project's default branch matches it."""
dollars: Dollars
start: Rung | None
rounds_past_first: int
@@ -66,11 +67,12 @@ class ChunkFigures:
escalated: collections.Counter[int]
unattributed: float
lacking: int = 0
fixed_later: int | None = None
@dataclasses.dataclass(frozen=True)
class Figures:
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole."""
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole; unmatched counts the chunks whose later fixes are unknown; unread names each project whose default branch could not be read, with why."""
chunks: int
dollars: Dollars
routed: dict[Rung, list[ChunkFigures]]
@@ -79,6 +81,8 @@ class Figures:
skipped: tuple[str, ...] = ()
unattributed: float = 0.0
lacking: int = 0
unmatched: int = 0
unread: tuple[str, ...] = ()
@dataclasses.dataclass(frozen=True)
@@ -97,7 +101,8 @@ class Spent(typing.NamedTuple):
message: Message
def measured(chunk: Chunk, home: str) -> ChunkFigures:
def measured(chunk: Chunk, home: str, history: list[Landed] | None = None) -> ChunkFigures:
"""history is the chunks on the project's default branch, None where it could not be read."""
cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0])
spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)]
launches = agent_calls(chunk.worker)
@@ -113,19 +118,31 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
spent += [Spent(kind, rung, message) for message in messages(subagent.entries)]
dollars, unattributed = costed(spent, chunk.project, recorded_costs(chunk.worker))
start = route_from(cycles[0][1]) if cycles else None
titles = commit_titles(chunk.worker, home)
return ChunkFigures(
dollars=dollars,
start=start.rung if start and start.item else None,
rounds_past_first=rounds_past_first(chunk.worker, home),
rounds_past_first=sum(max(0, rounds - 1) for rounds in round_counts(titles).values()),
unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes),
delegated=delegated,
reports=reports,
escalated=escalations(launches),
unattributed=unattributed,
lacking=max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in chunk.subagents) - len(chunk.subagents)),
fixed_later=later_fixes_of(titles, history or []),
)
def later_fixes_of(titles: list[str], history: list[Landed]) -> int | None:
"""How many chunks in history fixed code that the chunks holding one of titles shipped, each counted once and none of those chunks itself; None where no chunk holds one. Only a title no other chunk holds counts, since one such as a round's with no findings recurs."""
# A worker's commits may land as several chunks, as a rebase cut by commit time does, and every one of them is its work.
holders = collections.Counter(title for landed in history for title in landed.titles)
shipped = [landed for landed in history if any(holders[title] == 1 for title in landed.titles.intersection(titles))]
if not shipped:
return None
return len({later for landed in shipped for later in landed.fixed_by} - {landed.label for landed in shipped})
def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]:
"""How many of the worker's Agent calls open with each escalation trigger's number."""
opened = (ESCALATION.match(str(arguments.get("prompt") or "")) for _, arguments in launches.values())
@@ -207,15 +224,14 @@ def results(entries: list[dict]) -> dict[str, str]:
return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))}
def rounds_past_first(worker: list[dict], home: str) -> int:
# A commit retried after a failed hook repeats its title, so each title counts once.
titles = dict.fromkeys(
def commit_titles(worker: list[dict], home: str) -> list[str]:
"""The title of each commit the worker's Bash calls made, in order, each once: a commit retried after a failed hook repeats its title."""
return list(dict.fromkeys(
commit.messages[0].split("\n", 1)[0]
for entry in worker for part in assistant_parts(entry)
if (found := tool_call(part)) and found[0] == "Bash" and isinstance(found[1], dict)
for commit in commits(simple_commands(str(found[1].get("command", "")), str(entry.get("cwd") or "/"), home), home) if commit.messages
)
return sum(max(0, rounds - 1) for rounds in round_counts(list(titles)).values())
))
def due(cycle: int, last_measured: int) -> bool:
@@ -223,7 +239,7 @@ def due(cycle: int, last_measured: int) -> bool:
return cycle >= last_measured + CYCLES_PER_CHECK
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures:
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tuple[str, ...] = ()) -> Figures:
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
for chunk in chunks:
for dimension in DIMENSIONS:
@@ -236,7 +252,7 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures
routed.setdefault(chunk.start, []).append(chunk)
for kind, found in chunk.reports.items():
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found
return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks))
return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks), sum(chunk.fixed_later is None for chunk in chunks), unread)
def calls(figures: Figures) -> list[str]:
@@ -257,12 +273,15 @@ def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -
def basis(figures: Figures) -> str:
"""What the dollars are, what they leave out, and where the archive falls short of the recorded cost."""
"""What the dollars and the later fixes are, what they leave out, and where the archive falls short of the recorded cost."""
text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's runs are not archived, so their cost is not counted."
if figures.unattributed:
text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive."
if figures.lacking:
text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls."
text += " A chunk's later fixes are the chunks on its project's default branch, as last fetched, that fixed code it shipped, as `score-outcomes` counts them, so a recent chunk has had less time to gather them. What it shipped is each chunk there holding a title of the worker's commits that no other chunk there holds."
if figures.unmatched:
text += f" The later fixes of {figures.unmatched} of the chunks are unknown, since no chunk on the branch held such a title, or the branch could not be read."
return text
@@ -275,8 +294,8 @@ def render(figures: Figures, found: list[str], at: str, cycle: int, since: str)
"".join(f"- {call}\n" for call in found).rstrip("\n") or "None.",
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]))],
"## Routed chunks by the rung they started on",
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Subagent rungs", "Escalations by trigger"), [
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Later fixes, median", "Subagent rungs", "Escalations by trigger"), [
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", median_fixes(chunks), subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
for rung, chunks in sorted(figures.routed.items(), key=lambda item: position(item[0]))
]),
"## Escalations by trigger across every chunk, routed or not",
@@ -284,6 +303,7 @@ def render(figures: Figures, found: list[str], at: str, cycle: int, since: str)
"## Subagent reports against the searches they ran, in characters",
table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(found.subagents), str(found.report), str(found.searches)) for kind, found in sorted(figures.reports.items())]),
*(["## Chunks skipped, unreadable", "".join(f"- {folder}\n" for folder in figures.skipped).rstrip("\n")] if figures.skipped else []),
*(["## Project histories unread", "".join(f"- {project}\n" for project in figures.unread).rstrip("\n")] if figures.unread else []),
]
return "\n\n".join(sections) + "\n"
@@ -292,6 +312,12 @@ def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], colle
return sum(map(of, chunks), collections.Counter())
def median_fixes(chunks: list[ChunkFigures]) -> str:
"""The median later fixes of the chunks that matched one on their project's default branch, `unknown` where none did."""
known = [chunk.fixed_later for chunk in chunks if chunk.fixed_later is not None]
return f"{statistics.median(known):.1f}" if known else "unknown"
def subagent_rungs(chunks: list[ChunkFigures]) -> str:
"""The rungs the chunks' subagents ran on, most used first, as `claude-opus-5-5 at high effort 2, …`."""
return ", ".join(f"{label} {times}" for label, times in summed(chunks, lambda chunk: chunk.delegated).most_common())