Skip to main content

trusty_code/perf/
pricing.rs

1//! Cost computation, model pricing table, and small formatting helpers.
2//!
3//! Why: The pricing table + cost math is mechanically independent of the
4//! collector's lifecycle; isolating it keeps `mod.rs` focused on recording
5//! and persisting performance records.
6//! What: `cost_usd` (public), the `pricing_for`/`per_million` rate helpers, and
7//! the `filename_stamp` / `truncate_preview` formatters used by the collector.
8//! Test: `cost_usd_*` / `filename_stamp_format` / `truncate_preview_*` in
9//! `perf::tests`.
10
11/// Compute USD cost for a single LLM call given the model name and token
12/// counts. Unknown models fall back to Sonnet-class pricing.
13///
14/// Why: (#47) We hard-code the pricing table rather than hit a live endpoint
15/// so offline/CI runs still produce comparable cost figures. Pricing is
16/// per-million-tokens as published by Anthropic and OpenRouter.
17/// What: Substring-matches the model string (e.g. "anthropic/claude-sonnet-4-5"
18/// or "claude-haiku-4") and multiplies each token bucket by its rate.
19/// Test: `cost_usd_known_model`, `cost_usd_unknown_defaults_to_sonnet`.
20pub fn cost_usd(
21    model: &str,
22    prompt_tokens: u32,
23    completion_tokens: u32,
24    cache_read: u32,
25    cache_creation: u32,
26) -> f64 {
27    // Rates in USD per token (not per million).
28    let (rate_in, rate_out, rate_cache_r, rate_cache_w) = pricing_for(model);
29    let to_usd = |tokens: u32, rate: f64| tokens as f64 * rate;
30    to_usd(prompt_tokens, rate_in)
31        + to_usd(completion_tokens, rate_out)
32        + to_usd(cache_read, rate_cache_r)
33        + to_usd(cache_creation, rate_cache_w)
34}
35
36/// Returns (input, output, cache_read, cache_creation) rates per token.
37///
38/// Why: `RunReport.cost_usd` is compared against Claude Code's own
39/// `total_cost_usd` in the #8127 bake-off, so the Claude 5 tiers need their
40/// real published rates rather than the 4.x substring fallback they used to
41/// land on (#8128). Cache rates are derived from the published input rate by
42/// Anthropic's documented multipliers — a read is 0.1x input and a 5-minute
43/// write is 1.25x input.
44/// What: An ordered table. The explicitly-labelled Claude 5 / Haiku 4.5 rows
45/// come FIRST because their slugs also contain the older rows' substrings
46/// (`claude-haiku-4.5` contains `haiku-4`), so a later row would shadow them.
47/// Everything below them is the pre-#8128 4.x table, unchanged.
48/// Test: `perf::tests::cost_usd_opus_5_matches_published_rates`,
49/// `perf::tests::cost_usd_sonnet_5_matches_published_rates`,
50/// `perf::tests::cost_usd_haiku_4_5_matches_published_rates`,
51/// `perf::tests::cost_usd_legacy_4x_rows_are_unchanged`.
52// #8128: list prices from the `claude-api` skill's "Current Models" table
53// (cached 2026-06-24); cache multipliers from its `shared/prompt-caching.md`
54// § Economics (read 0.1x input, 5-minute write 1.25x input).
55fn pricing_for(model: &str) -> (f64, f64, f64, f64) {
56    let m = model.to_ascii_lowercase();
57    // Claude Opus 5 — $5 in, $25 out, $0.50 cache read, $6.25 cache write
58    if m.contains("opus-5") {
59        return (
60            per_million(5.0),
61            per_million(25.0),
62            per_million(0.50),
63            per_million(6.25),
64        );
65    }
66    // Claude Sonnet 5 — $2 in, $10 out, $0.20 cache read, $2.50 cache write
67    if m.contains("sonnet-5") {
68        return (
69            per_million(2.0),
70            per_million(10.0),
71            per_million(0.20),
72            per_million(2.50),
73        );
74    }
75    // Claude Haiku 4.5 — $1 in, $5 out, $0.10 cache read, $1.25 cache write.
76    // Both spellings: the OpenRouter slug (`claude-haiku-4.5`) and the
77    // Anthropic/Bedrock one (`claude-haiku-4-5`).
78    if m.contains("haiku-4.5") || m.contains("haiku-4-5") {
79        return (
80            per_million(1.0),
81            per_million(5.0),
82            per_million(0.10),
83            per_million(1.25),
84        );
85    }
86    // Claude Sonnet 4.x — $3 in, $15 out, $0.30 cache read, $3.75 cache write
87    if m.contains("sonnet-4") || m.contains("claude-sonnet-4") {
88        return (
89            per_million(3.0),
90            per_million(15.0),
91            per_million(0.30),
92            per_million(3.75),
93        );
94    }
95    // Claude Haiku 3/4 — $0.80 in, $4 out, $0.08 cache read, $1 cache write
96    if m.contains("haiku-3") || m.contains("haiku-4") || m.contains("claude-haiku") {
97        return (
98            per_million(0.80),
99            per_million(4.0),
100            per_million(0.08),
101            per_million(1.0),
102        );
103    }
104    // Claude Opus 4 — $15 in, $75 out (cache rates not published here, use
105    // conservative 10% / 125% of input, matching Anthropic convention).
106    if m.contains("opus-4") || m.contains("claude-opus") {
107        return (
108            per_million(15.0),
109            per_million(75.0),
110            per_million(1.50),
111            per_million(18.75),
112        );
113    }
114    // Default: Sonnet-class rates.
115    (
116        per_million(3.0),
117        per_million(15.0),
118        per_million(0.30),
119        per_million(3.75),
120    )
121}
122
123fn per_million(usd: f64) -> f64 {
124    usd / 1_000_000.0
125}
126
127/// Build the canonical filename stamp from an ISO8601 timestamp + build #.
128///
129/// Why: Deterministic filenames let tests assert exact paths and let humans
130/// sort runs chronologically with `ls`.
131/// What: Converts `2026-04-22T17:31:30Z` + build=42 to `20260422-173130-build42`.
132/// Test: `filename_stamp_format`.
133pub(super) fn filename_stamp(iso: &str, build: u64) -> String {
134    // Strip non-digit chars to keep only YYYYMMDDHHMMSS, then reinsert the dash.
135    let digits: String = iso.chars().filter(|c| c.is_ascii_digit()).collect();
136    // Expected layout: YYYYMMDDHHMMSS (14 digits). If shorter, just pad.
137    let date = digits.get(0..8).unwrap_or("00000000");
138    let time = digits.get(8..14).unwrap_or("000000");
139    format!("{date}-{time}-build{build}")
140}
141
142pub(super) fn truncate_preview(s: &str, max_chars: usize) -> String {
143    let trimmed = s.trim();
144    if trimmed.chars().count() <= max_chars {
145        return trimmed.to_string();
146    }
147    let mut out = String::with_capacity(max_chars + 3);
148    for (i, ch) in trimmed.chars().enumerate() {
149        if i >= max_chars {
150            break;
151        }
152        out.push(ch);
153    }
154    out.push_str("...");
155    out
156}