Skip to main content

agent_metering/
summary.rs

1//! Aggregation of invocation-level usage into run-level accounting summaries.
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6
7use crate::{CostEstimate, CostOrigin, CostStatus, ModelPricing, UsageRecord, calculate_cost};
8
9/// Totals for one normalized resource dimension.
10#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
11pub struct DimensionUsageSummary {
12    pub reported: u64,
13    pub estimated: u64,
14    pub unavailable_invocations: u64,
15}
16
17/// Cost totals retain the source of every amount.
18#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
19pub struct CurrencyCostSummary {
20    pub total_micros: u64,
21    pub provider_reported_micros: u64,
22    pub calculated_micros: u64,
23    pub estimated_micros: u64,
24    pub partial_invocations: u64,
25    pub unavailable_invocations: u64,
26}
27
28/// Run-level totals across all model invocations, retries, and fallbacks.
29#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30pub struct UsageSummary {
31    pub invocation_count: u64,
32    pub succeeded_count: u64,
33    pub failed_count: u64,
34    pub timed_out_count: u64,
35    pub cancelled_count: u64,
36    pub incomplete_invocations: u64,
37    pub unpriced_invocations: u64,
38    pub dimensions: BTreeMap<String, DimensionUsageSummary>,
39    pub costs: BTreeMap<String, CurrencyCostSummary>,
40}
41
42/// Aggregates records additively. Each invocation ID is expected to be unique;
43/// retries and fallback attempts are separate records and therefore counted.
44pub fn summarize_usage(records: &[UsageRecord], pricing: &[ModelPricing]) -> UsageSummary {
45    let mut summary = UsageSummary::default();
46
47    for record in records {
48        summary.invocation_count = summary.invocation_count.saturating_add(1);
49        match record.outcome {
50            crate::InvocationOutcome::Succeeded => summary.succeeded_count += 1,
51            crate::InvocationOutcome::Failed => summary.failed_count += 1,
52            crate::InvocationOutcome::TimedOut => summary.timed_out_count += 1,
53            crate::InvocationOutcome::Cancelled => summary.cancelled_count += 1,
54        }
55
56        let mut incomplete = false;
57        for (name, value) in record.usage.iter() {
58            let total = summary.dimensions.entry(name.to_owned()).or_default();
59            match value {
60                crate::MeteredValue::Reported(value) => {
61                    total.reported = total.reported.saturating_add(value);
62                }
63                crate::MeteredValue::Estimated(value) => {
64                    total.estimated = total.estimated.saturating_add(value);
65                    incomplete = true;
66                }
67                crate::MeteredValue::Unavailable => {
68                    total.unavailable_invocations = total.unavailable_invocations.saturating_add(1);
69                    incomplete = true;
70                }
71            }
72        }
73
74        let cost = record
75            .reported_cost
76            .as_ref()
77            .map(CostEstimate::from_reported)
78            .or_else(|| {
79                pricing
80                    .iter()
81                    .find(|price| price.applies_to(record))
82                    .and_then(|price| calculate_cost(record, price).ok())
83            });
84
85        match cost {
86            Some(cost) if cost.status != CostStatus::Unavailable => {
87                let totals = summary.costs.entry(cost.currency.clone()).or_default();
88                totals.total_micros = totals.total_micros.saturating_add(cost.amount_micros);
89                match cost.origin {
90                    CostOrigin::ProviderReported => {
91                        totals.provider_reported_micros = totals
92                            .provider_reported_micros
93                            .saturating_add(cost.amount_micros)
94                    }
95                    CostOrigin::Calculated => {
96                        totals.calculated_micros =
97                            totals.calculated_micros.saturating_add(cost.amount_micros)
98                    }
99                    CostOrigin::Estimated => {
100                        totals.estimated_micros =
101                            totals.estimated_micros.saturating_add(cost.amount_micros)
102                    }
103                }
104                if cost.status == CostStatus::Partial {
105                    totals.partial_invocations = totals.partial_invocations.saturating_add(1);
106                    incomplete = true;
107                }
108            }
109            Some(cost) => {
110                let totals = summary.costs.entry(cost.currency).or_default();
111                totals.unavailable_invocations = totals.unavailable_invocations.saturating_add(1);
112                summary.unpriced_invocations = summary.unpriced_invocations.saturating_add(1);
113                incomplete = true;
114            }
115            None => {
116                summary.unpriced_invocations = summary.unpriced_invocations.saturating_add(1);
117                incomplete = true;
118            }
119        }
120
121        if incomplete {
122            summary.incomplete_invocations = summary.incomplete_invocations.saturating_add(1);
123        }
124    }
125
126    summary
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    use crate::{InvocationOutcome, MeteredValue, ReportedCost, UsageDimensions};
133    use chrono::{DateTime, Utc};
134    use std::collections::BTreeMap;
135    use uuid::Uuid;
136
137    fn record(
138        id: u128,
139        outcome: InvocationOutcome,
140        usage: UsageDimensions,
141        reported_cost: Option<ReportedCost>,
142    ) -> UsageRecord {
143        let record = UsageRecord::new(
144            Uuid::from_u128(id),
145            Uuid::from_u128(99),
146            1,
147            "assistant",
148            Some("user-1".into()),
149            "openai",
150            "gpt-test",
151            outcome,
152            usage,
153            DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
154                .unwrap()
155                .with_timezone(&Utc),
156        )
157        .unwrap();
158        reported_cost.map_or(record.clone(), |cost| record.with_reported_cost(cost))
159    }
160
161    fn pricing() -> ModelPricing {
162        ModelPricing {
163            provider: "openai".into(),
164            model: "gpt-test".into(),
165            version: "v1".into(),
166            currency: "USD".into(),
167            effective_from: DateTime::parse_from_rfc3339("2025-12-01T00:00:00Z")
168                .unwrap()
169                .with_timezone(&Utc),
170            effective_until: None,
171            rates_per_million: BTreeMap::from([
172                (UsageDimensions::INPUT_TOKENS.into(), Some(2_000_000)),
173                (UsageDimensions::OUTPUT_TOKENS.into(), Some(8_000_000)),
174                (UsageDimensions::CACHED_INPUT_TOKENS.into(), Some(500_000)),
175                (UsageDimensions::REASONING_TOKENS.into(), Some(8_000_000)),
176            ]),
177        }
178    }
179
180    #[test]
181    fn aggregates_failed_and_successful_fallback_attempts_without_dropping_either() {
182        let records = vec![
183            record(
184                1,
185                InvocationOutcome::Failed,
186                UsageDimensions::new()
187                    .with(UsageDimensions::INPUT_TOKENS, MeteredValue::Estimated(100)),
188                None,
189            ),
190            record(
191                2,
192                InvocationOutcome::Succeeded,
193                UsageDimensions::new()
194                    .with(UsageDimensions::INPUT_TOKENS, MeteredValue::Reported(1_000))
195                    .with(UsageDimensions::OUTPUT_TOKENS, MeteredValue::Reported(500))
196                    .with(
197                        UsageDimensions::CACHED_INPUT_TOKENS,
198                        MeteredValue::Reported(0),
199                    )
200                    .with(UsageDimensions::REASONING_TOKENS, MeteredValue::Reported(0)),
201                None,
202            ),
203        ];
204
205        let summary = summarize_usage(&records, &[pricing()]);
206
207        assert_eq!(summary.invocation_count, 2);
208        assert_eq!(summary.failed_count, 1);
209        assert_eq!(summary.succeeded_count, 1);
210        assert_eq!(
211            summary.dimensions[UsageDimensions::INPUT_TOKENS].reported,
212            1_000
213        );
214        assert_eq!(
215            summary.dimensions[UsageDimensions::INPUT_TOKENS].estimated,
216            100
217        );
218        assert_eq!(summary.costs["USD"].calculated_micros, 6_000);
219        assert_eq!(summary.costs["USD"].estimated_micros, 200);
220        assert_eq!(summary.costs["USD"].partial_invocations, 1);
221        assert_eq!(summary.unpriced_invocations, 0);
222        assert_eq!(summary.incomplete_invocations, 1);
223    }
224
225    #[test]
226    fn provider_reported_cost_takes_precedence_over_catalogue_calculation() {
227        let record = record(
228            3,
229            InvocationOutcome::Succeeded,
230            UsageDimensions::new(),
231            Some(ReportedCost::new(123, "USD").unwrap()),
232        );
233
234        let summary = summarize_usage(&[record], &[pricing()]);
235
236        assert_eq!(summary.costs["USD"].provider_reported_micros, 123);
237        assert_eq!(summary.costs["USD"].calculated_micros, 0);
238    }
239}