Skip to main content

ftui_runtime/tick_strategy/
predictive.rs

1//! [`Predictive`] strategy: Markov-chain-driven tick allocation.
2//!
3//! The crown jewel of the tick strategy system. Uses a [`MarkovPredictor`] to
4//! learn screen transition patterns and a [`TickAllocation`] to convert
5//! predicted probabilities into tick divisors. Screens the user is likely to
6//! switch to get ticked more frequently; unlikely screens get throttled.
7//!
8//! Gracefully degrades to uniform behavior during cold start (insufficient
9//! data) via confidence-weighted blending in [`MarkovPredictor`].
10
11use std::collections::HashMap;
12#[cfg(feature = "state-persistence")]
13use std::path::PathBuf;
14
15use tracing::{debug, info, trace};
16
17use super::{MarkovPredictor, TickAllocation, TickDecision, TickStrategy, TransitionCounter};
18
19/// Configuration for the [`Predictive`] tick strategy.
20#[derive(Debug, Clone)]
21pub struct PredictiveStrategyConfig {
22    /// How probabilities map to tick divisors.
23    pub allocation: TickAllocation,
24    /// Divisor used for unknown screens (not in the predictor's vocabulary).
25    pub fallback_divisor: u64,
26    /// Minimum observations before predictions are fully trusted.
27    pub min_observations: u64,
28    /// Temporal decay factor applied during maintenance (0.0..1.0).
29    pub decay_factor: f64,
30    /// How many ticks between decay cycles.
31    pub decay_interval: u64,
32    /// How many ticks between auto-save cycles (0 = disabled).
33    pub auto_save_interval: u64,
34}
35
36impl Default for PredictiveStrategyConfig {
37    fn default() -> Self {
38        Self {
39            allocation: TickAllocation::default(),
40            fallback_divisor: 5,
41            min_observations: 20,
42            decay_factor: 0.85,
43            decay_interval: 500,
44            auto_save_interval: 3000,
45        }
46    }
47}
48
49/// Markov-chain-driven tick strategy.
50///
51/// Learns screen transition patterns and allocates tick budget proportionally
52/// to transition probability. High-probability next screens tick at near-full
53/// rate; low-probability screens are aggressively throttled.
54///
55/// See module-level docs for architecture details.
56#[derive(Debug, Clone)]
57pub struct Predictive {
58    predictor: MarkovPredictor<String>,
59    allocation: TickAllocation,
60    fallback_divisor: u64,
61    decay_factor: f64,
62    decay_interval: u64,
63    auto_save_interval: u64,
64    /// Cache: recomputed only when active screen changes.
65    cached_divisors: HashMap<String, u64>,
66    /// The active screen the cache was computed for.
67    cached_for_screen: Option<String>,
68    /// Tick counter for maintenance scheduling.
69    ticks_since_decay: u64,
70    /// Tick counter for auto-save scheduling.
71    ticks_since_save: u64,
72    /// Whether there's unsaved data (transitions recorded since last save).
73    dirty: bool,
74    /// Path for periodic auto-save. `None` disables auto-save I/O.
75    #[cfg(feature = "state-persistence")]
76    persistence_path: Option<PathBuf>,
77}
78
79impl Predictive {
80    /// Create a new predictive strategy with the given config.
81    #[must_use]
82    pub fn new(config: PredictiveStrategyConfig) -> Self {
83        info!(
84            target: crate::telemetry_schema::TARGET_RUNTIME,
85            strategy = "Predictive",
86            fallback_divisor = config.fallback_divisor,
87            min_observations = config.min_observations,
88            decay_factor = config.decay_factor,
89            decay_interval = config.decay_interval,
90            "tick_strategy.init"
91        );
92        Self {
93            predictor: MarkovPredictor::with_min_observations(config.min_observations),
94            allocation: config.allocation,
95            fallback_divisor: config.fallback_divisor.max(1),
96            decay_factor: config.decay_factor,
97            decay_interval: config.decay_interval.max(1),
98            auto_save_interval: config.auto_save_interval,
99            cached_divisors: HashMap::new(),
100            cached_for_screen: None,
101            ticks_since_decay: 0,
102            ticks_since_save: 0,
103            dirty: false,
104            #[cfg(feature = "state-persistence")]
105            persistence_path: None,
106        }
107    }
108
109    /// Create with pre-loaded transition data (e.g., from persistence).
110    #[must_use]
111    pub fn with_counter(
112        config: PredictiveStrategyConfig,
113        counter: TransitionCounter<String>,
114    ) -> Self {
115        info!(
116            target: crate::telemetry_schema::TARGET_RUNTIME,
117            strategy = "Predictive",
118            fallback_divisor = config.fallback_divisor,
119            min_observations = config.min_observations,
120            loaded_transitions = %counter.total(),
121            known_screens = counter.state_ids().len(),
122            "tick_strategy.init (with pre-loaded data)"
123        );
124        Self {
125            predictor: MarkovPredictor::with_counter(counter, config.min_observations),
126            allocation: config.allocation,
127            fallback_divisor: config.fallback_divisor.max(1),
128            decay_factor: config.decay_factor,
129            decay_interval: config.decay_interval.max(1),
130            auto_save_interval: config.auto_save_interval,
131            cached_divisors: HashMap::new(),
132            cached_for_screen: None,
133            ticks_since_decay: 0,
134            ticks_since_save: 0,
135            dirty: false,
136            #[cfg(feature = "state-persistence")]
137            persistence_path: None,
138        }
139    }
140
141    /// Create with persistence: load historical transitions from a file.
142    ///
143    /// - **Missing file**: cold start (empty counter), no error.
144    /// - **Corrupted file**: logs a warning, falls back to cold start.
145    /// - **Successful load**: applies a single decay (`load_decay_factor`)
146    ///   to prevent historical data from permanently dominating.
147    #[cfg(feature = "state-persistence")]
148    #[must_use]
149    pub fn with_persistence(
150        config: PredictiveStrategyConfig,
151        path: &std::path::Path,
152        load_decay_factor: f64,
153    ) -> Self {
154        let counter = match super::persistence::load_transitions(path) {
155            Ok(c) => {
156                info!(
157                    target: crate::telemetry_schema::TARGET_RUNTIME,
158                    path = %path.display(),
159                    loaded_transitions = %c.total(),
160                    known_screens = c.state_ids().len(),
161                    "tick_strategy.persistence_loaded"
162                );
163                c
164            }
165            Err(e) => {
166                tracing::warn!(
167                    target: crate::telemetry_schema::TARGET_RUNTIME,
168                    path = %path.display(),
169                    error = %e,
170                    "tick_strategy.persistence_load_failed (falling back to cold start)"
171                );
172                TransitionCounter::new()
173            }
174        };
175
176        let mut strategy = Self::with_counter(config, counter);
177
178        // Apply load decay to down-weight historical data.
179        let factor = load_decay_factor.clamp(0.0, 1.0);
180        if factor < 1.0 {
181            let total_before = strategy.predictor.counter().total();
182            strategy.predictor.counter_mut().decay(factor);
183            let total_after = strategy.predictor.counter().total();
184            if (total_after - total_before).abs() > f64::EPSILON {
185                strategy.dirty = true;
186            }
187            info!(
188                target: crate::telemetry_schema::TARGET_RUNTIME,
189                load_decay_factor = factor,
190                remaining_total = %total_after,
191                "tick_strategy.load_decay_applied"
192            );
193        }
194
195        // Remember the path for periodic auto-save.
196        strategy.persistence_path = Some(path.to_path_buf());
197        strategy
198    }
199
200    /// Access the underlying predictor.
201    #[must_use]
202    pub fn predictor(&self) -> &MarkovPredictor<String> {
203        &self.predictor
204    }
205
206    /// Access the underlying transition counter.
207    #[must_use]
208    pub fn counter(&self) -> &TransitionCounter<String> {
209        self.predictor.counter()
210    }
211
212    /// Whether there is unsaved transition data.
213    #[must_use]
214    pub fn is_dirty(&self) -> bool {
215        self.dirty
216    }
217
218    /// Save transitions to disk if dirty and a persistence path is configured.
219    ///
220    /// IO errors are logged and swallowed — auto-save must never crash the
221    /// runtime.
222    #[cfg(feature = "state-persistence")]
223    fn save_if_dirty(&mut self) {
224        if !self.dirty {
225            return;
226        }
227        let Some(path) = self.persistence_path.as_deref() else {
228            return;
229        };
230        match super::persistence::save_transitions(self.predictor.counter(), path) {
231            Ok(()) => {
232                self.dirty = false;
233                self.ticks_since_save = 0;
234                info!(
235                    target: crate::telemetry_schema::TARGET_RUNTIME,
236                    path = %path.display(),
237                    total = %self.predictor.counter().total(),
238                    "tick_strategy.auto_save"
239                );
240            }
241            Err(e) => {
242                tracing::warn!(
243                    target: crate::telemetry_schema::TARGET_RUNTIME,
244                    path = %path.display(),
245                    error = %e,
246                    "tick_strategy.auto_save_failed"
247                );
248            }
249        }
250    }
251
252    /// Recompute the cached divisor map for predictions from `active`.
253    fn refresh_cache(&mut self, active: &str) {
254        if self.cached_for_screen.as_deref() == Some(active) {
255            return;
256        }
257
258        self.cached_divisors.clear();
259        let predictions = self.predictor.predict(&active.to_owned());
260        let is_cold = self.predictor.is_cold_start(&active.to_owned());
261
262        if is_cold {
263            let obs = self.predictor.counter().total_from(&active.to_owned()) as u64;
264            info!(
265                target: crate::telemetry_schema::TARGET_RUNTIME,
266                screen = active,
267                observations = obs,
268                min_required = self.predictor.min_observations(),
269                using_fallback = true,
270                "tick_strategy.cold_start"
271            );
272        }
273
274        for p in &predictions {
275            let divisor = self.allocation.divisor_for(p.probability);
276            trace!(
277                target: crate::telemetry_schema::TARGET_RUNTIME,
278                screen = %p.screen,
279                divisor,
280                probability = %p.probability,
281                confidence = %p.confidence,
282                "tick_strategy.screen_divisor"
283            );
284            self.cached_divisors.insert(p.screen.clone(), divisor);
285        }
286
287        debug!(
288            target: crate::telemetry_schema::TARGET_RUNTIME,
289            strategy = "Predictive",
290            active_screen = active,
291            num_screens = predictions.len(),
292            cold_start = is_cold,
293            "tick_strategy.cache_refresh"
294        );
295
296        self.cached_for_screen = Some(active.to_owned());
297    }
298}
299
300impl TickStrategy for Predictive {
301    fn should_tick(
302        &mut self,
303        screen_id: &str,
304        tick_count: u64,
305        active_screen: &str,
306    ) -> TickDecision {
307        // Ensure cache is fresh for current active screen.
308        self.refresh_cache(active_screen);
309
310        let divisor = self
311            .cached_divisors
312            .get(screen_id)
313            .copied()
314            .unwrap_or(self.fallback_divisor);
315
316        if tick_count.is_multiple_of(divisor) {
317            TickDecision::Tick
318        } else {
319            TickDecision::Skip
320        }
321    }
322
323    fn on_screen_transition(&mut self, from: &str, to: &str) {
324        self.predictor
325            .record_transition(from.to_owned(), to.to_owned());
326        self.dirty = true;
327        debug!(
328            target: crate::telemetry_schema::TARGET_RUNTIME,
329            from,
330            to,
331            total_transitions = %self.predictor.counter().total(),
332            "tick_strategy.transition"
333        );
334        // Force cache refresh for the new active screen.
335        self.cached_for_screen = None;
336        self.refresh_cache(to);
337    }
338
339    fn maintenance_tick(&mut self, _tick_count: u64) {
340        self.ticks_since_decay += 1;
341        self.ticks_since_save += 1;
342
343        // Periodic decay.
344        if self.ticks_since_decay >= self.decay_interval {
345            let entries_before = self.predictor.counter().state_ids().len();
346            let total_before = self.predictor.counter().total();
347            self.predictor.counter_mut().decay(self.decay_factor);
348            let entries_after = self.predictor.counter().state_ids().len();
349            let total_after = self.predictor.counter().total();
350            debug!(
351                target: crate::telemetry_schema::TARGET_RUNTIME,
352                factor = self.decay_factor,
353                entries_before,
354                entries_after,
355                total_before = %total_before,
356                total_after = %total_after,
357                pruned = entries_before.saturating_sub(entries_after),
358                "tick_strategy.decay"
359            );
360            self.ticks_since_decay = 0;
361            // Invalidate cache since probabilities changed.
362            self.cached_for_screen = None;
363            if entries_after != entries_before || (total_after - total_before).abs() > f64::EPSILON
364            {
365                self.dirty = true;
366            }
367        }
368
369        // Periodic auto-save.
370        if self.auto_save_interval > 0 && self.ticks_since_save >= self.auto_save_interval {
371            #[cfg(feature = "state-persistence")]
372            self.save_if_dirty();
373            #[cfg(not(feature = "state-persistence"))]
374            {
375                self.ticks_since_save = 0;
376            }
377        }
378    }
379
380    fn shutdown(&mut self) {
381        #[cfg(feature = "state-persistence")]
382        self.save_if_dirty();
383    }
384
385    fn name(&self) -> &str {
386        "Predictive"
387    }
388
389    fn debug_stats(&self) -> Vec<(String, String)> {
390        let confidence = self
391            .cached_for_screen
392            .as_ref()
393            .map(|s| self.predictor.confidence(s))
394            .unwrap_or(0.0);
395
396        // Build top prediction string if cache is populated.
397        let top_prediction = self
398            .cached_for_screen
399            .as_ref()
400            .and_then(|screen| {
401                let preds = self.predictor.predict(screen);
402                preds.first().map(|p| {
403                    let divisor = self
404                        .cached_divisors
405                        .get(&p.screen)
406                        .copied()
407                        .unwrap_or(self.fallback_divisor);
408                    format!("{}:{:.2}/div={}", p.screen, p.probability, divisor)
409                })
410            })
411            .unwrap_or_else(|| "(none)".to_owned());
412
413        let decay_next_at = self.decay_interval.saturating_sub(self.ticks_since_decay);
414
415        vec![
416            ("strategy".into(), "Predictive".into()),
417            (
418                "total_transitions".into(),
419                format!("{:.0}", self.predictor.counter().total()),
420            ),
421            (
422                "known_screens".into(),
423                self.predictor.counter().state_ids().len().to_string(),
424            ),
425            (
426                "cached_divisors".into(),
427                self.cached_divisors.len().to_string(),
428            ),
429            (
430                "active_screen".into(),
431                self.cached_for_screen
432                    .as_deref()
433                    .unwrap_or("(none)")
434                    .to_owned(),
435            ),
436            ("confidence".into(), format!("{confidence:.2}")),
437            ("top_prediction".into(), top_prediction),
438            ("fallback_divisor".into(), self.fallback_divisor.to_string()),
439            ("decay_factor".into(), format!("{:.2}", self.decay_factor)),
440            ("decay_next_at".into(), decay_next_at.to_string()),
441            ("dirty".into(), self.dirty.to_string()),
442        ]
443    }
444}
445
446// =============================================================================
447// Tests
448// =============================================================================
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    fn default_config() -> PredictiveStrategyConfig {
455        PredictiveStrategyConfig {
456            min_observations: 5, // low threshold for test speed
457            fallback_divisor: 10,
458            decay_interval: 100,
459            ..PredictiveStrategyConfig::default()
460        }
461    }
462
463    #[test]
464    fn cold_start_uses_fallback_divisor() {
465        let mut s = Predictive::new(default_config());
466        // No transition data → unknown screen → fallback divisor
467        assert_eq!(s.should_tick("x", 0, "a"), TickDecision::Tick); // 0 % 10 == 0
468        assert_eq!(s.should_tick("x", 1, "a"), TickDecision::Skip);
469        assert_eq!(s.should_tick("x", 9, "a"), TickDecision::Skip);
470        assert_eq!(s.should_tick("x", 10, "a"), TickDecision::Tick); // 10 % 10 == 0
471    }
472
473    #[test]
474    fn learns_and_adjusts_divisors() {
475        let config = PredictiveStrategyConfig {
476            min_observations: 5,
477            fallback_divisor: 20,
478            ..PredictiveStrategyConfig::default()
479        };
480        let mut s = Predictive::new(config);
481
482        // Record many a→b transitions
483        for _ in 0..20 {
484            s.on_screen_transition("a", "b");
485        }
486        // Record few a→c transitions
487        for _ in 0..2 {
488            s.on_screen_transition("a", "c");
489        }
490
491        // Now when active is "a", "b" should have a lower divisor than "c"
492        s.refresh_cache("a");
493        let b_div = s.cached_divisors.get("b").copied().unwrap_or(99);
494        let c_div = s.cached_divisors.get("c").copied().unwrap_or(99);
495        assert!(
496            b_div < c_div,
497            "b should tick more: b_div={b_div}, c_div={c_div}"
498        );
499    }
500
501    #[test]
502    fn cache_refreshes_on_screen_transition() {
503        let mut s = Predictive::new(default_config());
504        s.on_screen_transition("a", "b");
505        assert_eq!(s.cached_for_screen.as_deref(), Some("b"));
506
507        s.on_screen_transition("b", "c");
508        assert_eq!(s.cached_for_screen.as_deref(), Some("c"));
509    }
510
511    #[test]
512    fn cache_reused_for_same_screen() {
513        let mut s = Predictive::new(default_config());
514        s.on_screen_transition("a", "b");
515
516        // First call refreshes cache
517        s.should_tick("x", 1, "b");
518        let cached = s.cached_for_screen.clone();
519
520        // Second call reuses cache (same active screen)
521        s.should_tick("x", 2, "b");
522        assert_eq!(s.cached_for_screen, cached);
523    }
524
525    #[test]
526    fn unknown_screen_uses_fallback() {
527        let mut s = Predictive::new(default_config());
528        s.on_screen_transition("a", "b");
529
530        // "unknown" not in any prediction → fallback_divisor
531        let div = s
532            .cached_divisors
533            .get("unknown")
534            .copied()
535            .unwrap_or(s.fallback_divisor);
536        assert_eq!(div, 10); // default_config fallback
537    }
538
539    #[test]
540    fn decay_triggers_at_interval() {
541        let config = PredictiveStrategyConfig {
542            decay_interval: 10,
543            decay_factor: 0.5,
544            min_observations: 5,
545            ..PredictiveStrategyConfig::default()
546        };
547        let mut s = Predictive::new(config);
548        s.on_screen_transition("a", "b");
549        let before = s.predictor.counter().total();
550
551        // Simulate maintenance ticks
552        for _ in 0..10 {
553            s.maintenance_tick(0);
554        }
555
556        let after = s.predictor.counter().total();
557        assert!(
558            after < before,
559            "decay should reduce total: {after} < {before}"
560        );
561    }
562
563    #[test]
564    fn dirty_flag_set_on_transition() {
565        let mut s = Predictive::new(default_config());
566        assert!(!s.is_dirty());
567
568        s.on_screen_transition("a", "b");
569        assert!(s.is_dirty());
570    }
571
572    #[test]
573    fn name_is_stable() {
574        let s = Predictive::new(default_config());
575        assert_eq!(s.name(), "Predictive");
576    }
577
578    #[test]
579    fn debug_stats_populated() {
580        let mut s = Predictive::new(default_config());
581        s.on_screen_transition("a", "b");
582
583        let stats = s.debug_stats();
584        assert!(!stats.is_empty());
585        assert!(stats.iter().any(|(k, _)| k == "strategy"));
586        assert!(stats.iter().any(|(k, _)| k == "total_transitions"));
587        assert!(stats.iter().any(|(k, _)| k == "confidence"));
588        assert!(stats.iter().any(|(k, _)| k == "top_prediction"));
589        assert!(stats.iter().any(|(k, _)| k == "decay_factor"));
590        assert!(stats.iter().any(|(k, _)| k == "decay_next_at"));
591    }
592
593    #[test]
594    fn with_counter_preloads_data() {
595        let mut counter = TransitionCounter::new();
596        for _ in 0..50 {
597            counter.record("a".to_owned(), "b".to_owned());
598        }
599
600        let s = Predictive::with_counter(default_config(), counter);
601        assert!(!s.predictor().is_cold_start(&"a".to_owned()));
602    }
603
604    #[test]
605    fn high_probability_screen_ticks_more() {
606        let config = PredictiveStrategyConfig {
607            min_observations: 5,
608            fallback_divisor: 20,
609            ..PredictiveStrategyConfig::default()
610        };
611        let mut s = Predictive::new(config);
612
613        // Build strong signal: a→b is very likely
614        for _ in 0..30 {
615            s.on_screen_transition("a", "b");
616        }
617        s.on_screen_transition("a", "c");
618
619        // Count ticks over 100 frames for each screen
620        let mut b_ticks = 0u64;
621        let mut c_ticks = 0u64;
622        for tick in 0..100 {
623            if s.should_tick("b", tick, "a") == TickDecision::Tick {
624                b_ticks += 1;
625            }
626            if s.should_tick("c", tick, "a") == TickDecision::Tick {
627                c_ticks += 1;
628            }
629        }
630
631        assert!(
632            b_ticks > c_ticks,
633            "b should tick more than c: b={b_ticks}, c={c_ticks}"
634        );
635    }
636
637    // ========================================================================
638    // Persistence integration tests (E.2 coverage)
639    // ========================================================================
640
641    #[cfg(feature = "state-persistence")]
642    mod persistence_tests {
643        use super::*;
644
645        fn retained_fixture_dir() -> tempfile::TempDir {
646            tempfile::Builder::new()
647                .prefix("ftui-tick-predictive-")
648                .disable_cleanup(true)
649                .tempdir()
650                .expect("create retained predictive fixture")
651        }
652
653        #[test]
654        fn with_persistence_loads_from_file() {
655            use crate::tick_strategy::persistence::save_transitions;
656
657            let dir = retained_fixture_dir();
658            let path = dir.path().join("transitions.json");
659
660            // Create and save historical data
661            let mut counter = TransitionCounter::new();
662            for _ in 0..50 {
663                counter.record("a".to_owned(), "b".to_owned());
664            }
665            for _ in 0..20 {
666                counter.record("a".to_owned(), "c".to_owned());
667            }
668            save_transitions(&counter, &path).unwrap();
669
670            // Load with no decay
671            let s = Predictive::with_persistence(default_config(), &path, 1.0);
672            assert!(!s.predictor().is_cold_start(&"a".to_owned()));
673            assert_eq!(s.counter().total(), 70.0);
674        }
675
676        #[test]
677        fn with_persistence_applies_load_decay() {
678            use crate::tick_strategy::persistence::save_transitions;
679
680            let dir = retained_fixture_dir();
681            let path = dir.path().join("transitions.json");
682
683            let mut counter = TransitionCounter::new();
684            for _ in 0..100 {
685                counter.record("a".to_owned(), "b".to_owned());
686            }
687            save_transitions(&counter, &path).unwrap();
688
689            // Load with 0.5 decay
690            let s = Predictive::with_persistence(default_config(), &path, 0.5);
691            let total = s.counter().total();
692            eprintln!("total after load_decay(0.5): {total}");
693            assert!(
694                (total - 50.0).abs() < 1e-9,
695                "expected ~50.0 after 0.5 decay, got {total}"
696            );
697        }
698
699        #[test]
700        fn with_persistence_missing_file_is_cold_start() {
701            let dir = retained_fixture_dir();
702            let path = dir.path().join("nonexistent.json");
703
704            let s = Predictive::with_persistence(default_config(), &path, 0.9);
705            assert_eq!(s.counter().total(), 0.0);
706            assert!(s.predictor().is_cold_start(&"a".to_owned()));
707        }
708
709        #[test]
710        fn with_persistence_corrupted_file_is_cold_start() {
711            let dir = retained_fixture_dir();
712            let path = dir.path().join("bad.json");
713            std::fs::write(&path, "not valid json {{{").unwrap();
714
715            let s = Predictive::with_persistence(default_config(), &path, 0.9);
716            assert_eq!(s.counter().total(), 0.0);
717        }
718
719        // ====================================================================
720        // Auto-save tests (E.3 coverage)
721        // ====================================================================
722
723        #[test]
724        fn auto_save_fires_at_interval() {
725            let dir = retained_fixture_dir();
726            let path = dir.path().join("auto.json");
727
728            let config = PredictiveStrategyConfig {
729                auto_save_interval: 10,
730                min_observations: 5,
731                decay_interval: 9999, // disable decay
732                ..PredictiveStrategyConfig::default()
733            };
734            let mut s = Predictive::with_persistence(config, &path, 1.0);
735
736            // Record a transition to make it dirty.
737            s.on_screen_transition("a", "b");
738            assert!(s.is_dirty());
739            assert!(!path.exists());
740
741            // Pump maintenance ticks up to the interval.
742            for _ in 0..10 {
743                s.maintenance_tick(0);
744            }
745
746            // File should now exist and dirty flag should be cleared.
747            assert!(path.exists(), "auto-save should have written the file");
748            assert!(!s.is_dirty(), "dirty flag should be cleared after save");
749        }
750
751        #[test]
752        fn auto_save_writes_valid_json() {
753            use crate::tick_strategy::persistence::load_transitions;
754
755            let dir = retained_fixture_dir();
756            let path = dir.path().join("valid.json");
757
758            let config = PredictiveStrategyConfig {
759                auto_save_interval: 5,
760                min_observations: 5,
761                decay_interval: 9999,
762                ..PredictiveStrategyConfig::default()
763            };
764            let mut s = Predictive::with_persistence(config, &path, 1.0);
765
766            for _ in 0..10 {
767                s.on_screen_transition("x", "y");
768            }
769
770            // Trigger auto-save.
771            for _ in 0..5 {
772                s.maintenance_tick(0);
773            }
774
775            // Load the file and verify contents.
776            let loaded = load_transitions(&path).unwrap();
777            assert_eq!(loaded.count(&"x".to_owned(), &"y".to_owned()), 10.0);
778        }
779
780        #[test]
781        fn auto_save_skips_when_not_dirty() {
782            let dir = retained_fixture_dir();
783            let path = dir.path().join("nodirty.json");
784
785            let config = PredictiveStrategyConfig {
786                auto_save_interval: 5,
787                min_observations: 5,
788                decay_interval: 9999,
789                ..PredictiveStrategyConfig::default()
790            };
791            let mut s = Predictive::with_persistence(config, &path, 1.0);
792
793            // No transitions → not dirty. Pump past the interval.
794            for _ in 0..10 {
795                s.maintenance_tick(0);
796            }
797
798            assert!(!path.exists(), "no file should be written when not dirty");
799        }
800
801        #[test]
802        fn shutdown_triggers_save() {
803            let dir = retained_fixture_dir();
804            let path = dir.path().join("shutdown.json");
805
806            let config = PredictiveStrategyConfig {
807                auto_save_interval: 99999, // won't fire during test
808                min_observations: 5,
809                decay_interval: 9999,
810                ..PredictiveStrategyConfig::default()
811            };
812            let mut s = Predictive::with_persistence(config, &path, 1.0);
813
814            s.on_screen_transition("p", "q");
815            assert!(s.is_dirty());
816
817            s.shutdown();
818
819            assert!(path.exists(), "shutdown should trigger a save");
820            assert!(!s.is_dirty(), "dirty flag cleared after shutdown save");
821        }
822
823        #[test]
824        fn auto_save_no_path_is_noop() {
825            // Strategy created without persistence → no crash, no save.
826            let config = PredictiveStrategyConfig {
827                auto_save_interval: 1,
828                min_observations: 5,
829                decay_interval: 9999,
830                ..PredictiveStrategyConfig::default()
831            };
832            let mut s = Predictive::new(config);
833
834            s.on_screen_transition("a", "b");
835            assert!(s.is_dirty());
836
837            // Pump past interval — should not panic.
838            for _ in 0..5 {
839                s.maintenance_tick(0);
840            }
841            s.shutdown();
842
843            // Still dirty because no path was configured.
844            assert!(s.is_dirty());
845        }
846
847        #[test]
848        fn auto_save_bad_path_does_not_crash() {
849            let config = PredictiveStrategyConfig {
850                auto_save_interval: 5,
851                min_observations: 5,
852                decay_interval: 9999,
853                ..PredictiveStrategyConfig::default()
854            };
855            let dir = retained_fixture_dir();
856            // Point at a child of a directory that does not exist.
857            let bad_path = dir.path().join("missing-parent").join("transitions.json");
858            let mut s = Predictive::with_persistence(config, &bad_path, 1.0);
859
860            s.on_screen_transition("a", "b");
861
862            // Trigger auto-save — should log error but not panic.
863            for _ in 0..5 {
864                s.maintenance_tick(0);
865            }
866
867            // dirty remains true because save failed.
868            assert!(s.is_dirty());
869        }
870
871        #[test]
872        fn maintenance_decay_marks_strategy_dirty_and_persists_on_shutdown() {
873            use crate::tick_strategy::persistence::load_transitions;
874
875            let dir = retained_fixture_dir();
876            let path = dir.path().join("decayed-on-shutdown.json");
877
878            let config = PredictiveStrategyConfig {
879                auto_save_interval: 99999,
880                min_observations: 5,
881                decay_interval: 1,
882                decay_factor: 0.5,
883                ..PredictiveStrategyConfig::default()
884            };
885            let mut s = Predictive::with_persistence(config, &path, 1.0);
886
887            for _ in 0..20 {
888                s.on_screen_transition("a", "b");
889            }
890            s.shutdown();
891            assert!(
892                !s.is_dirty(),
893                "initial shutdown should flush transition data"
894            );
895
896            s.maintenance_tick(0);
897            assert!(
898                s.is_dirty(),
899                "maintenance decay mutates persisted state and must mark it dirty"
900            );
901
902            s.shutdown();
903            let loaded = load_transitions(&path).unwrap();
904            assert!(
905                (loaded.total() - 10.0).abs() < 1e-9,
906                "expected decayed total to persist after shutdown, got {}",
907                loaded.total()
908            );
909        }
910
911        #[test]
912        fn load_decay_marks_strategy_dirty_until_persisted() {
913            use crate::tick_strategy::persistence::{load_transitions, save_transitions};
914
915            let dir = retained_fixture_dir();
916            let path = dir.path().join("load-decay.json");
917
918            let mut counter = TransitionCounter::new();
919            for _ in 0..12 {
920                counter.record("a".to_owned(), "b".to_owned());
921            }
922            save_transitions(&counter, &path).unwrap();
923
924            let config = PredictiveStrategyConfig {
925                auto_save_interval: 99999,
926                min_observations: 5,
927                decay_interval: 9999,
928                ..PredictiveStrategyConfig::default()
929            };
930            let mut s = Predictive::with_persistence(config, &path, 0.5);
931            assert!(
932                s.is_dirty(),
933                "load-time decay changes the in-memory counter and should be persisted"
934            );
935
936            s.shutdown();
937            let loaded = load_transitions(&path).unwrap();
938            assert!(
939                (loaded.total() - 6.0).abs() < 1e-9,
940                "expected shutdown to persist the decayed total, got {}",
941                loaded.total()
942            );
943        }
944    }
945}