Skip to main content

vibe/
replay_clock.rs

1//! Deterministic replay clock — the only WASM clock (W12, T71).
2//!
3//! In a WASM environment, there is no wall clock — `SystemTime::now()`
4//! is either unavailable or non-deterministic. The only honest clock
5//! is a **replay Instant**: an Instant from a recorded timeline that
6//! is fed to the engine deterministically.
7//!
8//! This module provides:
9//! - `ReplayClock`: a deterministic clock that yields Instants from a
10//!   recorded timeline. Each call to `tick()` advances to the next
11//!   recorded Instant.
12//! - `ReplayTimeline`: a recorded sequence of Instants with optional
13//!   payloads (for replaying sensor data, animation frames, etc.).
14//! - Integration with the Host trait: a WASM host uses `ReplayClock`
15//!   as its `time_now` implementation.
16//!
17//! ## One clock story (T71)
18//!
19//! This is part of the "one clock story" — replacing the scattered
20//! coarse Unix clocks (`time.unix()`, `asserted_time_unix: u32` in
21//! wellfare-core, etc.) with a single Instant-based clock. The replay
22//! clock is the WASM edge of that story: where native hosts use
23//! `SystemTime::now()`, WASM hosts use `ReplayClock::tick()`.
24//!
25//! Reference: `docs/vibescript-full-impl-PLAN.md` §8.14 T71,
26//! §8.15 W12, excellence-first §3.14, §4.
27
28use crate::value::{Instant, TimeScale, Value};
29use std::collections::BTreeMap;
30
31/// A recorded timeline of Instants with optional payloads (W12).
32#[derive(Debug, Clone, PartialEq)]
33pub struct ReplayTimeline {
34    /// The timeline's name/identifier.
35    pub name: String,
36    /// The recorded Instants in order.
37    pub instants: Vec<Instant>,
38    /// Optional payloads for each Instant (e.g. sensor readings).
39    pub payloads: Vec<Option<Value>>,
40    /// The time scale of this timeline.
41    pub scale: TimeScale,
42}
43
44impl ReplayTimeline {
45    /// Create a new empty timeline with the given name and scale.
46    pub fn new(name: &str, scale: TimeScale) -> Self {
47        Self {
48            name: name.into(),
49            instants: Vec::new(),
50            payloads: Vec::new(),
51            scale,
52        }
53    }
54
55    /// Create a timeline from a sequence of (secs, nanos) pairs.
56    pub fn from_secs_nanos(name: &str, scale: TimeScale, pts: &[(i64, u32)]) -> Self {
57        let mut tl = Self::new(name, scale.clone());
58        for &(secs, nanos) in pts {
59            tl.push(
60                Instant {
61                    scale: scale.clone(),
62                    secs,
63                    nanos,
64                    frame: None,
65                    seal: None,
66                },
67                None,
68            );
69        }
70        tl
71    }
72
73    /// Append an Instant with an optional payload.
74    pub fn push(&mut self, instant: Instant, payload: Option<Value>) -> &mut Self {
75        self.instants.push(instant);
76        self.payloads.push(payload);
77        self
78    }
79
80    /// Number of recorded Instants.
81    pub fn len(&self) -> usize {
82        self.instants.len()
83    }
84
85    /// Is the timeline empty?
86    pub fn is_empty(&self) -> bool {
87        self.instants.is_empty()
88    }
89
90    /// Get the Instant at the given index.
91    pub fn get(&self, idx: usize) -> Option<&Instant> {
92        self.instants.get(idx)
93    }
94
95    /// Get the payload at the given index.
96    pub fn payload(&self, idx: usize) -> Option<&Value> {
97        self.payloads.get(idx).and_then(|p| p.as_ref())
98    }
99}
100
101/// A deterministic replay clock — the only WASM clock (W12).
102///
103/// Yields Instants from a recorded timeline. Each call to `tick()`
104/// advances to the next recorded Instant. When the timeline is
105/// exhausted, the clock returns the last Instant (or fails closed
106/// if the timeline was empty).
107#[derive(Debug, Clone)]
108pub struct ReplayClock {
109    timeline: ReplayTimeline,
110    cursor: usize,
111    /// What to do when the timeline is exhausted.
112    exhausted_policy: ExhaustedPolicy,
113    /// The last Instant returned (for repeat-after-exhaustion).
114    last_instant: Option<Instant>,
115}
116
117/// What to do when the replay timeline is exhausted (W12).
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
119pub enum ExhaustedPolicy {
120    /// Return the last Instant indefinitely (replay loops on the last frame).
121    #[default]
122    RepeatLast,
123    /// Fail closed with E702 (no more time data).
124    FailClosed,
125    /// Loop back to the beginning of the timeline.
126    Loop,
127}
128
129impl ReplayClock {
130    /// Create a replay clock from a timeline.
131    pub fn new(timeline: ReplayTimeline) -> Self {
132        Self {
133            timeline,
134            cursor: 0,
135            exhausted_policy: ExhaustedPolicy::default(),
136            last_instant: None,
137        }
138    }
139
140    /// Set the exhausted policy.
141    pub fn with_exhausted_policy(mut self, policy: ExhaustedPolicy) -> Self {
142        self.exhausted_policy = policy;
143        self
144    }
145
146    /// Advance to the next Instant in the timeline.
147    /// Returns the next Instant, or an error string if exhausted and
148    /// FailClosed.
149    pub fn tick(&mut self) -> Result<Instant, String> {
150        if self.cursor < self.timeline.len() {
151            let instant = self.timeline.instants[self.cursor].clone();
152            self.last_instant = Some(instant.clone());
153            self.cursor += 1;
154            Ok(instant)
155        } else {
156            match self.exhausted_policy {
157                ExhaustedPolicy::RepeatLast => self
158                    .last_instant
159                    .clone()
160                    .ok_or_else(|| "empty timeline".into()),
161                ExhaustedPolicy::FailClosed => {
162                    Err("replay timeline exhausted (fail-closed)".into())
163                }
164                ExhaustedPolicy::Loop => {
165                    if self.timeline.is_empty() {
166                        return Err("empty timeline".into());
167                    }
168                    self.cursor = 0;
169                    let instant = self.timeline.instants[0].clone();
170                    self.last_instant = Some(instant.clone());
171                    self.cursor = 1;
172                    Ok(instant)
173                }
174            }
175        }
176    }
177
178    /// Get the current cursor position.
179    pub fn cursor(&self) -> usize {
180        self.cursor
181    }
182
183    /// Total timeline length.
184    pub fn len(&self) -> usize {
185        self.timeline.len()
186    }
187
188    /// Is the clock at the end of the timeline?
189    pub fn is_exhausted(&self) -> bool {
190        self.cursor >= self.timeline.len()
191    }
192
193    /// Get the payload at the current cursor position (before tick).
194    pub fn current_payload(&self) -> Option<&Value> {
195        if self.cursor < self.timeline.len() {
196            self.timeline
197                .payloads
198                .get(self.cursor)
199                .and_then(|p| p.as_ref())
200        } else {
201            None
202        }
203    }
204
205    /// Convert the clock state to a Value::Record for inspection.
206    pub fn to_value(&self) -> Value {
207        let mut rec = BTreeMap::new();
208        rec.insert("name".into(), Value::String(self.timeline.name.clone()));
209        rec.insert("cursor".into(), Value::U64(self.cursor as u64));
210        rec.insert("length".into(), Value::U64(self.timeline.len() as u64));
211        rec.insert("exhausted".into(), Value::Bool(self.is_exhausted()));
212        rec.insert(
213            "exhausted_policy".into(),
214            Value::String(
215                match self.exhausted_policy {
216                    ExhaustedPolicy::RepeatLast => "repeat_last",
217                    ExhaustedPolicy::FailClosed => "fail_closed",
218                    ExhaustedPolicy::Loop => "loop",
219                }
220                .into(),
221            ),
222        );
223        Value::Record(rec)
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    fn make_timeline() -> ReplayTimeline {
232        ReplayTimeline::from_secs_nanos(
233            "test",
234            TimeScale::Unix,
235            &[
236                (1000, 0),
237                (1000, 500_000_000),
238                (1001, 0),
239                (1001, 500_000_000),
240            ],
241        )
242    }
243
244    // ── ReplayTimeline tests ──────────────────────────────────────────
245
246    #[test]
247    fn w12_timeline_basic() {
248        let tl = make_timeline();
249        assert_eq!(tl.name, "test");
250        assert_eq!(tl.len(), 4);
251        assert!(!tl.is_empty());
252    }
253
254    #[test]
255    fn w12_timeline_get() {
256        let tl = make_timeline();
257        let i0 = tl.get(0).unwrap();
258        assert_eq!(i0.secs, 1000);
259        assert_eq!(i0.nanos, 0);
260        let i1 = tl.get(1).unwrap();
261        assert_eq!(i1.nanos, 500_000_000);
262    }
263
264    #[test]
265    fn w12_timeline_empty() {
266        let tl = ReplayTimeline::new("empty", TimeScale::Unix);
267        assert!(tl.is_empty());
268        assert_eq!(tl.len(), 0);
269    }
270
271    #[test]
272    fn w12_timeline_with_payloads() {
273        let mut tl = ReplayTimeline::new("sensors", TimeScale::Monotonic);
274        tl.push(Instant::monotonic(1000), Some(Value::F64(42.0)));
275        tl.push(Instant::monotonic(2000), None);
276        assert_eq!(tl.len(), 2);
277        assert_eq!(tl.payload(0), Some(&Value::F64(42.0)));
278        assert_eq!(tl.payload(1), None);
279    }
280
281    // ── ReplayClock tests ─────────────────────────────────────────────
282
283    #[test]
284    fn w12_clock_ticks_through_timeline() {
285        let mut clock = ReplayClock::new(make_timeline());
286        let i0 = clock.tick().unwrap();
287        assert_eq!(i0.secs, 1000);
288        assert_eq!(i0.nanos, 0);
289        let i1 = clock.tick().unwrap();
290        assert_eq!(i1.nanos, 500_000_000);
291        let i2 = clock.tick().unwrap();
292        assert_eq!(i2.secs, 1001);
293        assert_eq!(clock.cursor(), 3);
294    }
295
296    #[test]
297    fn w12_clock_exhausted_repeat_last() {
298        let mut clock = ReplayClock::new(make_timeline());
299        // Tick through all 4.
300        for _ in 0..4 {
301            clock.tick().unwrap();
302        }
303        assert!(clock.is_exhausted());
304        // Default policy: repeat last.
305        let i = clock.tick().unwrap();
306        assert_eq!(i.secs, 1001);
307        assert_eq!(i.nanos, 500_000_000);
308    }
309
310    #[test]
311    fn w12_clock_exhausted_fail_closed() {
312        let mut clock =
313            ReplayClock::new(make_timeline()).with_exhausted_policy(ExhaustedPolicy::FailClosed);
314        for _ in 0..4 {
315            clock.tick().unwrap();
316        }
317        let result = clock.tick();
318        assert!(result.is_err());
319        assert!(result.unwrap_err().contains("fail-closed"));
320    }
321
322    #[test]
323    fn w12_clock_exhausted_loop() {
324        let mut clock =
325            ReplayClock::new(make_timeline()).with_exhausted_policy(ExhaustedPolicy::Loop);
326        for _ in 0..4 {
327            clock.tick().unwrap();
328        }
329        assert!(clock.is_exhausted());
330        // Loop back to beginning.
331        let i = clock.tick().unwrap();
332        assert_eq!(i.secs, 1000);
333        assert_eq!(i.nanos, 0);
334        assert_eq!(clock.cursor(), 1);
335    }
336
337    #[test]
338    fn w12_clock_empty_timeline_fails() {
339        let mut clock = ReplayClock::new(ReplayTimeline::new("empty", TimeScale::Unix));
340        let result = clock.tick();
341        assert!(result.is_err());
342    }
343
344    #[test]
345    fn w12_clock_current_payload() {
346        let mut tl = ReplayTimeline::new("sensors", TimeScale::Monotonic);
347        tl.push(Instant::monotonic(1000), Some(Value::F64(42.0)));
348        tl.push(Instant::monotonic(2000), Some(Value::F64(43.0)));
349        let mut clock = ReplayClock::new(tl);
350        // Before tick, payload at cursor 0.
351        assert_eq!(clock.current_payload(), Some(&Value::F64(42.0)));
352        clock.tick().unwrap();
353        // After tick, payload at cursor 1.
354        assert_eq!(clock.current_payload(), Some(&Value::F64(43.0)));
355    }
356
357    #[test]
358    fn w12_clock_to_value() {
359        let mut clock = ReplayClock::new(make_timeline());
360        clock.tick().unwrap();
361        let v = clock.to_value();
362        match v {
363            Value::Record(r) => {
364                assert_eq!(r.get("name"), Some(&Value::String("test".into())));
365                assert_eq!(r.get("cursor"), Some(&Value::U64(1)));
366                assert_eq!(r.get("length"), Some(&Value::U64(4)));
367                assert_eq!(r.get("exhausted"), Some(&Value::Bool(false)));
368            }
369            _ => panic!("expected Record"),
370        }
371    }
372
373    #[test]
374    fn w12_exhausted_policy_default() {
375        assert_eq!(ExhaustedPolicy::default(), ExhaustedPolicy::RepeatLast);
376    }
377
378    #[test]
379    fn w12_clock_loop_empty_timeline_fails() {
380        let mut clock = ReplayClock::new(ReplayTimeline::new("empty", TimeScale::Unix))
381            .with_exhausted_policy(ExhaustedPolicy::Loop);
382        let result = clock.tick();
383        assert!(result.is_err());
384    }
385}