Skip to main content

aither_agent/
warmth.rs

1//! Whether the provider's prompt cache is still warm, and for how long.
2//!
3//! Keep-alive, idle compaction and reassembly in the agent, and a host's
4//! choice to retry on the same provider or to spend a cache-priced sidecar
5//! call, all hinge on one question about the cache entry. [`CacheWarmth`] is
6//! its single answer: the agent stamps it on every request and keep-alive,
7//! and everyone else reads it.
8
9use std::sync::Arc;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::Duration;
12
13use crate::clock::{AnyClock, Instant};
14use crate::context::CacheLifetime;
15
16/// Marks an entry that was never started.
17const NOT_STARTED: u64 = u64::MAX;
18
19/// The state of a prompt-cache entry at one moment.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum CacheState {
22    /// Nothing is cached: no request has been sent yet, or the entry's
23    /// lifetime has passed since it was last started.
24    Cold,
25    /// The entry can still be read.
26    Warm {
27        /// How long until the entry goes cold; `None` when it never does
28        /// ([`CacheLifetime::Permanent`]).
29        cold_in: Option<Duration>,
30    },
31}
32
33#[derive(Debug)]
34struct Inner {
35    lifetime: CacheLifetime,
36    clock: AnyClock,
37    /// The latest of the last request start and the last keep-alive send, in
38    /// nanoseconds on `clock`, or [`NOT_STARTED`].
39    entry_started_nanos: AtomicU64,
40}
41
42/// A shared view of one agent's prompt-cache entry.
43///
44/// Clones observe the same entry: a handle taken from
45/// [`Agent::cache_warmth`](crate::Agent::cache_warmth) before a later request
46/// sees that request refresh the entry.
47#[derive(Debug, Clone)]
48pub struct CacheWarmth {
49    inner: Arc<Inner>,
50}
51
52impl CacheWarmth {
53    /// A handle on an entry that was never started.
54    pub(crate) fn new(lifetime: CacheLifetime, clock: AnyClock) -> Self {
55        Self {
56            inner: Arc::new(Inner {
57                lifetime,
58                clock,
59                entry_started_nanos: AtomicU64::new(NOT_STARTED),
60            }),
61        }
62    }
63
64    /// Records that a request or keep-alive started the entry at `at`.
65    pub(crate) fn start_entry(&self, at: Instant) {
66        self.inner
67            .entry_started_nanos
68            .store(at.as_nanos(), Ordering::Relaxed);
69    }
70
71    /// Records that a request or keep-alive started the entry just now.
72    pub(crate) fn start_entry_now(&self) {
73        self.start_entry(self.inner.clock.now());
74    }
75
76    /// How long ago the entry was started; `None` before the first request.
77    fn idle(&self) -> Option<Duration> {
78        match self.inner.entry_started_nanos.load(Ordering::Relaxed) {
79            NOT_STARTED => None,
80            nanos => Some(self.inner.clock.since(Instant::from_nanos(nanos))),
81        }
82    }
83
84    /// Whether the entry was started and has since expired, as opposed to
85    /// never having been started.
86    pub(crate) fn has_expired(&self) -> bool {
87        match (self.inner.lifetime, self.idle()) {
88            (CacheLifetime::Limited(lifetime), Some(idle)) => idle >= lifetime,
89            _ => false,
90        }
91    }
92
93    /// The entry's state now. [`CacheState::Cold`] before the first request.
94    #[must_use]
95    pub fn state(&self) -> CacheState {
96        let Some(idle) = self.idle() else {
97            return CacheState::Cold;
98        };
99        match self.inner.lifetime {
100            CacheLifetime::Permanent => CacheState::Warm { cold_in: None },
101            CacheLifetime::Limited(lifetime) => match lifetime.checked_sub(idle) {
102                Some(remaining) if !remaining.is_zero() => CacheState::Warm {
103                    cold_in: Some(remaining),
104                },
105                _ => CacheState::Cold,
106            },
107        }
108    }
109
110    /// Whether the entry can still be read.
111    #[must_use]
112    pub fn is_warm(&self) -> bool {
113        matches!(self.state(), CacheState::Warm { .. })
114    }
115
116    /// How long until the entry goes cold; `Some` only when it is warm and
117    /// has a limited lifetime.
118    #[must_use]
119    pub fn cold_in(&self) -> Option<Duration> {
120        match self.state() {
121            CacheState::Warm { cold_in } => cold_in,
122            CacheState::Cold => None,
123        }
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::ManualClock;
131
132    const HOUR: Duration = Duration::from_secs(3600);
133
134    fn warmth(lifetime: CacheLifetime) -> (CacheWarmth, ManualClock) {
135        let clock = ManualClock::new();
136        (
137            CacheWarmth::new(lifetime, AnyClock::new(clock.clone())),
138            clock,
139        )
140    }
141
142    #[test]
143    fn it_is_cold_before_the_first_request() {
144        let (warmth, _clock) = warmth(CacheLifetime::Limited(HOUR));
145        assert_eq!(warmth.state(), CacheState::Cold);
146        assert!(!warmth.is_warm());
147        assert_eq!(warmth.cold_in(), None);
148        assert!(!warmth.has_expired());
149
150        let (permanent, _clock) = self::warmth(CacheLifetime::Permanent);
151        assert_eq!(permanent.state(), CacheState::Cold);
152    }
153
154    #[test]
155    fn a_warm_entry_goes_cold_once_its_lifetime_passes() {
156        let (warmth, clock) = warmth(CacheLifetime::Limited(HOUR));
157        clock.advance(Duration::from_secs(10));
158        warmth.start_entry_now();
159        assert_eq!(warmth.cold_in(), Some(HOUR));
160
161        clock.advance(Duration::from_secs(600));
162        assert!(warmth.is_warm());
163        assert_eq!(
164            warmth.state(),
165            CacheState::Warm {
166                cold_in: Some(Duration::from_secs(3000))
167            }
168        );
169
170        clock.advance(Duration::from_secs(3000) - Duration::from_nanos(1));
171        assert_eq!(warmth.cold_in(), Some(Duration::from_nanos(1)));
172        assert!(!warmth.has_expired());
173
174        clock.advance(Duration::from_nanos(1));
175        assert_eq!(warmth.state(), CacheState::Cold);
176        assert_eq!(warmth.cold_in(), None);
177        assert!(warmth.has_expired());
178    }
179
180    #[test]
181    fn a_permanent_entry_never_goes_cold() {
182        let (warmth, clock) = warmth(CacheLifetime::Permanent);
183        warmth.start_entry_now();
184        clock.advance(Duration::from_secs(100 * 86_400));
185        assert_eq!(warmth.state(), CacheState::Warm { cold_in: None });
186        assert!(warmth.is_warm());
187        assert_eq!(warmth.cold_in(), None);
188        assert!(!warmth.has_expired());
189    }
190
191    #[test]
192    fn a_clone_sees_later_requests() {
193        let (warmth, clock) = warmth(CacheLifetime::Limited(HOUR));
194        let early = warmth.clone();
195        warmth.start_entry_now();
196        clock.advance(Duration::from_secs(3000));
197        assert_eq!(early.cold_in(), Some(Duration::from_secs(600)));
198
199        warmth.start_entry_now();
200        assert_eq!(early.cold_in(), Some(HOUR));
201    }
202}