Skip to main content

base/interface/
environment.rs

1//! `Environment` — the two inputs that make a run different from the last one.
2//!
3//! Wall-clock time and fresh identifiers are read from the operating system in
4//! nearly two hundred places. Replacing all of them would be busywork: most
5//! are `Instant::now()` measuring how long something took, and a latency
6//! number that varies between runs is the number doing its job.
7//!
8//! The ones that matter are the ones whose answers are *kept*: a timestamp
9//! written into the session log, an id that names a log entry forever, a date
10//! that goes into the prompt the model reads. Those decide whether the same
11//! conversation, replayed, is the same conversation. They come from here.
12//!
13//! # Not `Instant`
14//!
15//! There is deliberately no monotonic clock on this contract. `Instant` cannot
16//! be formatted, stored or transmitted — everything it is used for is
17//! measurement, and measurement is exactly the category this is not for.
18//! Putting it here would invite hundreds of mechanical substitutions that buy
19//! nothing.
20
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::time::Instant;
23
24use time::OffsetDateTime;
25
26use crate::id::Id;
27
28/// Where kept time and kept identifiers come from.
29pub trait Environment: Send + Sync {
30    /// Wall-clock now.
31    fn now(&self) -> OffsetDateTime;
32
33    /// An identifier nothing else will be given.
34    fn new_id(&self) -> Id;
35}
36
37/// The machine's own answers.
38pub struct SystemEnvironment;
39
40impl Environment for SystemEnvironment {
41    fn now(&self) -> OffsetDateTime {
42        OffsetDateTime::now_utc()
43    }
44
45    fn new_id(&self) -> Id {
46        Id::new()
47    }
48}
49
50/// Time that moves only when it is asked, and identifiers that count.
51///
52/// The second implementation, and the one the whole contract is for: two runs
53/// of the same conversation under one of these produce the same log, byte for
54/// byte. That is the property a recorded session is replayed against, and it
55/// is unachievable while a timestamp and a UUID are read from the machine.
56///
57/// Each call to `now` advances the clock by `step`, so successive entries are
58/// ordered the way real ones are rather than sharing one instant.
59pub struct FixedEnvironment {
60    start: OffsetDateTime,
61    step: time::Duration,
62    ticks: AtomicU64,
63    ids: AtomicU64,
64}
65
66impl FixedEnvironment {
67    pub fn new(start: OffsetDateTime, step: time::Duration) -> Self {
68        Self {
69            start,
70            step,
71            ticks: AtomicU64::new(0),
72            ids: AtomicU64::new(0),
73        }
74    }
75
76    /// The epoch, one second per reading.
77    pub fn epoch() -> Self {
78        Self::new(OffsetDateTime::UNIX_EPOCH, time::Duration::seconds(1))
79    }
80}
81
82impl Environment for FixedEnvironment {
83    fn now(&self) -> OffsetDateTime {
84        let n = self.ticks.fetch_add(1, Ordering::SeqCst);
85        self.start + self.step * (n as i32)
86    }
87
88    fn new_id(&self) -> Id {
89        let n = self.ids.fetch_add(1, Ordering::SeqCst);
90        let mut bytes = [0u8; 16];
91        bytes[8..].copy_from_slice(&n.to_be_bytes());
92        Id::from_bytes(bytes)
93    }
94}
95
96/// The machine's clock moved to another starting point: it reads `start` when made, and from
97/// there runs at wall-clock speed. Identifiers stay fresh.
98///
99/// For a session whose kept time has to be some other day than today — replaying a recording, so
100/// the date in its prompt is the day it was recorded — while the order and spacing of what it
101/// writes stay real.
102pub struct ShiftedEnvironment {
103    start: OffsetDateTime,
104    origin: Instant,
105}
106
107impl ShiftedEnvironment {
108    pub fn starting_at(start: OffsetDateTime) -> Self {
109        Self {
110            start,
111            origin: Instant::now(),
112        }
113    }
114
115    /// From milliseconds since the Unix epoch; `None` when out of range.
116    pub fn starting_at_ms(ms: u64) -> Option<Self> {
117        let ns = i128::from(ms).checked_mul(1_000_000)?;
118        OffsetDateTime::from_unix_timestamp_nanos(ns)
119            .ok()
120            .map(Self::starting_at)
121    }
122}
123
124impl Environment for ShiftedEnvironment {
125    fn now(&self) -> OffsetDateTime {
126        self.start + self.origin.elapsed()
127    }
128
129    fn new_id(&self) -> Id {
130        Id::new()
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn the_fixed_clock_advances_one_step_per_reading() {
140        let env = FixedEnvironment::epoch();
141        let a = env.now();
142        let b = env.now();
143        assert_eq!(a, OffsetDateTime::UNIX_EPOCH);
144        assert_eq!(
145            b - a,
146            time::Duration::seconds(1),
147            "entries must still order"
148        );
149    }
150
151    #[test]
152    fn a_shifted_clock_starts_where_it_is_told_and_keeps_running() {
153        let start = OffsetDateTime::UNIX_EPOCH + time::Duration::days(20_000);
154        let env = ShiftedEnvironment::starting_at(start);
155        let a = env.now();
156        std::thread::sleep(std::time::Duration::from_millis(5));
157        let b = env.now();
158        assert!(a >= start && a - start < time::Duration::seconds(1));
159        assert!(b > a, "it runs");
160        assert_ne!(env.new_id(), env.new_id());
161        let from_ms = ShiftedEnvironment::starting_at_ms(1_761_955_200_000)
162            .unwrap()
163            .now();
164        assert_eq!(from_ms.date().to_string(), "2025-11-01");
165    }
166
167    #[test]
168    fn two_runs_of_the_same_length_agree_on_every_answer() {
169        let one = FixedEnvironment::epoch();
170        let two = FixedEnvironment::epoch();
171        for _ in 0..8 {
172            assert_eq!(one.now(), two.now());
173            assert_eq!(one.new_id(), two.new_id());
174        }
175    }
176
177    #[test]
178    fn fixed_identifiers_are_still_distinct() {
179        let env = FixedEnvironment::epoch();
180        let ids: Vec<Id> = (0..64).map(|_| env.new_id()).collect();
181        let mut sorted: Vec<String> = ids.iter().map(|i| i.to_string()).collect();
182        sorted.sort();
183        sorted.dedup();
184        assert_eq!(
185            sorted.len(),
186            64,
187            "a counter that repeats is not an id source"
188        );
189    }
190
191    #[test]
192    fn the_system_environment_does_not_repeat_itself() {
193        let env = SystemEnvironment;
194        assert_ne!(env.new_id(), env.new_id());
195    }
196}