Skip to main content

agent_metering/
pricing.rs

1//! Versioned model pricing and deterministic integer cost calculation.
2
3use std::collections::BTreeMap;
4
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9use crate::{ReportedCost, UsageRecord};
10
11const UNITS_PER_MILLION: u128 = 1_000_000;
12
13/// Rates are currency micro-units per one million resource units.
14/// A missing rate means that the dimension is not priced, not that it is free.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16pub struct ModelPricing {
17    pub provider: String,
18    pub model: String,
19    pub version: String,
20    pub currency: String,
21    pub effective_from: DateTime<Utc>,
22    pub effective_until: Option<DateTime<Utc>>,
23    pub rates_per_million: BTreeMap<String, Option<u64>>,
24}
25
26impl ModelPricing {
27    pub fn applies_to(&self, usage: &UsageRecord) -> bool {
28        self.provider == usage.provider
29            && self.model == usage.model
30            && usage.occurred_at >= self.effective_from
31            && self
32                .effective_until
33                .is_none_or(|until| usage.occurred_at < until)
34    }
35
36    pub fn overlaps(&self, other: &Self) -> bool {
37        self.provider == other.provider
38            && self.model == other.model
39            && !self
40                .effective_until
41                .is_some_and(|until| until <= other.effective_from)
42            && !other
43                .effective_until
44                .is_some_and(|until| until <= self.effective_from)
45    }
46
47    pub fn validate(&self) -> Result<(), PricingError> {
48        if self.provider.trim().is_empty() || self.model.trim().is_empty() {
49            return Err(PricingError::EmptyModelIdentity);
50        }
51        if self.version.trim().is_empty() {
52            return Err(PricingError::EmptyVersion);
53        }
54        if self.currency.len() != 3 || !self.currency.bytes().all(|byte| byte.is_ascii_uppercase())
55        {
56            return Err(PricingError::InvalidCurrency);
57        }
58        if self
59            .effective_until
60            .is_some_and(|until| until <= self.effective_from)
61        {
62            return Err(PricingError::InvalidEffectiveRange);
63        }
64        if !self.rates_per_million.values().any(|rate| rate.is_some()) {
65            return Err(PricingError::NoRates);
66        }
67        Ok(())
68    }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(rename_all = "snake_case")]
73pub enum CostStatus {
74    Complete,
75    Partial,
76    Unavailable,
77}
78
79/// Explains where a monetary amount came from.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "snake_case")]
82pub enum CostOrigin {
83    ProviderReported,
84    Calculated,
85    Estimated,
86}
87
88/// A reproducible cost calculation in integer currency micro-units.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct CostEstimate {
91    pub amount_micros: u64,
92    pub currency: String,
93    pub pricing_version: String,
94    pub status: CostStatus,
95    pub origin: CostOrigin,
96    pub contains_estimated_usage: bool,
97}
98
99impl CostEstimate {
100    /// Converts provider-reported cost without replacing or mutating the raw record.
101    pub fn from_reported(cost: &ReportedCost) -> Self {
102        Self {
103            amount_micros: cost.amount_micros,
104            currency: cost.currency.clone(),
105            pricing_version: "provider".into(),
106            status: CostStatus::Complete,
107            origin: CostOrigin::ProviderReported,
108            contains_estimated_usage: false,
109        }
110    }
111}
112
113#[derive(Debug, Error, PartialEq, Eq)]
114pub enum PricingError {
115    #[error("pricing provider and model must not be empty")]
116    EmptyModelIdentity,
117    #[error("pricing version must not be empty")]
118    EmptyVersion,
119    #[error("currency must be a three-letter uppercase code")]
120    InvalidCurrency,
121    #[error("pricing effective_until must be later than effective_from")]
122    InvalidEffectiveRange,
123    #[error("pricing must define at least one billable rate")]
124    NoRates,
125    #[error("cost calculation overflowed the supported integer range")]
126    Overflow,
127    #[error("cached input or reasoning tokens exceed their parent token dimension")]
128    InconsistentUsage,
129    #[error("pricing does not apply to this usage record")]
130    PricingDoesNotApply,
131}
132
133/// Calculates cost using one immutable pricing version. Unknown or unpriced
134/// dimensions make the result partial; estimated quantities remain marked.
135pub fn calculate_cost(
136    usage: &UsageRecord,
137    pricing: &ModelPricing,
138) -> Result<CostEstimate, PricingError> {
139    pricing.validate()?;
140    if !pricing.applies_to(usage) {
141        return Err(PricingError::PricingDoesNotApply);
142    }
143
144    let mut amount = 0_u128;
145    let mut complete = true;
146    let mut contains_estimated_usage = false;
147    let mut priced_dimensions = 0_usize;
148
149    // Cached input is a subset of input_tokens; reasoning tokens are a
150    // subset of output_tokens. Subtract those subsets before applying the
151    // standard rates, then bill them using their dedicated rates.
152    let cached_input = usage
153        .usage
154        .get(crate::UsageDimensions::CACHED_INPUT_TOKENS)
155        .value();
156    let reasoning = usage
157        .usage
158        .get(crate::UsageDimensions::REASONING_TOKENS)
159        .value();
160
161    for (name, quantity) in usage.usage.iter() {
162        let Some(rate) = pricing.rates_per_million.get(name).copied().flatten() else {
163            complete = false;
164            continue;
165        };
166        let Some(mut value) = quantity.value() else {
167            complete = false;
168            continue;
169        };
170        if name == crate::UsageDimensions::INPUT_TOKENS {
171            if let Some(cached) = cached_input {
172                value = value
173                    .checked_sub(cached)
174                    .ok_or(PricingError::InconsistentUsage)?;
175            }
176        } else if name == crate::UsageDimensions::OUTPUT_TOKENS
177            && let Some(reasoning) = reasoning
178        {
179            value = value
180                .checked_sub(reasoning)
181                .ok_or(PricingError::InconsistentUsage)?;
182        }
183        contains_estimated_usage |= quantity.is_estimated();
184        let dimension_cost = u128::from(value)
185            .checked_mul(u128::from(rate))
186            .ok_or(PricingError::Overflow)?
187            / UNITS_PER_MILLION;
188        amount = amount
189            .checked_add(dimension_cost)
190            .ok_or(PricingError::Overflow)?;
191        priced_dimensions += 1;
192    }
193
194    let status = if priced_dimensions == 0 {
195        CostStatus::Unavailable
196    } else if complete {
197        CostStatus::Complete
198    } else {
199        CostStatus::Partial
200    };
201    Ok(CostEstimate {
202        amount_micros: u64::try_from(amount).map_err(|_| PricingError::Overflow)?,
203        currency: pricing.currency.clone(),
204        pricing_version: pricing.version.clone(),
205        status,
206        origin: if contains_estimated_usage {
207            CostOrigin::Estimated
208        } else {
209            CostOrigin::Calculated
210        },
211        contains_estimated_usage,
212    })
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use crate::{InvocationOutcome, MeteredValue, UsageDimensions};
219    use uuid::Uuid;
220
221    fn usage(dimensions: UsageDimensions) -> UsageRecord {
222        UsageRecord::new(
223            Uuid::from_u128(1),
224            Uuid::from_u128(2),
225            1,
226            "assistant",
227            Some("user-1".into()),
228            "openai",
229            "gpt-test",
230            InvocationOutcome::Succeeded,
231            dimensions,
232            DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
233                .unwrap()
234                .with_timezone(&Utc),
235        )
236        .unwrap()
237    }
238
239    fn pricing() -> ModelPricing {
240        ModelPricing {
241            provider: "openai".into(),
242            model: "gpt-test".into(),
243            version: "2026-01".into(),
244            currency: "USD".into(),
245            effective_from: DateTime::parse_from_rfc3339("2025-12-01T00:00:00Z")
246                .unwrap()
247                .with_timezone(&Utc),
248            effective_until: None,
249            rates_per_million: BTreeMap::from([
250                (UsageDimensions::INPUT_TOKENS.into(), Some(2_000_000)),
251                (UsageDimensions::OUTPUT_TOKENS.into(), Some(8_000_000)),
252                (UsageDimensions::CACHED_INPUT_TOKENS.into(), Some(500_000)),
253                (UsageDimensions::REASONING_TOKENS.into(), Some(8_000_000)),
254            ]),
255        }
256    }
257
258    #[test]
259    fn calculates_cost_with_integer_arithmetic() {
260        let record = usage(
261            UsageDimensions::new()
262                .with(UsageDimensions::INPUT_TOKENS, MeteredValue::Reported(1_000))
263                .with(UsageDimensions::OUTPUT_TOKENS, MeteredValue::Reported(500)),
264        );
265        let cost = calculate_cost(&record, &pricing()).unwrap();
266        assert_eq!(cost.amount_micros, 6_000);
267        assert_eq!(cost.status, CostStatus::Partial);
268        assert_eq!(cost.origin, CostOrigin::Calculated);
269    }
270
271    #[test]
272    fn preserves_estimated_and_unavailable_usage_semantics() {
273        let record = usage(
274            UsageDimensions::new()
275                .with(
276                    UsageDimensions::INPUT_TOKENS,
277                    MeteredValue::Estimated(1_000),
278                )
279                .with(UsageDimensions::OUTPUT_TOKENS, MeteredValue::Reported(0))
280                .with(
281                    UsageDimensions::CACHED_INPUT_TOKENS,
282                    MeteredValue::Reported(0),
283                )
284                .with(UsageDimensions::REASONING_TOKENS, MeteredValue::Reported(0)),
285        );
286        let cost = calculate_cost(&record, &pricing()).unwrap();
287        assert_eq!(cost.amount_micros, 2_000);
288        assert_eq!(cost.status, CostStatus::Complete);
289        assert_eq!(cost.origin, CostOrigin::Estimated);
290        assert!(cost.contains_estimated_usage);
291    }
292
293    #[test]
294    fn prices_cached_and_reasoning_subsets_without_double_counting() {
295        let record = usage(
296            UsageDimensions::new()
297                .with(UsageDimensions::INPUT_TOKENS, MeteredValue::Reported(1_000))
298                .with(UsageDimensions::OUTPUT_TOKENS, MeteredValue::Reported(600))
299                .with(
300                    UsageDimensions::CACHED_INPUT_TOKENS,
301                    MeteredValue::Reported(400),
302                )
303                .with(
304                    UsageDimensions::REASONING_TOKENS,
305                    MeteredValue::Reported(100),
306                ),
307        );
308        let mut price = pricing();
309        price
310            .rates_per_million
311            .insert(UsageDimensions::REASONING_TOKENS.into(), Some(10_000_000));
312
313        let cost = calculate_cost(&record, &price).unwrap();
314
315        // 600 regular input * 2 + 400 cached input * 0.5
316        // + 500 regular output * 8 + 100 reasoning * 10 = 6,400 micros.
317        assert_eq!(cost.amount_micros, 6_400);
318        assert_eq!(cost.status, CostStatus::Complete);
319    }
320
321    #[test]
322    fn refuses_to_apply_a_different_model_price() {
323        let record = usage(UsageDimensions::new());
324        let mut price = pricing();
325        price.model = "other-model".into();
326        assert_eq!(
327            calculate_cost(&record, &price),
328            Err(PricingError::PricingDoesNotApply)
329        );
330    }
331
332    #[test]
333    fn missing_dimensions_are_not_silently_treated_as_zero() {
334        let record = usage(
335            UsageDimensions::new().with(UsageDimensions::INPUT_TOKENS, MeteredValue::Reported(10)),
336        );
337        let cost = calculate_cost(&record, &pricing()).unwrap();
338        assert_eq!(cost.amount_micros, 20);
339        assert_eq!(cost.status, CostStatus::Partial);
340    }
341
342    #[test]
343    fn rejects_pricing_without_any_billable_rates() {
344        let mut price = pricing();
345        for rate in price.rates_per_million.values_mut() {
346            *rate = None;
347        }
348        assert_eq!(price.validate(), Err(PricingError::NoRates));
349    }
350
351    #[test]
352    fn provider_reported_cost_is_distinguished_from_calculated_cost() {
353        let reported = ReportedCost::new(12_345, "USD").unwrap();
354        let cost = CostEstimate::from_reported(&reported);
355        assert_eq!(cost.origin, CostOrigin::ProviderReported);
356        assert_eq!(cost.amount_micros, 12_345);
357    }
358}