1use 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#[derive(Debug, Clone)]
21pub struct PredictiveStrategyConfig {
22 pub allocation: TickAllocation,
24 pub fallback_divisor: u64,
26 pub min_observations: u64,
28 pub decay_factor: f64,
30 pub decay_interval: u64,
32 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#[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 cached_divisors: HashMap<String, u64>,
66 cached_for_screen: Option<String>,
68 ticks_since_decay: u64,
70 ticks_since_save: u64,
72 dirty: bool,
74 #[cfg(feature = "state-persistence")]
76 persistence_path: Option<PathBuf>,
77}
78
79impl Predictive {
80 #[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 #[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 #[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 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 strategy.persistence_path = Some(path.to_path_buf());
197 strategy
198 }
199
200 #[must_use]
202 pub fn predictor(&self) -> &MarkovPredictor<String> {
203 &self.predictor
204 }
205
206 #[must_use]
208 pub fn counter(&self) -> &TransitionCounter<String> {
209 self.predictor.counter()
210 }
211
212 #[must_use]
214 pub fn is_dirty(&self) -> bool {
215 self.dirty
216 }
217
218 #[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 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 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 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 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 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 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 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#[cfg(test)]
451mod tests {
452 use super::*;
453
454 fn default_config() -> PredictiveStrategyConfig {
455 PredictiveStrategyConfig {
456 min_observations: 5, 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 assert_eq!(s.should_tick("x", 0, "a"), TickDecision::Tick); 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); }
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 for _ in 0..20 {
484 s.on_screen_transition("a", "b");
485 }
486 for _ in 0..2 {
488 s.on_screen_transition("a", "c");
489 }
490
491 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 s.should_tick("x", 1, "b");
518 let cached = s.cached_for_screen.clone();
519
520 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 let div = s
532 .cached_divisors
533 .get("unknown")
534 .copied()
535 .unwrap_or(s.fallback_divisor);
536 assert_eq!(div, 10); }
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 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 for _ in 0..30 {
615 s.on_screen_transition("a", "b");
616 }
617 s.on_screen_transition("a", "c");
618
619 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 #[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 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 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 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 #[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, ..PredictiveStrategyConfig::default()
733 };
734 let mut s = Predictive::with_persistence(config, &path, 1.0);
735
736 s.on_screen_transition("a", "b");
738 assert!(s.is_dirty());
739 assert!(!path.exists());
740
741 for _ in 0..10 {
743 s.maintenance_tick(0);
744 }
745
746 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 for _ in 0..5 {
772 s.maintenance_tick(0);
773 }
774
775 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 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, 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 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 for _ in 0..5 {
839 s.maintenance_tick(0);
840 }
841 s.shutdown();
842
843 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 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 for _ in 0..5 {
864 s.maintenance_tick(0);
865 }
866
867 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}