Skip to main content

ftui_runtime/
input_fairness.rs

1//! Input Fairness Guard (bd-1rz0.17)
2//!
3//! Prevents resize scheduling from starving input/keyboard events by monitoring
4//! event latencies and intervening when fairness thresholds are violated.
5//!
6//! # Design Philosophy
7//!
8//! In a responsive TUI, keyboard input must feel instantaneous. Even during rapid
9//! resize sequences (e.g., user dragging terminal corner), keystrokes should be
10//! processed without noticeable delay. This module enforces that guarantee.
11//!
12//! # Mathematical Model
13//!
14//! ## Jain's Fairness Index
15//!
16//! We track fairness across event types using Jain's fairness index:
17//! ```text
18//! F(x₁..xₙ) = (Σxᵢ)² / (n × Σxᵢ²)
19//! ```
20//!
21//! When applied to processing time allocations:
22//! - F = 1.0: Perfect fairness (equal allocation)
23//! - F = 1/n: Maximal unfairness (all time to one type)
24//!
25//! We maintain `F ≥ fairness_threshold` (default 0.8 for two event types).
26//!
27//! ## Starvation Detection
28//!
29//! Input starvation is detected when pending input is present and:
30//! 1. Input latency exceeds `input_priority_threshold` (default 50ms), OR
31//! 2. Consecutive resize-dominated cycles reach `dominance_threshold` (default 3), OR
32//! 3. Jain's fairness index `F < fairness_threshold` (default 0.8) with resize time exceeding input time
33//!
34//! ## Intervention
35//!
36//! When starvation is detected:
37//! 1. Defer applying the pending coalesced resize for that cycle (`FairnessDecision::yield_to_input = true`) so queued input and its frame render proceed first
38//! 2. Log the intervention (`fairness_decision` evidence with `decision = "yield"`)
39//! 3. Reset the resize dominance counter
40//!
41//! # Invariants
42//!
43//! 1. **Bounded Input Latency**: Input events are processed within `max_input_latency`
44//!    from their arrival time, guaranteed by intervention mechanism.
45//!
46//! 2. **Work Conservation**: The guard never blocks event processing; it only
47//!    changes priority ordering between event types.
48//!
49//! 3. **Monotonic Time**: All timestamps use `Instant` (monotonic) to prevent
50//!    clock drift from causing priority inversions.
51//!
52//! # Failure Modes
53//!
54//! | Condition | Behavior | Rationale |
55//! |-----------|----------|-----------|
56//! | Clock drift | Use monotonic `Instant` | Prevent priority inversion |
57//! | Resize storm | Force input processing | Bounded latency guarantee |
58//! | Input flood | Yield to BatchController | Not our concern; batch handles it |
59//! | Zero events | Return default (fair) | Safe default, no intervention |
60
61#![forbid(unsafe_code)]
62
63use std::collections::VecDeque;
64use web_time::{Duration, Instant};
65
66/// Default maximum input latency before intervention (50ms).
67const DEFAULT_MAX_INPUT_LATENCY_MS: u64 = 50;
68
69/// Default resize dominance threshold before intervention.
70const DEFAULT_DOMINANCE_THRESHOLD: u32 = 3;
71
72/// Default fairness threshold (Jain's index).
73const DEFAULT_FAIRNESS_THRESHOLD: f64 = 0.8;
74
75/// Sliding window size for fairness calculation.
76const FAIRNESS_WINDOW_SIZE: usize = 16;
77/// Numerical tolerance for fairness-threshold comparisons.
78const FAIRNESS_THRESHOLD_EPSILON: f64 = 1e-12;
79
80/// Event type for fairness classification.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum EventType {
83    /// User input events (keyboard, mouse).
84    Input,
85    /// Terminal resize events.
86    Resize,
87    /// Timer tick events.
88    Tick,
89}
90
91/// Type alias for compatibility with program.rs
92pub type FairnessEventType = EventType;
93
94/// Configuration for input fairness.
95#[derive(Debug, Clone)]
96pub struct FairnessConfig {
97    /// Maximum latency for input events before they get priority.
98    pub input_priority_threshold: Duration,
99    /// Enable fairness scheduling.
100    pub enabled: bool,
101    /// Number of consecutive resize-dominated cycles before intervention.
102    pub dominance_threshold: u32,
103    /// Minimum Jain's fairness index to maintain.
104    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, // Enable by default for bd-1rz0.17
112            dominance_threshold: DEFAULT_DOMINANCE_THRESHOLD,
113            fairness_threshold: DEFAULT_FAIRNESS_THRESHOLD,
114        }
115    }
116}
117
118impl FairnessConfig {
119    /// Create config with fairness disabled.
120    pub fn disabled() -> Self {
121        Self {
122            enabled: false,
123            ..Default::default()
124        }
125    }
126
127    /// Create config with custom max input latency.
128    #[must_use]
129    pub fn with_max_latency(mut self, latency: Duration) -> Self {
130        self.input_priority_threshold = latency;
131        self
132    }
133
134    /// Create config with custom dominance threshold.
135    #[must_use]
136    pub fn with_dominance_threshold(mut self, threshold: u32) -> Self {
137        self.dominance_threshold = threshold;
138        self
139    }
140}
141
142/// Intervention reason for fairness.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum InterventionReason {
145    /// No intervention needed.
146    None,
147    /// Input latency exceeded threshold.
148    InputLatency,
149    /// Resize dominated too many consecutive cycles.
150    ResizeDominance,
151    /// Jain's fairness index dropped below threshold.
152    FairnessIndex,
153}
154
155impl InterventionReason {
156    /// Whether this reason requires intervention.
157    pub fn requires_intervention(&self) -> bool {
158        !matches!(self, InterventionReason::None)
159    }
160
161    /// Stable string representation for logs.
162    #[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/// Fairness decision returned by the guard.
174#[derive(Debug, Clone)]
175pub struct FairnessDecision {
176    /// Whether to proceed with the event.
177    pub should_process: bool,
178    /// Pending input latency if any.
179    pub pending_input_latency: Option<Duration>,
180    /// Reason for the decision.
181    pub reason: InterventionReason,
182    /// Whether to yield to input processing.
183    pub yield_to_input: bool,
184    /// Jain fairness index (0.0-1.0).
185    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, // Perfect fairness when no events
196        }
197    }
198}
199
200/// Fairness log entry for telemetry.
201#[derive(Debug, Clone)]
202pub struct FairnessLogEntry {
203    /// Timestamp of the entry.
204    pub timestamp: Instant,
205    /// Event type processed.
206    pub event_type: EventType,
207    /// Duration of processing.
208    pub duration: Duration,
209}
210
211/// Statistics about fairness scheduling.
212#[derive(Debug, Clone, Default)]
213pub struct FairnessStats {
214    /// Total events processed.
215    pub events_processed: u64,
216    /// Input events processed.
217    pub input_events: u64,
218    /// Resize events processed.
219    pub resize_events: u64,
220    /// Tick events processed.
221    pub tick_events: u64,
222    /// Total fairness checks.
223    pub total_checks: u64,
224    /// Total interventions triggered.
225    pub total_interventions: u64,
226    /// Maximum observed input latency.
227    pub max_input_latency: Duration,
228}
229
230/// Counts of interventions by type.
231#[derive(Debug, Clone, Default)]
232pub struct InterventionCounts {
233    /// Input latency interventions.
234    pub input_latency: u64,
235    /// Resize dominance interventions.
236    pub resize_dominance: u64,
237    /// Fairness index interventions.
238    pub fairness_index: u64,
239}
240
241/// Record of an event processing cycle.
242#[derive(Debug, Clone)]
243struct ProcessingRecord {
244    /// Event type processed.
245    event_type: EventType,
246    /// Processing duration.
247    duration: Duration,
248}
249
250/// Guard for input fairness scheduling.
251///
252/// Monitors event processing fairness and triggers interventions when input
253/// events are at risk of starvation due to resize processing.
254#[derive(Debug)]
255pub struct InputFairnessGuard {
256    config: FairnessConfig,
257    stats: FairnessStats,
258    intervention_counts: InterventionCounts,
259
260    /// Time when an input event arrived but hasn't been fully processed.
261    pending_input_arrival: Option<Instant>,
262    /// Most recent input arrival since the last fairness check.
263    recent_input_arrival: Option<Instant>,
264
265    /// Number of consecutive resize-dominated cycles.
266    resize_dominance_count: u32,
267
268    /// Sliding window of processing records for fairness calculation.
269    processing_window: VecDeque<ProcessingRecord>,
270
271    /// Accumulated processing time by event type (for Jain's index).
272    input_time_us: u128,
273    resize_time_us: u128,
274}
275
276impl InputFairnessGuard {
277    /// Create a new fairness guard with default configuration.
278    pub fn new() -> Self {
279        Self::with_config(FairnessConfig::default())
280    }
281
282    /// Create a new fairness guard with the given configuration.
283    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    /// Signal that an input event has arrived.
298    ///
299    /// Call this when an input event is received but before processing.
300    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        // Track the most recent arrival seen since the last fairness check.
305        self.recent_input_arrival = Some(now);
306    }
307
308    /// Check fairness and return a decision.
309    ///
310    /// Call this before processing a resize event to check if input is starving.
311    pub fn check_fairness(&mut self, now: Instant) -> FairnessDecision {
312        self.stats.total_checks += 1;
313
314        // If disabled, return default (no intervention)
315        if !self.config.enabled {
316            self.recent_input_arrival = None;
317            return FairnessDecision::default();
318        }
319
320        // Calculate Jain's index for input vs resize
321        let jain = self.calculate_jain_index();
322
323        // Check pending input latency (including recent input seen this cycle for stats).
324        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        // Determine if intervention is needed
337        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            // Reset dominance counter on intervention
355            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        // Clear recent input marker after evaluating fairness.
371        self.recent_input_arrival = None;
372
373        decision
374    }
375
376    /// Record that an event was processed.
377    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        // Skip fairness tracking if disabled
386        if !self.config.enabled {
387            return;
388        }
389
390        // Record processing
391        let record = ProcessingRecord {
392            event_type,
393            duration,
394        };
395
396        // Update sliding window
397        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        // Add new record
414        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; // Reset dominance on input
419            }
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    /// Calculate Jain's fairness index for input vs resize processing time.
431    fn calculate_jain_index(&self) -> f64 {
432        // F(x,y) = (x + y)² / (2 × (x² + y²))
433        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; // Perfect fairness when no events
438        }
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    /// Determine if and why intervention is needed.
451    fn determine_intervention_reason(
452        &self,
453        pending_latency: Option<Duration>,
454        jain: f64,
455        has_pending_input: bool,
456    ) -> InterventionReason {
457        // Priority 1: Latency threshold (most urgent)
458        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        // Priority 2: Resize dominance
466        if has_pending_input && self.resize_dominance_count >= self.config.dominance_threshold {
467            return InterventionReason::ResizeDominance;
468        }
469
470        // Priority 3: Fairness index
471        //
472        // Keep this active whenever input is pending. If only one class has been
473        // processed in the recent window (for example, resize flood with
474        // input_time_us == 0), Jain's index will be at the low-bound for two
475        // classes and should still trigger intervention.
476        // We only intervene if the unfairness is at the expense of input
477        // (i.e. resize_time_us > input_time_us).
478        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    /// Get current statistics.
489    pub fn stats(&self) -> &FairnessStats {
490        &self.stats
491    }
492
493    /// Get intervention counts.
494    pub fn intervention_counts(&self) -> &InterventionCounts {
495        &self.intervention_counts
496    }
497
498    /// Get current configuration.
499    pub fn config(&self) -> &FairnessConfig {
500        &self.config
501    }
502
503    /// Current resize dominance count.
504    pub fn resize_dominance_count(&self) -> u32 {
505        self.resize_dominance_count
506    }
507
508    /// Check if fairness is enabled.
509    pub fn is_enabled(&self) -> bool {
510        self.config.enabled
511    }
512
513    /// Get current Jain's fairness index.
514    pub fn jain_index(&self) -> f64 {
515        self.calculate_jain_index()
516    }
517
518    /// Check if there is pending input.
519    pub fn has_pending_input(&self) -> bool {
520        self.pending_input_arrival.is_some()
521    }
522
523    /// Pure query returning whether a fairness check at `now` would intervene
524    /// to yield resize work to pending input, without mutating counters.
525    #[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    /// Reset the guard state (useful for testing).
543    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        // For two classes, Jain's index is bounded to [0.5, 1.0], so a threshold
575        // at or below 0.5 makes fairness-index intervention unreachable.
576        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        // Equal time for input and resize
629        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        // Much more resize time than input
642        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        // F = (1+100)² / (2 × (1² + 100²)) = 10201 / 20002 ≈ 0.51
647        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        // Advance logical time beyond threshold (deterministic)
666        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        // Signal pending input
678        guard.input_arrived(now);
679
680        // Process resize events (dominance)
681        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        // Balanced processing
695        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        // Seed both classes in the fairness window, then leave a pending input
715        // so fairness intervention applies to actual starvation risk.
716        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        // Pending input exists, but only resize work has been observed so far.
737        // FairnessIndex should still intervene to prevent starvation.
738        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        // Build up resize dominance
752        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        // Process input - should reset
757        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        // Perform some checks
819        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        // Fill window beyond capacity
831        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    // Property tests for core invariants
856
857    #[test]
858    fn test_invariant_jain_index_bounds() {
859        // Jain's index is always in [0.5, 1.0] for two event types
860        let mut guard = InputFairnessGuard::new();
861        let now = Instant::now();
862
863        // Test various ratios
864        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        // Build dominance
891        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        // Intervention should reset
896        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        // Even with pending input, disabled guard should not intervene
921        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    // =========================================================================
932    // Fairness guard + resize scheduling integration tests (bd-plwf)
933    // =========================================================================
934
935    #[test]
936    fn fairness_decision_fields_match_state() {
937        let mut guard = InputFairnessGuard::new();
938        let now = Instant::now();
939
940        // No pending input → decision has no pending latency
941        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        // Signal input, then check fairness later
949        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        // Equal allocation: x = y = 100ms → F = 1.0
963        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        // Extreme imbalance: x = 1ms, y = 100ms
974        // F = (1 + 100)^2 / (2 * (1 + 10000)) = 10201 / 20002 ≈ 0.51
975        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        // Jain's index with n=2 types is always in [0.5, 1.0].
985        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        // InputLatency > ResizeDominance > FairnessIndex
1016        let config = FairnessConfig {
1017            input_priority_threshold: Duration::from_millis(20),
1018            dominance_threshold: 2,
1019            fairness_threshold: 0.9, // High threshold to easily trigger
1020            enabled: true,
1021        };
1022        let mut guard = InputFairnessGuard::with_config(config);
1023        let now = Instant::now();
1024
1025        // Set up conditions for all three reasons:
1026        // 1. Pending input with high latency
1027        guard.input_arrived(now);
1028        // 2. Resize dominance (3 consecutive resizes)
1029        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        // Check fairness well past latency threshold
1034        let later = now + Duration::from_millis(100);
1035        let d = guard.check_fairness(later);
1036
1037        // InputLatency should win (highest priority)
1038        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            // Keep fairness-index intervention out of scope for this test so it
1051            // isolates dominance-threshold behavior.
1052            fairness_threshold: 0.5,
1053            ..FairnessConfig::default()
1054        };
1055        let mut guard = InputFairnessGuard::with_config(config);
1056        let now = Instant::now();
1057
1058        // Need pending input for dominance to matter
1059        guard.input_arrived(now);
1060
1061        // 2 resizes → no intervention
1062        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        // Signal input again (previous check cleared it)
1068        guard.input_arrived(now);
1069
1070        // 3rd resize → dominance triggers
1071        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        // Trigger InputLatency intervention
1089        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        // Trigger ResizeDominance intervention
1099        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        // Simulate balanced workload over 50 cycles
1114        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            // With balanced processing, no intervention should fire
1121            assert!(!d.yield_to_input, "Unexpected intervention at cycle {i}");
1122            // Jain index should remain near 1.0
1123            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        // One input event, then flood of resizes
1143        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        // input_time = 5ms = 5000us, resize_time = 300ms = 300000us
1150        // Highly unfair → index should be well below threshold
1151        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        // Second check had 50ms latency
1170        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        // No pending input remains, so latency stats should not grow.
1182        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        // Window capacity is 16 (FAIRNESS_WINDOW_SIZE)
1192        // Fill with resize events
1193        for _ in 0..16 {
1194            guard.event_processed(EventType::Resize, Duration::from_millis(10), now);
1195        }
1196
1197        // Now add input events - they should evict oldest resize events
1198        for _ in 0..16 {
1199            guard.event_processed(EventType::Input, Duration::from_millis(10), now);
1200        }
1201
1202        // After all resizes evicted and replaced with input, Jain should show
1203        // only input time remaining (resize_time_us = 0 after full eviction)
1204        let j = guard.jain_index();
1205        // When only one type has time, index = (x+0)^2 / (2*(x^2+0)) = 0.5
1206        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        // With high thresholds, moderate conditions should not trigger
1224        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}