313 lines
17 KiB
Python
313 lines
17 KiB
Python
"""Dollar spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`. A chunk that cannot be read is skipped and named in the figures."""
|
|
import collections
|
|
import dataclasses
|
|
import re
|
|
import statistics
|
|
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 routing_figures.prices import listed
|
|
from model_routing.ladder import position, Rung
|
|
from round_titles import round_counts
|
|
from shell_command import simple_commands
|
|
from transcript_archive.outcomes import UNFINISHED_AT, workers
|
|
|
|
CYCLES_PER_CHECK = 20
|
|
MEASURED_AT = re.compile(r"^Measured .+, at cycle ([0-9]+) across", re.MULTILINE)
|
|
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
|
|
MEASURED_AT_LEAST = 5
|
|
DIMENSIONS = ("project", "subagent type", "rung", "tool")
|
|
# Each of DIMENSIONS to its labels' dollars.
|
|
Dollars = dict[str, collections.defaultdict[str, float]]
|
|
# The tool label of a message that follows no tool call, such as the first message after a prompt.
|
|
PROMPT = "prompt"
|
|
ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):")
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Subagent:
|
|
"""kind is the agentType and launched_by the toolUseId of the launching Agent call, as the subagent's .meta.json names them, each empty where it names none; entries are its transcript's entries."""
|
|
kind: str
|
|
launched_by: str
|
|
entries: list[dict]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Chunk:
|
|
"""outcomes holds each outcomes file archived for the chunk, one per transcript copy, each opening with its task; worker is its finished transcript's entries."""
|
|
project: str
|
|
outcomes: list[str]
|
|
worker: list[dict]
|
|
subagents: list[Subagent]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Reports:
|
|
"""How many subagents of a type reported, and the characters of their reports and of the tool results they read."""
|
|
subagents: int
|
|
report: int
|
|
searches: int
|
|
|
|
def __add__(self, other: "Reports") -> "Reports":
|
|
return Reports(self.subagents + other.subagents, self.report + other.report, self.searches + other.searches)
|
|
|
|
|
|
@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: Dollars
|
|
start: Rung | None
|
|
rounds_past_first: int
|
|
unfinished: int
|
|
delegated: collections.Counter[str]
|
|
reports: dict[str, Reports]
|
|
escalated: collections.Counter[int]
|
|
unattributed: float
|
|
lacking: int = 0
|
|
|
|
|
|
@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."""
|
|
chunks: int
|
|
dollars: Dollars
|
|
routed: dict[Rung, list[ChunkFigures]]
|
|
reports: dict[str, Reports]
|
|
escalated: collections.Counter[int]
|
|
skipped: tuple[str, ...] = ()
|
|
unattributed: float = 0.0
|
|
lacking: int = 0
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Message:
|
|
"""An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices."""
|
|
at: str
|
|
tools: list[str]
|
|
model: str
|
|
list_price: float
|
|
|
|
|
|
class Spent(typing.NamedTuple):
|
|
"""A message with the subagent type that wrote it, or `worker`, and the rung it ran on."""
|
|
kind: str
|
|
rung: str
|
|
message: Message
|
|
|
|
|
|
def measured(chunk: Chunk, home: str) -> ChunkFigures:
|
|
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)
|
|
reported = results(chunk.worker)
|
|
delegated: collections.Counter[str] = collections.Counter()
|
|
reports: dict[str, Reports] = {}
|
|
for subagent in chunk.subagents:
|
|
launched_at, arguments = launches.get(subagent.launched_by, ("", {}))
|
|
kind = subagent.kind or str(arguments.get("subagent_type") or "unknown")
|
|
rung = str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at)))
|
|
delegated[rung] += 1
|
|
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values())))
|
|
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
|
|
return ChunkFigures(
|
|
dollars=dollars,
|
|
start=start.rung if start and start.item else None,
|
|
rounds_past_first=rounds_past_first(chunk.worker, home),
|
|
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)),
|
|
)
|
|
|
|
|
|
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())
|
|
return collections.Counter(int(found[1]) for found in opened if found)
|
|
|
|
|
|
def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]:
|
|
"""The timestamp and the arguments of each Agent call, by the call's id."""
|
|
found = {}
|
|
for entry in worker:
|
|
for part in assistant_parts(entry):
|
|
call = tool_call(part)
|
|
if call and call[0] == "Agent" and isinstance(part, dict) and isinstance(call[1], dict):
|
|
found[str(part.get("id"))] = (str(entry.get("timestamp", "")), call[1])
|
|
return found
|
|
|
|
|
|
# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...}
|
|
def recorded_costs(worker: list[dict]) -> dict[str, float]:
|
|
"""The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too."""
|
|
for entry in reversed(worker):
|
|
if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict):
|
|
return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))}
|
|
return {}
|
|
|
|
|
|
def costed(spent: list[Spent], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]:
|
|
"""Each message's dollars by DIMENSIONS, and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices."""
|
|
listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float)
|
|
for _, _, message in spent:
|
|
listed_by_model[message.model] += message.list_price
|
|
scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded}
|
|
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
|
for kind, rung, message in spent:
|
|
cost = message.list_price * scale.get(message.model, 1.0)
|
|
dollars["project"][project] += cost
|
|
dollars["subagent type"][kind] += cost
|
|
dollars["rung"][rung] += cost
|
|
for tool in message.tools:
|
|
dollars["tool"][tool] += cost / len(message.tools)
|
|
return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model])
|
|
|
|
|
|
def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str:
|
|
"""The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker."""
|
|
second = timestamp[:19] + "Z"
|
|
found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted")
|
|
route = route_from(found)
|
|
return route.rung if route else found
|
|
|
|
|
|
def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung:
|
|
"""The model the subagent ran, at the effort its Agent call set, or else at the worker's."""
|
|
model = next((message["model"] for entry in entries if entry.get("type") == "assistant" and isinstance(message := entry.get("message"), dict) and isinstance(message.get("model"), str)), str(arguments.get("model") or "unknown"))
|
|
effort = arguments.get("effort") or (worker.effort if isinstance(worker, Rung) else "")
|
|
return Rung(model, str(effort))
|
|
|
|
|
|
def messages(entries: list[dict]) -> list[Message]:
|
|
"""The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in."""
|
|
# Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last.
|
|
kept: dict[str, tuple[str, dict, list[str]]] = {}
|
|
for entry in entries:
|
|
if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict):
|
|
continue
|
|
found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, []))
|
|
found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str))
|
|
counted = []
|
|
before = [PROMPT]
|
|
for at, message, called in kept.values():
|
|
model = str(message.get("model") or "")
|
|
counted.append(Message(at, before, model, listed(model, message.get("usage"))))
|
|
before = called or [PROMPT]
|
|
return counted
|
|
|
|
|
|
def results(entries: list[dict]) -> dict[str, str]:
|
|
"""Each tool result's text by the id of the call it answers."""
|
|
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(
|
|
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:
|
|
"""Whether CYCLES_PER_CHECK cycles have closed since the figures were last measured. Counting from the last measurement still measures when another loop's cycles carried the count past a multiple of CYCLES_PER_CHECK."""
|
|
return cycle >= last_measured + CYCLES_PER_CHECK
|
|
|
|
|
|
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures:
|
|
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
|
for chunk in chunks:
|
|
for dimension in DIMENSIONS:
|
|
for label, amount in chunk.dollars.get(dimension, {}).items():
|
|
dollars[dimension][label] += amount
|
|
routed: dict[Rung, list[ChunkFigures]] = {}
|
|
reports: dict[str, Reports] = {}
|
|
for chunk in chunks:
|
|
if chunk.start:
|
|
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))
|
|
|
|
|
|
def calls(figures: Figures) -> list[str]:
|
|
"""Each routing change the figures call for, worded alike whatever the numbers, so a call already raised is known again."""
|
|
compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position)
|
|
found = []
|
|
for lower, upper in zip(compared, compared[1:]):
|
|
for what, of in (("review rounds past each pass's first", lambda chunk: chunk.rounds_past_first), ("unfinished verdicts", lambda chunk: chunk.unfinished)):
|
|
if mean(figures.routed[lower], of) > mean(figures.routed[upper], of):
|
|
found.append(f"Chunks routed onto {lower} took more {what} than chunks routed onto {upper}.")
|
|
# Characters stand in for tokens: reports and searches are both text the worker would read, so their sums compare their shares of its context.
|
|
found += [f"{kind} subagents' reports took more of the worker's context than their searches would have." for kind, reports in sorted(figures.reports.items()) if reports.subagents >= MEASURED_AT_LEAST and reports.report > reports.searches]
|
|
return found
|
|
|
|
|
|
def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -> float:
|
|
return statistics.mean(map(of, chunks))
|
|
|
|
|
|
def basis(figures: Figures) -> str:
|
|
"""What the dollars 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."
|
|
return text
|
|
|
|
|
|
def render(figures: Figures, found: list[str], at: str, cycle: int, since: str) -> str:
|
|
"""The figures as markdown; MEASURED_AT reads the cycle back. since is the latest reset's stamp, empty for none."""
|
|
sections = [
|
|
"# Routing figures",
|
|
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
|
|
"## Calls for a routing change",
|
|
"".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)))
|
|
for rung, chunks in sorted(figures.routed.items(), key=lambda item: position(item[0]))
|
|
]),
|
|
"## Escalations by trigger across every chunk, routed or not",
|
|
f"{triggers(figures.escalated) or 'None'}.",
|
|
"## 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 []),
|
|
]
|
|
return "\n\n".join(sections) + "\n"
|
|
|
|
|
|
def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], collections.Counter]) -> collections.Counter:
|
|
return sum(map(of, chunks), collections.Counter())
|
|
|
|
|
|
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())
|
|
|
|
|
|
def triggers(escalated: collections.Counter[int]) -> str:
|
|
"""Escalations as `trigger 2: 3, trigger 3: 1`."""
|
|
return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items()))
|
|
|
|
|
|
def money(dollars: float) -> str:
|
|
return f"${dollars:,.2f}"
|
|
|
|
|
|
def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
|
|
if not rows:
|
|
return "None."
|
|
return "\n".join(f"| {' | '.join(row)} |" for row in [header, tuple("---" for _ in header), *rows])
|