Skip to main content

aither_agent/
cache_stats.rs

1//! Rolling KV-cache hit-rate statistics for a running agent.
2//!
3//! Models like Claude expose `cache_read_tokens` and `cache_write_tokens`
4//! in their [`aither_core::llm::Usage`] payloads. Prompt caching is
5//! dramatically cheaper than uncached input (Anthropic pricing: ~0.30 vs
6//! 3.00 USD/MTok, a 10× difference), so a production-grade agent host
7//! should track the cumulative hit rate to catch regressions where a
8//! stable system prefix is accidentally invalidated between requests.
9//!
10//! [`CacheStats`] is a pure accumulator: hosts call
11//! [`CacheStats::record`] with each observed `Usage` (typically when
12//! handling an [`AgentEvent::Usage`](crate::AgentEvent::Usage) event)
13//! and read the current rolling metrics back via the getters. The
14//! accumulator stores raw totals so hosts can trivially diff two
15//! snapshots if they want per-turn ratios.
16
17use aither_core::llm::Usage;
18
19/// Aggregate prompt-caching statistics collected across one agent session.
20///
21/// The counters are cumulative totals, not per-turn deltas. Hosts wanting
22/// per-turn metrics should take snapshots via [`CacheStats::snapshot`]
23/// and diff two snapshots; hosts wanting a single rolling rate can read
24/// [`CacheStats::hit_rate`] directly.
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub struct CacheStats {
27    /// Number of usage payloads recorded so far.
28    requests: u64,
29    /// Cumulative prompt tokens billed (both cached and fresh).
30    prompt_tokens: u64,
31    /// Cumulative prompt tokens that were served from the KV cache.
32    cache_read_tokens: u64,
33    /// Cumulative prompt tokens newly written to the KV cache.
34    cache_write_tokens: u64,
35}
36
37impl CacheStats {
38    /// Creates an empty accumulator.
39    #[must_use]
40    pub const fn new() -> Self {
41        Self {
42            requests: 0,
43            prompt_tokens: 0,
44            cache_read_tokens: 0,
45            cache_write_tokens: 0,
46        }
47    }
48
49    /// Records a single `Usage` observation.
50    ///
51    /// Missing fields on `usage` are treated as zero so providers that
52    /// do not report cache metrics simply contribute nothing to the
53    /// cache numerator. The request counter increments on every call
54    /// regardless of field availability, so [`Self::requests`] is a
55    /// faithful count of observed usage payloads.
56    pub fn record(&mut self, usage: &Usage) {
57        self.requests = self.requests.saturating_add(1);
58        if let Some(prompt) = usage.prompt_tokens {
59            self.prompt_tokens = self.prompt_tokens.saturating_add(u64::from(prompt));
60        }
61        if let Some(read) = usage.cache_read_tokens {
62            self.cache_read_tokens = self.cache_read_tokens.saturating_add(u64::from(read));
63        }
64        if let Some(write) = usage.cache_write_tokens {
65            self.cache_write_tokens = self.cache_write_tokens.saturating_add(u64::from(write));
66        }
67    }
68
69    /// Resets all counters.
70    pub const fn reset(&mut self) {
71        *self = Self::new();
72    }
73
74    /// Returns the number of usage payloads recorded.
75    #[must_use]
76    pub const fn requests(&self) -> u64 {
77        self.requests
78    }
79
80    /// Returns cumulative prompt tokens (cached + fresh).
81    #[must_use]
82    pub const fn prompt_tokens(&self) -> u64 {
83        self.prompt_tokens
84    }
85
86    /// Returns cumulative tokens served from the KV cache.
87    #[must_use]
88    pub const fn cache_read_tokens(&self) -> u64 {
89        self.cache_read_tokens
90    }
91
92    /// Returns cumulative tokens freshly written to the KV cache.
93    #[must_use]
94    pub const fn cache_write_tokens(&self) -> u64 {
95        self.cache_write_tokens
96    }
97
98    /// Returns the rolling cache-read share of prompt tokens.
99    ///
100    /// Computed as `cache_read_tokens / prompt_tokens`. Returns `None`
101    /// when no prompt tokens have been observed yet — attempting to
102    /// answer "what's our hit rate?" before any request has run would
103    /// be misleading.
104    #[must_use]
105    pub fn hit_rate(&self) -> Option<f64> {
106        if self.prompt_tokens == 0 {
107            return None;
108        }
109        #[allow(clippy::cast_precision_loss)]
110        let rate = self.cache_read_tokens as f64 / self.prompt_tokens as f64;
111        Some(rate)
112    }
113
114    /// Returns a copy of the current counters as a plain value.
115    ///
116    /// Useful for comparing two moments in time without taking a
117    /// mutable reference to the live accumulator.
118    #[must_use]
119    pub const fn snapshot(&self) -> Self {
120        *self
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    fn usage(prompt: u32, cache_read: u32, cache_write: u32) -> Usage {
129        Usage::new(prompt, 0).with_cache_tokens(cache_read, cache_write)
130    }
131
132    #[test]
133    fn empty_stats_have_no_hit_rate() {
134        let stats = CacheStats::new();
135        assert_eq!(stats.requests(), 0);
136        assert_eq!(stats.hit_rate(), None);
137    }
138
139    #[test]
140    fn record_aggregates_prompt_and_cache_tokens() {
141        let mut stats = CacheStats::new();
142        stats.record(&usage(1_000, 800, 200));
143        stats.record(&usage(500, 450, 50));
144
145        assert_eq!(stats.requests(), 2);
146        assert_eq!(stats.prompt_tokens(), 1_500);
147        assert_eq!(stats.cache_read_tokens(), 1_250);
148        assert_eq!(stats.cache_write_tokens(), 250);
149        assert!((stats.hit_rate().unwrap() - (1_250.0 / 1_500.0)).abs() < 1e-9);
150    }
151
152    #[test]
153    fn missing_fields_do_not_poison_totals() {
154        let mut stats = CacheStats::new();
155        // Provider that reports no cache fields at all.
156        let bare = Usage {
157            prompt_tokens: Some(400),
158            ..Usage::default()
159        };
160        stats.record(&bare);
161
162        assert_eq!(stats.requests(), 1);
163        assert_eq!(stats.prompt_tokens(), 400);
164        assert_eq!(stats.cache_read_tokens(), 0);
165        assert_eq!(stats.hit_rate(), Some(0.0));
166    }
167
168    #[test]
169    fn reset_clears_all_counters() {
170        let mut stats = CacheStats::new();
171        stats.record(&usage(100, 50, 50));
172        stats.reset();
173        assert_eq!(stats, CacheStats::new());
174    }
175
176    #[test]
177    fn snapshot_is_independent_of_the_live_accumulator() {
178        let mut stats = CacheStats::new();
179        stats.record(&usage(100, 50, 50));
180        let snap = stats.snapshot();
181        stats.record(&usage(100, 100, 0));
182        assert_eq!(snap.prompt_tokens(), 100);
183        assert_eq!(snap.cache_read_tokens(), 50);
184        assert_eq!(stats.prompt_tokens(), 200);
185        assert_eq!(stats.cache_read_tokens(), 150);
186    }
187}