1#![forbid(unsafe_code)]
62
63use std::collections::VecDeque;
64use web_time::{Duration, Instant};
65
66const DEFAULT_MAX_INPUT_LATENCY_MS: u64 = 50;
68
69const DEFAULT_DOMINANCE_THRESHOLD: u32 = 3;
71
72const DEFAULT_FAIRNESS_THRESHOLD: f64 = 0.8;
74
75const FAIRNESS_WINDOW_SIZE: usize = 16;
77const FAIRNESS_THRESHOLD_EPSILON: f64 = 1e-12;
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum EventType {
83 Input,
85 Resize,
87 Tick,
89}
90
91pub type FairnessEventType = EventType;
93
94#[derive(Debug, Clone)]
96pub struct FairnessConfig {
97 pub input_priority_threshold: Duration,
99 pub enabled: bool,
101 pub dominance_threshold: u32,
103 pub fairness_threshold: f64,
105}
106
107impl Default for FairnessConfig {
108 fn default() -> Self {
109 Self {
110 input_priority_threshold: Duration::from_millis(DEFAULT_MAX_INPUT_LATENCY_MS),
111 enabled: true, dominance_threshold: DEFAULT_DOMINANCE_THRESHOLD,
113 fairness_threshold: DEFAULT_FAIRNESS_THRESHOLD,
114 }
115 }
116}
117
118impl FairnessConfig {
119 pub fn disabled() -> Self {
121 Self {
122 enabled: false,
123 ..Default::default()
124 }
125 }
126
127 #[must_use]
129 pub fn with_max_latency(mut self, latency: Duration) -> Self {
130 self.input_priority_threshold = latency;
131 self
132 }
133
134 #[must_use]
136 pub fn with_dominance_threshold(mut self, threshold: u32) -> Self {
137 self.dominance_threshold = threshold;
138 self
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum InterventionReason {
145 None,
147 InputLatency,
149 ResizeDominance,
151 FairnessIndex,
153}
154
155impl InterventionReason {
156 pub fn requires_intervention(&self) -> bool {
158 !matches!(self, InterventionReason::None)
159 }
160
161 #[must_use]
163 pub const fn as_str(self) -> &'static str {
164 match self {
165 Self::None => "none",
166 Self::InputLatency => "input_latency",
167 Self::ResizeDominance => "resize_dominance",
168 Self::FairnessIndex => "fairness_index",
169 }
170 }
171}
172
173#[derive(Debug, Clone)]
175pub struct FairnessDecision {
176 pub should_process: bool,
178 pub pending_input_latency: Option<Duration>,
180 pub reason: InterventionReason,
182 pub yield_to_input: bool,
184 pub jain_index: f64,
186}
187
188impl Default for FairnessDecision {
189 fn default() -> Self {
190 Self {
191 should_process: true,
192 pending_input_latency: None,
193 reason: InterventionReason::None,
194 yield_to_input: false,
195 jain_index: 1.0, }
197 }
198}
199
200#[derive(Debug, Clone)]
202pub struct FairnessLogEntry {
203 pub timestamp: Instant,
205 pub event_type: EventType,
207 pub duration: Duration,
209}
210
211#[derive(Debug, Clone, Default)]
213pub struct FairnessStats {
214 pub events_processed: u64,
216 pub input_events: u64,
218 pub resize_events: u64,
220 pub tick_events: u64,
222 pub total_checks: u64,
224 pub total_interventions: u64,
226 pub max_input_latency: Duration,
228}
229
230#[derive(Debug, Clone, Default)]
232pub struct InterventionCounts {
233 pub input_latency: u64,
235 pub resize_dominance: u64,
237 pub fairness_index: u64,
239}
240
241#[derive(Debug, Clone)]
243struct ProcessingRecord {
244 event_type: EventType,
246 duration: Duration,
248}
249
250#[derive(Debug)]
255pub struct InputFairnessGuard {
256 config: FairnessConfig,
257 stats: FairnessStats,
258 intervention_counts: InterventionCounts,
259
260 pending_input_arrival: Option<Instant>,
262 recent_input_arrival: Option<Instant>,
264
265 resize_dominance_count: u32,
267
268 processing_window: VecDeque<ProcessingRecord>,
270
271 input_time_us: u128,
273 resize_time_us: u128,
274}
275
276impl InputFairnessGuard {
277 pub fn new() -> Self {
279 Self::with_config(FairnessConfig::default())
280 }
281
282 pub fn with_config(config: FairnessConfig) -> Self {
284 Self {
285 config,
286 stats: FairnessStats::default(),
287 intervention_counts: InterventionCounts::default(),
288 pending_input_arrival: None,
289 recent_input_arrival: None,
290 resize_dominance_count: 0,
291 processing_window: VecDeque::with_capacity(FAIRNESS_WINDOW_SIZE),
292 input_time_us: 0,
293 resize_time_us: 0,
294 }
295 }
296
297 pub fn input_arrived(&mut self, now: Instant) {
301 if self.pending_input_arrival.is_none() {
302 self.pending_input_arrival = Some(now);
303 }
304 self.recent_input_arrival = Some(now);
306 }
307
308 pub fn check_fairness(&mut self, now: Instant) -> FairnessDecision {
312 self.stats.total_checks += 1;
313
314 if !self.config.enabled {
316 self.recent_input_arrival = None;
317 return FairnessDecision::default();
318 }
319
320 let jain = self.calculate_jain_index();
322
323 let has_pending_input = self.pending_input_arrival.is_some();
325 let pending_latency = self
326 .pending_input_arrival
327 .or(self.recent_input_arrival)
328 .map(|t| now.checked_duration_since(t).unwrap_or(Duration::ZERO));
329 if has_pending_input
330 && let Some(latency) = pending_latency
331 && latency > self.stats.max_input_latency
332 {
333 self.stats.max_input_latency = latency;
334 }
335
336 let reason = self.determine_intervention_reason(pending_latency, jain, has_pending_input);
338 let yield_to_input = reason.requires_intervention();
339
340 if yield_to_input {
341 self.stats.total_interventions += 1;
342 match reason {
343 InterventionReason::InputLatency => {
344 self.intervention_counts.input_latency += 1;
345 }
346 InterventionReason::ResizeDominance => {
347 self.intervention_counts.resize_dominance += 1;
348 }
349 InterventionReason::FairnessIndex => {
350 self.intervention_counts.fairness_index += 1;
351 }
352 InterventionReason::None => {}
353 }
354 self.resize_dominance_count = 0;
356 }
357
358 let decision = FairnessDecision {
359 should_process: !yield_to_input,
360 pending_input_latency: if has_pending_input {
361 pending_latency
362 } else {
363 None
364 },
365 reason,
366 yield_to_input,
367 jain_index: jain,
368 };
369
370 self.recent_input_arrival = None;
372
373 decision
374 }
375
376 pub fn event_processed(&mut self, event_type: EventType, duration: Duration, _now: Instant) {
378 self.stats.events_processed += 1;
379 match event_type {
380 EventType::Input => self.stats.input_events += 1,
381 EventType::Resize => self.stats.resize_events += 1,
382 EventType::Tick => self.stats.tick_events += 1,
383 }
384
385 if !self.config.enabled {
387 return;
388 }
389
390 let record = ProcessingRecord {
392 event_type,
393 duration,
394 };
395
396 if self.processing_window.len() >= FAIRNESS_WINDOW_SIZE
398 && let Some(old) = self.processing_window.pop_front()
399 {
400 match old.event_type {
401 EventType::Input => {
402 self.input_time_us =
403 self.input_time_us.saturating_sub(old.duration.as_micros());
404 }
405 EventType::Resize => {
406 self.resize_time_us =
407 self.resize_time_us.saturating_sub(old.duration.as_micros());
408 }
409 EventType::Tick => {}
410 }
411 }
412
413 match event_type {
415 EventType::Input => {
416 self.input_time_us = self.input_time_us.saturating_add(duration.as_micros());
417 self.pending_input_arrival = None;
418 self.resize_dominance_count = 0; }
420 EventType::Resize => {
421 self.resize_time_us = self.resize_time_us.saturating_add(duration.as_micros());
422 self.resize_dominance_count = self.resize_dominance_count.saturating_add(1);
423 }
424 EventType::Tick => {}
425 }
426
427 self.processing_window.push_back(record);
428 }
429
430 fn calculate_jain_index(&self) -> f64 {
432 let x = self.input_time_us as f64;
434 let y = self.resize_time_us as f64;
435
436 if x == 0.0 && y == 0.0 {
437 return 1.0; }
439
440 let sum = x + y;
441 let sum_sq = x * x + y * y;
442
443 if sum_sq == 0.0 {
444 return 1.0;
445 }
446
447 (sum * sum) / (2.0 * sum_sq)
448 }
449
450 fn determine_intervention_reason(
452 &self,
453 pending_latency: Option<Duration>,
454 jain: f64,
455 has_pending_input: bool,
456 ) -> InterventionReason {
457 if has_pending_input
459 && let Some(latency) = pending_latency
460 && latency >= self.config.input_priority_threshold
461 {
462 return InterventionReason::InputLatency;
463 }
464
465 if has_pending_input && self.resize_dominance_count >= self.config.dominance_threshold {
467 return InterventionReason::ResizeDominance;
468 }
469
470 if has_pending_input
479 && jain + FAIRNESS_THRESHOLD_EPSILON < self.config.fairness_threshold
480 && self.resize_time_us > self.input_time_us
481 {
482 return InterventionReason::FairnessIndex;
483 }
484
485 InterventionReason::None
486 }
487
488 pub fn stats(&self) -> &FairnessStats {
490 &self.stats
491 }
492
493 pub fn intervention_counts(&self) -> &InterventionCounts {
495 &self.intervention_counts
496 }
497
498 pub fn config(&self) -> &FairnessConfig {
500 &self.config
501 }
502
503 pub fn resize_dominance_count(&self) -> u32 {
505 self.resize_dominance_count
506 }
507
508 pub fn is_enabled(&self) -> bool {
510 self.config.enabled
511 }
512
513 pub fn jain_index(&self) -> f64 {
515 self.calculate_jain_index()
516 }
517
518 pub fn has_pending_input(&self) -> bool {
520 self.pending_input_arrival.is_some()
521 }
522
523 #[must_use]
526 pub fn should_yield_resize(&self, now: Instant) -> bool {
527 if !self.config.enabled {
528 return false;
529 }
530 let Some(arrival) = self.pending_input_arrival else {
531 return false;
532 };
533 let pending_latency = Some(
534 now.checked_duration_since(arrival)
535 .unwrap_or(Duration::ZERO),
536 );
537 let jain = self.calculate_jain_index();
538 self.determine_intervention_reason(pending_latency, jain, true)
539 .requires_intervention()
540 }
541
542 pub fn reset(&mut self) {
544 self.pending_input_arrival = None;
545 self.recent_input_arrival = None;
546 self.resize_dominance_count = 0;
547 self.processing_window.clear();
548 self.input_time_us = 0;
549 self.resize_time_us = 0;
550 self.stats = FairnessStats::default();
551 self.intervention_counts = InterventionCounts::default();
552 }
553}
554
555impl Default for InputFairnessGuard {
556 fn default() -> Self {
557 Self::new()
558 }
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 #[test]
566 fn default_config_is_enabled() {
567 let config = FairnessConfig::default();
568 assert!(config.enabled);
569 }
570
571 #[test]
572 fn default_fairness_threshold_is_above_two_class_floor() {
573 let config = FairnessConfig::default();
574 assert!(config.fairness_threshold > 0.5 + FAIRNESS_THRESHOLD_EPSILON);
577 }
578
579 #[test]
580 fn disabled_config() {
581 let config = FairnessConfig::disabled();
582 assert!(!config.enabled);
583 }
584
585 #[test]
586 fn default_decision_allows_processing() {
587 let mut guard = InputFairnessGuard::default();
588 let decision = guard.check_fairness(Instant::now());
589 assert!(decision.should_process);
590 }
591
592 #[test]
593 fn event_processing_updates_stats() {
594 let mut guard = InputFairnessGuard::default();
595 let now = Instant::now();
596
597 guard.event_processed(EventType::Input, Duration::from_millis(10), now);
598 guard.event_processed(EventType::Resize, Duration::from_millis(5), now);
599 guard.event_processed(EventType::Tick, Duration::from_millis(1), now);
600
601 let stats = guard.stats();
602 assert_eq!(stats.events_processed, 3);
603 assert_eq!(stats.input_events, 1);
604 assert_eq!(stats.resize_events, 1);
605 assert_eq!(stats.tick_events, 1);
606 }
607
608 #[test]
609 fn event_processing_duration_counters_do_not_truncate() {
610 let mut guard = InputFairnessGuard::default();
611 let now = Instant::now();
612
613 guard.event_processed(EventType::Input, Duration::MAX, now);
614 guard.event_processed(EventType::Input, Duration::from_micros(1), now);
615 guard.event_processed(EventType::Resize, Duration::MAX, now);
616 guard.event_processed(EventType::Resize, Duration::from_micros(1), now);
617
618 let expected = Duration::MAX.as_micros().saturating_add(1);
619 assert_eq!(guard.input_time_us, expected);
620 assert_eq!(guard.resize_time_us, expected);
621 }
622
623 #[test]
624 fn test_jain_index_perfect_fairness() {
625 let mut guard = InputFairnessGuard::new();
626 let now = Instant::now();
627
628 guard.event_processed(EventType::Input, Duration::from_millis(10), now);
630 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
631
632 let jain = guard.jain_index();
633 assert!((jain - 1.0).abs() < 0.001, "Expected ~1.0, got {}", jain);
634 }
635
636 #[test]
637 fn test_jain_index_unfair() {
638 let mut guard = InputFairnessGuard::new();
639 let now = Instant::now();
640
641 guard.event_processed(EventType::Input, Duration::from_millis(1), now);
643 guard.event_processed(EventType::Resize, Duration::from_millis(100), now);
644
645 let jain = guard.jain_index();
646 assert!(jain < 0.6, "Expected unfair index < 0.6, got {}", jain);
648 }
649
650 #[test]
651 fn test_jain_index_empty() {
652 let guard = InputFairnessGuard::new();
653 let jain = guard.jain_index();
654 assert!((jain - 1.0).abs() < 0.001, "Empty should be fair (1.0)");
655 }
656
657 #[test]
658 fn test_latency_threshold_intervention() {
659 let config = FairnessConfig::default().with_max_latency(Duration::from_millis(20));
660 let mut guard = InputFairnessGuard::with_config(config);
661
662 let start = Instant::now();
663 guard.input_arrived(start);
664
665 let decision = guard.check_fairness(start + Duration::from_millis(25));
667 assert!(decision.yield_to_input);
668 assert_eq!(decision.reason, InterventionReason::InputLatency);
669 }
670
671 #[test]
672 fn test_resize_dominance_intervention() {
673 let config = FairnessConfig::default().with_dominance_threshold(2);
674 let mut guard = InputFairnessGuard::with_config(config);
675 let now = Instant::now();
676
677 guard.input_arrived(now);
679
680 guard.event_processed(EventType::Resize, Duration::from_millis(5), now);
682 guard.event_processed(EventType::Resize, Duration::from_millis(5), now);
683
684 let decision = guard.check_fairness(now);
685 assert!(decision.yield_to_input);
686 assert_eq!(decision.reason, InterventionReason::ResizeDominance);
687 }
688
689 #[test]
690 fn test_no_intervention_when_fair() {
691 let mut guard = InputFairnessGuard::new();
692 let now = Instant::now();
693
694 guard.event_processed(EventType::Input, Duration::from_millis(10), now);
696 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
697
698 let decision = guard.check_fairness(now);
699 assert!(!decision.yield_to_input);
700 assert_eq!(decision.reason, InterventionReason::None);
701 }
702
703 #[test]
704 fn test_fairness_index_intervention() {
705 let config = FairnessConfig {
706 input_priority_threshold: Duration::from_secs(10),
707 dominance_threshold: 100,
708 fairness_threshold: 0.9,
709 ..Default::default()
710 };
711 let mut guard = InputFairnessGuard::with_config(config);
712 let now = Instant::now();
713
714 guard.event_processed(EventType::Input, Duration::from_millis(1), now);
717 guard.input_arrived(now);
718 guard.event_processed(EventType::Resize, Duration::from_millis(100), now);
719
720 let decision = guard.check_fairness(now + Duration::from_millis(1));
721 assert!(decision.yield_to_input);
722 assert_eq!(decision.reason, InterventionReason::FairnessIndex);
723 }
724
725 #[test]
726 fn fairness_index_triggers_when_input_is_starved_in_window() {
727 let config = FairnessConfig {
728 input_priority_threshold: Duration::from_secs(10),
729 dominance_threshold: 100,
730 fairness_threshold: 0.9,
731 ..Default::default()
732 };
733 let mut guard = InputFairnessGuard::with_config(config);
734 let now = Instant::now();
735
736 guard.input_arrived(now);
739 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
740
741 let decision = guard.check_fairness(now);
742 assert_eq!(decision.reason, InterventionReason::FairnessIndex);
743 assert!(decision.yield_to_input);
744 }
745
746 #[test]
747 fn test_dominance_reset_on_input() {
748 let mut guard = InputFairnessGuard::new();
749 let now = Instant::now();
750
751 guard.event_processed(EventType::Resize, Duration::from_millis(5), now);
753 guard.event_processed(EventType::Resize, Duration::from_millis(5), now);
754 assert_eq!(guard.resize_dominance_count, 2);
755
756 guard.event_processed(EventType::Input, Duration::from_millis(5), now);
758 assert_eq!(guard.resize_dominance_count, 0);
759 }
760
761 #[test]
762 fn test_pending_input_cleared_on_processing() {
763 let mut guard = InputFairnessGuard::new();
764 let now = Instant::now();
765
766 guard.input_arrived(now);
767 assert!(guard.has_pending_input());
768
769 guard.event_processed(EventType::Input, Duration::from_millis(5), now);
770 assert!(!guard.has_pending_input());
771 }
772
773 #[test]
774 fn no_intervention_without_pending_input_under_resize_flood() {
775 let config = FairnessConfig {
776 input_priority_threshold: Duration::from_millis(1),
777 dominance_threshold: 1,
778 fairness_threshold: 0.99,
779 enabled: true,
780 };
781 let mut guard = InputFairnessGuard::with_config(config);
782 let now = Instant::now();
783
784 guard.event_processed(EventType::Resize, Duration::from_millis(50), now);
785 let decision = guard.check_fairness(now + Duration::from_millis(50));
786
787 assert!(!decision.yield_to_input);
788 assert_eq!(decision.reason, InterventionReason::None);
789 assert!(decision.pending_input_latency.is_none());
790 }
791
792 #[test]
793 fn processed_input_does_not_cause_spurious_followup_intervention() {
794 let config = FairnessConfig {
795 input_priority_threshold: Duration::from_millis(1),
796 dominance_threshold: 1,
797 fairness_threshold: 0.99,
798 enabled: true,
799 };
800 let mut guard = InputFairnessGuard::with_config(config);
801 let now = Instant::now();
802
803 guard.input_arrived(now);
804 guard.event_processed(EventType::Input, Duration::from_millis(1), now);
805 guard.event_processed(EventType::Resize, Duration::from_millis(50), now);
806
807 let decision = guard.check_fairness(now + Duration::from_millis(50));
808 assert!(!decision.yield_to_input);
809 assert_eq!(decision.reason, InterventionReason::None);
810 assert!(decision.pending_input_latency.is_none());
811 }
812
813 #[test]
814 fn test_stats_tracking() {
815 let mut guard = InputFairnessGuard::new();
816 let now = Instant::now();
817
818 guard.check_fairness(now);
820 guard.check_fairness(now);
821
822 assert_eq!(guard.stats().total_checks, 2);
823 }
824
825 #[test]
826 fn test_sliding_window_eviction() {
827 let mut guard = InputFairnessGuard::new();
828 let now = Instant::now();
829
830 for _ in 0..(FAIRNESS_WINDOW_SIZE + 5) {
832 guard.event_processed(EventType::Input, Duration::from_millis(1), now);
833 }
834
835 assert_eq!(guard.processing_window.len(), FAIRNESS_WINDOW_SIZE);
836 }
837
838 #[test]
839 fn test_reset() {
840 let mut guard = InputFairnessGuard::new();
841 let now = Instant::now();
842
843 guard.input_arrived(now);
844 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
845 guard.check_fairness(now);
846
847 guard.reset();
848
849 assert!(!guard.has_pending_input());
850 assert_eq!(guard.resize_dominance_count, 0);
851 assert_eq!(guard.stats().total_checks, 0);
852 assert!(guard.processing_window.is_empty());
853 }
854
855 #[test]
858 fn test_invariant_jain_index_bounds() {
859 let mut guard = InputFairnessGuard::new();
861 let now = Instant::now();
862
863 for (input_ms, resize_ms) in [(1, 1), (1, 100), (100, 1), (50, 50), (0, 100), (100, 0)] {
865 guard.reset();
866 if input_ms > 0 {
867 guard.event_processed(EventType::Input, Duration::from_millis(input_ms), now);
868 }
869 if resize_ms > 0 {
870 guard.event_processed(EventType::Resize, Duration::from_millis(resize_ms), now);
871 }
872
873 let jain = guard.jain_index();
874 assert!(
875 (0.5..=1.0).contains(&jain),
876 "Jain index {} out of bounds for input={}, resize={}",
877 jain,
878 input_ms,
879 resize_ms
880 );
881 }
882 }
883
884 #[test]
885 fn test_invariant_intervention_resets_dominance() {
886 let config = FairnessConfig::default().with_dominance_threshold(2);
887 let mut guard = InputFairnessGuard::with_config(config);
888 let now = Instant::now();
889
890 guard.input_arrived(now);
892 guard.event_processed(EventType::Resize, Duration::from_millis(5), now);
893 guard.event_processed(EventType::Resize, Duration::from_millis(5), now);
894
895 let decision = guard.check_fairness(now);
897 assert!(decision.yield_to_input);
898 assert_eq!(guard.resize_dominance_count, 0);
899 }
900
901 #[test]
902 fn test_invariant_monotonic_stats() {
903 let mut guard = InputFairnessGuard::new();
904 let now = Instant::now();
905
906 let mut prev_checks = 0u64;
907 for _ in 0..10 {
908 guard.check_fairness(now);
909 assert!(guard.stats().total_checks > prev_checks);
910 prev_checks = guard.stats().total_checks;
911 }
912 }
913
914 #[test]
915 fn test_disabled_returns_no_intervention() {
916 let config = FairnessConfig::disabled();
917 let mut guard = InputFairnessGuard::with_config(config);
918 let now = Instant::now();
919
920 guard.input_arrived(now);
922 guard.event_processed(EventType::Resize, Duration::from_millis(100), now);
923 guard.event_processed(EventType::Resize, Duration::from_millis(100), now);
924 guard.event_processed(EventType::Resize, Duration::from_millis(100), now);
925
926 let decision = guard.check_fairness(now);
927 assert!(!decision.yield_to_input);
928 assert_eq!(decision.reason, InterventionReason::None);
929 }
930
931 #[test]
936 fn fairness_decision_fields_match_state() {
937 let mut guard = InputFairnessGuard::new();
938 let now = Instant::now();
939
940 let d = guard.check_fairness(now);
942 assert!(d.pending_input_latency.is_none());
943 assert_eq!(d.reason, InterventionReason::None);
944 assert!(!d.yield_to_input);
945 assert!(d.should_process);
946 assert!((d.jain_index - 1.0).abs() < f64::EPSILON);
947
948 guard.input_arrived(now);
950 let later = now + Duration::from_millis(10);
951 let d = guard.check_fairness(later);
952 assert!(d.pending_input_latency.is_some());
953 let lat = d.pending_input_latency.unwrap();
954 assert!(lat >= Duration::from_millis(10));
955 }
956
957 #[test]
958 fn jain_index_exact_values() {
959 let mut guard = InputFairnessGuard::new();
960 let now = Instant::now();
961
962 guard.event_processed(EventType::Input, Duration::from_millis(100), now);
964 guard.event_processed(EventType::Resize, Duration::from_millis(100), now);
965 let j = guard.jain_index();
966 assert!(
967 (j - 1.0).abs() < 1e-9,
968 "Equal allocation should yield 1.0, got {j}"
969 );
970
971 guard.reset();
972
973 guard.event_processed(EventType::Input, Duration::from_millis(1), now);
976 guard.event_processed(EventType::Resize, Duration::from_millis(100), now);
977 let j = guard.jain_index();
978 assert!(j > 0.5, "F should be > 0.5 for two types, got {j}");
979 assert!(j < 0.6, "F should be < 0.6 for 1:100 ratio, got {j}");
980 }
981
982 #[test]
983 fn jain_index_bounded_across_ratios() {
984 let ratios: &[(u64, u64)] = &[
986 (0, 0),
987 (1, 0),
988 (0, 1),
989 (1, 1),
990 (1, 1000),
991 (1000, 1),
992 (50, 50),
993 (100, 1),
994 (999, 1),
995 ];
996 for &(input_ms, resize_ms) in ratios {
997 let mut guard = InputFairnessGuard::new();
998 let now = Instant::now();
999 if input_ms > 0 {
1000 guard.event_processed(EventType::Input, Duration::from_millis(input_ms), now);
1001 }
1002 if resize_ms > 0 {
1003 guard.event_processed(EventType::Resize, Duration::from_millis(resize_ms), now);
1004 }
1005 let j = guard.jain_index();
1006 assert!(
1007 (0.5..=1.0).contains(&j),
1008 "Jain index out of bounds for ({input_ms}, {resize_ms}): {j}"
1009 );
1010 }
1011 }
1012
1013 #[test]
1014 fn intervention_reason_priority_order() {
1015 let config = FairnessConfig {
1017 input_priority_threshold: Duration::from_millis(20),
1018 dominance_threshold: 2,
1019 fairness_threshold: 0.9, enabled: true,
1021 };
1022 let mut guard = InputFairnessGuard::with_config(config);
1023 let now = Instant::now();
1024
1025 guard.input_arrived(now);
1028 guard.event_processed(EventType::Resize, Duration::from_millis(50), now);
1030 guard.event_processed(EventType::Resize, Duration::from_millis(50), now);
1031 guard.event_processed(EventType::Resize, Duration::from_millis(50), now);
1032
1033 let later = now + Duration::from_millis(100);
1035 let d = guard.check_fairness(later);
1036
1037 assert_eq!(
1039 d.reason,
1040 InterventionReason::InputLatency,
1041 "InputLatency should have highest priority"
1042 );
1043 assert!(d.yield_to_input);
1044 }
1045
1046 #[test]
1047 fn resize_dominance_triggers_after_threshold() {
1048 let config = FairnessConfig {
1049 dominance_threshold: 3,
1050 fairness_threshold: 0.5,
1053 ..FairnessConfig::default()
1054 };
1055 let mut guard = InputFairnessGuard::with_config(config);
1056 let now = Instant::now();
1057
1058 guard.input_arrived(now);
1060
1061 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
1063 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
1064 let d = guard.check_fairness(now);
1065 assert_eq!(d.reason, InterventionReason::None);
1066
1067 guard.input_arrived(now);
1069
1070 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
1072 let d = guard.check_fairness(now);
1073 assert_eq!(d.reason, InterventionReason::ResizeDominance);
1074 assert!(d.yield_to_input);
1075 }
1076
1077 #[test]
1078 fn intervention_counts_track_each_reason() {
1079 let config = FairnessConfig {
1080 input_priority_threshold: Duration::from_millis(10),
1081 dominance_threshold: 2,
1082 fairness_threshold: 0.8,
1083 enabled: true,
1084 };
1085 let mut guard = InputFairnessGuard::with_config(config);
1086 let now = Instant::now();
1087
1088 guard.input_arrived(now);
1090 let later = now + Duration::from_millis(50);
1091 guard.check_fairness(later);
1092
1093 let counts = guard.intervention_counts();
1094 assert_eq!(counts.input_latency, 1);
1095 assert_eq!(counts.resize_dominance, 0);
1096 assert_eq!(counts.fairness_index, 0);
1097
1098 guard.input_arrived(now);
1100 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
1101 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
1102 guard.check_fairness(now);
1103
1104 let counts = guard.intervention_counts();
1105 assert_eq!(counts.resize_dominance, 1);
1106 }
1107
1108 #[test]
1109 fn fairness_stable_across_repeated_check_cycles() {
1110 let mut guard = InputFairnessGuard::new();
1111 let now = Instant::now();
1112
1113 for i in 0..50 {
1115 let t = now + Duration::from_millis(i * 16);
1116 guard.event_processed(EventType::Input, Duration::from_millis(5), t);
1117 guard.event_processed(EventType::Resize, Duration::from_millis(5), t);
1118 let d = guard.check_fairness(t);
1119
1120 assert!(!d.yield_to_input, "Unexpected intervention at cycle {i}");
1122 assert!(
1124 d.jain_index > 0.95,
1125 "Jain index degraded at cycle {i}: {}",
1126 d.jain_index
1127 );
1128 }
1129
1130 let stats = guard.stats();
1131 assert_eq!(stats.events_processed, 100);
1132 assert_eq!(stats.input_events, 50);
1133 assert_eq!(stats.resize_events, 50);
1134 assert_eq!(stats.total_interventions, 0);
1135 }
1136
1137 #[test]
1138 fn fairness_index_degrades_under_resize_flood() {
1139 let mut guard = InputFairnessGuard::new();
1140 let now = Instant::now();
1141
1142 guard.event_processed(EventType::Input, Duration::from_millis(5), now);
1144 for _ in 0..15 {
1145 guard.event_processed(EventType::Resize, Duration::from_millis(20), now);
1146 }
1147
1148 let j = guard.jain_index();
1149 assert!(
1152 j < 0.55,
1153 "Jain index should be low under resize flood, got {j}"
1154 );
1155 }
1156
1157 #[test]
1158 fn max_input_latency_tracked_across_checks() {
1159 let mut guard = InputFairnessGuard::new();
1160 let now = Instant::now();
1161
1162 guard.input_arrived(now);
1163 guard.check_fairness(now + Duration::from_millis(30));
1164
1165 guard.input_arrived(now + Duration::from_millis(50));
1166 guard.check_fairness(now + Duration::from_millis(100));
1167
1168 let stats = guard.stats();
1169 assert!(stats.max_input_latency >= Duration::from_millis(30));
1171 }
1172
1173 #[test]
1174 fn max_input_latency_ignores_recent_when_no_pending_input() {
1175 let mut guard = InputFairnessGuard::new();
1176 let now = Instant::now();
1177
1178 guard.input_arrived(now);
1179 guard.event_processed(EventType::Input, Duration::from_millis(1), now);
1180
1181 guard.check_fairness(now + Duration::from_millis(100));
1183 assert_eq!(guard.stats().max_input_latency, Duration::ZERO);
1184 }
1185
1186 #[test]
1187 fn sliding_window_evicts_oldest_entries() {
1188 let mut guard = InputFairnessGuard::new();
1189 let now = Instant::now();
1190
1191 for _ in 0..16 {
1194 guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
1195 }
1196
1197 for _ in 0..16 {
1199 guard.event_processed(EventType::Input, Duration::from_millis(10), now);
1200 }
1201
1202 let j = guard.jain_index();
1205 assert!(
1207 j < 0.6,
1208 "After full eviction to input-only, Jain should be ~0.5, got {j}"
1209 );
1210 }
1211
1212 #[test]
1213 fn custom_config_thresholds_work() {
1214 let config = FairnessConfig {
1215 input_priority_threshold: Duration::from_millis(200),
1216 dominance_threshold: 10,
1217 fairness_threshold: 0.3,
1218 enabled: true,
1219 };
1220 let mut guard = InputFairnessGuard::with_config(config);
1221 let now = Instant::now();
1222
1223 guard.input_arrived(now);
1225 guard.event_processed(EventType::Resize, Duration::from_millis(50), now);
1226 guard.event_processed(EventType::Resize, Duration::from_millis(50), now);
1227 guard.event_processed(EventType::Resize, Duration::from_millis(50), now);
1228
1229 let later = now + Duration::from_millis(100);
1230 let d = guard.check_fairness(later);
1231 assert_eq!(d.reason, InterventionReason::None);
1232 assert!(!d.yield_to_input);
1233 }
1234}