Files
ai-agent/backend/test_project_costs.py
gabrielvidalandClaude Fable 5.2 de546b2e58 fix(costs): the project split by token type adds up to the recorded cost
_type_costs priced a usage sum at the model's base rates only, so a run
with Claude fast mode, a Haiku or OpenAI long-prompt call or a pi-reported
cost had a split that disagreed with the project's own total. The shares now
come from pricing.usage_type_costs and are rescaled to each model's recorded
cost, then to the conversation's (what the frontend's splitByType does). A
local run is one whose model the book prices at nothing, not one whose
token cost happened to be 0.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 22:31:11 +01:00

98 lines
4.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The per-project spend rollup splits a conversation's cost per token type
with the one price book (``conversations.pricing``): the shares add up to the
cost the parser recorded call by call, whatever the vendor and the tier.
``python3 -m unittest test_project_costs``"""
import unittest
from conversations import pricing
from projects.costs import TYPES, _aggregate
def _u(i=0, o=0, cr=0, cw=0) -> dict:
return pricing.norm_usage({"input_tokens": i, "output_tokens": o,
"cache_read_input_tokens": cr,
"cache_creation_input_tokens": cw})
def _conv(model: str, calls: list[dict], speed: str | None = None) -> dict:
"""A summary as the parser builds it: every call priced on its own."""
total = pricing.zero_usage()
for c in calls:
total = pricing.add_usage(total, c)
cost = sum(pricing.usage_cost(c, model, speed) for c in calls)
return {"model": model, "cost": cost, "tokens": pricing.usage_tokens(total),
"usage": total, "byModel": {model: {"usage": total, "cost": cost}}}
def _split(agg: dict) -> dict:
return {t: agg["byType"][t]["cost"] for t in TYPES}
class Split(unittest.TestCase):
def test_a_gpt_run_on_a_priority_tier(self):
# every token at 6× gpt-6.1-sol's $2 / $10 / $0.10
s = _conv("gpt-6.1-sol-ultrafast", [_u(i=100_000, o=10_000, cr=50_000)] * 2)
by = _split(_aggregate([s]))
self.assertAlmostEqual(by["input"], 200_000 * 12 / 1e6)
self.assertAlmostEqual(by["output"], 20_000 * 60 / 1e6)
self.assertAlmostEqual(by["cacheRead"], 100_000 * 0.6 / 1e6)
self.assertAlmostEqual(sum(by.values()), s["cost"])
def test_a_gpt_long_context_call_stays_in_the_total(self):
# one call past 272K (input-side 2×, output 1.5×) and a short one: the
# split can't tell which tokens were in the long call, but it adds up
# to the recorded cost instead of the list price of the sum
s = _conv("gpt-5.5", [_u(i=300_000, o=4_000), _u(i=20_000, o=4_000)])
list_price = pricing.usage_type_costs(s["usage"], "gpt-5.5")
self.assertGreater(s["cost"], sum(list_price.values()) * 1.5)
by = _split(_aggregate([s]))
self.assertAlmostEqual(sum(by.values()), s["cost"])
self.assertAlmostEqual(by["input"] / by["output"],
list_price["input"] / list_price["output"])
def test_a_gemini_run(self):
# agy's per-level slug, Gemini 4 Carbon: $4 / $20 / $0.20
s = _conv("gemini-4-carbon-high", [_u(i=50_000, o=5_000, cr=400_000)])
by = _split(_aggregate([s]))
self.assertAlmostEqual(by["input"], 0.2)
self.assertAlmostEqual(by["output"], 0.1)
self.assertAlmostEqual(by["cacheRead"], 0.08)
self.assertEqual(by["cacheWrite"], 0)
self.assertAlmostEqual(sum(by.values()), s["cost"])
def test_claude_fast_mode_and_the_haiku_long_prompt_tier(self):
fast = _conv("claude-opus-5-5", [_u(i=10_000, o=2_000, cw=1_000)], speed="fast")
long = _conv("claude-haiku-5-5", [_u(i=150_000, o=1_000), _u(i=1_000, o=1_000)])
for s in (fast, long):
self.assertAlmostEqual(sum(_split(_aggregate([s])).values()), s["cost"])
# fast bills every type 2×: exact, not just in total
self.assertAlmostEqual(_split(_aggregate([fast]))["output"], 2_000 * 20 / 1e6 * 2)
def test_each_model_of_a_mixed_run_keeps_its_own_cost(self):
a = _conv("gpt-6-luna", [_u(i=250_000)] * 4)
b = _conv("claude-opus-5-5", [_u(o=100_000)])
s = {"model": "claude-opus-5-5", "cost": a["cost"] + b["cost"], "tokens": 1_100_000,
"usage": pricing.add_usage(a["usage"], b["usage"]),
"byModel": {**a["byModel"], **b["byModel"]}}
by = _split(_aggregate([s]))
self.assertAlmostEqual(by["input"], 0.1)
self.assertAlmostEqual(by["output"], 2.0)
def test_a_summary_without_per_model_costs_still_adds_up(self):
s = _conv("gemini-4-neon", [_u(i=100_000, o=10_000)])
s["byModel"]["gemini-4-neon"].pop("cost")
self.assertAlmostEqual(sum(_split(_aggregate([s])).values()), s["cost"])
s.pop("byModel")
self.assertAlmostEqual(sum(_split(_aggregate([s])).values()), s["cost"])
def test_the_shares_are_the_books_own_arithmetic(self):
u = _u(i=1234, o=567, cr=8910, cw=1112)
for model in ("claude-fable-5-1", "gpt-5.6-terra", "gemini-3.8-flash"):
self.assertAlmostEqual(sum(pricing.usage_type_costs(u, model).values()),
pricing.usage_cost(u, model), msg=model)
if __name__ == "__main__":
unittest.main()