Skip to main content

lean_ctx/core/context_kernel/
provider_normalization.rs

1//! Provider-specific usage normalization for execution receipts.
2//!
3//! Provider APIs do not agree on field names, and a response can be a stream of
4//! partial usage observations rather than one JSON object.  This module keeps
5//! the provider differences at the boundary and deliberately represents absent
6//! observations as `None`.  The receipt builder can then decide how to project
7//! those observations onto the existing wire contract.
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12/// Provider-neutral usage for one logical model invocation.
13///
14/// Token and cost fields are optional because an API may omit a field or omit
15/// usage entirely.  An absent field is not equivalent to a provider reporting
16/// zero.  `provider` is the normalized route label supplied by the caller and
17/// `model` is empty when the response did not identify a serving model.
18#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
19pub struct NormalizedUsage {
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub fresh_input_tokens: Option<u64>,
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub cached_input_tokens: Option<u64>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub output_tokens: Option<u64>,
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub reasoning_tokens: Option<u64>,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub total_model_calls: Option<u32>,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub retries: Option<u32>,
32    pub provider: String,
33    pub model: String,
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub requested_model: Option<String>,
36    /// Provider-reported charge, represented as USD micros when available.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub provider_cost_micros: Option<u64>,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub latency_ms: Option<u64>,
41}
42
43impl NormalizedUsage {
44    /// Creates a complete observation without introducing floating-point cost.
45    #[must_use]
46    pub fn complete(
47        provider: impl Into<String>,
48        model: impl Into<String>,
49        fresh_input_tokens: u64,
50        cached_input_tokens: u64,
51        output_tokens: u64,
52        reasoning_tokens: u64,
53    ) -> Self {
54        Self {
55            fresh_input_tokens: Some(fresh_input_tokens),
56            cached_input_tokens: Some(cached_input_tokens),
57            output_tokens: Some(output_tokens),
58            reasoning_tokens: Some(reasoning_tokens),
59            total_model_calls: Some(1),
60            retries: Some(0),
61            provider: provider.into(),
62            model: model.into(),
63            ..Self::default()
64        }
65    }
66
67    /// Returns whether at least one usage fact was observed.
68    #[must_use]
69    pub fn has_observation(&self) -> bool {
70        self.fresh_input_tokens.is_some()
71            || self.cached_input_tokens.is_some()
72            || self.output_tokens.is_some()
73            || self.reasoning_tokens.is_some()
74            || self.provider_cost_micros.is_some()
75    }
76
77    /// Adds independent observations while preserving unknown fields.
78    ///
79    /// If any contributing observation is missing a field, the aggregate for
80    /// that field remains unknown.  This prevents a partial provider response
81    /// from being made to look complete by aggregation.
82    pub fn merge_additive(&mut self, other: &Self) {
83        if !self.has_observation()
84            && self.provider.is_empty()
85            && self.model.is_empty()
86            && self.requested_model.is_none()
87        {
88            *self = other.clone();
89            return;
90        }
91        merge_optional_sum(&mut self.fresh_input_tokens, other.fresh_input_tokens);
92        merge_optional_sum(&mut self.cached_input_tokens, other.cached_input_tokens);
93        merge_optional_sum(&mut self.output_tokens, other.output_tokens);
94        merge_optional_sum(&mut self.reasoning_tokens, other.reasoning_tokens);
95        merge_optional_sum(&mut self.total_model_calls, other.total_model_calls);
96        merge_optional_sum(&mut self.retries, other.retries);
97        merge_optional_sum(&mut self.provider_cost_micros, other.provider_cost_micros);
98        merge_optional_sum(&mut self.latency_ms, other.latency_ms);
99
100        if self.provider.is_empty() {
101            self.provider.clone_from(&other.provider);
102        } else if !other.provider.is_empty() && self.provider != other.provider {
103            self.provider = String::from("mixed");
104        }
105        if self.model.is_empty() {
106            self.model.clone_from(&other.model);
107        } else if !other.model.is_empty() && self.model != other.model {
108            self.model = String::from("mixed");
109        }
110        if self.requested_model.is_none() {
111            self.requested_model.clone_from(&other.requested_model);
112        }
113    }
114
115    /// Applies the newest observation from a streaming response.
116    ///
117    /// Streaming usage objects are commonly cumulative.  The newest known
118    /// value therefore replaces an earlier value instead of being added to it.
119    pub fn replace_known_from(&mut self, other: &Self) {
120        replace_if_some(&mut self.fresh_input_tokens, other.fresh_input_tokens);
121        replace_if_some(&mut self.cached_input_tokens, other.cached_input_tokens);
122        replace_if_some(&mut self.output_tokens, other.output_tokens);
123        replace_if_some(&mut self.reasoning_tokens, other.reasoning_tokens);
124        replace_if_some(&mut self.total_model_calls, other.total_model_calls);
125        replace_if_some(&mut self.retries, other.retries);
126        replace_if_some(&mut self.provider_cost_micros, other.provider_cost_micros);
127        replace_if_some(&mut self.latency_ms, other.latency_ms);
128        if !other.provider.is_empty() {
129            self.provider.clone_from(&other.provider);
130        }
131        if !other.model.is_empty() {
132            self.model.clone_from(&other.model);
133        }
134        if other.requested_model.is_some() {
135            self.requested_model.clone_from(&other.requested_model);
136        }
137    }
138}
139
140fn merge_optional_sum<T>(current: &mut Option<T>, incoming: Option<T>)
141where
142    T: Copy + std::ops::Add<Output = T>,
143{
144    *current = match (*current, incoming) {
145        (Some(left), Some(right)) => Some(left + right),
146        _ => None,
147    };
148}
149
150fn replace_if_some<T: Copy>(current: &mut Option<T>, incoming: Option<T>) {
151    if incoming.is_some() {
152        *current = incoming;
153    }
154}
155
156fn provider_base(provider: &str, requested_model: Option<&str>) -> NormalizedUsage {
157    NormalizedUsage {
158        provider: canonical_provider(provider),
159        requested_model: requested_model
160            .filter(|model| !model.trim().is_empty())
161            .map(str::to_owned),
162        ..NormalizedUsage::default()
163    }
164}
165
166fn finish(mut usage: NormalizedUsage, retries: u32, observed: bool) -> NormalizedUsage {
167    if observed {
168        usage.total_model_calls = Some(1);
169        usage.retries = Some(retries);
170    }
171    usage
172}
173
174fn canonical_provider(provider: &str) -> String {
175    match provider.trim().to_ascii_lowercase().as_str() {
176        "openai" | "chatgpt" | "azure" | "azure_openai" | "openai_responses" => "openai".to_owned(),
177        "anthropic" | "claude" | "bedrock" => "anthropic".to_owned(),
178        "gemini" | "google" | "google_ai" => "gemini".to_owned(),
179        "openrouter" => "openrouter".to_owned(),
180        other => other.to_owned(),
181    }
182}
183
184fn usage_value<'a>(value: &'a Value, names: &[&str]) -> Option<&'a Value> {
185    names.iter().find_map(|name| value.get(*name))
186}
187
188fn optional_u64(value: &Value, names: &[&str]) -> Option<u64> {
189    usage_value(value, names).and_then(Value::as_u64)
190}
191
192fn optional_model(value: &Value) -> Option<String> {
193    value
194        .get("model")
195        .or_else(|| value.get("modelVersion"))
196        .and_then(Value::as_str)
197        .filter(|model| !model.is_empty())
198        .map(str::to_owned)
199}
200
201fn openai_root(value: &Value) -> &Value {
202    value.get("response").unwrap_or(value)
203}
204
205fn provider_usage(value: &Value) -> Option<&Value> {
206    value.get("usage").filter(|usage| !usage.is_null())
207}
208
209/// Normalizes an OpenAI Chat Completions, Responses, or OpenRouter object.
210#[must_use]
211pub fn normalize_openai(
212    value: &Value,
213    requested_model: Option<&str>,
214    retries: u32,
215) -> NormalizedUsage {
216    let root = openai_root(value);
217    let mut result = provider_base("openai", requested_model);
218    result.model = optional_model(root).unwrap_or_default();
219    let Some(usage) = provider_usage(root) else {
220        return result;
221    };
222
223    let input_details = usage
224        .get("input_tokens_details")
225        .or_else(|| usage.get("prompt_tokens_details"));
226    let cached = input_details
227        .and_then(|details| details.get("cached_tokens"))
228        .and_then(Value::as_u64);
229    let cache_write = input_details
230        .and_then(|details| details.get("cache_write_tokens"))
231        .and_then(Value::as_u64);
232    let total_input = optional_u64(usage, &["input_tokens", "prompt_tokens"]);
233    result.fresh_input_tokens = total_input.map(|total| {
234        total
235            .saturating_sub(cached.unwrap_or(0))
236            .saturating_sub(cache_write.unwrap_or(0))
237    });
238    result.cached_input_tokens = cached;
239    result.output_tokens = optional_u64(usage, &["output_tokens", "completion_tokens"]);
240    result.reasoning_tokens = usage
241        .get("output_tokens_details")
242        .or_else(|| usage.get("completion_tokens_details"))
243        .and_then(|details| details.get("reasoning_tokens"))
244        .and_then(Value::as_u64);
245    result.provider_cost_micros = openrouter_cost_micros(usage);
246    let observed = total_input.is_some()
247        || result.output_tokens.is_some()
248        || result.provider_cost_micros.is_some();
249    finish(result, retries, observed)
250}
251
252/// Normalizes an Anthropic message, message stream event, or non-streaming body.
253#[must_use]
254pub fn normalize_anthropic(
255    value: &Value,
256    requested_model: Option<&str>,
257    retries: u32,
258) -> NormalizedUsage {
259    let message = value.get("message").unwrap_or(value);
260    let mut result = provider_base("anthropic", requested_model);
261    result.model = optional_model(message).unwrap_or_default();
262    let usage = message
263        .get("usage")
264        .or_else(|| value.get("usage"))
265        .filter(|usage| !usage.is_null());
266    let Some(usage) = usage else {
267        return result;
268    };
269
270    result.fresh_input_tokens = usage.get("input_tokens").and_then(Value::as_u64);
271    result.cached_input_tokens = usage.get("cache_read_input_tokens").and_then(Value::as_u64);
272    // Anthropic calls this a cache creation count; it is not part of the
273    // receipt's read-cache bucket, but it is retained as an input observation.
274    if let Some(cache_write) = usage
275        .get("cache_creation_input_tokens")
276        .and_then(Value::as_u64)
277    {
278        result.fresh_input_tokens = result
279            .fresh_input_tokens
280            .map(|fresh| fresh.saturating_add(cache_write));
281    }
282    result.output_tokens = usage.get("output_tokens").and_then(Value::as_u64);
283    let observed = usage.get("input_tokens").and_then(Value::as_u64).is_some()
284        || usage
285            .get("cache_read_input_tokens")
286            .and_then(Value::as_u64)
287            .is_some()
288        || usage
289            .get("cache_creation_input_tokens")
290            .and_then(Value::as_u64)
291            .is_some()
292        || usage.get("output_tokens").and_then(Value::as_u64).is_some();
293    finish(result, retries, observed)
294}
295
296/// Normalizes a Gemini `usageMetadata` object or stream chunk.
297#[must_use]
298pub fn normalize_gemini(
299    value: &Value,
300    requested_model: Option<&str>,
301    retries: u32,
302) -> NormalizedUsage {
303    let mut result = provider_base("gemini", requested_model);
304    result.model = optional_model(value).unwrap_or_default();
305    let Some(metadata) = value.get("usageMetadata") else {
306        return result;
307    };
308    let prompt = metadata.get("promptTokenCount").and_then(Value::as_u64);
309    let cached = metadata
310        .get("cachedContentTokenCount")
311        .and_then(Value::as_u64);
312    let candidates = metadata.get("candidatesTokenCount").and_then(Value::as_u64);
313    let thoughts = metadata.get("thoughtsTokenCount").and_then(Value::as_u64);
314    result.fresh_input_tokens = prompt.map(|total| total.saturating_sub(cached.unwrap_or(0)));
315    result.cached_input_tokens = cached;
316    result.output_tokens = match (candidates, thoughts) {
317        (Some(candidates), Some(thoughts)) => Some(candidates.saturating_add(thoughts)),
318        (Some(candidates), None) => Some(candidates),
319        (None, Some(thoughts)) => Some(thoughts),
320        (None, None) => None,
321    };
322    result.reasoning_tokens = thoughts;
323    finish(
324        result,
325        retries,
326        prompt.is_some() || candidates.is_some() || thoughts.is_some(),
327    )
328}
329
330/// Normalizes a provider response while retaining the provider-specific model.
331#[must_use]
332pub fn normalize_provider(
333    provider: &str,
334    value: &Value,
335    requested_model: Option<&str>,
336    retries: u32,
337) -> NormalizedUsage {
338    match canonical_provider(provider).as_str() {
339        "openai" => normalize_openai(value, requested_model, retries),
340        "openrouter" => {
341            let mut usage = normalize_openai(value, requested_model, retries);
342            usage.provider = String::from("openrouter");
343            usage
344        }
345        "anthropic" => normalize_anthropic(value, requested_model, retries),
346        "gemini" => normalize_gemini(value, requested_model, retries),
347        _ => {
348            let mut result = provider_base(provider, requested_model);
349            result.model = optional_model(value).unwrap_or_default();
350            result
351        }
352    }
353}
354
355/// Normalizes newline-delimited streaming events.
356///
357/// Each provider's usage event is cumulative in the common streaming APIs, so
358/// the newest known field replaces the previous field. Invalid or keep-alive
359/// lines are ignored; a missing usage event remains an all-`None` result.
360#[must_use]
361pub fn normalize_stream<I, S>(
362    provider: &str,
363    chunks: I,
364    requested_model: Option<&str>,
365    retries: u32,
366) -> NormalizedUsage
367where
368    I: IntoIterator<Item = S>,
369    S: AsRef<str>,
370{
371    let mut result = provider_base(provider, requested_model);
372    for chunk in chunks {
373        let line = chunk.as_ref().trim();
374        let line = line.strip_prefix("data:").map_or(line, str::trim);
375        if line.is_empty() || line == "[DONE]" {
376            continue;
377        }
378        let Ok(value) = serde_json::from_str::<Value>(line) else {
379            continue;
380        };
381        let observation = normalize_provider(provider, &value, requested_model, retries);
382        result.replace_known_from(&observation);
383    }
384    result
385}
386
387/// Alias with an explicit name for callers that already have JSON lines.
388#[must_use]
389pub fn normalize_json_lines<I, S>(
390    provider: &str,
391    lines: I,
392    requested_model: Option<&str>,
393    retries: u32,
394) -> NormalizedUsage
395where
396    I: IntoIterator<Item = S>,
397    S: AsRef<str>,
398{
399    normalize_stream(provider, lines, requested_model, retries)
400}
401
402/// Returns a normalized response only when a usage fact was observed.
403#[must_use]
404pub fn try_normalize_provider(
405    provider: &str,
406    value: &Value,
407    requested_model: Option<&str>,
408    retries: u32,
409) -> Option<NormalizedUsage> {
410    let usage = normalize_provider(provider, value, requested_model, retries);
411    usage.has_observation().then_some(usage)
412}
413
414fn openrouter_cost_micros(usage: &Value) -> Option<u64> {
415    let cost = usage.get("cost").and_then(decimal_value_to_micros);
416    let upstream = usage
417        .get("cost_details")
418        .and_then(|details| details.get("upstream_inference_cost"))
419        .and_then(decimal_value_to_micros);
420    match (cost, upstream) {
421        (Some(cost), Some(upstream)) if upstream != cost => cost.checked_add(upstream),
422        (Some(cost), _) => Some(cost),
423        (None, Some(upstream)) => Some(upstream),
424        (None, None) => None,
425    }
426}
427
428/// Converts a JSON decimal USD value into micros without using floating point.
429///
430/// Values smaller than one micro are truncated, and negative values are
431/// rejected.  Scientific notation is accepted because `serde_json::Number`
432/// may render large or small values that way.
433#[must_use]
434pub fn decimal_value_to_micros(value: &Value) -> Option<u64> {
435    match value {
436        Value::Number(number) => decimal_to_micros(&number.to_string()),
437        Value::String(value) => decimal_to_micros(value),
438        _ => None,
439    }
440}
441
442/// Converts a decimal string in USD into integer micros.
443#[must_use]
444pub fn decimal_to_micros(input: &str) -> Option<u64> {
445    let input = input.trim();
446    if input.is_empty() || input.starts_with('-') || input.starts_with('+') {
447        return None;
448    }
449    let (mantissa, exponent) = match input.find(['e', 'E']) {
450        Some(index) => {
451            let exponent = input.get(index + 1..)?.parse::<i32>().ok()?;
452            (input.get(..index)?, exponent)
453        }
454        None => (input, 0),
455    };
456    let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
457    if whole.is_empty() && fraction.is_empty()
458        || !whole.chars().all(|ch| ch.is_ascii_digit())
459        || !fraction.chars().all(|ch| ch.is_ascii_digit())
460    {
461        return None;
462    }
463    let digits = format!("{whole}{fraction}");
464    let significant = digits.trim_start_matches('0');
465    let base = if significant.is_empty() {
466        0
467    } else {
468        significant.parse::<u64>().ok()?
469    };
470    let decimal_places = i32::try_from(fraction.len()).ok()?;
471    let shift = 6i32.checked_sub(decimal_places)?.checked_add(exponent)?;
472    if shift >= 0 {
473        base.checked_mul(pow10(u32::try_from(shift).ok()?))
474    } else {
475        Some(base / pow10(u32::try_from(-shift).ok()?))
476    }
477}
478
479fn pow10(power: u32) -> u64 {
480    (0..power).fold(1u64, |value, _| value.saturating_mul(10))
481}
482
483#[cfg(test)]
484mod tests {
485    use serde_json::json;
486
487    use super::{
488        NormalizedUsage, decimal_to_micros, normalize_anthropic, normalize_gemini,
489        normalize_openai, normalize_stream,
490    };
491
492    #[test]
493    fn openai_missing_fields_stay_unknown() {
494        let usage = normalize_openai(
495            &json!({"model": "gpt-test", "usage": {"prompt_tokens": 20}}),
496            Some("requested"),
497            0,
498        );
499        assert_eq!(usage.fresh_input_tokens, Some(20));
500        assert_eq!(usage.cached_input_tokens, None);
501        assert_eq!(usage.output_tokens, None);
502        assert_eq!(usage.requested_model.as_deref(), Some("requested"));
503    }
504
505    #[test]
506    fn provider_shapes_are_normalized() {
507        let anthropic = normalize_anthropic(
508            &json!({
509                "message": {"model": "claude-test", "usage": {
510                    "input_tokens": 100,
511                    "cache_read_input_tokens": 20,
512                    "output_tokens": 30
513                }}
514            }),
515            None,
516            1,
517        );
518        assert_eq!(anthropic.fresh_input_tokens, Some(100));
519        assert_eq!(anthropic.cached_input_tokens, Some(20));
520        assert_eq!(anthropic.output_tokens, Some(30));
521        assert_eq!(anthropic.retries, Some(1));
522
523        let gemini = normalize_gemini(
524            &json!({
525                "modelVersion": "gemini-test",
526                "usageMetadata": {
527                    "promptTokenCount": 100,
528                    "cachedContentTokenCount": 10,
529                    "candidatesTokenCount": 20,
530                    "thoughtsTokenCount": 5
531                }
532            }),
533            None,
534            0,
535        );
536        assert_eq!(gemini.fresh_input_tokens, Some(90));
537        assert_eq!(gemini.output_tokens, Some(25));
538        assert_eq!(gemini.reasoning_tokens, Some(5));
539    }
540
541    #[test]
542    fn streaming_uses_latest_cumulative_usage() {
543        let usage = normalize_stream(
544            "openai",
545            [
546                r#"data: {"model":"gpt","usage":{"prompt_tokens":10,"completion_tokens":2}}"#,
547                r#"data: {"model":"gpt","usage":{"prompt_tokens":12,"completion_tokens":4}}"#,
548                "data: [DONE]",
549            ],
550            None,
551            0,
552        );
553        assert_eq!(usage.fresh_input_tokens, Some(12));
554        assert_eq!(usage.output_tokens, Some(4));
555        assert_eq!(usage.total_model_calls, Some(1));
556    }
557
558    #[test]
559    fn decimal_costs_use_micros() {
560        assert_eq!(decimal_to_micros("1.234567"), Some(1_234_567));
561        assert_eq!(decimal_to_micros("0.0000009"), Some(0));
562        assert_eq!(decimal_to_micros("1e-3"), Some(1_000));
563        assert_eq!(decimal_to_micros("-1"), None);
564    }
565
566    #[test]
567    fn additive_merge_keeps_unknown_unknown() {
568        let mut left = NormalizedUsage::complete("openai", "gpt", 1, 2, 3, 4);
569        let right = NormalizedUsage {
570            output_tokens: None,
571            ..NormalizedUsage::complete("openai", "gpt", 1, 2, 3, 4)
572        };
573        left.merge_additive(&right);
574        assert_eq!(left.fresh_input_tokens, Some(2));
575        assert_eq!(left.output_tokens, None);
576    }
577
578    #[test]
579    fn additive_merge_copies_empty_accumulator_once() {
580        let mut accumulated = NormalizedUsage::default();
581        let observation = NormalizedUsage::complete("openai", "gpt", 1, 2, 3, 4);
582        accumulated.merge_additive(&observation);
583        assert_eq!(accumulated.fresh_input_tokens, Some(1));
584        assert_eq!(accumulated.cached_input_tokens, Some(2));
585        assert_eq!(accumulated.output_tokens, Some(3));
586        assert_eq!(accumulated.reasoning_tokens, Some(4));
587        assert_eq!(accumulated.total_model_calls, Some(1));
588    }
589}