Skip to main content

vibe/
tick_policy.rs

1//! Tick policy under load — drop / coalesce / tear (T68).
2//!
3//! When tick events arrive faster than the engine can process them,
4//! the system must have an explicit policy. Without one, animation
5//! and sensor fusion lie — they report stale data as if it were
6//! current, or drop frames silently.
7//!
8//! ## Three policies
9//!
10//! - **Drop**: discard ticks that arrive while a previous tick is
11//!   still being processed. The next tick after the current one
12//!   completes is processed normally. Simple, but loses information.
13//!
14//! - **Coalesce**: merge pending ticks into a single tick that carries
15//!   the latest timestamp and a count of dropped ticks. Preserves
16//!   temporal recency at the cost of intermediate states.
17//!
18//! - **Tear**: emit a `TopologicalTear` diagnostic when ticks are
19//!   dropped, so the principal knows the system is overloaded. The
20//!   tear carries (μ, λ) evidence: μ = how many ticks were dropped,
21//!   λ = the latency of the last processed tick.
22//!
23//! The default is **Coalesce** — it preserves the most information
24//! while preventing unbounded queue growth. The policy is a host
25//! constant, not a language constant (per T46 design principle).
26//!
27//! Reference: `docs/vibescript-full-impl-PLAN.md` §8.14 T68,
28//! excellence-first §3.9.
29
30use crate::value::{Instant, Value};
31use std::collections::BTreeMap;
32
33/// The tick policy — what happens when ticks arrive under load (T68).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
35pub enum TickPolicy {
36    /// Discard ticks that arrive while a previous tick is processing.
37    /// The next tick after the current one completes is processed.
38    Drop,
39    /// Merge pending ticks into one with the latest timestamp and a
40    /// count of dropped ticks. Default.
41    #[default]
42    Coalesce,
43    /// Emit a TopologicalTear when ticks are dropped, carrying (μ, λ)
44    /// evidence. Still coalesces, but also reports the overload.
45    Tear,
46}
47
48impl TickPolicy {
49    /// `str` form.
50    pub fn as_str(&self) -> &'static str {
51        match self {
52            Self::Drop => "drop",
53            Self::Coalesce => "coalesce",
54            Self::Tear => "tear",
55        }
56    }
57
58    /// Constructs from str.
59    pub fn from_str(s: &str) -> Option<Self> {
60        match s {
61            "drop" => Some(Self::Drop),
62            "coalesce" => Some(Self::Coalesce),
63            "tear" => Some(Self::Tear),
64            _ => None,
65        }
66    }
67}
68
69/// A tick event — a timestamped signal from the host's tick loop.
70#[derive(Debug, Clone, PartialEq)]
71pub struct TickEvent {
72    /// When the tick was generated (Instant from the host clock).
73    pub instant: Instant,
74    /// The tick sequence number (monotonically increasing).
75    pub seq: u64,
76    /// Optional payload (e.g. dt for animation, sensor reading).
77    pub payload: Option<Value>,
78}
79
80/// The result of applying a tick policy to a queue of pending ticks.
81#[derive(Debug, Clone, PartialEq)]
82pub struct TickDecision {
83    /// The tick to actually process (if any).
84    pub process: Option<TickEvent>,
85    /// How many ticks were dropped or coalesced.
86    pub dropped_count: u64,
87    /// Whether a topological tear should be emitted.
88    pub emit_tear: bool,
89    /// The tear evidence (μ = dropped, λ = latency_nanos), if tearing.
90    pub tear_evidence: Option<(f64, f64)>,
91}
92
93impl TickDecision {
94    /// No ticks to process — the queue was empty.
95    pub fn idle() -> Self {
96        Self {
97            process: None,
98            dropped_count: 0,
99            emit_tear: false,
100            tear_evidence: None,
101        }
102    }
103
104    /// Process a single tick with no drops.
105    pub fn process_one(tick: TickEvent) -> Self {
106        Self {
107            process: Some(tick),
108            dropped_count: 0,
109            emit_tear: false,
110            tear_evidence: None,
111        }
112    }
113}
114
115/// A tick queue with a policy. Bounded — never grows unboundedly.
116#[derive(Debug, Clone)]
117pub struct TickQueue {
118    policy: TickPolicy,
119    /// The pending tick (at most one — we coalesce immediately).
120    pending: Option<TickEvent>,
121    /// Total ticks dropped since the queue was created.
122    total_dropped: u64,
123    /// Total ticks processed.
124    total_processed: u64,
125    /// The last processed tick's seq (for latency calculation).
126    last_processed_seq: u64,
127    /// The last processed tick's instant (for latency calculation).
128    last_processed_instant: Instant,
129}
130
131impl TickQueue {
132    /// Creates a new `TickQueue`.
133    pub fn new(policy: TickPolicy) -> Self {
134        Self {
135            policy,
136            pending: None,
137            total_dropped: 0,
138            total_processed: 0,
139            last_processed_seq: 0,
140            last_processed_instant: Instant::unix(0, 0),
141        }
142    }
143
144    /// Enqueue a tick. If a tick is already pending, the policy
145    /// determines what happens.
146    pub fn enqueue(&mut self, tick: TickEvent) {
147        match self.policy {
148            TickPolicy::Drop => {
149                if self.pending.is_some() {
150                    self.total_dropped += 1;
151                    // Replace with the newer tick (drop the older one).
152                    self.pending = Some(tick);
153                } else {
154                    self.pending = Some(tick);
155                }
156            }
157            TickPolicy::Coalesce | TickPolicy::Tear => {
158                if let Some(ref mut existing) = self.pending {
159                    // Coalesce: keep the latest timestamp, increment dropped.
160                    self.total_dropped += 1;
161                    existing.instant = tick.instant;
162                    existing.seq = tick.seq;
163                    // Keep the newer payload.
164                    existing.payload = tick.payload;
165                } else {
166                    self.pending = Some(tick);
167                }
168            }
169        }
170    }
171
172    /// Dequeue the next tick to process. Returns a TickDecision
173    /// describing what happened.
174    pub fn dequeue(&mut self) -> TickDecision {
175        let tick = match self.pending.take() {
176            None => return TickDecision::idle(),
177            Some(t) => t,
178        };
179
180        let dropped = if self.total_dropped > 0 {
181            // How many were dropped since last dequeue.
182            let dropped_this_round = self.total_dropped;
183            self.total_dropped = 0;
184            dropped_this_round
185        } else {
186            0
187        };
188
189        // Calculate latency (difference between this tick's seq and
190        // the last processed seq).
191        let latency = tick.seq.saturating_sub(self.last_processed_seq);
192
193        self.last_processed_seq = tick.seq;
194        self.last_processed_instant = tick.instant.clone();
195        self.total_processed += 1;
196
197        match self.policy {
198            TickPolicy::Tear if dropped > 0 => {
199                // μ = dropped count, λ = latency in ticks.
200                let mu = dropped as f64;
201                let lambda = latency as f64;
202                TickDecision {
203                    process: Some(tick),
204                    dropped_count: dropped,
205                    emit_tear: true,
206                    tear_evidence: Some((mu, lambda)),
207                }
208            }
209            _ => TickDecision {
210                process: Some(tick),
211                dropped_count: dropped,
212                emit_tear: false,
213                tear_evidence: None,
214            },
215        }
216    }
217
218    /// Total ticks dropped since the queue was created.
219    pub fn total_dropped(&self) -> u64 {
220        self.total_dropped
221    }
222
223    /// Total ticks processed.
224    pub fn total_processed(&self) -> u64 {
225        self.total_processed
226    }
227
228    /// Is there a pending tick?
229    pub fn has_pending(&self) -> bool {
230        self.pending.is_some()
231    }
232
233    /// The current policy.
234    pub fn policy(&self) -> TickPolicy {
235        self.policy
236    }
237
238    /// Convert the queue state to a Value::Record for inspection.
239    pub fn to_value(&self) -> Value {
240        let mut rec = BTreeMap::new();
241        rec.insert("policy".into(), Value::String(self.policy.as_str().into()));
242        rec.insert("has_pending".into(), Value::Bool(self.pending.is_some()));
243        rec.insert("total_dropped".into(), Value::U64(self.total_dropped));
244        rec.insert("total_processed".into(), Value::U64(self.total_processed));
245        Value::Record(rec)
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    fn make_tick(seq: u64, secs: i64) -> TickEvent {
254        TickEvent {
255            instant: Instant::unix(secs, 0),
256            seq,
257            payload: None,
258        }
259    }
260
261    // ── TickPolicy tests ──────────────────────────────────────────────
262
263    #[test]
264    fn t68_policy_round_trip() {
265        for p in &[TickPolicy::Drop, TickPolicy::Coalesce, TickPolicy::Tear] {
266            let s = p.as_str();
267            assert_eq!(TickPolicy::from_str(s), Some(*p));
268        }
269        assert_eq!(TickPolicy::from_str("unknown"), None);
270    }
271
272    #[test]
273    fn t68_default_is_coalesce() {
274        assert_eq!(TickPolicy::default(), TickPolicy::Coalesce);
275    }
276
277    // ── Drop policy tests ─────────────────────────────────────────────
278
279    #[test]
280    fn t68_drop_policy_replaces_older_tick() {
281        let mut q = TickQueue::new(TickPolicy::Drop);
282        q.enqueue(make_tick(1, 100));
283        q.enqueue(make_tick(2, 200));
284        // The newer tick (seq=2) should be pending.
285        let decision = q.dequeue();
286        assert!(decision.process.is_some());
287        assert_eq!(decision.process.unwrap().seq, 2);
288        assert_eq!(decision.dropped_count, 1);
289        assert!(!decision.emit_tear);
290    }
291
292    #[test]
293    fn t68_drop_policy_no_drop_when_empty() {
294        let mut q = TickQueue::new(TickPolicy::Drop);
295        q.enqueue(make_tick(1, 100));
296        let decision = q.dequeue();
297        assert_eq!(decision.dropped_count, 0);
298        assert!(decision.process.is_some());
299    }
300
301    // ── Coalesce policy tests ─────────────────────────────────────────
302
303    #[test]
304    fn t68_coalesce_keeps_latest_timestamp() {
305        let mut q = TickQueue::new(TickPolicy::Coalesce);
306        q.enqueue(make_tick(1, 100));
307        q.enqueue(make_tick(2, 200));
308        q.enqueue(make_tick(3, 300));
309        let decision = q.dequeue();
310        let tick = decision.process.unwrap();
311        assert_eq!(tick.seq, 3);
312        assert_eq!(tick.instant.secs, 300);
313        assert_eq!(decision.dropped_count, 2);
314        assert!(!decision.emit_tear);
315    }
316
317    #[test]
318    fn t68_coalesce_empty_queue_returns_idle() {
319        let mut q = TickQueue::new(TickPolicy::Coalesce);
320        let decision = q.dequeue();
321        assert!(decision.process.is_none());
322        assert_eq!(decision.dropped_count, 0);
323    }
324
325    // ── Tear policy tests ─────────────────────────────────────────────
326
327    #[test]
328    fn t68_tear_policy_emits_tear_on_drop() {
329        let mut q = TickQueue::new(TickPolicy::Tear);
330        q.enqueue(make_tick(1, 100));
331        q.enqueue(make_tick(2, 200));
332        q.enqueue(make_tick(3, 300));
333        let decision = q.dequeue();
334        assert!(decision.emit_tear);
335        assert_eq!(decision.dropped_count, 2);
336        let (mu, lambda) = decision.tear_evidence.unwrap();
337        assert_eq!(mu, 2.0);
338        // lambda = seq 3 - last_processed_seq 0 = 3
339        assert_eq!(lambda, 3.0);
340    }
341
342    #[test]
343    fn t68_tear_policy_no_tear_when_no_drops() {
344        let mut q = TickQueue::new(TickPolicy::Tear);
345        q.enqueue(make_tick(1, 100));
346        let decision = q.dequeue();
347        assert!(!decision.emit_tear);
348        assert_eq!(decision.dropped_count, 0);
349    }
350
351    // ── Queue state tests ─────────────────────────────────────────────
352
353    #[test]
354    fn t68_queue_tracks_totals() {
355        let mut q = TickQueue::new(TickPolicy::Coalesce);
356        q.enqueue(make_tick(1, 100));
357        q.enqueue(make_tick(2, 200));
358        q.enqueue(make_tick(3, 300));
359        q.dequeue();
360        q.enqueue(make_tick(4, 400));
361        q.enqueue(make_tick(5, 500));
362        q.dequeue();
363        assert_eq!(q.total_processed(), 2);
364        // 2 dropped in first round + 1 dropped in second round = 3
365        // But total_dropped is reset after each dequeue, so we check
366        // via the decision instead.
367    }
368
369    #[test]
370    fn t68_queue_has_pending() {
371        let mut q = TickQueue::new(TickPolicy::Coalesce);
372        assert!(!q.has_pending());
373        q.enqueue(make_tick(1, 100));
374        assert!(q.has_pending());
375        q.dequeue();
376        assert!(!q.has_pending());
377    }
378
379    #[test]
380    fn t68_queue_to_value() {
381        let mut q = TickQueue::new(TickPolicy::Tear);
382        q.enqueue(make_tick(1, 100));
383        let v = q.to_value();
384        match v {
385            Value::Record(r) => {
386                assert_eq!(r.get("policy"), Some(&Value::String("tear".into())));
387                assert_eq!(r.get("has_pending"), Some(&Value::Bool(true)));
388                assert_eq!(r.get("total_processed"), Some(&Value::U64(0)));
389            }
390            _ => panic!("expected Record"),
391        }
392    }
393
394    // ── Sequential dequeue tests ──────────────────────────────────────
395
396    #[test]
397    fn t68_sequential_dequeue_no_drops() {
398        let mut q = TickQueue::new(TickPolicy::Coalesce);
399        q.enqueue(make_tick(1, 100));
400        let d1 = q.dequeue();
401        assert_eq!(d1.process.unwrap().seq, 1);
402        assert_eq!(d1.dropped_count, 0);
403
404        q.enqueue(make_tick(2, 200));
405        let d2 = q.dequeue();
406        assert_eq!(d2.process.unwrap().seq, 2);
407        assert_eq!(d2.dropped_count, 0);
408    }
409
410    #[test]
411    fn t68_tear_evidence_mu_lambda() {
412        let mut q = TickQueue::new(TickPolicy::Tear);
413        // Process first tick normally.
414        q.enqueue(make_tick(10, 100));
415        q.dequeue();
416
417        // Now enqueue 3 ticks rapidly (2 will be coalesced/dropped).
418        q.enqueue(make_tick(11, 200));
419        q.enqueue(make_tick(12, 300));
420        q.enqueue(make_tick(13, 400));
421        let decision = q.dequeue();
422        assert!(decision.emit_tear);
423        let (mu, lambda) = decision.tear_evidence.unwrap();
424        assert_eq!(mu, 2.0); // 2 ticks dropped
425        assert_eq!(lambda, 3.0); // seq 13 - seq 10 = 3
426    }
427}