Skip to main content

trusty_code/llm/
usage.rs

1//! Token-usage wire types for the OpenRouter / OpenAI chat-completions API.
2//!
3//! Why: Isolating the `UsageBlock` → `TokenUsage` mapping in its own module
4//! keeps request and response types independent and makes the accounting logic
5//! easy to audit and test in isolation.
6//! What: Defines `UsageBlock` (the wire representation) and its conversion to
7//! the crate's `TokenUsage`.
8//! Test: `usage_block_maps_to_token_usage`, `default_usage_block_is_zero`,
9//! `usage_block_maps_openrouter_prompt_tokens_details`,
10//! `usage_block_prefers_authoritative_cost`.
11
12use serde::{Deserialize, Serialize};
13
14use crate::perf::TokenUsage;
15
16/// OpenRouter/OpenAI-shaped nested cache-accounting object (closes the
17/// response-side gap blocking #2156's cost validation).
18///
19/// Why: Anthropic-native responses report cache tokens as flat
20/// `cache_read_input_tokens` / `cache_creation_input_tokens` fields, but
21/// OpenRouter's own usage-accounting normalisation (verified against
22/// OpenRouter's `usage-accounting` docs) nests them instead under
23/// `prompt_tokens_details`, using the OpenAI-style names `cached_tokens` (read)
24/// and `cache_write_tokens` (write). Without parsing this shape, `UsageBlock`'s
25/// `#[serde(default)]` cache fields silently stayed zero on every OpenRouter
26/// call — cache_read/cache_creation always reported 0 and cost never reflected
27/// the cache discount, even though the request-side `cache_control` marker
28/// (#2156) was being honoured upstream.
29/// What: Carries the two cache counters OpenRouter reports; `audio_tokens` is
30/// deliberately not modelled (irrelevant to this crate's text-only usage).
31/// Test: `usage_block_maps_openrouter_prompt_tokens_details`.
32#[derive(Debug, Clone, Serialize, Deserialize, Default)]
33pub struct PromptTokensDetails {
34    /// Prompt tokens served from the cache (OpenRouter's OpenAI-style name for
35    /// what Anthropic calls `cache_read_input_tokens`).
36    #[serde(default)]
37    pub cached_tokens: u32,
38
39    /// Prompt tokens newly written into the cache this turn (OpenRouter's
40    /// OpenAI-style name for what Anthropic calls
41    /// `cache_creation_input_tokens`).
42    #[serde(default)]
43    pub cache_write_tokens: u32,
44}
45
46/// Token usage block from the API response.
47///
48/// Why: Mapping the wire `usage` object to our internal `TokenUsage` is easiest
49/// when we first deserialise into this intermediate struct.
50/// What: Carries `prompt_tokens`, `completion_tokens`, and `total_tokens` from
51/// the wire; optional Anthropic-native cache fields (flat
52/// `cache_read_input_tokens` / `cache_creation_input_tokens`, present on the
53/// direct/Bedrock path) AND the OpenRouter-shaped nested
54/// `prompt_tokens_details` object — both are accepted so either provider's
55/// wire shape populates the canonical `TokenUsage` cache fields. `cost` is
56/// OpenRouter's authoritative, already-discounted USD cost for the call (only
57/// present when OpenRouter includes detailed usage accounting).
58/// Test: `usage_block_maps_to_token_usage`,
59/// `usage_block_maps_openrouter_prompt_tokens_details`,
60/// `usage_block_prefers_authoritative_cost`.
61#[derive(Debug, Clone, Serialize, Deserialize, Default)]
62pub struct UsageBlock {
63    /// Tokens consumed by the prompt (including cached tokens).
64    #[serde(default)]
65    pub prompt_tokens: u32,
66
67    /// Tokens produced by the completion.
68    #[serde(default)]
69    pub completion_tokens: u32,
70
71    /// Sum of prompt + completion; informational only.
72    #[serde(default)]
73    pub total_tokens: u32,
74
75    /// Anthropic-native (direct/Bedrock path): prompt tokens served from the
76    /// cache (not re-computed).
77    #[serde(default)]
78    pub cache_read_input_tokens: u32,
79
80    /// Anthropic-native (direct/Bedrock path): prompt tokens written into the
81    /// cache this turn.
82    #[serde(default)]
83    pub cache_creation_input_tokens: u32,
84
85    /// OpenRouter-shaped nested cache counters (OpenAI wire style). `None`
86    /// when the provider reports the flat Anthropic-native fields instead (or
87    /// omits cache accounting entirely).
88    #[serde(default)]
89    pub prompt_tokens_details: Option<PromptTokensDetails>,
90
91    /// OpenRouter's authoritative total USD cost for this call, already
92    /// netting any cache discount. `None` for providers that don't report it
93    /// (direct/Bedrock) or when OpenRouter's detailed-usage accounting wasn't
94    /// returned.
95    #[serde(default)]
96    pub cost: Option<f64>,
97}
98
99impl UsageBlock {
100    /// Convert this wire usage block into the crate's `TokenUsage`.
101    ///
102    /// Why: `PerfCollector` speaks `TokenUsage`; this conversion centralises the
103    /// mapping so callers don't need to know the wire field names, and merges
104    /// whichever of the two wire cache shapes (Anthropic-native flat fields vs.
105    /// OpenRouter's nested `prompt_tokens_details`) the provider populated.
106    /// What: `cache_read_tokens` is `cache_read_input_tokens` when non-zero,
107    /// else `prompt_tokens_details.cached_tokens`; `cache_creation_tokens`
108    /// follows the same fallback using `cache_creation_input_tokens` /
109    /// `cache_write_tokens`. `cost_usd` on the resulting `TokenUsage` carries
110    /// `self.cost` verbatim so callers can prefer OpenRouter's authoritative,
111    /// cache-aware price over a static per-token recompute.
112    /// Test: `usage_block_maps_to_token_usage`,
113    /// `usage_block_maps_openrouter_prompt_tokens_details`,
114    /// `usage_block_prefers_authoritative_cost`.
115    pub fn into_token_usage(self) -> TokenUsage {
116        let (details_read, details_write) = self
117            .prompt_tokens_details
118            .map(|d| (d.cached_tokens, d.cache_write_tokens))
119            .unwrap_or((0, 0));
120
121        let cache_read = if self.cache_read_input_tokens != 0 {
122            self.cache_read_input_tokens
123        } else {
124            details_read
125        };
126        let cache_creation = if self.cache_creation_input_tokens != 0 {
127            self.cache_creation_input_tokens
128        } else {
129            details_write
130        };
131
132        let mut usage = TokenUsage::new(
133            self.prompt_tokens,
134            self.completion_tokens,
135            cache_read,
136            cache_creation,
137        );
138        usage.cost_usd = self.cost;
139        usage
140    }
141}
142
143// ── Tests ─────────────────────────────────────────────────────────────────────
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    /// `UsageBlock::into_token_usage` maps all four fields correctly.
150    ///
151    /// Why: Correct usage mapping is critical for cost tracking; a mis-map
152    /// would silently produce wrong cost calculations.
153    /// What: Build a `UsageBlock` with known values, convert, assert each field.
154    /// Test: this test.
155    #[test]
156    fn usage_block_maps_to_token_usage() {
157        let block = UsageBlock {
158            prompt_tokens: 100,
159            completion_tokens: 50,
160            total_tokens: 150,
161            cache_read_input_tokens: 20,
162            cache_creation_input_tokens: 10,
163            prompt_tokens_details: None,
164            cost: None,
165        };
166        let usage = block.into_token_usage();
167        assert_eq!(usage.prompt_tokens, 100);
168        assert_eq!(usage.completion_tokens, 50);
169        assert_eq!(usage.cache_read_tokens, 20);
170        assert_eq!(usage.cache_creation_tokens, 10);
171        assert_eq!(usage.cost_usd, None);
172    }
173
174    /// Default `UsageBlock` produces a zero `TokenUsage`.
175    ///
176    /// Why: When the API omits the `usage` field (rare but possible), the
177    /// default should not crash and should produce zero counts.
178    /// What: Build `UsageBlock::default()`, convert, assert all zeros.
179    /// Test: this test.
180    #[test]
181    fn default_usage_block_is_zero() {
182        let usage = UsageBlock::default().into_token_usage();
183        assert_eq!(usage.prompt_tokens, 0);
184        assert_eq!(usage.completion_tokens, 0);
185        assert_eq!(usage.cache_read_tokens, 0);
186        assert_eq!(usage.cache_creation_tokens, 0);
187        assert_eq!(usage.cost_usd, None);
188    }
189
190    /// An OpenRouter-shaped `usage` block (nested `prompt_tokens_details`,
191    /// NEITHER flat Anthropic-native cache field present) deserialises into a
192    /// non-zero `cache_read_tokens` / `cache_creation_tokens` — the exact gap
193    /// that made #2156's OpenRouter-path cache accounting always report 0.
194    ///
195    /// Why: This is the empirically observed shape from the bake-off pilot:
196    /// OpenRouter reports cache accounting under
197    /// `prompt_tokens_details: { cached_tokens, cache_write_tokens }`, not the
198    /// Anthropic-native flat fields.
199    /// What: Deserialise the OpenRouter-shaped fixture, assert cache_read /
200    /// cache_creation map from the nested object.
201    /// Test: this test.
202    #[test]
203    fn usage_block_maps_openrouter_prompt_tokens_details() {
204        let fixture = r#"{
205          "prompt_tokens": 1200,
206          "completion_tokens": 80,
207          "total_tokens": 1280,
208          "prompt_tokens_details": {"cached_tokens": 900, "cache_write_tokens": 300}
209        }"#;
210        let block: UsageBlock = serde_json::from_str(fixture).expect("deserialise");
211        let usage = block.into_token_usage();
212        assert_eq!(usage.prompt_tokens, 1200);
213        assert_eq!(usage.completion_tokens, 80);
214        assert_eq!(usage.cache_read_tokens, 900);
215        assert_eq!(usage.cache_creation_tokens, 300);
216    }
217
218    /// The Anthropic-native flat shape still deserialises and maps correctly
219    /// when both wire shapes are theoretically present (flat fields win, since
220    /// they are the shape this crate has verified against the direct/Bedrock
221    /// path).
222    ///
223    /// Why: The fix must not regress the pre-existing direct/Bedrock parsing
224    /// path while adding OpenRouter support.
225    /// What: Deserialise a fixture with only the Anthropic-native flat fields
226    /// set, assert they map through unchanged.
227    /// Test: this test.
228    #[test]
229    fn usage_block_still_maps_anthropic_native_shape() {
230        let fixture = r#"{
231          "prompt_tokens": 500,
232          "completion_tokens": 20,
233          "total_tokens": 520,
234          "cache_read_input_tokens": 400,
235          "cache_creation_input_tokens": 50
236        }"#;
237        let block: UsageBlock = serde_json::from_str(fixture).expect("deserialise");
238        let usage = block.into_token_usage();
239        assert_eq!(usage.cache_read_tokens, 400);
240        assert_eq!(usage.cache_creation_tokens, 50);
241    }
242
243    /// When OpenRouter's authoritative `usage.cost` is present, it is carried
244    /// through onto `TokenUsage::cost_usd` verbatim (issue: cost never
245    /// reflected the cache discount because tcode recomputed from static
246    /// pricing instead of reading this field).
247    ///
248    /// Why: The static per-token pricing table cannot see the cache discount;
249    /// only OpenRouter's own `cost` field nets it correctly.
250    /// What: Deserialise a fixture with `cost` set, assert `cost_usd` matches.
251    /// Test: this test.
252    #[test]
253    fn usage_block_prefers_authoritative_cost() {
254        let fixture = r#"{
255          "prompt_tokens": 1200,
256          "completion_tokens": 80,
257          "total_tokens": 1280,
258          "prompt_tokens_details": {"cached_tokens": 900, "cache_write_tokens": 0},
259          "cost": 0.001234
260        }"#;
261        let block: UsageBlock = serde_json::from_str(fixture).expect("deserialise");
262        let usage = block.into_token_usage();
263        assert_eq!(usage.cost_usd, Some(0.001234));
264    }
265}