Skip to main content

aither_agent/
clock.rs

1//! The time source behind the prompt cache's warmth.
2//!
3//! [`CacheWarmth`](crate::CacheWarmth) measures how long ago the provider's
4//! cache entry was started. It reads the time through a [`Clock`] passed to
5//! the builder, so a host can drive it from a clock it advances itself.
6
7use std::fmt;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::time::Duration;
11
12use jiff::{SignedDuration, Timestamp};
13
14/// A point on a [`Clock`]'s timeline.
15///
16/// Opaque and only meaningful against other instants of the same clock. Unlike
17/// [`std::time::Instant`], which does not advance while the machine sleeps on
18/// the platforms the agent supports, the timeline of the [`SystemClock`] keeps
19/// counting through sleep.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct Instant {
22    nanos: u64,
23}
24
25impl Instant {
26    /// Builds an instant `nanos` nanoseconds after the clock's origin.
27    pub(crate) const fn from_nanos(nanos: u64) -> Self {
28        Self { nanos }
29    }
30
31    /// Nanoseconds since the clock's origin.
32    pub(crate) const fn as_nanos(self) -> u64 {
33        self.nanos
34    }
35
36    /// Time from `earlier` to `self`, or `None` when `earlier` is later.
37    #[must_use]
38    pub const fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
39        match self.nanos.checked_sub(earlier.nanos) {
40            Some(nanos) => Some(Duration::from_nanos(nanos)),
41            None => None,
42        }
43    }
44
45    /// Time from `earlier` to `self`, zero when `earlier` is later.
46    #[must_use]
47    pub const fn duration_since(self, earlier: Self) -> Duration {
48        Duration::from_nanos(self.nanos.saturating_sub(earlier.nanos))
49    }
50
51    /// `self` moved forward by `by`, or `None` on overflow.
52    #[must_use]
53    pub fn checked_add(self, by: Duration) -> Option<Self> {
54        let nanos = u64::try_from(by.as_nanos()).ok()?;
55        self.nanos.checked_add(nanos).map(Self::from_nanos)
56    }
57
58    /// `self` moved back by `by`, or `None` when that precedes the origin.
59    #[must_use]
60    pub fn checked_sub(self, by: Duration) -> Option<Self> {
61        let nanos = u64::try_from(by.as_nanos()).ok()?;
62        self.nanos.checked_sub(nanos).map(Self::from_nanos)
63    }
64}
65
66/// A source of monotonic time.
67pub trait Clock: Send + Sync + 'static {
68    /// The current instant.
69    fn now(&self) -> Instant;
70
71    /// The current wall-clock time, stamped on the user messages the model
72    /// reads.
73    fn utc_now(&self) -> Timestamp;
74}
75
76/// The operating system's monotonic clock that keeps counting while the
77/// machine sleeps; the default.
78///
79/// Reads `CLOCK_MONOTONIC` on Apple targets (which counts sleep, unlike
80/// `CLOCK_UPTIME_RAW`, the source of [`std::time::Instant`] there),
81/// `CLOCK_BOOTTIME` on Linux and Android, other Unix targets' `CLOCK_MONOTONIC`,
82/// and the biased interrupt time (`QueryInterruptTime`) on Windows.
83#[derive(Debug, Clone, Copy, Default)]
84pub struct SystemClock;
85
86impl Clock for SystemClock {
87    fn now(&self) -> Instant {
88        Instant::from_nanos(system_nanos())
89    }
90
91    fn utc_now(&self) -> Timestamp {
92        Timestamp::now()
93    }
94}
95
96#[cfg(any(target_os = "linux", target_os = "android"))]
97const SYSTEM_CLOCK: rustix::time::ClockId = rustix::time::ClockId::Boottime;
98
99#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
100const SYSTEM_CLOCK: rustix::time::ClockId = rustix::time::ClockId::Monotonic;
101
102#[cfg(unix)]
103fn system_nanos() -> u64 {
104    let now = rustix::time::clock_gettime(SYSTEM_CLOCK);
105    let secs = u64::try_from(now.tv_sec).expect("the system clock is not negative");
106    let subsec = u64::try_from(now.tv_nsec).expect("tv_nsec is not negative");
107    secs.checked_mul(1_000_000_000)
108        .and_then(|nanos| nanos.checked_add(subsec))
109        .expect("the system clock fits in u64 nanoseconds")
110}
111
112#[cfg(windows)]
113fn system_nanos() -> u64 {
114    let mut ticks = 0_u64;
115    // SAFETY: `ticks` is a valid, writable `u64` for the whole call.
116    unsafe { windows_sys::Win32::System::WindowsProgramming::QueryInterruptTime(&raw mut ticks) };
117    // The count is in units of 100 nanoseconds.
118    ticks
119        .checked_mul(100)
120        .expect("the interrupt time fits in u64 nanoseconds")
121}
122
123/// A clock that only moves when told to.
124///
125/// Clones share one timeline starting at its origin, so a test keeps a handle,
126/// gives the builder another, and advances time without waiting.
127#[derive(Debug, Clone)]
128pub struct ManualClock {
129    advanced_nanos: Arc<AtomicU64>,
130    origin_utc: Timestamp,
131}
132
133impl ManualClock {
134    /// Creates a clock standing at its origin.
135    #[must_use]
136    pub fn new() -> Self {
137        Self::at_utc(Timestamp::UNIX_EPOCH)
138    }
139
140    /// Creates a clock standing at its origin, whose wall-clock time there is
141    /// `origin_utc`.
142    #[must_use]
143    pub fn at_utc(origin_utc: Timestamp) -> Self {
144        Self {
145            advanced_nanos: Arc::new(AtomicU64::new(0)),
146            origin_utc,
147        }
148    }
149
150    /// Moves the clock forward by `by`.
151    ///
152    /// # Panics
153    ///
154    /// Panics when `by` exceeds `u64::MAX` nanoseconds (about 584 years).
155    pub fn advance(&self, by: Duration) {
156        let nanos = u64::try_from(by.as_nanos()).expect("advance fits in u64 nanoseconds");
157        self.advanced_nanos.fetch_add(nanos, Ordering::Relaxed);
158    }
159}
160
161impl Default for ManualClock {
162    fn default() -> Self {
163        Self::new()
164    }
165}
166
167impl Clock for ManualClock {
168    fn now(&self) -> Instant {
169        Instant::from_nanos(self.advanced_nanos.load(Ordering::Relaxed))
170    }
171
172    fn utc_now(&self) -> Timestamp {
173        let advanced = i64::try_from(self.advanced_nanos.load(Ordering::Relaxed))
174            .expect("a manual clock stays within i64 nanoseconds");
175        self.origin_utc
176            .checked_add(SignedDuration::from_nanos(advanced))
177            .expect("a manual clock stays within the timestamp range")
178    }
179}
180
181/// A type-erased [`Clock`], what the agent stores.
182///
183/// The agent already carries five type parameters; the clock is read a few
184/// times per turn, so erasing it costs nothing that matters.
185#[derive(Clone)]
186pub struct AnyClock(Arc<dyn Clock>);
187
188impl AnyClock {
189    /// Erases `clock`.
190    #[must_use]
191    pub fn new(clock: impl Clock) -> Self {
192        Self(Arc::new(clock))
193    }
194
195    /// The current instant on the wrapped clock.
196    #[must_use]
197    pub fn now(&self) -> Instant {
198        self.0.now()
199    }
200
201    /// The current wall-clock time on the wrapped clock.
202    #[must_use]
203    pub fn utc_now(&self) -> Timestamp {
204        self.0.utc_now()
205    }
206
207    /// Time elapsed since `earlier`, zero when `earlier` is in the future.
208    #[must_use]
209    pub fn since(&self, earlier: Instant) -> Duration {
210        self.now().duration_since(earlier)
211    }
212}
213
214impl Default for AnyClock {
215    fn default() -> Self {
216        Self::new(SystemClock)
217    }
218}
219
220impl fmt::Debug for AnyClock {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        f.write_str("AnyClock")
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn the_system_clock_advances() {
232        let clock = SystemClock;
233        let first = clock.now();
234        std::thread::sleep(Duration::from_millis(20));
235        assert!(clock.now().duration_since(first) >= Duration::from_millis(20));
236    }
237
238    #[test]
239    fn instants_do_arithmetic() {
240        let at = Instant::from_nanos(10_000);
241        let later = at.checked_add(Duration::from_micros(5)).unwrap();
242        assert_eq!(later.duration_since(at), Duration::from_micros(5));
243        assert_eq!(at.duration_since(later), Duration::ZERO);
244        assert_eq!(at.checked_duration_since(later), None);
245        assert_eq!(later.checked_sub(Duration::from_micros(5)), Some(at));
246        assert_eq!(at.checked_sub(Duration::from_secs(1)), None);
247    }
248}