Skip to main content

ftui_runtime/
resize_coalescer.rs

1//! Adaptive resize stream coalescer.
2//!
3//! This module implements the resize coalescing behavior specified in
4//! `docs/spec/resize-scheduler.md`. It provides:
5//!
6//! - **Latest-wins semantics**: Only the final size in a burst is rendered
7//! - **Bounded latency**: Hard deadline guarantees render within max wait
8//! - **Regime awareness**: Adapts behavior between steady and burst modes
9//! - **Decision logging**: JSONL-compatible evidence for each decision
10//!
11//! # Usage
12//!
13//! ```ignore
14//! use ftui_runtime::resize_coalescer::{ResizeCoalescer, CoalescerConfig};
15//!
16//! let config = CoalescerConfig::default();
17//! let mut coalescer = ResizeCoalescer::new(config, (80, 24));
18//!
19//! // On resize event
20//! let action = coalescer.handle_resize(100, 40);
21//!
22//! // On tick (called each frame)
23//! let action = coalescer.tick();
24//! ```
25//!
26//! # Regime Detection
27//!
28//! The coalescer uses a simplified regime model with two states:
29//! - **Steady**: Single resize or slow sequence — prioritize responsiveness
30//! - **Burst**: Rapid resize events — prioritize coalescing to reduce work
31//!
32//! Regime transitions are detected via event rate tracking with hysteresis.
33//!
34//! # Invariants
35//!
36//! - **Latest-wins**: the final resize in a burst is never dropped.
37//! - **Bounded latency**: pending resizes apply within `hard_deadline_ms`.
38//! - **Deterministic**: identical event sequences yield identical decisions.
39//!
40//! # Failure Modes
41//!
42//! | Condition | Behavior | Rationale |
43//! |-----------|----------|-----------|
44//! | `hard_deadline_ms = 0` | Apply immediately | Avoids zero-latency stall |
45//! | `rate_window_size < 2` | `event_rate = 0` | No divide-by-zero in rate |
46//! | No pending size | Return `None` | Avoids spurious applies |
47//!
48//! # Decision Rule (Explainable)
49//!
50//! 1) If `time_since_render ≥ hard_deadline_ms`, **apply** (forced).
51//! 2) If `dt ≥ delay_ms`, **apply** when in **Steady** (or when BOCPD is
52//!    enabled). (`delay_ms` = steady/burst delay, or BOCPD posterior-interpolated
53//!    delay when enabled.)
54//! 3) If `event_rate ≥ burst_enter_rate`, switch to **Burst**.
55//! 4) If in **Burst** and `event_rate < burst_exit_rate` for `cooldown_frames`,
56//!    switch to **Steady**.
57//! 5) Otherwise, **coalesce** and optionally show a placeholder.
58
59#![forbid(unsafe_code)]
60
61use std::collections::VecDeque;
62use web_time::{Duration, Instant};
63
64use crate::bocpd::{BocpdConfig, BocpdDetector, BocpdRegime};
65use crate::evidence_sink::{EVIDENCE_SCHEMA_VERSION, EvidenceSink};
66use crate::terminal_writer::ScreenMode;
67
68/// FNV-1a 64-bit offset basis.
69/// Bound on retained cycle-time samples: percentiles are computed over the
70/// most recent window, and unbounded retention (one sample per applied
71/// resize) is a slow leak in long-lived sessions.
72const MAX_CYCLE_TIME_SAMPLES: usize = 1024;
73
74/// Bound on retained regime-transition evidence entries (one per regime
75/// flip, otherwise never truncated by the runtime).
76const MAX_TRANSITION_LOGS: usize = 256;
77
78const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
79/// FNV-1a 64-bit prime.
80const FNV_PRIME: u64 = 0x100000001b3;
81
82fn fnv_hash_bytes(hash: &mut u64, bytes: &[u8]) {
83    for byte in bytes {
84        *hash ^= *byte as u64;
85        *hash = hash.wrapping_mul(FNV_PRIME);
86    }
87}
88
89#[inline]
90fn duration_since_or_zero(now: Instant, earlier: Instant) -> Duration {
91    now.saturating_duration_since(earlier)
92}
93
94fn default_resize_run_id() -> String {
95    format!("resize-{}", std::process::id())
96}
97
98pub(crate) fn screen_mode_str(mode: ScreenMode) -> &'static str {
99    match mode {
100        ScreenMode::Inline { .. } => "inline",
101        ScreenMode::InlineAuto { .. } => "inline_auto",
102        ScreenMode::AltScreen => "altscreen",
103    }
104}
105
106#[inline]
107fn json_escape(value: &str) -> String {
108    let mut out = String::with_capacity(value.len());
109    for ch in value.chars() {
110        match ch {
111            '"' => out.push_str("\\\""),
112            '\\' => out.push_str("\\\\"),
113            '\n' => out.push_str("\\n"),
114            '\r' => out.push_str("\\r"),
115            '\t' => out.push_str("\\t"),
116            c if c.is_control() => {
117                use std::fmt::Write as _;
118                let _ = write!(out, "\\u{:04X}", c as u32);
119            }
120            _ => out.push(ch),
121        }
122    }
123    out
124}
125
126fn evidence_prefix(
127    run_id: &str,
128    screen_mode: ScreenMode,
129    cols: u16,
130    rows: u16,
131    event_idx: u64,
132) -> String {
133    format!(
134        r#""schema_version":"{}","run_id":"{}","event_idx":{},"screen_mode":"{}","cols":{},"rows":{}"#,
135        EVIDENCE_SCHEMA_VERSION,
136        json_escape(run_id),
137        event_idx,
138        screen_mode_str(screen_mode),
139        cols,
140        rows,
141    )
142}
143
144/// Configuration for the resize coalescer.
145///
146/// # Defaults
147///
148/// | Field | Default | Meaning |
149/// |---|---|---|
150/// | `steady_delay_ms` | 16 | how long a resize is held in the steady regime |
151/// | `burst_delay_ms` | 40 | how long a resize is held in the burst regime |
152/// | `hard_deadline_ms` | 100 | applied regardless of regime once this elapses |
153/// | `enable_bocpd` | `false` | the rate heuristic is the detector |
154/// | `heuristic_fallback` | `true` | the rate heuristic covers what it cannot |
155///
156/// These are *hold* times. They are not [`BocpdConfig`]'s `mu_steady_ms` (200)
157/// and `mu_burst_ms` (20), which are the expected *inter-arrival* times the
158/// observation model is written in terms of. The README reported the latter
159/// pair as the coalescing delays for a while; the two pairs are easy to swap
160/// and mean opposite things.
161///
162/// # The fallback rule
163///
164/// With `heuristic_fallback` on, the 10/5 events-per-second rate heuristic
165/// decides only where the posterior cannot: the first event of a session (no
166/// inter-arrival yet), an inter-arrival outside
167/// `[min_observation_ms, max_observation_ms]`, or a non-finite posterior.
168/// While the heuristic owns the decision it also owns the burst exit.
169/// [`CoalescerConfig::without_bocpd`] returns to the heuristic alone;
170/// `heuristic_fallback = false` hands even the first event to the posterior.
171///
172/// Every decision row records which of the two decided, in `detector`, and
173/// carries `p_burst` whenever the posterior is finite — including on rows the
174/// heuristic decided, so the log can answer what BOCPD would have said.
175#[derive(Debug, Clone)]
176pub struct CoalescerConfig {
177    /// Maximum coalesce delay in steady regime (ms).
178    /// In steady state, we want quick response.
179    pub steady_delay_ms: u64,
180
181    /// Maximum coalesce delay in burst regime (ms).
182    /// During bursts, we coalesce more aggressively.
183    pub burst_delay_ms: u64,
184
185    /// Hard deadline — always render within this time (ms).
186    /// Guarantees bounded worst-case latency.
187    pub hard_deadline_ms: u64,
188
189    /// Event rate threshold to enter burst mode (events/second).
190    pub burst_enter_rate: f64,
191
192    /// Event rate threshold to exit burst mode (events/second).
193    /// Lower than enter_rate for hysteresis.
194    pub burst_exit_rate: f64,
195
196    /// Number of frames to hold in burst mode after rate drops.
197    pub cooldown_frames: u32,
198
199    /// Window size for rate calculation (number of events).
200    pub rate_window_size: usize,
201
202    /// Enable decision logging (JSONL format).
203    pub enable_logging: bool,
204
205    /// Enable BOCPD (Bayesian Online Change-Point Detection) for regime
206    /// detection. **Off by default**: the rate threshold heuristic
207    /// (`burst_enter_rate` / `burst_exit_rate`) is the detector unless
208    /// [`Self::with_bocpd`] turns the posterior on.
209    ///
210    /// When enabled, the coalescer uses a Bayesian posterior over run-lengths
211    /// to detect regime changes instead of the thresholds, which buys
212    /// uncertainty quantification via P(burst), adaptation without hand-tuned
213    /// rates, and per-decision evidence rows.
214    ///
215    /// # Why it is not the default
216    ///
217    /// It was, from 2026-09-02. The differential replay that was supposed to
218    /// justify that flip landed two and a half weeks later and said the flip
219    /// was not justified: driven over identical schedules on a virtual clock,
220    /// the posterior drew **more** frames during a drag on 6 of 6 recorded
221    /// storm patterns, and was no better on settling latency (each detector
222    /// over the 40 ms budget on 3 of 6). The plan's own rule for that outcome
223    /// was to restore the default rather than lower the bar.
224    ///
225    /// The likely cause is that `recommended_delay` interpolates between the
226    /// steady and burst holds while `p_burst` sits in the transitional band,
227    /// so on storms that straddle `mu_burst` it holds for an intermediate
228    /// delay instead of committing — less holding, more repaints. Retuning
229    /// that is open as a separate question, not a reason to default it on.
230    ///
231    /// Evidence: `docs/perf/resize_differential_2026-09.md`, regenerated by
232    /// `scripts/resize_storm_differential_e2e.sh`. bd-h8l3d.
233    pub enable_bocpd: bool,
234
235    /// Let the rate heuristic decide when the BOCPD posterior is undefined.
236    ///
237    /// The posterior needs an inter-arrival observation, and it clamps
238    /// observations to `[min_observation_ms, max_observation_ms]`. With this
239    /// flag (the default) the first event of a session, an event whose
240    /// inter-arrival lies outside that range, and a non-finite posterior are
241    /// decided by the heuristic instead of a clamped or empty posterior. The
242    /// detector that made each decision is recorded as `detector` on the
243    /// `decision` and `regime_transition` evidence rows.
244    pub heuristic_fallback: bool,
245
246    /// BOCPD configuration; `None` means [`BocpdConfig::default`].
247    pub bocpd_config: Option<BocpdConfig>,
248}
249
250impl Default for CoalescerConfig {
251    fn default() -> Self {
252        Self {
253            steady_delay_ms: 16, // ~60fps responsiveness
254            burst_delay_ms: 40,  // Aggressive coalescing
255            hard_deadline_ms: 100,
256            burst_enter_rate: 10.0, // 10 events/sec to enter burst
257            burst_exit_rate: 5.0,   // 5 events/sec to exit burst
258            cooldown_frames: 3,
259            rate_window_size: 8,
260            enable_logging: false,
261            // The differential replay that was meant to justify making the
262            // posterior the default said it loses; see the field's doc.
263            enable_bocpd: false,
264            heuristic_fallback: true,
265            bocpd_config: None,
266        }
267    }
268}
269
270impl CoalescerConfig {
271    /// Enable or disable decision logging.
272    #[must_use]
273    pub fn with_logging(mut self, enabled: bool) -> Self {
274        self.enable_logging = enabled;
275        self
276    }
277
278    /// Enable BOCPD-based regime detection with default configuration.
279    #[must_use]
280    pub fn with_bocpd(mut self) -> Self {
281        self.enable_bocpd = true;
282        self.bocpd_config = Some(BocpdConfig::default());
283        self
284    }
285
286    /// Enable BOCPD-based regime detection with custom configuration.
287    #[must_use]
288    pub fn with_bocpd_config(mut self, config: BocpdConfig) -> Self {
289        self.enable_bocpd = true;
290        self.bocpd_config = Some(config);
291        self
292    }
293
294    /// Disable BOCPD: the rate threshold heuristic becomes the only regime
295    /// detector (no `BocpdDetector` is built).
296    #[must_use]
297    pub fn without_bocpd(mut self) -> Self {
298        self.enable_bocpd = false;
299        self.bocpd_config = None;
300        self
301    }
302
303    /// Set whether the heuristic decides while the BOCPD posterior is
304    /// undefined (see [`Self::heuristic_fallback`]).
305    #[must_use]
306    pub fn with_heuristic_fallback(mut self, enabled: bool) -> Self {
307        self.heuristic_fallback = enabled;
308        self
309    }
310
311    /// Serialize configuration to JSONL format.
312    #[must_use]
313    pub fn to_jsonl(
314        &self,
315        run_id: &str,
316        screen_mode: ScreenMode,
317        cols: u16,
318        rows: u16,
319        event_idx: u64,
320    ) -> String {
321        let prefix = evidence_prefix(run_id, screen_mode, cols, rows, event_idx);
322        format!(
323            r#"{{{prefix},"event":"config","steady_delay_ms":{},"burst_delay_ms":{},"hard_deadline_ms":{},"burst_enter_rate":{:.3},"burst_exit_rate":{:.3},"cooldown_frames":{},"rate_window_size":{},"logging_enabled":{},"enable_bocpd":{},"heuristic_fallback":{}}}"#,
324            self.steady_delay_ms,
325            self.burst_delay_ms,
326            self.hard_deadline_ms,
327            self.burst_enter_rate,
328            self.burst_exit_rate,
329            self.cooldown_frames,
330            self.rate_window_size,
331            self.enable_logging,
332            self.enable_bocpd,
333            self.heuristic_fallback
334        )
335    }
336}
337
338/// Which detector made a regime decision.
339///
340/// BOCPD is the default detector; the rate heuristic decides when BOCPD is
341/// off ([`CoalescerConfig::without_bocpd`]) or, with
342/// [`CoalescerConfig::heuristic_fallback`], while the posterior is undefined
343/// (first event, inter-arrival outside the observation range, non-finite
344/// posterior). Recorded on `decision` and `regime_transition` evidence rows.
345#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
346pub enum RegimeDetector {
347    /// Rate threshold heuristic (`burst_enter_rate` / `burst_exit_rate`).
348    #[default]
349    Heuristic,
350    /// BOCPD run-length posterior.
351    Bocpd,
352}
353
354impl RegimeDetector {
355    /// Stable string form for JSONL evidence.
356    #[must_use]
357    pub const fn as_str(self) -> &'static str {
358        match self {
359            Self::Heuristic => "heuristic",
360            Self::Bocpd => "bocpd",
361        }
362    }
363}
364
365/// How many regime decisions each detector made in this session.
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
367pub struct DetectorDecisions {
368    /// Decisions made by the BOCPD posterior.
369    pub bocpd: u64,
370    /// Decisions made by the rate heuristic (BOCPD off or fallback active).
371    pub heuristic: u64,
372}
373
374/// Action returned by the coalescer.
375#[derive(Debug, Clone, Copy, PartialEq, Eq)]
376pub enum CoalesceAction {
377    /// Nothing to apply this cycle: either no resize is pending or the
378    /// pending one is still being coalesced (check
379    /// [`ResizeCoalescer::has_pending`] to tell the two apart).
380    None,
381
382    /// Apply the resize with the given dimensions.
383    ApplyResize {
384        width: u16,
385        height: u16,
386        /// Time spent coalescing.
387        coalesce_time: Duration,
388        /// Whether this was forced by hard deadline.
389        forced_by_deadline: bool,
390    },
391}
392
393/// Detected regime for resize events.
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
395pub enum Regime {
396    /// Single resize or slow sequence.
397    #[default]
398    Steady,
399    /// Rapid resize events (storm).
400    Burst,
401}
402
403impl Regime {
404    /// Get the stable string representation.
405    #[must_use]
406    pub const fn as_str(self) -> &'static str {
407        match self {
408            Self::Steady => "steady",
409            Self::Burst => "burst",
410        }
411    }
412}
413
414/// Structured reason codes for regime transitions.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum TransitionReasonCode {
417    /// Heuristic detector entered burst because event rate crossed enter threshold.
418    HeuristicEnterBurstRate,
419    /// Heuristic detector exited burst after cooldown with low event rate.
420    HeuristicExitBurstCooldown,
421    /// Heuristic detector exited burst on the immediate path because the
422    /// event rate had fallen below the exit threshold (no frame ticks run
423    /// the cooldown in `ResizeBehavior::Immediate`).
424    HeuristicExitBurstRate,
425    /// BOCPD posterior crossed burst threshold.
426    BocpdPosteriorBurst,
427    /// BOCPD posterior crossed steady threshold.
428    BocpdPosteriorSteady,
429    /// BOCPD mode exited burst on a tick because no event arrived for at
430    /// least the steady mean inter-arrival (`mu_steady_ms`). The posterior
431    /// only updates on events, so without this a burst followed by silence
432    /// would stay `Burst` (and keep the load governor in soft overload)
433    /// until the next resize.
434    BocpdIdleExit,
435}
436
437impl TransitionReasonCode {
438    /// Stable string form for JSONL evidence.
439    #[must_use]
440    pub const fn as_str(self) -> &'static str {
441        match self {
442            Self::HeuristicEnterBurstRate => "heuristic_enter_burst_rate",
443            Self::HeuristicExitBurstCooldown => "heuristic_exit_burst_cooldown",
444            Self::HeuristicExitBurstRate => "heuristic_exit_burst_rate",
445            Self::BocpdPosteriorBurst => "bocpd_posterior_burst",
446            Self::BocpdPosteriorSteady => "bocpd_posterior_steady",
447            Self::BocpdIdleExit => "bocpd_idle_exit",
448        }
449    }
450}
451
452/// Event emitted when a resize operation is applied (bd-bksf.6 stub).
453///
454/// Used by `ResizeSlaMonitor` for latency tracking.
455#[derive(Debug, Clone)]
456pub struct ResizeAppliedEvent {
457    /// New terminal size after resize.
458    pub new_size: (u16, u16),
459    /// Previous terminal size.
460    pub old_size: (u16, u16),
461    /// Time elapsed from resize request to apply.
462    pub elapsed: Duration,
463    /// Whether the apply was forced (hard deadline).
464    pub forced: bool,
465}
466
467/// Event emitted when regime changes between Steady and Burst (bd-bksf.6 stub).
468///
469/// Used by SLA monitoring for regime-aware alerting.
470#[derive(Debug, Clone)]
471pub struct RegimeChangeEvent {
472    /// Previous regime.
473    pub from: Regime,
474    /// New regime.
475    pub to: Regime,
476    /// Event index when transition occurred.
477    pub event_idx: u64,
478    /// Structured reason for the transition.
479    pub reason_code: TransitionReasonCode,
480    /// Transition confidence in [0, 1].
481    pub confidence: f64,
482}
483
484// =============================================================================
485// Evidence Ledger for Scheduler Decisions (bd-1rz0.27)
486// =============================================================================
487
488/// Evidence supporting a scheduler decision with Bayes factors.
489///
490/// This captures the mathematical reasoning behind coalesce/apply decisions,
491/// providing explainability for the regime-adaptive scheduler.
492///
493/// # Bayes Factor Interpretation
494///
495/// The `log_bayes_factor` represents log10(P(evidence|apply_now) / P(evidence|coalesce)):
496/// - Positive values favor immediate apply (respond quickly)
497/// - Negative values favor coalescing (wait for more events)
498/// - |LBF| > 1 is "strong" evidence, |LBF| > 2 is "decisive"
499///
500/// # Example
501///
502/// ```ignore
503/// let evidence = DecisionEvidence {
504///     log_bayes_factor: 1.5,  // Strong evidence to apply now
505///     regime_contribution: 0.8,
506///     timing_contribution: 0.5,
507///     rate_contribution: 0.2,
508///     explanation: "Steady regime with long idle interval".to_string(),
509/// };
510/// ```
511#[derive(Debug, Clone)]
512pub struct DecisionEvidence {
513    /// Log10 Bayes factor: positive favors apply, negative favors coalesce.
514    pub log_bayes_factor: f64,
515
516    /// Contribution from regime detection (Steady vs Burst).
517    pub regime_contribution: f64,
518
519    /// Contribution from timing (dt_ms, time since last render).
520    pub timing_contribution: f64,
521
522    /// Contribution from event rate.
523    pub rate_contribution: f64,
524
525    /// Human-readable explanation of the decision.
526    pub explanation: String,
527}
528
529impl DecisionEvidence {
530    /// Evidence strongly favoring immediate apply (Steady regime, long idle).
531    #[must_use]
532    pub fn favor_apply(regime: Regime, dt_ms: f64, event_rate: f64) -> Self {
533        let regime_contrib = if regime == Regime::Steady { 1.0 } else { -0.5 };
534        let timing_contrib = (dt_ms / 50.0).min(2.0); // Higher dt -> favor apply
535        let rate_contrib = if event_rate < 5.0 { 0.5 } else { -0.3 };
536
537        let lbf = regime_contrib + timing_contrib + rate_contrib;
538
539        Self {
540            log_bayes_factor: lbf,
541            regime_contribution: regime_contrib,
542            timing_contribution: timing_contrib,
543            rate_contribution: rate_contrib,
544            explanation: format!(
545                "Regime={:?} (contrib={:.2}), dt={:.1}ms (contrib={:.2}), rate={:.1}/s (contrib={:.2})",
546                regime, regime_contrib, dt_ms, timing_contrib, event_rate, rate_contrib
547            ),
548        }
549    }
550
551    /// Evidence favoring coalescing (Burst regime, high rate).
552    #[must_use]
553    pub fn favor_coalesce(regime: Regime, dt_ms: f64, event_rate: f64) -> Self {
554        let regime_contrib = if regime == Regime::Burst { 1.0 } else { -0.5 };
555        let timing_contrib = (20.0 / dt_ms.max(1.0)).min(2.0); // Lower dt -> favor coalesce
556        let rate_contrib = if event_rate > 10.0 { 0.5 } else { -0.3 };
557
558        let lbf = -(regime_contrib + timing_contrib + rate_contrib);
559
560        Self {
561            log_bayes_factor: lbf,
562            regime_contribution: regime_contrib,
563            timing_contribution: timing_contrib,
564            rate_contribution: rate_contrib,
565            explanation: format!(
566                "Regime={:?} (contrib={:.2}), dt={:.1}ms (contrib={:.2}), rate={:.1}/s (contrib={:.2})",
567                regime, regime_contrib, dt_ms, timing_contrib, event_rate, rate_contrib
568            ),
569        }
570    }
571
572    /// Evidence for a forced deadline decision.
573    #[must_use]
574    pub fn forced_deadline(deadline_ms: f64) -> Self {
575        Self {
576            log_bayes_factor: f64::INFINITY,
577            regime_contribution: 0.0,
578            timing_contribution: deadline_ms,
579            rate_contribution: 0.0,
580            explanation: format!("Forced by hard deadline ({:.1}ms)", deadline_ms),
581        }
582    }
583
584    /// Serialize to JSONL format.
585    #[must_use]
586    pub fn to_jsonl(
587        &self,
588        run_id: &str,
589        screen_mode: ScreenMode,
590        cols: u16,
591        rows: u16,
592        event_idx: u64,
593    ) -> String {
594        let lbf_str = if self.log_bayes_factor.is_infinite() {
595            "\"inf\"".to_string()
596        } else {
597            format!("{:.3}", self.log_bayes_factor)
598        };
599        let prefix = evidence_prefix(run_id, screen_mode, cols, rows, event_idx);
600        format!(
601            r#"{{{prefix},"event":"decision_evidence","log_bayes_factor":{},"regime_contribution":{:.3},"timing_contribution":{:.3},"rate_contribution":{:.3},"explanation":"{}"}}"#,
602            lbf_str,
603            self.regime_contribution,
604            self.timing_contribution,
605            self.rate_contribution,
606            json_escape(&self.explanation)
607        )
608    }
609
610    /// Check if evidence strongly supports the action (|LBF| > 1).
611    #[must_use]
612    pub fn is_strong(&self) -> bool {
613        self.log_bayes_factor.abs() > 1.0
614    }
615
616    /// Check if evidence decisively supports the action (|LBF| > 2).
617    #[must_use]
618    pub fn is_decisive(&self) -> bool {
619        self.log_bayes_factor.abs() > 2.0 || self.log_bayes_factor.is_infinite()
620    }
621}
622
623/// Decision log entry for observability.
624#[derive(Debug, Clone)]
625pub struct DecisionLog {
626    /// Timestamp of the decision.
627    pub timestamp: Instant,
628    /// Elapsed time since logging started (ms).
629    pub elapsed_ms: f64,
630    /// Event index in session.
631    pub event_idx: u64,
632    /// Time since last event (ms).
633    pub dt_ms: f64,
634    /// Current event rate (events/sec).
635    pub event_rate: f64,
636    /// Detected regime.
637    pub regime: Regime,
638    /// Chosen action.
639    pub action: &'static str,
640    /// Pending size (if any).
641    pub pending_size: Option<(u16, u16)>,
642    /// Applied size (for apply decisions).
643    pub applied_size: Option<(u16, u16)>,
644    /// Time since last render (ms).
645    pub time_since_render_ms: f64,
646    /// Time spent coalescing until apply (ms).
647    pub coalesce_ms: Option<f64>,
648    /// Was forced by deadline.
649    pub forced: bool,
650    /// Transition reason code if this decision coincided with a regime transition.
651    pub transition_reason_code: Option<TransitionReasonCode>,
652    /// Transition confidence if this decision coincided with a regime transition.
653    pub transition_confidence: Option<f64>,
654    /// Detector that made the regime decision this row reflects.
655    pub detector: RegimeDetector,
656    /// BOCPD posterior probability of burst at decision time (`None` when
657    /// BOCPD is off or the posterior is not finite).
658    pub p_burst: Option<f64>,
659}
660
661impl DecisionLog {
662    /// Serialize decision log to JSONL format.
663    #[must_use]
664    pub fn to_jsonl(&self, run_id: &str, screen_mode: ScreenMode, cols: u16, rows: u16) -> String {
665        let (pending_w, pending_h) = match self.pending_size {
666            Some((w, h)) => (w.to_string(), h.to_string()),
667            None => ("null".to_string(), "null".to_string()),
668        };
669        let (applied_w, applied_h) = match self.applied_size {
670            Some((w, h)) => (w.to_string(), h.to_string()),
671            None => ("null".to_string(), "null".to_string()),
672        };
673        let coalesce_ms = match self.coalesce_ms {
674            Some(ms) => format!("{:.3}", ms),
675            None => "null".to_string(),
676        };
677        let transition_reason_code = self
678            .transition_reason_code
679            .map(TransitionReasonCode::as_str)
680            .map(|code| format!(r#""{code}""#))
681            .unwrap_or_else(|| "null".to_string());
682        let transition_confidence = self
683            .transition_confidence
684            .map(|confidence| format!("{confidence:.6}"))
685            .unwrap_or_else(|| "null".to_string());
686        let prefix = evidence_prefix(run_id, screen_mode, cols, rows, self.event_idx);
687
688        format!(
689            r#"{{{prefix},"event":"decision","idx":{},"elapsed_ms":{:.3},"dt_ms":{:.3},"event_rate":{:.3},"regime":"{}","action":"{}","pending_w":{},"pending_h":{},"applied_w":{},"applied_h":{},"time_since_render_ms":{:.3},"coalesce_ms":{},"forced":{},"transition_reason_code":{},"transition_confidence":{},"detector":"{}","p_burst":{}}}"#,
690            self.event_idx,
691            self.elapsed_ms,
692            self.dt_ms,
693            self.event_rate,
694            self.regime.as_str(),
695            self.action,
696            pending_w,
697            pending_h,
698            applied_w,
699            applied_h,
700            self.time_since_render_ms,
701            coalesce_ms,
702            self.forced,
703            transition_reason_code,
704            transition_confidence,
705            self.detector.as_str(),
706            self.p_burst
707                .map_or_else(|| "null".to_string(), |p| format!("{p:.6}"))
708        )
709    }
710}
711
712#[derive(Debug, Clone, Copy)]
713struct PendingTransitionEvidence {
714    reason_code: TransitionReasonCode,
715    confidence: f64,
716}
717
718/// Transition evidence entry emitted when the controller changes regime.
719#[derive(Debug, Clone)]
720pub struct RegimeTransitionLog {
721    /// Timestamp when transition occurred.
722    pub timestamp: Instant,
723    /// Event index when transition occurred.
724    pub event_idx: u64,
725    /// Previous regime.
726    pub from_regime: Regime,
727    /// New regime.
728    pub to_regime: Regime,
729    /// Structured reason code.
730    pub reason_code: TransitionReasonCode,
731    /// Confidence in [0, 1].
732    pub confidence: f64,
733    /// Event rate at transition time.
734    pub event_rate: f64,
735    /// BOCPD posterior probability of burst, if available.
736    pub p_burst: Option<f64>,
737    /// Current cooldown counter after transition accounting.
738    pub cooldown_remaining: u32,
739    /// Detector that made the transition.
740    pub detector: RegimeDetector,
741}
742
743impl RegimeTransitionLog {
744    /// Serialize transition evidence to JSONL format.
745    #[must_use]
746    pub fn to_jsonl(&self, run_id: &str, screen_mode: ScreenMode, cols: u16, rows: u16) -> String {
747        let prefix = evidence_prefix(run_id, screen_mode, cols, rows, self.event_idx);
748        let p_burst = self
749            .p_burst
750            .map(|value| format!("{value:.6}"))
751            .unwrap_or_else(|| "null".to_string());
752        format!(
753            r#"{{{prefix},"event":"regime_transition","from_regime":"{}","to_regime":"{}","reason_code":"{}","confidence":{:.6},"event_rate":{:.3},"p_burst":{},"detector":"{}","cooldown_remaining":{}}}"#,
754            self.from_regime.as_str(),
755            self.to_regime.as_str(),
756            self.reason_code.as_str(),
757            self.confidence,
758            self.event_rate,
759            p_burst,
760            self.detector.as_str(),
761            self.cooldown_remaining,
762        )
763    }
764}
765
766/// Adaptive resize stream coalescer.
767///
768/// Implements latest-wins coalescing with regime-aware behavior.
769#[derive(Debug)]
770pub struct ResizeCoalescer {
771    config: CoalescerConfig,
772
773    /// Currently pending size (latest wins).
774    pending_size: Option<(u16, u16)>,
775
776    /// Last applied size.
777    last_applied: (u16, u16),
778
779    /// Timestamp of first event in current coalesce window.
780    window_start: Option<Instant>,
781
782    /// Timestamp of last resize event.
783    last_event: Option<Instant>,
784
785    /// Timestamp of last render.
786    last_render: Instant,
787
788    /// Current detected regime.
789    regime: Regime,
790
791    /// Frames remaining in cooldown (for burst exit hysteresis).
792    cooldown_remaining: u32,
793
794    /// Recent event timestamps for rate calculation.
795    event_times: VecDeque<Instant>,
796
797    /// Total event count.
798    event_count: u64,
799
800    /// Logging start time for elapsed timestamps.
801    log_start: Option<Instant>,
802
803    /// Decision logs (if logging enabled).
804    logs: Vec<DecisionLog>,
805    /// Regime transition evidence logs.
806    transition_logs: Vec<RegimeTransitionLog>,
807    /// Pending transition evidence to attach to the next decision row.
808    pending_transition_evidence: Option<PendingTransitionEvidence>,
809    /// Evidence sink for JSONL decision logs.
810    evidence_sink: Option<EvidenceSink>,
811    /// Whether config has been logged to the evidence sink.
812    config_logged: bool,
813    /// Run identifier for evidence logs.
814    evidence_run_id: String,
815    /// Screen mode label for evidence logs.
816    evidence_screen_mode: ScreenMode,
817
818    // --- Telemetry integration (bd-1rz0.7) ---
819    /// Telemetry hooks for external observability.
820    telemetry_hooks: Option<TelemetryHooks>,
821
822    /// Count of regime transitions during this session.
823    regime_transitions: u64,
824
825    /// Events coalesced in current window.
826    events_in_window: u64,
827
828    /// History of cycle times (ms) for percentile calculation.
829    cycle_times: Vec<f64>,
830
831    /// BOCPD detector for Bayesian regime detection (when enabled).
832    bocpd: Option<BocpdDetector>,
833
834    /// Detector that made the most recent regime decision.
835    last_detector: RegimeDetector,
836
837    /// Regime decisions per detector.
838    detector_decisions: DetectorDecisions,
839}
840
841/// Cycle time percentiles for reflow diagnostics (bd-1rz0.7).
842#[derive(Debug, Clone, Copy)]
843pub struct CycleTimePercentiles {
844    /// 50th percentile (median) cycle time in ms.
845    pub p50_ms: f64,
846    /// 95th percentile cycle time in ms.
847    pub p95_ms: f64,
848    /// 99th percentile cycle time in ms.
849    pub p99_ms: f64,
850    /// Number of samples.
851    pub count: usize,
852    /// Mean cycle time in ms.
853    pub mean_ms: f64,
854}
855
856impl CycleTimePercentiles {
857    /// Serialize to JSONL format.
858    #[must_use]
859    pub fn to_jsonl(&self) -> String {
860        format!(
861            r#"{{"event":"cycle_time_percentiles","p50_ms":{:.3},"p95_ms":{:.3},"p99_ms":{:.3},"mean_ms":{:.3},"count":{}}}"#,
862            self.p50_ms, self.p95_ms, self.p99_ms, self.mean_ms, self.count
863        )
864    }
865}
866
867impl ResizeCoalescer {
868    /// Create a new coalescer with the given configuration and initial size.
869    pub fn new(config: CoalescerConfig, initial_size: (u16, u16)) -> Self {
870        let bocpd = if config.enable_bocpd {
871            let mut bocpd_cfg = config.bocpd_config.clone().unwrap_or_default();
872            if config.enable_logging {
873                bocpd_cfg.enable_logging = true;
874            }
875            Some(BocpdDetector::new(bocpd_cfg))
876        } else {
877            None
878        };
879
880        Self {
881            config,
882            pending_size: None,
883            last_applied: initial_size,
884            window_start: None,
885            last_event: None,
886            last_render: Instant::now(),
887            regime: Regime::Steady,
888            cooldown_remaining: 0,
889            event_times: VecDeque::new(),
890            event_count: 0,
891            log_start: None,
892            logs: Vec::new(),
893            transition_logs: Vec::new(),
894            pending_transition_evidence: None,
895            evidence_sink: None,
896            config_logged: false,
897            evidence_run_id: default_resize_run_id(),
898            evidence_screen_mode: ScreenMode::AltScreen,
899            telemetry_hooks: None,
900            regime_transitions: 0,
901            events_in_window: 0,
902            cycle_times: Vec::new(),
903            bocpd,
904            last_detector: RegimeDetector::Heuristic,
905            detector_decisions: DetectorDecisions::default(),
906        }
907    }
908
909    /// Attach telemetry hooks for external observability.
910    #[must_use]
911    pub fn with_telemetry_hooks(mut self, hooks: TelemetryHooks) -> Self {
912        self.telemetry_hooks = Some(hooks);
913        self
914    }
915
916    /// Attach an evidence sink for JSONL decision logs.
917    #[must_use]
918    pub fn with_evidence_sink(mut self, sink: EvidenceSink) -> Self {
919        self.evidence_sink = Some(sink);
920        self.config_logged = false;
921        self
922    }
923
924    /// Set the run identifier used in evidence logs.
925    #[must_use]
926    pub fn with_evidence_run_id(mut self, run_id: impl Into<String>) -> Self {
927        self.evidence_run_id = run_id.into();
928        self
929    }
930
931    /// Set the screen mode label used in evidence logs.
932    #[must_use]
933    pub fn with_screen_mode(mut self, screen_mode: ScreenMode) -> Self {
934        self.evidence_screen_mode = screen_mode;
935        self
936    }
937
938    /// Set or clear the evidence sink.
939    pub fn set_evidence_sink(&mut self, sink: Option<EvidenceSink>) {
940        self.evidence_sink = sink;
941        self.config_logged = false;
942    }
943
944    /// Set the last render time (for deterministic testing).
945    #[must_use]
946    pub fn with_last_render(mut self, time: Instant) -> Self {
947        self.last_render = time;
948        self
949    }
950
951    /// Record an externally-applied resize (immediate path).
952    pub fn record_external_apply(&mut self, width: u16, height: u16, now: Instant) {
953        self.event_count += 1;
954        self.event_times.push_back(now);
955        while self.event_times.len() > self.config.rate_window_size {
956            self.event_times.pop_front();
957        }
958        self.update_regime(now);
959        // The frame loop never ticks the coalescer in
960        // `ResizeBehavior::Immediate`, so the cooldown-based exit in `tick_at`
961        // cannot run on this path; without an event-path exit one burst
962        // pinned the regime to `Burst` for the rest of the session
963        // (bd-1za0z item 2). BOCPD mode exits through its posterior above;
964        // while the heuristic fallback is deciding, it owns the exit too.
965        if self.heuristic_decides() && self.regime == Regime::Burst {
966            let rate = self.calculate_event_rate(now);
967            if rate < self.config.burst_exit_rate {
968                self.record_regime_transition(
969                    now,
970                    Regime::Steady,
971                    TransitionReasonCode::HeuristicExitBurstRate,
972                    (1.0 - (rate / self.config.burst_exit_rate)).clamp(0.0, 1.0),
973                    rate,
974                    None,
975                );
976            }
977        }
978
979        self.pending_size = None;
980        self.window_start = None;
981        self.last_event = Some(now);
982        self.last_applied = (width, height);
983        self.last_render = now;
984        self.events_in_window = 0;
985        self.cooldown_remaining = 0;
986
987        self.log_decision(now, "apply_immediate", false, Some(0.0), Some(0.0));
988
989        if let Some(ref hooks) = self.telemetry_hooks
990            && let Some(entry) = self.logs.last()
991        {
992            hooks.fire_resize_applied(entry);
993        }
994    }
995
996    /// Get current regime transition count.
997    #[must_use]
998    pub fn regime_transition_count(&self) -> u64 {
999        self.regime_transitions
1000    }
1001
1002    /// Get cycle time percentiles (p50, p95, p99) in milliseconds.
1003    /// Returns None if no cycle times recorded.
1004    #[must_use]
1005    pub fn cycle_time_percentiles(&self) -> Option<CycleTimePercentiles> {
1006        if self.cycle_times.is_empty() {
1007            return None;
1008        }
1009
1010        let mut sorted = self.cycle_times.clone();
1011        sorted.sort_by(f64::total_cmp);
1012
1013        let len = sorted.len();
1014        let p50_idx = len / 2;
1015        let p95_idx = (len * 95) / 100;
1016        let p99_idx = (len * 99) / 100;
1017
1018        Some(CycleTimePercentiles {
1019            p50_ms: sorted[p50_idx],
1020            p95_ms: sorted[p95_idx.min(len - 1)],
1021            p99_ms: sorted[p99_idx.min(len - 1)],
1022            count: len,
1023            mean_ms: sorted.iter().sum::<f64>() / len as f64,
1024        })
1025    }
1026
1027    /// Handle a resize event.
1028    ///
1029    /// Returns the action to take immediately.
1030    pub fn handle_resize(&mut self, width: u16, height: u16) -> CoalesceAction {
1031        self.handle_resize_at(width, height, Instant::now())
1032    }
1033
1034    /// Handle a resize event at a specific time (for testing).
1035    pub fn handle_resize_at(&mut self, width: u16, height: u16, now: Instant) -> CoalesceAction {
1036        self.event_count += 1;
1037
1038        // Calculate dt
1039        let dt = self.last_event.map(|t| duration_since_or_zero(now, t));
1040        let dt_ms = dt.map(|d| d.as_secs_f64() * 1000.0).unwrap_or(0.0);
1041
1042        // Track event time for rate calculation
1043        // Clear stale events that artificially inflate the window duration
1044        if dt_ms > 1000.0 {
1045            self.event_times.clear();
1046        }
1047
1048        self.event_times.push_back(now);
1049        while self.event_times.len() > self.config.rate_window_size {
1050            self.event_times.pop_front();
1051        }
1052
1053        // Update regime based on event rate
1054        self.update_regime(now);
1055
1056        self.last_event = Some(now);
1057
1058        // If no pending, and this matches current size, no action needed
1059        if self.pending_size.is_none() && (width, height) == self.last_applied {
1060            self.log_decision(now, "skip_same_size", false, Some(dt_ms), None);
1061            return CoalesceAction::None;
1062        }
1063
1064        // Whether work was already waiting BEFORE this event arrived: a
1065        // deadline apply counts as forced only if it breached the SLA of
1066        // previously-pending work, not this fresh event (bd-1za0z).
1067        let had_pending_before_event = self.pending_size.is_some();
1068
1069        // Update pending size (latest wins)
1070        self.pending_size = Some((width, height));
1071
1072        // Track events in current coalesce window (bd-1rz0.7)
1073        self.events_in_window += 1;
1074
1075        // Mark window start if this is first event
1076        if self.window_start.is_none() {
1077            self.window_start = Some(now);
1078        }
1079
1080        // Check hard deadline. `forced` must mean "work was ALREADY waiting
1081        // and sat past its SLA deadline" — an isolated resize arriving after
1082        // a quiet gap is applied instantly, but it is not a deadline breach
1083        // and must not inflate the SLA forced count (bd-1za0z).
1084        let time_since_render = duration_since_or_zero(now, self.last_render);
1085        if time_since_render >= Duration::from_millis(self.config.hard_deadline_ms) {
1086            return self.apply_pending_at(now, had_pending_before_event);
1087        }
1088
1089        // If enough time has passed since the last event, apply now.
1090        // In heuristic mode, only apply immediately in Steady; burst applies via tick.
1091        let time_ok = match dt {
1092            Some(d) => d >= Duration::from_millis(self.current_delay_ms()),
1093            None => false, // First event must be coalesced to establish steady state timing
1094        };
1095
1096        if time_ok && (!self.heuristic_decides() || self.regime == Regime::Steady) {
1097            return self.apply_pending_at(now, false);
1098        }
1099
1100        self.log_decision(now, "coalesce", false, Some(dt_ms), None);
1101
1102        // Fire decision hook for coalesce events (bd-1rz0.7)
1103        if let Some(ref hooks) = self.telemetry_hooks
1104            && let Some(entry) = self.logs.last()
1105        {
1106            hooks.fire_decision(entry);
1107        }
1108
1109        // Coalescing: the runtime keeps showing the last frame. (A separate
1110        // `ShowPlaceholder` action existed here for years and was consumed by
1111        // nothing; removed under bd-1za0z item 2 / G12.)
1112        CoalesceAction::None
1113    }
1114
1115    /// Tick the coalescer (call each frame).
1116    ///
1117    /// Returns the action to take.
1118    pub fn tick(&mut self) -> CoalesceAction {
1119        self.tick_at(Instant::now())
1120    }
1121
1122    /// Tick at a specific time (for testing).
1123    pub fn tick_at(&mut self, now: Instant) -> CoalesceAction {
1124        // Heuristic cooldown exit: HEURISTIC MODE ONLY. In BOCPD mode the
1125        // posterior owns regime changes (BocpdPosteriorSteady on the next
1126        // event); letting this rate-based exit fire too produced
1127        // contradictory transitions — and with a low-rate custom BocpdConfig
1128        // it was the only between-events Burst exit, fighting the posterior
1129        // and flapping the regime (bd-1za0z). While the heuristic fallback
1130        // is deciding (BOCPD posterior undefined) it must own the exit too,
1131        // or an out-of-range burst would pin the regime until the posterior
1132        // sees an in-range event again.
1133        if self.regime == Regime::Burst && self.heuristic_decides() {
1134            let rate = self.calculate_event_rate(now);
1135            if rate >= self.config.burst_exit_rate {
1136                self.cooldown_remaining = self.config.cooldown_frames.max(1);
1137            } else if self.cooldown_remaining > 0 {
1138                self.cooldown_remaining -= 1;
1139                if self.cooldown_remaining == 0 {
1140                    self.record_regime_transition(
1141                        now,
1142                        Regime::Steady,
1143                        TransitionReasonCode::HeuristicExitBurstCooldown,
1144                        (1.0 - (rate / self.config.burst_exit_rate)).clamp(0.0, 1.0),
1145                        rate,
1146                        None,
1147                    );
1148                }
1149            }
1150        }
1151
1152        // BOCPD idle exit: the posterior only moves on events, so a burst
1153        // followed by silence would otherwise stay `Burst` until the next
1154        // resize. Once the silence is at least the steady mean inter-arrival
1155        // the run is over by the model's own parameters; the confidence is
1156        // the probability a burst inter-arrival would not have lasted this
1157        // long, 1 - exp(-idle / mu_burst).
1158        if self.regime == Regime::Burst
1159            && !self.heuristic_decides()
1160            && let Some(idle_exit) = self.bocpd_idle_exit(now)
1161        {
1162            let (confidence, rate, p_burst) = idle_exit;
1163            self.record_regime_transition(
1164                now,
1165                Regime::Steady,
1166                TransitionReasonCode::BocpdIdleExit,
1167                confidence,
1168                rate,
1169                Some(p_burst),
1170            );
1171        }
1172
1173        if self.pending_size.is_none() {
1174            return CoalesceAction::None;
1175        }
1176
1177        if self.window_start.is_none() {
1178            return CoalesceAction::None;
1179        }
1180
1181        // Check hard deadline
1182        let time_since_render = duration_since_or_zero(now, self.last_render);
1183        if time_since_render >= Duration::from_millis(self.config.hard_deadline_ms) {
1184            return self.apply_pending_at(now, true);
1185        }
1186
1187        let delay_ms = self.current_delay_ms();
1188
1189        // Check if enough time has passed since last event
1190        if let Some(last_event) = self.last_event {
1191            let since_last_event = duration_since_or_zero(now, last_event);
1192            if since_last_event >= Duration::from_millis(delay_ms) {
1193                return self.apply_pending_at(now, false);
1194            }
1195        }
1196
1197        CoalesceAction::None
1198    }
1199
1200    /// Time until the pending resize should be applied.
1201    pub fn time_until_apply(&self, now: Instant) -> Option<Duration> {
1202        let _pending = self.pending_size?;
1203
1204        // 1. Check hard deadline relative to last_render
1205        let time_since_render = duration_since_or_zero(now, self.last_render);
1206        let hard_deadline = Duration::from_millis(self.config.hard_deadline_ms);
1207        let hard_deadline_remaining = hard_deadline.saturating_sub(time_since_render);
1208
1209        // 2. Check delay since last event
1210        let delay_remaining = if let Some(last_event) = self.last_event {
1211            let since_last_event = duration_since_or_zero(now, last_event);
1212            let delay = Duration::from_millis(self.current_delay_ms());
1213            delay.saturating_sub(since_last_event)
1214        } else {
1215            Duration::ZERO
1216        };
1217
1218        // We apply when BOTH conditions are met (or hard deadline reached)
1219        // Wait, the logic in handle_resize/tick is:
1220        // IF (time_since_render >= hard_deadline) OR (since_last_event >= delay)
1221        // So time_until_apply should be the MIN of these two.
1222        Some(hard_deadline_remaining.min(delay_remaining))
1223    }
1224
1225    /// Check if there's a pending resize.
1226    #[inline]
1227    pub fn has_pending(&self) -> bool {
1228        self.pending_size.is_some()
1229    }
1230
1231    /// Get the current regime.
1232    #[inline]
1233    pub fn regime(&self) -> Regime {
1234        self.regime
1235    }
1236
1237    /// Check if BOCPD-based regime detection is enabled.
1238    #[inline]
1239    pub fn bocpd_enabled(&self) -> bool {
1240        self.bocpd.is_some()
1241    }
1242
1243    /// Detector that made the most recent regime decision (`Heuristic`
1244    /// before the first event).
1245    #[inline]
1246    pub fn last_detector(&self) -> RegimeDetector {
1247        self.last_detector
1248    }
1249
1250    /// Regime decisions made by each detector in this session.
1251    #[inline]
1252    pub fn detector_decisions(&self) -> DetectorDecisions {
1253        self.detector_decisions
1254    }
1255
1256    /// Get the BOCPD detector for inspection (if enabled).
1257    ///
1258    /// Returns `None` if BOCPD is not enabled.
1259    #[inline]
1260    pub fn bocpd(&self) -> Option<&BocpdDetector> {
1261        self.bocpd.as_ref()
1262    }
1263
1264    /// Get the current P(burst) from BOCPD (if enabled).
1265    ///
1266    /// Returns the posterior probability that the system is in burst regime.
1267    /// Returns `None` if BOCPD is not enabled.
1268    #[inline]
1269    pub fn bocpd_p_burst(&self) -> Option<f64> {
1270        self.bocpd.as_ref().map(|b| b.p_burst())
1271    }
1272
1273    /// Get the recommended delay from BOCPD (if enabled).
1274    ///
1275    /// Returns the recommended coalesce delay in milliseconds based on the
1276    /// current posterior distribution. Returns `None` if BOCPD is not enabled.
1277    #[inline]
1278    pub fn bocpd_recommended_delay(&self) -> Option<u64> {
1279        self.bocpd
1280            .as_ref()
1281            .map(|b| b.recommended_delay(self.config.steady_delay_ms, self.config.burst_delay_ms))
1282    }
1283
1284    /// Get the current event rate (events/second).
1285    pub fn event_rate(&self) -> f64 {
1286        self.calculate_event_rate(Instant::now())
1287    }
1288
1289    /// Get the last applied size.
1290    #[inline]
1291    pub fn last_applied(&self) -> (u16, u16) {
1292        self.last_applied
1293    }
1294
1295    /// Get decision logs (if logging enabled).
1296    pub fn logs(&self) -> &[DecisionLog] {
1297        &self.logs
1298    }
1299
1300    /// Get regime transition evidence logs.
1301    pub fn transition_logs(&self) -> &[RegimeTransitionLog] {
1302        &self.transition_logs
1303    }
1304
1305    /// Record a coalesce cycle time, retaining only the most recent window.
1306    ///
1307    /// Unbounded retention is a slow leak in long-lived sessions (one entry
1308    /// per applied resize); percentiles over the recent window are also the
1309    /// more meaningful telemetry.
1310    fn record_cycle_time(&mut self, coalesce_ms: f64) {
1311        self.cycle_times.push(coalesce_ms);
1312        let len = self.cycle_times.len();
1313        if len > MAX_CYCLE_TIME_SAMPLES {
1314            self.cycle_times.drain(..len - MAX_CYCLE_TIME_SAMPLES);
1315        }
1316    }
1317
1318    /// Append a regime-transition evidence entry, retaining only the most
1319    /// recent window (one entry per regime flip, never truncated by the
1320    /// runtime otherwise).
1321    fn push_transition_log(&mut self, log: RegimeTransitionLog) {
1322        self.transition_logs.push(log);
1323        let len = self.transition_logs.len();
1324        if len > MAX_TRANSITION_LOGS {
1325            self.transition_logs.drain(..len - MAX_TRANSITION_LOGS);
1326        }
1327    }
1328
1329    /// Clear decision logs.
1330    pub fn clear_logs(&mut self) {
1331        self.logs.clear();
1332        self.transition_logs.clear();
1333        self.pending_transition_evidence = None;
1334        self.log_start = None;
1335        self.config_logged = false;
1336    }
1337
1338    /// Get statistics about the coalescer.
1339    pub fn stats(&self) -> CoalescerStats {
1340        CoalescerStats {
1341            event_count: self.event_count,
1342            regime: self.regime,
1343            event_rate: self.event_rate(),
1344            has_pending: self.pending_size.is_some(),
1345            last_applied: self.last_applied,
1346            detector: self.last_detector,
1347            detector_decisions: self.detector_decisions,
1348        }
1349    }
1350
1351    /// Export decision logs as JSONL (one entry per line).
1352    ///
1353    /// Stamping semantics (by design, bd-1za0z item 2): every row carries its
1354    /// own decision-time `pending_size` / `applied_size`; the `cols` / `rows`
1355    /// header fields are the size applied at export time, so a batch export
1356    /// answers "what was the terminal when this file was written", not "what
1357    /// was it at each decision". Consumers that need the per-decision size
1358    /// read the row's own fields.
1359    #[must_use]
1360    pub fn decision_logs_jsonl(&self) -> String {
1361        let (cols, rows) = self.last_applied;
1362        let run_id = self.evidence_run_id.as_str();
1363        let screen_mode = self.evidence_screen_mode;
1364        self.logs
1365            .iter()
1366            .map(|entry| entry.to_jsonl(run_id, screen_mode, cols, rows))
1367            .collect::<Vec<_>>()
1368            .join("\n")
1369    }
1370
1371    /// Compute a deterministic checksum of decision logs.
1372    #[must_use]
1373    pub fn decision_checksum(&self) -> u64 {
1374        let mut hash = FNV_OFFSET_BASIS;
1375        for entry in &self.logs {
1376            fnv_hash_bytes(&mut hash, &entry.event_idx.to_le_bytes());
1377            fnv_hash_bytes(&mut hash, &entry.elapsed_ms.to_bits().to_le_bytes());
1378            fnv_hash_bytes(&mut hash, &entry.dt_ms.to_bits().to_le_bytes());
1379            fnv_hash_bytes(&mut hash, &entry.event_rate.to_bits().to_le_bytes());
1380            fnv_hash_bytes(
1381                &mut hash,
1382                &[match entry.regime {
1383                    Regime::Steady => 0u8,
1384                    Regime::Burst => 1u8,
1385                }],
1386            );
1387            fnv_hash_bytes(&mut hash, entry.action.as_bytes());
1388            fnv_hash_bytes(&mut hash, &[0u8]); // separator
1389
1390            fnv_hash_bytes(&mut hash, &[entry.pending_size.is_some() as u8]);
1391            if let Some((w, h)) = entry.pending_size {
1392                fnv_hash_bytes(&mut hash, &w.to_le_bytes());
1393                fnv_hash_bytes(&mut hash, &h.to_le_bytes());
1394            }
1395
1396            fnv_hash_bytes(&mut hash, &[entry.applied_size.is_some() as u8]);
1397            if let Some((w, h)) = entry.applied_size {
1398                fnv_hash_bytes(&mut hash, &w.to_le_bytes());
1399                fnv_hash_bytes(&mut hash, &h.to_le_bytes());
1400            }
1401
1402            fnv_hash_bytes(
1403                &mut hash,
1404                &entry.time_since_render_ms.to_bits().to_le_bytes(),
1405            );
1406            fnv_hash_bytes(&mut hash, &[entry.coalesce_ms.is_some() as u8]);
1407            if let Some(ms) = entry.coalesce_ms {
1408                fnv_hash_bytes(&mut hash, &ms.to_bits().to_le_bytes());
1409            }
1410            fnv_hash_bytes(&mut hash, &[entry.forced as u8]);
1411            fnv_hash_bytes(&mut hash, &[entry.transition_reason_code.is_some() as u8]);
1412            if let Some(reason_code) = entry.transition_reason_code {
1413                fnv_hash_bytes(&mut hash, reason_code.as_str().as_bytes());
1414            }
1415            fnv_hash_bytes(&mut hash, &[entry.transition_confidence.is_some() as u8]);
1416            if let Some(confidence) = entry.transition_confidence {
1417                fnv_hash_bytes(&mut hash, &confidence.to_bits().to_le_bytes());
1418            }
1419        }
1420        hash
1421    }
1422
1423    /// Compute checksum as hex string.
1424    #[must_use]
1425    pub fn decision_checksum_hex(&self) -> String {
1426        format!("{:016x}", self.decision_checksum())
1427    }
1428
1429    /// Compute a summary of the decision log.
1430    #[must_use]
1431    #[allow(clippy::field_reassign_with_default)]
1432    pub fn decision_summary(&self) -> DecisionSummary {
1433        let mut summary = DecisionSummary::default();
1434        summary.decision_count = self.logs.len();
1435        summary.last_applied = self.last_applied;
1436        summary.regime = self.regime;
1437
1438        for entry in &self.logs {
1439            match entry.action {
1440                "apply" | "apply_forced" | "apply_immediate" => {
1441                    summary.apply_count += 1;
1442                    if entry.forced {
1443                        summary.forced_apply_count += 1;
1444                    }
1445                }
1446                "coalesce" => summary.coalesce_count += 1,
1447                "skip_same_size" => summary.skip_count += 1,
1448                _ => {}
1449            }
1450        }
1451
1452        summary.checksum = self.decision_checksum();
1453        summary
1454    }
1455
1456    /// Export config + decision logs + summary as JSONL.
1457    #[must_use]
1458    pub fn evidence_to_jsonl(&self) -> String {
1459        let mut lines = Vec::with_capacity(self.logs.len() + self.transition_logs.len() + 2);
1460        let (cols, rows) = self.last_applied;
1461        let run_id = self.evidence_run_id.as_str();
1462        let screen_mode = self.evidence_screen_mode;
1463        let summary_event_idx = self
1464            .logs
1465            .last()
1466            .map(|entry| entry.event_idx)
1467            .or_else(|| self.transition_logs.last().map(|entry| entry.event_idx))
1468            .unwrap_or(0);
1469        lines.push(self.config.to_jsonl(run_id, screen_mode, cols, rows, 0));
1470        lines.extend(
1471            self.logs
1472                .iter()
1473                .map(|entry| entry.to_jsonl(run_id, screen_mode, cols, rows)),
1474        );
1475        lines.extend(
1476            self.transition_logs
1477                .iter()
1478                .map(|entry| entry.to_jsonl(run_id, screen_mode, cols, rows)),
1479        );
1480        lines.push(self.decision_summary().to_jsonl(
1481            run_id,
1482            screen_mode,
1483            cols,
1484            rows,
1485            summary_event_idx,
1486        ));
1487        lines.join("\n")
1488    }
1489
1490    // --- Internal methods ---
1491
1492    fn apply_pending_at(&mut self, now: Instant, forced: bool) -> CoalesceAction {
1493        let Some((width, height)) = self.pending_size.take() else {
1494            return CoalesceAction::None;
1495        };
1496
1497        let coalesce_time = self
1498            .window_start
1499            .map(|s| duration_since_or_zero(now, s))
1500            .unwrap_or(Duration::ZERO);
1501        let coalesce_ms = coalesce_time.as_secs_f64() * 1000.0;
1502
1503        // Track cycle time for percentile calculation (bd-1rz0.7)
1504        self.record_cycle_time(coalesce_ms);
1505
1506        self.window_start = None;
1507        self.last_applied = (width, height);
1508        self.last_render = now;
1509
1510        // Reset events in window counter
1511        self.events_in_window = 0;
1512
1513        self.log_decision(
1514            now,
1515            if forced { "apply_forced" } else { "apply" },
1516            forced,
1517            None,
1518            Some(coalesce_ms),
1519        );
1520
1521        // Fire telemetry hooks (bd-1rz0.7)
1522        if let Some(ref hooks) = self.telemetry_hooks
1523            && let Some(entry) = self.logs.last()
1524        {
1525            hooks.fire_resize_applied(entry);
1526        }
1527
1528        CoalesceAction::ApplyResize {
1529            width,
1530            height,
1531            coalesce_time,
1532            forced_by_deadline: forced,
1533        }
1534    }
1535
1536    #[inline]
1537    fn current_delay_ms(&self) -> u64 {
1538        match (&self.bocpd, self.last_detector) {
1539            (Some(bocpd), RegimeDetector::Bocpd) => {
1540                bocpd.recommended_delay(self.config.steady_delay_ms, self.config.burst_delay_ms)
1541            }
1542            _ => match self.regime {
1543                Regime::Steady => self.config.steady_delay_ms,
1544                Regime::Burst => self.config.burst_delay_ms,
1545            },
1546        }
1547    }
1548
1549    /// True when the rate heuristic owns regime decisions right now: BOCPD
1550    /// is off, or the fallback decided the most recent event.
1551    #[inline]
1552    fn heuristic_decides(&self) -> bool {
1553        self.bocpd.is_none() || self.last_detector == RegimeDetector::Heuristic
1554    }
1555
1556    /// BOCPD-mode idle check for `tick_at`: when the silence since the last
1557    /// event has reached the steady mean inter-arrival, returns the
1558    /// transition confidence, the current event rate and the posterior so
1559    /// the caller can record a `BocpdIdleExit`.
1560    fn bocpd_idle_exit(&self, now: Instant) -> Option<(f64, f64, f64)> {
1561        let bocpd = self.bocpd.as_ref()?;
1562        let last_event = self.last_event?;
1563        let idle_ms = duration_since_or_zero(now, last_event).as_secs_f64() * 1000.0;
1564        let cfg = bocpd.config();
1565        if idle_ms < cfg.mu_steady_ms {
1566            return None;
1567        }
1568        let confidence =
1569            (1.0 - (-idle_ms / cfg.mu_burst_ms.max(f64::EPSILON)).exp()).clamp(0.0, 1.0);
1570        Some((confidence, self.calculate_event_rate(now), bocpd.p_burst()))
1571    }
1572
1573    /// Choose the detector for an event whose inter-arrival is
1574    /// `observation_ms` (`None` for the first event of the session).
1575    fn select_detector(&self, observation_ms: Option<f64>) -> RegimeDetector {
1576        let Some(bocpd) = self.bocpd.as_ref() else {
1577            return RegimeDetector::Heuristic;
1578        };
1579        if !self.config.heuristic_fallback {
1580            return RegimeDetector::Bocpd;
1581        }
1582        let cfg = bocpd.config();
1583        match observation_ms {
1584            None => RegimeDetector::Heuristic,
1585            Some(obs) if !obs.is_finite() => RegimeDetector::Heuristic,
1586            Some(obs) if obs < cfg.min_observation_ms || obs > cfg.max_observation_ms => {
1587                RegimeDetector::Heuristic
1588            }
1589            Some(_) => RegimeDetector::Bocpd,
1590        }
1591    }
1592
1593    fn update_regime(&mut self, now: Instant) {
1594        // Inter-arrival as the posterior would see it (`last_event` is the
1595        // previous event at this point of the event path).
1596        let observation_ms = self
1597            .last_event
1598            .map(|t| duration_since_or_zero(now, t).as_secs_f64() * 1000.0);
1599        let mut detector = self.select_detector(observation_ms);
1600
1601        // The posterior is always updated so it tracks the stream even while
1602        // the heuristic decides; only the verdict source changes.
1603        let posterior = self.bocpd.as_mut().map(|bocpd| {
1604            bocpd.observe_event(now);
1605            (bocpd.regime(), bocpd.p_burst())
1606        });
1607        if self.config.heuristic_fallback
1608            && let Some((_, p_burst)) = posterior
1609            && !p_burst.is_finite()
1610        {
1611            detector = RegimeDetector::Heuristic;
1612        }
1613
1614        if detector != self.last_detector {
1615            tracing::debug!(
1616                target: crate::telemetry_schema::TARGET_RESIZE,
1617                from = self.last_detector.as_str(),
1618                to = detector.as_str(),
1619                observation_ms = ?observation_ms,
1620                event_idx = self.event_count,
1621                "resize regime detector switched"
1622            );
1623        }
1624        self.last_detector = detector;
1625
1626        match detector {
1627            RegimeDetector::Bocpd => {
1628                self.detector_decisions.bocpd += 1;
1629                let Some((bocpd_regime, p_burst)) = posterior else {
1630                    return;
1631                };
1632                // Map BOCPD regime to coalescer regime.
1633                let proposed = match bocpd_regime {
1634                    BocpdRegime::Steady => Regime::Steady,
1635                    BocpdRegime::Burst => Regime::Burst,
1636                    // During transition, maintain current regime to avoid thrashing.
1637                    BocpdRegime::Transitional => self.regime,
1638                };
1639                if proposed != self.regime {
1640                    let (reason_code, confidence) = if proposed == Regime::Burst {
1641                        (
1642                            TransitionReasonCode::BocpdPosteriorBurst,
1643                            p_burst.clamp(0.0, 1.0),
1644                        )
1645                    } else {
1646                        (
1647                            TransitionReasonCode::BocpdPosteriorSteady,
1648                            (1.0 - p_burst).clamp(0.0, 1.0),
1649                        )
1650                    };
1651                    let rate = self.calculate_event_rate(now);
1652                    self.record_regime_transition(
1653                        now,
1654                        proposed,
1655                        reason_code,
1656                        confidence,
1657                        rate,
1658                        Some(p_burst),
1659                    );
1660                }
1661            }
1662            RegimeDetector::Heuristic => {
1663                self.detector_decisions.heuristic += 1;
1664                let rate = self.calculate_event_rate(now);
1665                let p_burst = posterior.map(|(_, p)| p).filter(|p| p.is_finite());
1666
1667                match self.regime {
1668                    Regime::Steady => {
1669                        if rate >= self.config.burst_enter_rate {
1670                            self.cooldown_remaining = self.config.cooldown_frames.max(1);
1671                            let confidence = (rate / self.config.burst_enter_rate).clamp(0.0, 1.0);
1672                            self.record_regime_transition(
1673                                now,
1674                                Regime::Burst,
1675                                TransitionReasonCode::HeuristicEnterBurstRate,
1676                                confidence,
1677                                rate,
1678                                p_burst,
1679                            );
1680                        }
1681                    }
1682                    Regime::Burst => {
1683                        if rate >= self.config.burst_exit_rate {
1684                            self.cooldown_remaining = self.config.cooldown_frames.max(1);
1685                        }
1686                    }
1687                }
1688            }
1689        }
1690    }
1691
1692    fn record_regime_transition(
1693        &mut self,
1694        now: Instant,
1695        to_regime: Regime,
1696        reason_code: TransitionReasonCode,
1697        confidence: f64,
1698        event_rate: f64,
1699        p_burst: Option<f64>,
1700    ) {
1701        let from_regime = self.regime;
1702        if from_regime == to_regime {
1703            return;
1704        }
1705        self.regime = to_regime;
1706        self.regime_transitions += 1;
1707        self.pending_transition_evidence = Some(PendingTransitionEvidence {
1708            reason_code,
1709            confidence,
1710        });
1711        self.push_transition_log(RegimeTransitionLog {
1712            timestamp: now,
1713            event_idx: self.event_count,
1714            from_regime,
1715            to_regime,
1716            reason_code,
1717            confidence,
1718            event_rate,
1719            p_burst,
1720            cooldown_remaining: self.cooldown_remaining,
1721            detector: self.last_detector,
1722        });
1723        if let Some(ref hooks) = self.telemetry_hooks {
1724            hooks.fire_regime_change(from_regime, to_regime);
1725        }
1726
1727        if let Some(ref sink) = self.evidence_sink {
1728            let (cols, rows) = self.last_applied;
1729            let run_id = self.evidence_run_id.as_str();
1730            let screen_mode = self.evidence_screen_mode;
1731            if !self.config_logged {
1732                let _ = sink.write_jsonl(&self.config.to_jsonl(run_id, screen_mode, cols, rows, 0));
1733                self.config_logged = true;
1734            }
1735            if let Some(entry) = self.transition_logs.last() {
1736                let _ = sink.write_jsonl(&entry.to_jsonl(run_id, screen_mode, cols, rows));
1737            }
1738        }
1739    }
1740
1741    fn calculate_event_rate(&self, now: Instant) -> f64 {
1742        if self.event_times.len() < 2 {
1743            return 0.0;
1744        }
1745
1746        let first = *self
1747            .event_times
1748            .front()
1749            .expect("event_times has >=2 elements per length guard");
1750        let window_duration = match now.checked_duration_since(first) {
1751            Some(duration) => duration,
1752            None => return 0.0,
1753        };
1754
1755        // Enforce a minimum duration of 1ms to prevent divide-by-zero or instability
1756        // and to correctly reflect high rates for near-instantaneous bursts.
1757        let duration_secs = window_duration.as_secs_f64().max(0.001);
1758
1759        // Number of intervals is len - 1
1760        ((self.event_times.len() - 1) as f64) / duration_secs
1761    }
1762
1763    fn log_decision(
1764        &mut self,
1765        now: Instant,
1766        action: &'static str,
1767        forced: bool,
1768        dt_ms_override: Option<f64>,
1769        coalesce_ms: Option<f64>,
1770    ) {
1771        if !self.config.enable_logging {
1772            return;
1773        }
1774
1775        if self.log_start.is_none() {
1776            self.log_start = Some(now);
1777        }
1778
1779        let elapsed_ms = self
1780            .log_start
1781            .map(|t| duration_since_or_zero(now, t).as_secs_f64() * 1000.0)
1782            .unwrap_or(0.0);
1783
1784        let dt_ms = dt_ms_override
1785            .or_else(|| {
1786                self.last_event
1787                    .map(|t| duration_since_or_zero(now, t).as_secs_f64() * 1000.0)
1788            })
1789            .unwrap_or(0.0);
1790
1791        let time_since_render_ms =
1792            duration_since_or_zero(now, self.last_render).as_secs_f64() * 1000.0;
1793
1794        let applied_size =
1795            if action == "apply" || action == "apply_forced" || action == "apply_immediate" {
1796                Some(self.last_applied)
1797            } else {
1798                None
1799            };
1800        let (transition_reason_code, transition_confidence) =
1801            match self.pending_transition_evidence.take() {
1802                Some(ev) => (Some(ev.reason_code), Some(ev.confidence)),
1803                None => (None, None),
1804            };
1805
1806        self.logs.push(DecisionLog {
1807            timestamp: now,
1808            elapsed_ms,
1809            event_idx: self.event_count,
1810            dt_ms,
1811            event_rate: self.calculate_event_rate(now),
1812            regime: self.regime,
1813            action,
1814            pending_size: self.pending_size,
1815            applied_size,
1816            time_since_render_ms,
1817            coalesce_ms,
1818            forced,
1819            transition_reason_code,
1820            transition_confidence,
1821            detector: self.last_detector,
1822            p_burst: self.bocpd_p_burst().filter(|p| p.is_finite()),
1823        });
1824
1825        if let Some(ref sink) = self.evidence_sink {
1826            let (cols, rows) = self.last_applied;
1827            let run_id = self.evidence_run_id.as_str();
1828            let screen_mode = self.evidence_screen_mode;
1829            if !self.config_logged {
1830                let _ = sink.write_jsonl(&self.config.to_jsonl(run_id, screen_mode, cols, rows, 0));
1831                self.config_logged = true;
1832            }
1833            if let Some(entry) = self.logs.last() {
1834                let _ = sink.write_jsonl(&entry.to_jsonl(run_id, screen_mode, cols, rows));
1835            }
1836            if let Some(ref bocpd) = self.bocpd
1837                && let Some(jsonl) = bocpd.decision_log_jsonl(
1838                    self.config.steady_delay_ms,
1839                    self.config.burst_delay_ms,
1840                    forced,
1841                )
1842            {
1843                let _ = sink.write_jsonl(&jsonl);
1844            }
1845        }
1846    }
1847}
1848
1849/// Statistics about the coalescer state.
1850#[derive(Debug, Clone)]
1851pub struct CoalescerStats {
1852    /// Total events processed.
1853    pub event_count: u64,
1854    /// Current regime.
1855    pub regime: Regime,
1856    /// Current event rate (events/sec).
1857    pub event_rate: f64,
1858    /// Whether there's a pending resize.
1859    pub has_pending: bool,
1860    /// Last applied size.
1861    pub last_applied: (u16, u16),
1862    /// Detector that made the most recent regime decision.
1863    pub detector: RegimeDetector,
1864    /// Regime decisions per detector.
1865    pub detector_decisions: DetectorDecisions,
1866}
1867
1868/// Summary of decision logs.
1869#[derive(Debug, Clone, Default)]
1870pub struct DecisionSummary {
1871    /// Total number of decisions logged.
1872    pub decision_count: usize,
1873    /// Total apply decisions.
1874    pub apply_count: usize,
1875    /// Applies forced by deadline.
1876    pub forced_apply_count: usize,
1877    /// Total coalesce decisions.
1878    pub coalesce_count: usize,
1879    /// Total skip decisions.
1880    pub skip_count: usize,
1881    /// Final regime at summary time.
1882    pub regime: Regime,
1883    /// Last applied size.
1884    pub last_applied: (u16, u16),
1885    /// Checksum for the decision log.
1886    pub checksum: u64,
1887}
1888
1889impl DecisionSummary {
1890    /// Checksum as hex string.
1891    #[must_use]
1892    pub fn checksum_hex(&self) -> String {
1893        format!("{:016x}", self.checksum)
1894    }
1895
1896    /// Serialize summary to JSONL format.
1897    #[must_use]
1898    pub fn to_jsonl(
1899        &self,
1900        run_id: &str,
1901        screen_mode: ScreenMode,
1902        cols: u16,
1903        rows: u16,
1904        event_idx: u64,
1905    ) -> String {
1906        let prefix = evidence_prefix(run_id, screen_mode, cols, rows, event_idx);
1907        format!(
1908            r#"{{{prefix},"event":"summary","decisions":{},"applies":{},"forced_applies":{},"coalesces":{},"skips":{},"regime":"{}","last_w":{},"last_h":{},"checksum":"{}"}}"#,
1909            self.decision_count,
1910            self.apply_count,
1911            self.forced_apply_count,
1912            self.coalesce_count,
1913            self.skip_count,
1914            self.regime.as_str(),
1915            self.last_applied.0,
1916            self.last_applied.1,
1917            self.checksum_hex()
1918        )
1919    }
1920}
1921
1922// =============================================================================
1923// Telemetry Hooks (bd-1rz0.7)
1924// =============================================================================
1925
1926/// Callback type for resize applied events.
1927pub type OnResizeApplied = Box<dyn Fn(&DecisionLog) + Send + Sync>;
1928/// Callback type for regime change events.
1929pub type OnRegimeChange = Box<dyn Fn(Regime, Regime) + Send + Sync>;
1930/// Callback type for coalesce decision events.
1931pub type OnCoalesceDecision = Box<dyn Fn(&DecisionLog) + Send + Sync>;
1932
1933/// Telemetry hooks for observing resize coalescer events.
1934///
1935/// # Example
1936///
1937/// ```ignore
1938/// use ftui_runtime::resize_coalescer::{ResizeCoalescer, TelemetryHooks, CoalescerConfig};
1939///
1940/// let hooks = TelemetryHooks::new()
1941///     .on_resize_applied(|entry| println!("Applied: {}x{}", entry.applied_size.unwrap().0, entry.applied_size.unwrap().1))
1942///     .on_regime_change(|from, to| println!("Regime: {:?} -> {:?}", from, to));
1943///
1944/// let mut coalescer = ResizeCoalescer::new(CoalescerConfig::default(), (80, 24))
1945///     .with_telemetry_hooks(hooks);
1946/// ```
1947pub struct TelemetryHooks {
1948    /// Called when a resize is applied.
1949    on_resize_applied: Option<OnResizeApplied>,
1950    /// Called when regime changes (Steady <-> Burst).
1951    on_regime_change: Option<OnRegimeChange>,
1952    /// Called for every decision (coalesce, apply, skip).
1953    on_decision: Option<OnCoalesceDecision>,
1954    /// Enable tracing events (requires `tracing` feature).
1955    emit_tracing: bool,
1956}
1957
1958impl Default for TelemetryHooks {
1959    fn default() -> Self {
1960        Self::new()
1961    }
1962}
1963
1964impl std::fmt::Debug for TelemetryHooks {
1965    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1966        f.debug_struct("TelemetryHooks")
1967            .field("on_resize_applied", &self.on_resize_applied.is_some())
1968            .field("on_regime_change", &self.on_regime_change.is_some())
1969            .field("on_decision", &self.on_decision.is_some())
1970            .field("emit_tracing", &self.emit_tracing)
1971            .finish()
1972    }
1973}
1974
1975impl TelemetryHooks {
1976    /// Create a new empty hooks instance.
1977    #[must_use]
1978    pub fn new() -> Self {
1979        Self {
1980            on_resize_applied: None,
1981            on_regime_change: None,
1982            on_decision: None,
1983            emit_tracing: false,
1984        }
1985    }
1986
1987    /// Set callback for resize applied events.
1988    #[must_use]
1989    pub fn on_resize_applied<F>(mut self, callback: F) -> Self
1990    where
1991        F: Fn(&DecisionLog) + Send + Sync + 'static,
1992    {
1993        self.on_resize_applied = Some(Box::new(callback));
1994        self
1995    }
1996
1997    /// Set callback for regime change events.
1998    #[must_use]
1999    pub fn on_regime_change<F>(mut self, callback: F) -> Self
2000    where
2001        F: Fn(Regime, Regime) + Send + Sync + 'static,
2002    {
2003        self.on_regime_change = Some(Box::new(callback));
2004        self
2005    }
2006
2007    /// Set callback for all decision events.
2008    #[must_use]
2009    pub fn on_decision<F>(mut self, callback: F) -> Self
2010    where
2011        F: Fn(&DecisionLog) + Send + Sync + 'static,
2012    {
2013        self.on_decision = Some(Box::new(callback));
2014        self
2015    }
2016
2017    /// Enable tracing event emission for OpenTelemetry integration.
2018    ///
2019    /// When enabled, decision events are emitted as `tracing::event!` calls
2020    /// with target `ftui.decision.resize` and all evidence ledger fields.
2021    #[must_use]
2022    pub fn with_tracing(mut self, enabled: bool) -> Self {
2023        self.emit_tracing = enabled;
2024        self
2025    }
2026
2027    /// Check if a resize-applied hook is registered.
2028    pub fn has_resize_applied(&self) -> bool {
2029        self.on_resize_applied.is_some()
2030    }
2031
2032    /// Check if a regime-change hook is registered.
2033    pub fn has_regime_change(&self) -> bool {
2034        self.on_regime_change.is_some()
2035    }
2036
2037    /// Check if a decision hook is registered.
2038    pub fn has_decision(&self) -> bool {
2039        self.on_decision.is_some()
2040    }
2041
2042    /// Invoke the resize applied callback if set.
2043    fn fire_resize_applied(&self, entry: &DecisionLog) {
2044        if let Some(ref cb) = self.on_resize_applied {
2045            cb(entry);
2046        }
2047        if self.emit_tracing {
2048            Self::emit_resize_tracing(entry);
2049        }
2050    }
2051
2052    /// Invoke the regime change callback if set.
2053    fn fire_regime_change(&self, from: Regime, to: Regime) {
2054        if let Some(ref cb) = self.on_regime_change {
2055            cb(from, to);
2056        }
2057        if self.emit_tracing {
2058            tracing::debug!(
2059                target: crate::telemetry_schema::TARGET_RESIZE,
2060                from_regime = %from.as_str(),
2061                to_regime = %to.as_str(),
2062                "regime_change"
2063            );
2064        }
2065    }
2066
2067    /// Invoke the decision callback if set.
2068    fn fire_decision(&self, entry: &DecisionLog) {
2069        if let Some(ref cb) = self.on_decision {
2070            cb(entry);
2071        }
2072    }
2073
2074    /// Emit a tracing event for resize decisions.
2075    fn emit_resize_tracing(entry: &DecisionLog) {
2076        let (pending_w, pending_h) = entry.pending_size.unwrap_or((0, 0));
2077        let (applied_w, applied_h) = entry.applied_size.unwrap_or((0, 0));
2078        let coalesce_ms = entry.coalesce_ms.unwrap_or(0.0);
2079
2080        tracing::info!(
2081            target: crate::telemetry_schema::TARGET_RESIZE,
2082            event_idx = entry.event_idx,
2083            elapsed_ms = entry.elapsed_ms,
2084            dt_ms = entry.dt_ms,
2085            event_rate = entry.event_rate,
2086            regime = %entry.regime.as_str(),
2087            action = entry.action,
2088            pending_w = pending_w,
2089            pending_h = pending_h,
2090            applied_w = applied_w,
2091            applied_h = applied_h,
2092            time_since_render_ms = entry.time_since_render_ms,
2093            coalesce_ms = coalesce_ms,
2094            forced = entry.forced,
2095            "resize_decision"
2096        );
2097    }
2098}
2099
2100#[cfg(test)]
2101mod tests {
2102    use super::*;
2103
2104    #[test]
2105    fn retained_diagnostics_are_bounded() {
2106        let mut c = ResizeCoalescer::new(test_config(), (80, 24));
2107        for i in 0..(MAX_CYCLE_TIME_SAMPLES + 500) {
2108            c.record_cycle_time(i as f64);
2109        }
2110        assert_eq!(c.cycle_times.len(), MAX_CYCLE_TIME_SAMPLES);
2111        // The retained window is the most recent samples.
2112        assert_eq!(c.cycle_times[0], 500.0);
2113        // Percentiles still work over the bounded window.
2114        assert!(c.cycle_time_percentiles().is_some());
2115
2116        let now = Instant::now();
2117        for i in 0..(MAX_TRANSITION_LOGS + 100) {
2118            c.push_transition_log(RegimeTransitionLog {
2119                timestamp: now,
2120                event_idx: i as u64,
2121                from_regime: Regime::Steady,
2122                to_regime: Regime::Burst,
2123                reason_code: TransitionReasonCode::HeuristicEnterBurstRate,
2124                confidence: 1.0,
2125                event_rate: 0.0,
2126                p_burst: None,
2127                cooldown_remaining: 0,
2128                detector: RegimeDetector::Heuristic,
2129            });
2130        }
2131        assert_eq!(c.transition_logs.len(), MAX_TRANSITION_LOGS);
2132        assert_eq!(c.transition_logs[0].event_idx, 100);
2133    }
2134
2135    fn test_config() -> CoalescerConfig {
2136        CoalescerConfig {
2137            steady_delay_ms: 16,
2138            burst_delay_ms: 40,
2139            hard_deadline_ms: 100,
2140            burst_enter_rate: 10.0,
2141            burst_exit_rate: 5.0,
2142            cooldown_frames: 3,
2143            rate_window_size: 8,
2144            enable_logging: true,
2145            enable_bocpd: false,
2146            heuristic_fallback: true,
2147            bocpd_config: None,
2148        }
2149    }
2150
2151    #[derive(Debug, Clone, Copy)]
2152    struct SimulationMetrics {
2153        event_count: u64,
2154        apply_count: u64,
2155        forced_count: u64,
2156        mean_coalesce_ms: f64,
2157        max_coalesce_ms: f64,
2158        decision_checksum: u64,
2159        final_regime: Regime,
2160    }
2161
2162    impl SimulationMetrics {
2163        fn to_jsonl(self, pattern: &str, mode: &str) -> String {
2164            let pattern = json_escape(pattern);
2165            let mode = json_escape(mode);
2166            let apply_ratio = if self.event_count == 0 {
2167                0.0
2168            } else {
2169                self.apply_count as f64 / self.event_count as f64
2170            };
2171
2172            format!(
2173                r#"{{"event":"simulation_summary","pattern":"{pattern}","mode":"{mode}","events":{},"applies":{},"forced":{},"apply_ratio":{:.4},"mean_coalesce_ms":{:.3},"max_coalesce_ms":{:.3},"final_regime":"{}","checksum":"{:016x}"}}"#,
2174                self.event_count,
2175                self.apply_count,
2176                self.forced_count,
2177                apply_ratio,
2178                self.mean_coalesce_ms,
2179                self.max_coalesce_ms,
2180                self.final_regime.as_str(),
2181                self.decision_checksum
2182            )
2183        }
2184    }
2185
2186    #[derive(Debug, Clone, Copy)]
2187    struct SimulationComparison {
2188        apply_delta: i64,
2189        mean_coalesce_delta_ms: f64,
2190    }
2191
2192    impl SimulationComparison {
2193        fn from_metrics(heuristic: SimulationMetrics, bocpd: SimulationMetrics) -> Self {
2194            let heuristic_apply = i64::try_from(heuristic.apply_count).unwrap_or(i64::MAX);
2195            let bocpd_apply = i64::try_from(bocpd.apply_count).unwrap_or(i64::MAX);
2196            let apply_delta = heuristic_apply.saturating_sub(bocpd_apply);
2197            let mean_coalesce_delta_ms = heuristic.mean_coalesce_ms - bocpd.mean_coalesce_ms;
2198            Self {
2199                apply_delta,
2200                mean_coalesce_delta_ms,
2201            }
2202        }
2203
2204        fn to_jsonl(self, pattern: &str) -> String {
2205            let pattern = json_escape(pattern);
2206            format!(
2207                r#"{{"event":"simulation_compare","pattern":"{pattern}","apply_delta":{},"mean_coalesce_delta_ms":{:.3}}}"#,
2208                self.apply_delta, self.mean_coalesce_delta_ms
2209            )
2210        }
2211    }
2212
2213    fn as_u64(value: usize) -> u64 {
2214        u64::try_from(value).unwrap_or(u64::MAX)
2215    }
2216
2217    fn build_schedule(base: Instant, events: &[(u16, u16, u64)]) -> Vec<(Instant, u16, u16)> {
2218        let mut schedule = Vec::with_capacity(events.len());
2219        let mut elapsed_ms = 0u64;
2220        for (w, h, delay_ms) in events {
2221            elapsed_ms = elapsed_ms.saturating_add(*delay_ms);
2222            schedule.push((base + Duration::from_millis(elapsed_ms), *w, *h));
2223        }
2224        schedule
2225    }
2226
2227    fn run_simulation(
2228        events: &[(u16, u16, u64)],
2229        config: CoalescerConfig,
2230        tick_ms: u64,
2231    ) -> SimulationMetrics {
2232        let mut c = ResizeCoalescer::new(config, (80, 24));
2233        let base = Instant::now();
2234        let schedule = build_schedule(base, events);
2235        let last_event_ms = schedule
2236            .last()
2237            .map(|(time, _, _)| {
2238                u64::try_from(duration_since_or_zero(*time, base).as_millis()).unwrap_or(u64::MAX)
2239            })
2240            .unwrap_or(0);
2241        let end_ms = last_event_ms
2242            .saturating_add(c.config.hard_deadline_ms)
2243            .saturating_add(tick_ms);
2244
2245        let mut next_idx = 0usize;
2246        let mut now_ms = 0u64;
2247        while now_ms <= end_ms {
2248            let now = base + Duration::from_millis(now_ms);
2249
2250            while next_idx < schedule.len() && schedule[next_idx].0 <= now {
2251                let (event_time, w, h) = schedule[next_idx];
2252                let _ = c.handle_resize_at(w, h, event_time);
2253                next_idx += 1;
2254            }
2255
2256            let _ = c.tick_at(now);
2257            now_ms = now_ms.saturating_add(tick_ms);
2258        }
2259
2260        let mut coalesce_values = Vec::new();
2261        let mut apply_count = 0usize;
2262        let mut forced_count = 0usize;
2263        for entry in c.logs() {
2264            if matches!(entry.action, "apply" | "apply_forced" | "apply_immediate") {
2265                apply_count += 1;
2266                if entry.forced {
2267                    forced_count += 1;
2268                }
2269                if let Some(ms) = entry.coalesce_ms {
2270                    coalesce_values.push(ms);
2271                }
2272            }
2273        }
2274
2275        let max_coalesce_ms = coalesce_values
2276            .iter()
2277            .copied()
2278            .fold(0.0_f64, |acc, value| acc.max(value));
2279        let mean_coalesce_ms = if coalesce_values.is_empty() {
2280            0.0
2281        } else {
2282            let sum = coalesce_values.iter().sum::<f64>();
2283            sum / as_u64(coalesce_values.len()) as f64
2284        };
2285
2286        SimulationMetrics {
2287            event_count: as_u64(events.len()),
2288            apply_count: as_u64(apply_count),
2289            forced_count: as_u64(forced_count),
2290            mean_coalesce_ms,
2291            max_coalesce_ms,
2292            decision_checksum: c.decision_checksum(),
2293            final_regime: c.regime(),
2294        }
2295    }
2296
2297    fn steady_pattern() -> Vec<(u16, u16, u64)> {
2298        let mut events = Vec::new();
2299        for i in 0..8u16 {
2300            let width = 90 + i;
2301            let height = 30 + (i % 3);
2302            events.push((width, height, 300));
2303        }
2304        events
2305    }
2306
2307    fn burst_pattern() -> Vec<(u16, u16, u64)> {
2308        let mut events = Vec::new();
2309        for i in 0..30u16 {
2310            let width = 100 + i;
2311            let height = 25 + (i % 5);
2312            events.push((width, height, 10));
2313        }
2314        events
2315    }
2316
2317    fn oscillatory_pattern() -> Vec<(u16, u16, u64)> {
2318        let mut events = Vec::new();
2319        let sizes = [(120, 40), (140, 28), (130, 36), (150, 32)];
2320        let delays = [40u64, 200u64, 60u64, 180u64];
2321        for i in 0..16usize {
2322            let (w, h) = sizes[i % sizes.len()];
2323            let delay = delays[i % delays.len()];
2324            events.push((w + (i as u16 % 3), h, delay));
2325        }
2326        events
2327    }
2328
2329    #[test]
2330    fn new_coalescer_starts_in_steady() {
2331        let c = ResizeCoalescer::new(CoalescerConfig::default(), (80, 24));
2332        assert_eq!(c.regime(), Regime::Steady);
2333        assert!(!c.has_pending());
2334    }
2335
2336    #[test]
2337    fn same_size_returns_none() {
2338        let mut c = ResizeCoalescer::new(test_config(), (80, 24));
2339        let action = c.handle_resize(80, 24);
2340        assert_eq!(action, CoalesceAction::None);
2341    }
2342
2343    #[test]
2344    fn different_size_coalesces_with_no_action_and_a_pending_size() {
2345        let mut c = ResizeCoalescer::new(test_config(), (80, 24));
2346        let action = c.handle_resize(100, 40);
2347        assert_eq!(action, CoalesceAction::None);
2348        assert!(c.has_pending(), "the size is held until the delay elapses");
2349    }
2350
2351    #[test]
2352    fn latest_wins_semantics() {
2353        let config = test_config();
2354        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2355
2356        let base = Instant::now();
2357
2358        // Rapid sequence of resizes
2359        c.handle_resize_at(90, 30, base);
2360        c.handle_resize_at(100, 40, base + Duration::from_millis(5));
2361        c.handle_resize_at(110, 50, base + Duration::from_millis(10));
2362
2363        // Wait for coalesce delay
2364        let action = c.tick_at(base + Duration::from_millis(60));
2365
2366        let (width, height) = if let CoalesceAction::ApplyResize { width, height, .. } = action {
2367            (width, height)
2368        } else {
2369            assert!(
2370                matches!(action, CoalesceAction::ApplyResize { .. }),
2371                "Expected ApplyResize, got {action:?}"
2372            );
2373            return;
2374        };
2375        assert_eq!((width, height), (110, 50), "Should apply latest size");
2376    }
2377
2378    #[test]
2379    fn hard_deadline_forces_apply() {
2380        let config = test_config();
2381        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2382
2383        let base = Instant::now();
2384
2385        // First resize
2386        c.handle_resize_at(100, 40, base);
2387
2388        // Wait past hard deadline
2389        let action = c.tick_at(base + Duration::from_millis(150));
2390
2391        let forced_by_deadline = if let CoalesceAction::ApplyResize {
2392            forced_by_deadline, ..
2393        } = action
2394        {
2395            forced_by_deadline
2396        } else {
2397            assert!(
2398                matches!(action, CoalesceAction::ApplyResize { .. }),
2399                "Expected ApplyResize, got {action:?}"
2400            );
2401            return;
2402        };
2403        assert!(forced_by_deadline, "Should be forced by deadline");
2404    }
2405
2406    /// The hard deadline holds with the posterior on.
2407    ///
2408    /// `hard_deadline_forces_apply` above proves it for the heuristic, which
2409    /// is what ships. This one covers the opt-in path: a 100 ms SLA that
2410    /// quietly stopped applying under `with_bocpd()` would be a regression
2411    /// nothing else here would catch.
2412    #[test]
2413    fn hard_deadline_still_forces_apply_with_bocpd_on() {
2414        let config = CoalescerConfig::default().with_bocpd().with_logging(true);
2415        assert!(config.enable_bocpd, "the detector under test is on");
2416        let mut c = ResizeCoalescer::new(config, (80, 24));
2417
2418        let base = Instant::now();
2419        // A drag: 30 events 5 ms apart is well inside burst territory, so the
2420        // posterior will want to keep coalescing. The deadline must win.
2421        let mut forced_at_ms = None;
2422        for i in 0..30u16 {
2423            let elapsed = u64::from(i) * 5;
2424            if let CoalesceAction::ApplyResize {
2425                forced_by_deadline: true,
2426                ..
2427            } = c.handle_resize_at(100 + i, 40, base + Duration::from_millis(elapsed))
2428            {
2429                forced_at_ms.get_or_insert(elapsed);
2430            }
2431        }
2432        // 30 events at 5 ms only spans 145 ms, and the first is not pending
2433        // until it arrives, so give the tick path the chance the event path
2434        // may not have had.
2435        if forced_at_ms.is_none()
2436            && let CoalesceAction::ApplyResize {
2437                forced_by_deadline: true,
2438                ..
2439            } = c.tick_at(base + Duration::from_millis(200))
2440        {
2441            forced_at_ms = Some(200);
2442        }
2443
2444        assert!(
2445            forced_at_ms.is_some(),
2446            "BOCPD on: nothing was ever forced by the {} ms deadline across 30 events",
2447            CoalescerConfig::default().hard_deadline_ms
2448        );
2449        // Every decision in this window should have been the posterior's, not
2450        // the rate heuristic's -- otherwise the test proves the deadline holds
2451        // for the fallback rather than for BOCPD.
2452        assert!(
2453            c.detector_decisions().bocpd > 0,
2454            "expected the posterior to have decided at least once: {:?}",
2455            c.detector_decisions()
2456        );
2457    }
2458
2459    /// The two delays the README prints, read back from the posterior.
2460    ///
2461    /// README: "Decision thresholds: p_burst > 0.7 → Burst regime (aggressive
2462    /// coalescing), p_burst < 0.3 → Steady regime (responsive)", against
2463    /// `steady_delay_ms: 16` and `burst_delay_ms: 40`.
2464    #[test]
2465    fn steady_regime_delay_is_16ms_and_burst_is_40ms() {
2466        // The thresholds this documents are the posterior's, so opt in.
2467        let config = CoalescerConfig::default().with_bocpd();
2468        assert_eq!((config.steady_delay_ms, config.burst_delay_ms), (16, 40));
2469        let thresholds = config.bocpd_config.clone().unwrap_or_default();
2470
2471        // Steady: 200 ms spacing is exactly mu_steady_ms.
2472        let mut steady = ResizeCoalescer::new(config.clone(), (80, 24));
2473        let base = Instant::now();
2474        for i in 1..=12u64 {
2475            steady.handle_resize_at(100, 40, base + Duration::from_millis(i * 200));
2476        }
2477        let p_steady = steady.bocpd_p_burst().expect("bocpd is on by default");
2478        assert!(
2479            p_steady < thresholds.steady_threshold,
2480            "200 ms spacing should read as steady, p_burst={p_steady}"
2481        );
2482        assert_eq!(steady.bocpd_recommended_delay(), Some(16));
2483
2484        // Burst: 5 ms spacing is well under mu_burst_ms.
2485        let mut burst = ResizeCoalescer::new(config, (80, 24));
2486        let base = Instant::now();
2487        for i in 1..=30u64 {
2488            burst.handle_resize_at(100, 40, base + Duration::from_millis(i * 5));
2489        }
2490        let p_burst = burst.bocpd_p_burst().expect("bocpd is on by default");
2491        assert!(
2492            p_burst > thresholds.burst_threshold,
2493            "5 ms spacing should read as burst, p_burst={p_burst}"
2494        );
2495        assert_eq!(burst.bocpd_recommended_delay(), Some(40));
2496    }
2497
2498    /// Every decision row names its detector, and carries the posterior
2499    /// whenever there is a finite one to carry.
2500    ///
2501    /// README: "Every `decision` and `regime_transition` evidence row carries
2502    /// `detector` (`bocpd` or `heuristic`) and `p_burst`". Note *every*: a row
2503    /// the rate heuristic decided still reports what the posterior thought at
2504    /// the time, which is what makes the log able to answer "should BOCPD have
2505    /// taken this one?". `p_burst` is `None` only where the field's own doc
2506    /// says so -- BOCPD off, or a non-finite posterior.
2507    ///
2508    /// bd-g00-root-epic-ewths.16.3 specifies the opposite, "`p_burst` is
2509    /// `null` exactly when the heuristic decided". That is not what the code
2510    /// does (`p_burst: self.bocpd_p_burst().filter(|p| p.is_finite())`), not
2511    /// what `DecisionLog::p_burst` documents, and not what the README claims.
2512    /// Asserting the bead's version failed on the very first row: the first
2513    /// event of a session has no inter-arrival, so the heuristic decides it,
2514    /// and the posterior is already initialised at its prior. The code is the
2515    /// self-consistent one of the two, so this pins the code.
2516    #[test]
2517    fn decision_evidence_json_has_detector_and_p_burst() {
2518        // `p_burst` only exists when the posterior is running.
2519        let config = CoalescerConfig::default().with_bocpd().with_logging(true);
2520        let mut c = ResizeCoalescer::new(config, (80, 24));
2521
2522        let base = Instant::now();
2523        // Mixed schedule so both detectors get to decide: the first event has
2524        // no inter-arrival and falls back to the heuristic, then a burst, then
2525        // gaps, ending outside the clamp window.
2526        let mut elapsed = 0u64;
2527        let schedule = [0u64, 5, 5, 5, 5, 5, 5, 400, 200, 12_000];
2528        for (i, dt) in schedule.iter().enumerate() {
2529            elapsed += dt;
2530            c.handle_resize_at(
2531                100 + u16::try_from(i).expect("fixture is short"),
2532                40,
2533                base + Duration::from_millis(elapsed),
2534            );
2535        }
2536
2537        let logs = c.logs();
2538        assert!(
2539            !logs.is_empty(),
2540            "logging was enabled but nothing was logged"
2541        );
2542        let mut saw_heuristic = false;
2543        let mut saw_bocpd = false;
2544        for log in logs {
2545            match log.detector {
2546                RegimeDetector::Heuristic => saw_heuristic = true,
2547                RegimeDetector::Bocpd => {
2548                    saw_bocpd = true;
2549                    assert!(
2550                        log.p_burst.is_some(),
2551                        "a bocpd decision must carry the posterior it decided on: {log:?}"
2552                    );
2553                }
2554            }
2555            if let Some(p) = log.p_burst {
2556                assert!(
2557                    (0.0..=1.0).contains(&p) && p.is_finite(),
2558                    "p_burst outside [0,1] or non-finite: {log:?}"
2559                );
2560            }
2561        }
2562        assert!(
2563            saw_heuristic,
2564            "the first event has no inter-arrival and should fall back to the heuristic"
2565        );
2566        assert!(
2567            saw_bocpd,
2568            "the burst should have been decided by the posterior"
2569        );
2570
2571        // The JSONL the evidence pipeline actually emits carries both fields.
2572        let jsonl = c.decision_logs_jsonl();
2573        assert!(jsonl.contains("\"detector\":"), "{jsonl}");
2574        assert!(jsonl.contains("\"p_burst\":"), "{jsonl}");
2575
2576        // The one case where `p_burst` really is absent, per the field's doc:
2577        // BOCPD off. Without this the `Option` would look decorative.
2578        let mut off = ResizeCoalescer::new(
2579            CoalescerConfig::default()
2580                .without_bocpd()
2581                .with_logging(true),
2582            (80, 24),
2583        );
2584        for i in 1..=6u64 {
2585            off.handle_resize_at(100, 40, base + Duration::from_millis(i * 5));
2586        }
2587        assert!(!off.logs().is_empty(), "heuristic-only run logged nothing");
2588        for log in off.logs() {
2589            assert_eq!(log.detector, RegimeDetector::Heuristic, "{log:?}");
2590            assert!(
2591                log.p_burst.is_none(),
2592                "bocpd off must mean no posterior: {log:?}"
2593            );
2594        }
2595    }
2596
2597    /// CONTRACT (bd-1za0z): an isolated resize arriving after a quiet gap is
2598    /// applied instantly but NOT flagged forced — nothing was waiting on the
2599    /// deadline, so it is not an SLA breach.
2600    #[test]
2601    fn isolated_resize_after_quiet_gap_is_not_forced() {
2602        let config = test_config();
2603        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2604
2605        let base = Instant::now();
2606        let action = c.handle_resize_at(120, 40, base + Duration::from_millis(500));
2607
2608        match action {
2609            CoalesceAction::ApplyResize {
2610                forced_by_deadline, ..
2611            } => {
2612                assert!(
2613                    !forced_by_deadline,
2614                    "quiet-gap instant apply must not count as forced"
2615                );
2616            }
2617            other => panic!("Expected ApplyResize, got {other:?}"),
2618        }
2619    }
2620
2621    /// CONTRACT (bd-1za0z): when a resize arrives while an earlier resize is
2622    /// STILL pending past the hard deadline, that IS an SLA breach — forced
2623    /// stays true on the event path too.
2624    #[test]
2625    fn resize_arriving_while_pending_past_deadline_stays_forced() {
2626        let config = test_config();
2627        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2628
2629        let base = Instant::now();
2630        // First event coalesces (no dt yet), leaving work waiting.
2631        c.handle_resize_at(90, 30, base);
2632
2633        // Second event arrives after the hard deadline elapsed with the
2634        // first still unapplied.
2635        let action = c.handle_resize_at(120, 40, base + Duration::from_millis(500));
2636
2637        match action {
2638            CoalesceAction::ApplyResize {
2639                forced_by_deadline, ..
2640            } => {
2641                assert!(
2642                    forced_by_deadline,
2643                    "deadline breach of WAITING work must stay forced"
2644                );
2645            }
2646            other => panic!("Expected ApplyResize, got {other:?}"),
2647        }
2648    }
2649
2650    #[test]
2651    fn burst_mode_detection() {
2652        let config = test_config();
2653        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2654
2655        let base = Instant::now();
2656
2657        // Rapid events to trigger burst mode
2658        for i in 0..15 {
2659            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 10));
2660        }
2661
2662        assert_eq!(c.regime(), Regime::Burst);
2663    }
2664
2665    #[test]
2666    fn steady_mode_fast_response() {
2667        let config = test_config();
2668        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2669
2670        let base = Instant::now();
2671
2672        // Single resize
2673        c.handle_resize_at(100, 40, base);
2674
2675        // In steady mode, should apply after steady_delay
2676        let action = c.tick_at(base + Duration::from_millis(20));
2677
2678        assert!(matches!(action, CoalesceAction::ApplyResize { .. }));
2679    }
2680
2681    #[test]
2682    fn record_external_apply_updates_state_and_logs() {
2683        let config = test_config();
2684        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2685
2686        let base = Instant::now();
2687        c.handle_resize_at(100, 40, base);
2688        c.record_external_apply(120, 50, base + Duration::from_millis(5));
2689
2690        assert!(!c.has_pending());
2691        assert_eq!(c.last_applied(), (120, 50));
2692
2693        let summary = c.decision_summary();
2694        assert_eq!(summary.apply_count, 1);
2695        assert_eq!(summary.last_applied, (120, 50));
2696        assert!(
2697            c.logs()
2698                .iter()
2699                .any(|entry| entry.action == "apply_immediate"),
2700            "record_external_apply should emit apply_immediate decision"
2701        );
2702    }
2703
2704    #[test]
2705    fn coalesce_time_tracked() {
2706        let config = test_config();
2707        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2708
2709        let base = Instant::now();
2710
2711        c.handle_resize_at(100, 40, base);
2712        let action = c.tick_at(base + Duration::from_millis(50));
2713
2714        let coalesce_time = if let CoalesceAction::ApplyResize { coalesce_time, .. } = action {
2715            coalesce_time
2716        } else {
2717            assert!(
2718                matches!(action, CoalesceAction::ApplyResize { .. }),
2719                "Expected ApplyResize"
2720            );
2721            return;
2722        };
2723        assert!(coalesce_time >= Duration::from_millis(40));
2724        assert!(coalesce_time <= Duration::from_millis(60));
2725    }
2726
2727    #[test]
2728    fn event_rate_calculation() {
2729        let config = test_config();
2730        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2731
2732        let base = Instant::now();
2733
2734        // 10 events over 1 second = 10 events/sec
2735        for i in 0..10 {
2736            c.handle_resize_at(80 + i, 24, base + Duration::from_millis(i as u64 * 100));
2737        }
2738
2739        let rate = c.calculate_event_rate(base + Duration::from_millis(1000));
2740        assert!(rate > 8.0 && rate < 12.0, "Rate should be ~10 events/sec");
2741    }
2742
2743    #[test]
2744    fn rapid_burst_triggers_high_rate() {
2745        let config = test_config();
2746        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2747        let base = Instant::now();
2748
2749        // Simulate 8 events arriving at the EXACT same time (or < 1ms)
2750        for _ in 0..8 {
2751            c.handle_resize_at(80, 24, base);
2752        }
2753
2754        let rate = c.calculate_event_rate(base);
2755        // 8 events / 0.001s = 8000 events/sec
2756        assert!(
2757            rate >= 1000.0,
2758            "Rate should be high for instantaneous burst, got {}",
2759            rate
2760        );
2761    }
2762
2763    #[test]
2764    fn cooldown_prevents_immediate_exit() {
2765        let config = test_config();
2766        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
2767
2768        let base = Instant::now();
2769
2770        // Enter burst mode
2771        for i in 0..15 {
2772            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 10));
2773        }
2774        assert_eq!(c.regime(), Regime::Burst);
2775
2776        // Rate should drop but cooldown prevents immediate exit
2777        c.tick_at(base + Duration::from_millis(500));
2778        c.tick_at(base + Duration::from_millis(600));
2779
2780        // Cooldown holds while the rate window still reports the storm.
2781        assert_eq!(c.regime(), Regime::Burst);
2782
2783        // The event-rate window clears after a >1s quiet gap; the cooldown
2784        // then decrements per tick and Burst exits.
2785        for i in 0..6 {
2786            c.tick_at(base + Duration::from_millis(1300 + 100 * i));
2787        }
2788
2789        // Should have exited burst (this pins the cooldown exit path —
2790        // with cooldown_frames armed to at least 1, Burst always has an
2791        // exit once the rate decays).
2792        assert_eq!(c.stats().regime, Regime::Steady);
2793    }
2794
2795    #[test]
2796    fn cooldown_frames_zero_cannot_dead_end_burst() {
2797        // Regression: cooldown_frames = 0 armed cooldown_remaining = 0 on
2798        // Burst entry; the only Burst->Steady exit required
2799        // cooldown_remaining > 0, so the regime pinned at Burst forever and
2800        // the load governor latched Stressed for the session. Arming now
2801        // clamps to >= 1 frame.
2802        let mut c = ResizeCoalescer::new(
2803            CoalescerConfig {
2804                cooldown_frames: 0,
2805                ..Default::default()
2806            },
2807            (80, 24),
2808        );
2809        let base = Instant::now();
2810        // Storm: enter Burst.
2811        for i in 0..10 {
2812            let _ =
2813                c.handle_resize_at(100 + i, 40, base + Duration::from_millis(10 * u64::from(i)));
2814        }
2815        assert_eq!(c.stats().regime, Regime::Burst);
2816        // Storm over: quiet ticks must eventually exit Burst.
2817        for i in 1..=20 {
2818            c.tick_at(base + Duration::from_millis(100 + 200 * i));
2819        }
2820        assert_eq!(
2821            c.stats().regime,
2822            Regime::Steady,
2823            "Burst must always have an exit path"
2824        );
2825    }
2826
2827    #[test]
2828    fn logging_captures_decisions() {
2829        let mut config = test_config();
2830        config.enable_logging = true;
2831        let mut c = ResizeCoalescer::new(config, (80, 24));
2832
2833        let base = Instant::now();
2834        c.handle_resize_at(100, 40, base);
2835        c.tick_at(base + Duration::from_millis(50));
2836
2837        assert!(!c.logs().is_empty());
2838        assert_eq!(c.logs()[0].action, "coalesce");
2839    }
2840
2841    #[test]
2842    fn logging_jsonl_format() {
2843        let mut config = test_config();
2844        config.enable_logging = true;
2845        let mut c = ResizeCoalescer::new(config, (80, 24));
2846
2847        c.handle_resize_at(100, 40, Instant::now());
2848        c.tick_at(Instant::now() + Duration::from_millis(50));
2849
2850        let (cols, rows) = c.last_applied();
2851        let jsonl = c.logs()[0].to_jsonl("resize-test", ScreenMode::AltScreen, cols, rows);
2852
2853        assert!(jsonl.contains("\"event\":\"decision\""));
2854        assert!(jsonl.contains("\"action\":\"coalesce\""));
2855        assert!(jsonl.contains("\"regime\":\"steady\""));
2856        assert!(jsonl.contains("\"pending_w\":100"));
2857        assert!(jsonl.contains("\"pending_h\":40"));
2858    }
2859
2860    #[test]
2861    fn apply_logs_coalesce_ms() {
2862        let mut config = test_config();
2863        config.enable_logging = true;
2864        let mut c = ResizeCoalescer::new(config, (80, 24));
2865
2866        let base = Instant::now();
2867        c.handle_resize_at(100, 40, base);
2868        let action = c.tick_at(base + Duration::from_millis(50));
2869        assert!(matches!(action, CoalesceAction::ApplyResize { .. }));
2870
2871        let last = c.logs().last().expect("Expected a decision log entry");
2872        assert!(last.coalesce_ms.is_some());
2873        assert!(last.coalesce_ms.unwrap() >= 0.0);
2874    }
2875
2876    #[test]
2877    fn decision_checksum_is_stable() {
2878        let mut config = test_config();
2879        config.enable_logging = true;
2880
2881        let base = Instant::now();
2882        let mut c1 = ResizeCoalescer::new(config.clone(), (80, 24)).with_last_render(base);
2883        let mut c2 = ResizeCoalescer::new(config, (80, 24)).with_last_render(base);
2884
2885        for c in [&mut c1, &mut c2] {
2886            c.handle_resize_at(90, 30, base);
2887            c.handle_resize_at(100, 40, base + Duration::from_millis(10));
2888            let _ = c.tick_at(base + Duration::from_millis(80));
2889        }
2890
2891        assert_eq!(c1.decision_checksum(), c2.decision_checksum());
2892    }
2893
2894    #[test]
2895    fn evidence_jsonl_includes_summary() {
2896        let mut config = test_config();
2897        config.enable_logging = true;
2898        let mut c = ResizeCoalescer::new(config, (80, 24));
2899
2900        c.handle_resize_at(100, 40, Instant::now());
2901        c.tick_at(Instant::now() + Duration::from_millis(50));
2902
2903        let jsonl = c.evidence_to_jsonl();
2904
2905        assert!(jsonl.contains("\"event\":\"config\""));
2906        assert!(jsonl.contains("\"event\":\"summary\""));
2907    }
2908
2909    #[test]
2910    fn evidence_jsonl_parses_and_has_required_fields() {
2911        use serde_json::Value;
2912
2913        let mut config = test_config();
2914        config.enable_logging = true;
2915        let base = Instant::now();
2916        let mut c = ResizeCoalescer::new(config, (80, 24))
2917            .with_last_render(base)
2918            .with_evidence_run_id("resize-test")
2919            .with_screen_mode(ScreenMode::AltScreen);
2920
2921        c.handle_resize_at(90, 30, base);
2922        c.handle_resize_at(100, 40, base + Duration::from_millis(10));
2923        let _ = c.tick_at(base + Duration::from_millis(120));
2924
2925        let jsonl = c.evidence_to_jsonl();
2926        let mut saw_config = false;
2927        let mut saw_decision = false;
2928        let mut saw_summary = false;
2929
2930        for line in jsonl.lines() {
2931            let value: Value = serde_json::from_str(line).expect("valid JSONL evidence");
2932            let event = value
2933                .get("event")
2934                .and_then(Value::as_str)
2935                .expect("event field");
2936            assert_eq!(value["schema_version"], EVIDENCE_SCHEMA_VERSION);
2937            assert_eq!(value["run_id"], "resize-test");
2938            assert!(
2939                value["event_idx"].is_number(),
2940                "event_idx should be numeric"
2941            );
2942            assert_eq!(value["screen_mode"], "altscreen");
2943            assert!(value["cols"].is_number(), "cols should be numeric");
2944            assert!(value["rows"].is_number(), "rows should be numeric");
2945            match event {
2946                "config" => {
2947                    for key in [
2948                        "steady_delay_ms",
2949                        "burst_delay_ms",
2950                        "hard_deadline_ms",
2951                        "burst_enter_rate",
2952                        "burst_exit_rate",
2953                        "cooldown_frames",
2954                        "rate_window_size",
2955                        "logging_enabled",
2956                    ] {
2957                        assert!(value.get(key).is_some(), "missing config field {key}");
2958                    }
2959                    saw_config = true;
2960                }
2961                "decision" => {
2962                    for key in [
2963                        "idx",
2964                        "elapsed_ms",
2965                        "dt_ms",
2966                        "event_rate",
2967                        "regime",
2968                        "action",
2969                        "pending_w",
2970                        "pending_h",
2971                        "applied_w",
2972                        "applied_h",
2973                        "time_since_render_ms",
2974                        "coalesce_ms",
2975                        "forced",
2976                        "transition_reason_code",
2977                        "transition_confidence",
2978                    ] {
2979                        assert!(value.get(key).is_some(), "missing decision field {key}");
2980                    }
2981                    saw_decision = true;
2982                }
2983                "summary" => {
2984                    for key in [
2985                        "decisions",
2986                        "applies",
2987                        "forced_applies",
2988                        "coalesces",
2989                        "skips",
2990                        "regime",
2991                        "last_w",
2992                        "last_h",
2993                        "checksum",
2994                    ] {
2995                        assert!(value.get(key).is_some(), "missing summary field {key}");
2996                    }
2997                    saw_summary = true;
2998                }
2999                _ => {}
3000            }
3001        }
3002
3003        assert!(saw_config, "config evidence missing");
3004        assert!(saw_decision, "decision evidence missing");
3005        assert!(saw_summary, "summary evidence missing");
3006    }
3007
3008    #[test]
3009    fn evidence_jsonl_is_deterministic_for_fixed_schedule() {
3010        let mut config = test_config();
3011        config.enable_logging = true;
3012        let base = Instant::now();
3013
3014        let run = || {
3015            let mut c = ResizeCoalescer::new(config.clone(), (80, 24))
3016                .with_last_render(base)
3017                .with_evidence_run_id("resize-test")
3018                .with_screen_mode(ScreenMode::AltScreen);
3019            c.handle_resize_at(90, 30, base);
3020            c.handle_resize_at(100, 40, base + Duration::from_millis(10));
3021            let _ = c.tick_at(base + Duration::from_millis(120));
3022            c.evidence_to_jsonl()
3023        };
3024
3025        let first = run();
3026        let second = run();
3027        assert_eq!(first, second);
3028    }
3029
3030    #[test]
3031    fn bocpd_logging_inherits_coalescer_logging() {
3032        let mut config = test_config();
3033        config.enable_bocpd = true;
3034        config.bocpd_config = Some(BocpdConfig::default());
3035
3036        let c = ResizeCoalescer::new(config, (80, 24));
3037        let bocpd = c.bocpd().expect("BOCPD should be enabled");
3038        assert!(bocpd.config().enable_logging);
3039    }
3040
3041    #[test]
3042    fn stats_reflect_state() {
3043        let mut c = ResizeCoalescer::new(test_config(), (80, 24));
3044        let base = Instant::now();
3045
3046        c.handle_resize_at(100, 40, base);
3047        let action = c.tick_at(base + Duration::from_millis(5));
3048        assert_eq!(action, CoalesceAction::None);
3049
3050        let stats = c.stats();
3051        assert_eq!(stats.event_count, 1);
3052        assert!(stats.has_pending);
3053        assert_eq!(stats.last_applied, (80, 24));
3054
3055        let action = c.tick_at(base + Duration::from_millis(50));
3056        assert_eq!(
3057            action,
3058            CoalesceAction::ApplyResize {
3059                width: 100,
3060                height: 40,
3061                coalesce_time: Duration::from_millis(50),
3062                forced_by_deadline: false,
3063            }
3064        );
3065
3066        let stats = c.stats();
3067        assert!(!stats.has_pending);
3068        assert_eq!(stats.last_applied, (100, 40));
3069    }
3070
3071    #[test]
3072    fn time_until_apply_calculation() {
3073        let config = test_config();
3074        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
3075
3076        let base = Instant::now();
3077        c.handle_resize_at(100, 40, base);
3078
3079        let time_left = c.time_until_apply(base + Duration::from_millis(5));
3080        assert!(time_left.is_some());
3081        let time_left = time_left.unwrap();
3082        assert!(time_left.as_millis() > 0);
3083        assert!(time_left.as_millis() < config.steady_delay_ms as u128);
3084    }
3085
3086    #[test]
3087    fn deterministic_behavior() {
3088        let config = test_config();
3089
3090        // Run twice with same inputs
3091        let results: Vec<_> = (0..2)
3092            .map(|_| {
3093                let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
3094                let base = Instant::now();
3095
3096                for i in 0..5 {
3097                    c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 20));
3098                }
3099
3100                c.tick_at(base + Duration::from_millis(200))
3101            })
3102            .collect();
3103
3104        assert_eq!(results[0], results[1], "Results must be deterministic");
3105    }
3106
3107    #[test]
3108    fn transition_reason_codes_and_evidence_fields_are_logged() {
3109        let mut config = test_config();
3110        config.enable_logging = true;
3111        config.hard_deadline_ms = 5_000;
3112        config.burst_delay_ms = 50;
3113        let base = Instant::now();
3114        let mut c = ResizeCoalescer::new(config, (80, 24)).with_last_render(base);
3115
3116        for i in 0..12 {
3117            c.handle_resize_at(90 + i, 30, base + Duration::from_millis(i as u64 * 10));
3118        }
3119
3120        let transition = c
3121            .transition_logs()
3122            .first()
3123            .expect("rapid events should trigger a transition");
3124        assert_eq!(transition.from_regime, Regime::Steady);
3125        assert_eq!(transition.to_regime, Regime::Burst);
3126        assert_eq!(
3127            transition.reason_code,
3128            TransitionReasonCode::HeuristicEnterBurstRate
3129        );
3130        assert!(
3131            (0.0..=1.0).contains(&transition.confidence),
3132            "transition confidence should be normalized"
3133        );
3134        assert!(
3135            transition.event_rate >= 0.0,
3136            "event-rate evidence should be included"
3137        );
3138
3139        let decision_with_transition = c
3140            .logs()
3141            .iter()
3142            .find(|entry| entry.transition_reason_code.is_some())
3143            .expect("transition decisions should include reason code/evidence");
3144        assert_eq!(
3145            decision_with_transition.transition_reason_code,
3146            Some(TransitionReasonCode::HeuristicEnterBurstRate)
3147        );
3148        assert!(decision_with_transition.transition_confidence.is_some());
3149
3150        let jsonl = c.evidence_to_jsonl();
3151        assert!(jsonl.contains("\"event\":\"regime_transition\""));
3152        assert!(jsonl.contains("\"reason_code\":\"heuristic_enter_burst_rate\""));
3153        assert!(jsonl.contains("\"transition_reason_code\":"));
3154    }
3155
3156    #[test]
3157    fn regime_transition_sequence_is_deterministic_for_fixed_schedule() {
3158        let config = CoalescerConfig {
3159            burst_enter_rate: 5.0,
3160            burst_exit_rate: 2.0,
3161            cooldown_frames: 3,
3162            rate_window_size: 4,
3163            steady_delay_ms: 10,
3164            burst_delay_ms: 50,
3165            hard_deadline_ms: 5_000,
3166            enable_logging: true,
3167            enable_bocpd: false,
3168            heuristic_fallback: true,
3169            bocpd_config: None,
3170        };
3171        let base = Instant::now();
3172
3173        let run = || {
3174            let mut c = ResizeCoalescer::new(config.clone(), (80, 24)).with_last_render(base);
3175
3176            // Enter burst with rapid events.
3177            for i in 0..8u64 {
3178                let t = base + Duration::from_millis(30 * i);
3179                c.handle_resize_at(80 + i as u16, 24 + i as u16, t);
3180            }
3181
3182            // Apply pending and flush rate window with slow events.
3183            let mut t = base + Duration::from_millis(280);
3184            let _ = c.tick_at(t);
3185            for i in 0..5u64 {
3186                t += Duration::from_secs(1);
3187                c.handle_resize_at(100 + i as u16, 30 + i as u16, t);
3188                let _ = c.tick_at(t + Duration::from_millis(60));
3189            }
3190
3191            // Drain cooldown without triggering apply.
3192            t += Duration::from_millis(70);
3193            c.handle_resize_at(120, 35, t);
3194            for step in 1..=config.cooldown_frames {
3195                let _ = c.tick_at(t + Duration::from_millis(step as u64 * 5));
3196            }
3197
3198            c.transition_logs()
3199                .iter()
3200                .map(|entry| {
3201                    (
3202                        entry.from_regime,
3203                        entry.to_regime,
3204                        entry.reason_code,
3205                        entry.event_idx,
3206                        entry.cooldown_remaining,
3207                    )
3208                })
3209                .collect::<Vec<_>>()
3210        };
3211
3212        let first = run();
3213        let second = run();
3214        assert_eq!(first, second);
3215        assert!(
3216            first.iter().any(|(_, to, reason, _, _)| {
3217                *to == Regime::Burst && *reason == TransitionReasonCode::HeuristicEnterBurstRate
3218            }),
3219            "expected steady->burst transition with heuristic reason"
3220        );
3221        assert!(
3222            first.iter().any(|(_, to, reason, _, _)| {
3223                *to == Regime::Steady && *reason == TransitionReasonCode::HeuristicExitBurstCooldown
3224            }),
3225            "expected burst->steady transition with cooldown reason"
3226        );
3227    }
3228
3229    #[test]
3230    fn bounded_oscillation_and_converges_to_steady() {
3231        let config = CoalescerConfig {
3232            burst_enter_rate: 5.0,
3233            burst_exit_rate: 2.0,
3234            cooldown_frames: 3,
3235            rate_window_size: 4,
3236            steady_delay_ms: 10,
3237            burst_delay_ms: 50,
3238            hard_deadline_ms: 5_000,
3239            enable_logging: true,
3240            enable_bocpd: false,
3241            heuristic_fallback: true,
3242            bocpd_config: None,
3243        };
3244        let base = Instant::now();
3245        let mut c = ResizeCoalescer::new(config.clone(), (80, 24)).with_last_render(base);
3246        let mut t = base;
3247
3248        // Alternate burst pulses with limited cooldown opportunities.
3249        for cycle in 0..30u64 {
3250            for pulse in 0..6u64 {
3251                t += Duration::from_millis(30);
3252                c.handle_resize_at(80 + ((cycle + pulse) % 40) as u16, 24 + pulse as u16, t);
3253            }
3254            t += Duration::from_millis(70);
3255            let _ = c.tick_at(t);
3256
3257            t += Duration::from_secs(1);
3258            c.handle_resize_at(120 + (cycle % 20) as u16, 30 + (cycle % 5) as u16, t);
3259            let _ = c.tick_at(t + Duration::from_millis(60));
3260        }
3261
3262        let transitions_before_convergence = c.regime_transition_count();
3263        assert!(
3264            transitions_before_convergence <= 4,
3265            "oscillation should stay bounded, transitions={}",
3266            transitions_before_convergence
3267        );
3268
3269        // Final quiet period: explicitly drain cooldown and verify convergence.
3270        t += Duration::from_secs(1);
3271        c.handle_resize_at(160, 40, t);
3272        for step in 1..=config.cooldown_frames {
3273            let _ = c.tick_at(t + Duration::from_millis(step as u64 * 5));
3274        }
3275        assert_eq!(c.regime(), Regime::Steady);
3276        let last_transition = c
3277            .transition_logs()
3278            .last()
3279            .expect("expected at least one transition");
3280        assert_eq!(last_transition.to_regime, Regime::Steady);
3281        assert_eq!(
3282            last_transition.reason_code,
3283            TransitionReasonCode::HeuristicExitBurstCooldown
3284        );
3285    }
3286
3287    #[test]
3288    fn simulation_bocpd_vs_heuristic_metrics() {
3289        let tick_ms = 5;
3290        // Keep heuristic thresholds high so burst classification is conservative,
3291        // while BOCPD uses a responsive posterior to detect bursty streams.
3292        let mut heuristic_config = test_config();
3293        heuristic_config.burst_enter_rate = 60.0;
3294        heuristic_config.burst_exit_rate = 30.0;
3295        let mut bocpd_cfg = BocpdConfig::responsive();
3296        bocpd_cfg.burst_prior = 0.35;
3297        bocpd_cfg.steady_threshold = 0.2;
3298        bocpd_cfg.burst_threshold = 0.6;
3299        let bocpd_config = heuristic_config.clone().with_bocpd_config(bocpd_cfg);
3300        let patterns = vec![
3301            ("steady", steady_pattern()),
3302            ("burst", burst_pattern()),
3303            ("oscillatory", oscillatory_pattern()),
3304        ];
3305
3306        for (pattern, events) in patterns {
3307            let heuristic = run_simulation(&events, heuristic_config.clone(), tick_ms);
3308            let bocpd = run_simulation(&events, bocpd_config.clone(), tick_ms);
3309
3310            let heuristic_jsonl = heuristic.to_jsonl(pattern, "heuristic");
3311            let bocpd_jsonl = bocpd.to_jsonl(pattern, "bocpd");
3312            let comparison = SimulationComparison::from_metrics(heuristic, bocpd);
3313            let comparison_jsonl = comparison.to_jsonl(pattern);
3314
3315            eprintln!("{heuristic_jsonl}");
3316            eprintln!("{bocpd_jsonl}");
3317            eprintln!("{comparison_jsonl}");
3318
3319            assert!(heuristic_jsonl.contains("\"event\":\"simulation_summary\""));
3320            assert!(bocpd_jsonl.contains("\"event\":\"simulation_summary\""));
3321            assert!(comparison_jsonl.contains("\"event\":\"simulation_compare\""));
3322
3323            #[allow(clippy::cast_precision_loss)]
3324            let max_allowed = test_config().hard_deadline_ms as f64 + 1.0;
3325            assert!(
3326                heuristic.max_coalesce_ms <= max_allowed,
3327                "heuristic latency bounded for {pattern}"
3328            );
3329            assert!(
3330                bocpd.max_coalesce_ms <= max_allowed,
3331                "bocpd latency bounded for {pattern}"
3332            );
3333
3334            if pattern == "burst" {
3335                let event_count = as_u64(events.len());
3336                assert!(
3337                    heuristic.apply_count < event_count,
3338                    "heuristic should coalesce under burst pattern"
3339                );
3340                assert!(
3341                    bocpd.apply_count < event_count,
3342                    "bocpd should coalesce under burst pattern"
3343                );
3344                assert!(
3345                    comparison.apply_delta >= 0,
3346                    "BOCPD should not increase renders in burst (apply_delta={})",
3347                    comparison.apply_delta
3348                );
3349            }
3350        }
3351    }
3352
3353    #[test]
3354    fn never_drops_final_size() {
3355        let config = test_config();
3356        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
3357
3358        let base = Instant::now();
3359
3360        // Many rapid resizes that may trigger some applies due to hard deadline
3361        let mut intermediate_applies = Vec::new();
3362        for i in 0..100 {
3363            let action = c.handle_resize_at(
3364                80 + (i % 50),
3365                24 + (i % 30),
3366                base + Duration::from_millis(i as u64 * 5),
3367            );
3368            if let CoalesceAction::ApplyResize { width, height, .. } = action {
3369                intermediate_applies.push((width, height));
3370            }
3371        }
3372
3373        // The final size - may apply immediately if deadline is hit
3374        let final_action = c.handle_resize_at(200, 100, base + Duration::from_millis(600));
3375
3376        let applied_size = if let CoalesceAction::ApplyResize { width, height, .. } = final_action {
3377            Some((width, height))
3378        } else {
3379            // If not applied immediately, tick until it is
3380            let mut result = None;
3381            for tick in 0..100 {
3382                let action = c.tick_at(base + Duration::from_millis(700 + tick * 20));
3383                if let CoalesceAction::ApplyResize { width, height, .. } = action {
3384                    result = Some((width, height));
3385                    break;
3386                }
3387            }
3388            result
3389        };
3390
3391        assert_eq!(
3392            applied_size,
3393            Some((200, 100)),
3394            "Must apply final size 200x100"
3395        );
3396    }
3397
3398    #[test]
3399    fn bounded_latency_invariant() {
3400        let config = test_config();
3401        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
3402
3403        let base = Instant::now();
3404        c.handle_resize_at(100, 40, base);
3405
3406        // Simulate time passing without any new events
3407        let mut applied_at = None;
3408        for ms in 0..200 {
3409            let now = base + Duration::from_millis(ms);
3410            let action = c.tick_at(now);
3411            if matches!(action, CoalesceAction::ApplyResize { .. }) {
3412                applied_at = Some(ms);
3413                break;
3414            }
3415        }
3416
3417        assert!(applied_at.is_some(), "Must apply within reasonable time");
3418        assert!(
3419            applied_at.unwrap() <= config.hard_deadline_ms,
3420            "Must apply within hard deadline"
3421        );
3422    }
3423
3424    // =========================================================================
3425    // Property tests (bd-1rz0.8)
3426    // =========================================================================
3427
3428    mod property {
3429        use super::*;
3430        use proptest::prelude::*;
3431
3432        /// Strategy for generating resize dimensions.
3433        fn dimension() -> impl Strategy<Value = u16> {
3434            1u16..500
3435        }
3436
3437        /// Strategy for generating resize event sequences.
3438        fn resize_sequence(max_len: usize) -> impl Strategy<Value = Vec<(u16, u16, u64)>> {
3439            proptest::collection::vec((dimension(), dimension(), 0u64..200), 0..max_len)
3440        }
3441
3442        proptest! {
3443            /// Property: identical sequences yield identical final results.
3444            ///
3445            /// The coalescer must be deterministic - same inputs → same outputs.
3446            #[test]
3447            fn determinism_across_sequences(
3448                events in resize_sequence(50),
3449                tick_offset in 100u64..500
3450            ) {
3451                let config = CoalescerConfig::default();
3452
3453                let results: Vec<_> = (0..2)
3454                    .map(|_| {
3455                        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
3456                        let base = Instant::now();
3457
3458                        for (i, (w, h, delay)) in events.iter().enumerate() {
3459                            let offset = events[..i].iter().map(|(_, _, d)| *d).sum::<u64>() + delay;
3460                            c.handle_resize_at(*w, *h, base + Duration::from_millis(offset));
3461                        }
3462
3463                        // Tick to trigger apply
3464                        let total_time = events.iter().map(|(_, _, d)| d).sum::<u64>() + tick_offset;
3465                        c.tick_at(base + Duration::from_millis(total_time))
3466                    })
3467                    .collect();
3468
3469                prop_assert_eq!(results[0], results[1], "Results must be deterministic");
3470            }
3471
3472            /// Property: the latest resize is never lost (latest-wins semantics).
3473            ///
3474            /// When all coalescing completes, the applied size must match the
3475            /// final requested size.
3476            #[test]
3477            fn latest_wins_never_drops(
3478                events in resize_sequence(20),
3479                final_w in dimension(),
3480                final_h in dimension()
3481            ) {
3482                if events.is_empty() {
3483                    // No events to test
3484                    return Ok(());
3485                }
3486
3487                let config = CoalescerConfig::default();
3488                let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
3489                let base = Instant::now();
3490
3491                // Feed all events
3492                let mut offset = 0u64;
3493                for (w, h, delay) in &events {
3494                    offset += delay;
3495                    c.handle_resize_at(*w, *h, base + Duration::from_millis(offset));
3496                }
3497
3498                // Add final event
3499                offset += 50;
3500                c.handle_resize_at(final_w, final_h, base + Duration::from_millis(offset));
3501
3502                // Tick until we get an apply
3503                let mut result = None;
3504                for tick in 0..200 {
3505                    let action = c.tick_at(base + Duration::from_millis(offset + 10 + tick * 20));
3506                    if let CoalesceAction::ApplyResize { width, height, .. } = action {
3507                        result = Some((width, height));
3508                        break;
3509                    }
3510                }
3511
3512                // The final applied size must match the latest requested size
3513                if let Some((applied_w, applied_h)) = result {
3514                    prop_assert_eq!(
3515                        (applied_w, applied_h),
3516                        (final_w, final_h),
3517                        "Must apply the final size {} x {}",
3518                        final_w,
3519                        final_h
3520                    );
3521                }
3522            }
3523
3524            /// Property: bounded latency is always maintained.
3525            ///
3526            /// A pending resize must be applied within hard_deadline_ms.
3527            #[test]
3528            fn bounded_latency_maintained(
3529                w in dimension(),
3530                h in dimension()
3531            ) {
3532                let config = CoalescerConfig::default();
3533                // Use (0,0) so no generated size (1..500) hits the skip_same_size path
3534                let mut c = ResizeCoalescer::new(config.clone(), (0, 0));
3535                let base = Instant::now();
3536
3537                c.handle_resize_at(w, h, base);
3538
3539                // Tick forward until applied
3540                let mut applied_at = None;
3541                for ms in 0..=config.hard_deadline_ms + 50 {
3542                    let action = c.tick_at(base + Duration::from_millis(ms));
3543                    if matches!(action, CoalesceAction::ApplyResize { .. }) {
3544                        applied_at = Some(ms);
3545                        break;
3546                    }
3547                }
3548
3549                prop_assert!(applied_at.is_some(), "Resize must be applied");
3550                prop_assert!(
3551                    applied_at.unwrap() <= config.hard_deadline_ms,
3552                    "Must apply within hard deadline ({}ms), took {}ms",
3553                    config.hard_deadline_ms,
3554                    applied_at.unwrap()
3555                );
3556            }
3557
3558            /// Property: applied sizes are never corrupted.
3559            ///
3560            /// When a resize is applied, the dimensions must exactly match
3561            /// what was requested (no off-by-one, no swapped axes).
3562            #[test]
3563            fn no_size_corruption(
3564                w in dimension(),
3565                h in dimension()
3566            ) {
3567                let config = CoalescerConfig::default();
3568                // Use (0,0) so no generated size (1..500) hits the skip_same_size path
3569                let mut c = ResizeCoalescer::new(config.clone(), (0, 0));
3570                let base = Instant::now();
3571
3572                c.handle_resize_at(w, h, base);
3573
3574                // Tick until applied
3575                let mut result = None;
3576                for ms in 0..200 {
3577                    let action = c.tick_at(base + Duration::from_millis(ms));
3578                    if let CoalesceAction::ApplyResize { width, height, .. } = action {
3579                        result = Some((width, height));
3580                        break;
3581                    }
3582                }
3583
3584                prop_assert!(result.is_some());
3585                let (applied_w, applied_h) = result.unwrap();
3586                prop_assert_eq!(applied_w, w, "Width must not be corrupted");
3587                prop_assert_eq!(applied_h, h, "Height must not be corrupted");
3588            }
3589
3590            /// Property: regime transitions are monotonic with event rate.
3591            ///
3592            /// Higher event rates should more reliably trigger burst mode.
3593            #[test]
3594            fn regime_follows_event_rate(
3595                event_count in 1usize..30
3596            ) {
3597                // This property is about the rate rule itself, so run the
3598                // heuristic detector alone.
3599                let config = CoalescerConfig {
3600                    burst_enter_rate: 10.0,
3601                    burst_exit_rate: 5.0,
3602                    ..CoalescerConfig::default().without_bocpd()
3603                };
3604                let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
3605                let base = Instant::now();
3606
3607                // Very fast events (>10/sec) should trigger burst mode
3608                for i in 0..event_count {
3609                    c.handle_resize_at(
3610                        80 + i as u16,
3611                        24,
3612                        base + Duration::from_millis(i as u64 * 50), // 20 events/sec
3613                    );
3614                }
3615
3616                // With enough fast events, should enter burst
3617                if event_count >= 10 {
3618                    prop_assert_eq!(
3619                        c.regime(),
3620                        Regime::Burst,
3621                        "Many rapid events should trigger burst mode"
3622                    );
3623                }
3624            }
3625
3626            /// Property: event count invariant - coalescer tracks all incoming events.
3627            ///
3628            /// The `event_count` field tracks ALL resize events for rate calculation
3629            /// and telemetry, including same-size events that are skipped.
3630            #[test]
3631            fn event_count_invariant(
3632                events in resize_sequence(100)
3633            ) {
3634                let config = CoalescerConfig::default();
3635                let mut c = ResizeCoalescer::new(config, (80, 24));
3636                let base = Instant::now();
3637
3638                for (w, h, delay) in &events {
3639                    c.handle_resize_at(*w, *h, base + Duration::from_millis(*delay));
3640                }
3641
3642                let stats = c.stats();
3643                // Event count should equal total incoming events (for rate calculation).
3644                prop_assert_eq!(
3645                    stats.event_count,
3646                    events.len() as u64,
3647                    "Event count should match total incoming events"
3648                );
3649            }
3650
3651            // =========================================================================
3652            // BOCPD Property Tests (bd-3e1t.2.5)
3653            // =========================================================================
3654
3655            /// Property: BOCPD determinism - identical sequences yield identical results.
3656            #[test]
3657            fn bocpd_determinism_across_sequences(
3658                events in resize_sequence(30),
3659                tick_offset in 100u64..400
3660            ) {
3661                let config = CoalescerConfig::default().with_bocpd();
3662
3663                let results: Vec<_> = (0..2)
3664                    .map(|_| {
3665                        let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
3666                        let base = Instant::now();
3667
3668                        for (i, (w, h, delay)) in events.iter().enumerate() {
3669                            let offset = events[..i].iter().map(|(_, _, d)| *d).sum::<u64>() + delay;
3670                            c.handle_resize_at(*w, *h, base + Duration::from_millis(offset));
3671                        }
3672
3673                        let total_time = events.iter().map(|(_, _, d)| d).sum::<u64>() + tick_offset;
3674                        let action = c.tick_at(base + Duration::from_millis(total_time));
3675                        (action, c.regime(), c.bocpd_p_burst())
3676                    })
3677                    .collect();
3678
3679                prop_assert_eq!(results[0], results[1], "BOCPD results must be deterministic");
3680            }
3681
3682            /// Property: BOCPD latest-wins - final resize is always applied.
3683            #[test]
3684            fn bocpd_latest_wins_never_drops(
3685                events in resize_sequence(15),
3686                final_w in dimension(),
3687                final_h in dimension()
3688            ) {
3689                if events.is_empty() {
3690                    return Ok(());
3691                }
3692
3693                let config = CoalescerConfig::default().with_bocpd();
3694                let mut c = ResizeCoalescer::new(config, (80, 24));
3695                let base = Instant::now();
3696
3697                let mut offset = 0u64;
3698                for (w, h, delay) in &events {
3699                    offset += delay;
3700                    c.handle_resize_at(*w, *h, base + Duration::from_millis(offset));
3701                }
3702
3703                offset += 50;
3704                c.handle_resize_at(final_w, final_h, base + Duration::from_millis(offset));
3705
3706                let mut final_applied = None;
3707                for tick in 0..200 {
3708                    let action = c.tick_at(base + Duration::from_millis(offset + 10 + tick * 20));
3709                    if let CoalesceAction::ApplyResize { width, height, .. } = action {
3710                        final_applied = Some((width, height));
3711                    }
3712                    if !c.has_pending() && final_applied.is_some() {
3713                        break;
3714                    }
3715                }
3716
3717                if let Some((applied_w, applied_h)) = final_applied {
3718                    prop_assert_eq!(
3719                        (applied_w, applied_h),
3720                        (final_w, final_h),
3721                        "BOCPD must apply the final size"
3722                    );
3723                }
3724            }
3725
3726            /// Property: BOCPD bounded latency - hard deadline is always met.
3727            #[test]
3728            fn bocpd_bounded_latency_maintained(
3729                w in dimension(),
3730                h in dimension()
3731            ) {
3732                let config = CoalescerConfig::default().with_bocpd();
3733                let mut c = ResizeCoalescer::new(config.clone(), (0, 0));
3734                let base = Instant::now();
3735
3736                c.handle_resize_at(w, h, base);
3737
3738                let mut applied_at = None;
3739                for ms in 0..=config.hard_deadline_ms + 50 {
3740                    let action = c.tick_at(base + Duration::from_millis(ms));
3741                    if matches!(action, CoalesceAction::ApplyResize { .. }) {
3742                        applied_at = Some(ms);
3743                        break;
3744                    }
3745                }
3746
3747                prop_assert!(applied_at.is_some(), "BOCPD resize must be applied");
3748                prop_assert!(
3749                    applied_at.unwrap() <= config.hard_deadline_ms,
3750                    "BOCPD must apply within hard deadline ({}ms), took {}ms",
3751                    config.hard_deadline_ms,
3752                    applied_at.unwrap()
3753                );
3754            }
3755
3756            /// Property: BOCPD posterior always valid (normalized, bounded).
3757            #[test]
3758            fn bocpd_posterior_always_valid(
3759                events in resize_sequence(50)
3760            ) {
3761                if events.is_empty() {
3762                    return Ok(());
3763                }
3764
3765                let config = CoalescerConfig::default().with_bocpd();
3766                let mut c = ResizeCoalescer::new(config, (80, 24));
3767                let base = Instant::now();
3768
3769                for (w, h, delay) in &events {
3770                    c.handle_resize_at(*w, *h, base + Duration::from_millis(*delay));
3771
3772                    // Check posterior validity after each event
3773                    if let Some(bocpd) = c.bocpd() {
3774                        let sum: f64 = bocpd.run_length_posterior().iter().sum();
3775                        prop_assert!(
3776                            (sum - 1.0).abs() < 1e-8,
3777                            "Posterior must sum to 1, got {}",
3778                            sum
3779                        );
3780                    }
3781
3782                    let p_burst = c.bocpd_p_burst().unwrap();
3783                    prop_assert!(
3784                        (0.0..=1.0).contains(&p_burst),
3785                        "P(burst) must be in [0,1], got {}",
3786                        p_burst
3787                    );
3788                }
3789            }
3790        }
3791
3792        /// Inter-arrivals from a mixture of a burst-like and a steady-like
3793        /// exponential, which is the schedule BOCPD's observation model is
3794        /// written for. Drawn by inverse-CDF from a uniform so proptest keeps
3795        /// its shrinking and its seeds.
3796        fn mixed_interarrivals(max_len: usize) -> impl Strategy<Value = Vec<u64>> {
3797            proptest::collection::vec((0u32..1000, any::<bool>()), 0..max_len).prop_map(|draws| {
3798                draws
3799                    .into_iter()
3800                    .map(|(u, burst)| {
3801                        let mean = if burst { 20.0 } else { 200.0 };
3802                        let uniform = f64::from(u).mul_add(1.0 / 1000.0, 1e-9).min(1.0 - 1e-9);
3803                        // -mean * ln(1 - U) is Exp(1/mean).
3804                        (-mean * (1.0 - uniform).ln()).round() as u64
3805                    })
3806                    .collect()
3807            })
3808        }
3809
3810        proptest! {
3811            /// The transition log is a walk, and each row's tag matches the
3812            /// path that produced it.
3813            ///
3814            /// Three separate claims the README makes about the evidence, none
3815            /// of which a single scripted schedule can cover:
3816            /// transitions alternate (`to` of one is `from` of the next, and
3817            /// no transition is a self-loop); a BOCPD-tagged row carries a
3818            /// posterior in [0,1]; and no heuristic cooldown reason code
3819            /// appears while the posterior is the detector, because the
3820            /// cooldown belongs to the heuristic's burst exit.
3821            #[test]
3822            fn proptest_transitions_alternate_and_tags_match_path(
3823                gaps in mixed_interarrivals(500),
3824                tick_every in 1usize..8,
3825            ) {
3826                // Two of the three claims are about BOCPD-tagged rows, so the
3827                // posterior has to be running for this to check anything.
3828                let mut c = ResizeCoalescer::new(
3829                    CoalescerConfig::default().with_bocpd().with_logging(true),
3830                    (80, 24),
3831                );
3832                let base = Instant::now();
3833                let mut elapsed = 0u64;
3834                for (i, gap) in gaps.iter().enumerate() {
3835                    elapsed = elapsed.saturating_add(*gap);
3836                    let now = base + Duration::from_millis(elapsed);
3837                    c.handle_resize_at(
3838                        100 + u16::try_from(i % 200).expect("bounded by modulo"),
3839                        40,
3840                        now,
3841                    );
3842                    // Frame ticks are what run the idle exits, so a schedule
3843                    // without them never reaches those reason codes at all.
3844                    if i % tick_every == 0 {
3845                        c.tick_at(now + Duration::from_millis(1));
3846                    }
3847                }
3848
3849                // The invariants below are safety properties: they say no bad
3850                // transition appears, so they would also hold if no transition
3851                // appeared at all. This keeps that from passing silently --
3852                // every event logs a decision, so an empty log means logging
3853                // stopped rather than that the schedule was calm. That
3854                // transitions do occur on realistic schedules is pinned
3855                // deterministically by
3856                // `transition_reason_codes_and_evidence_fields_are_logged`.
3857                if !gaps.is_empty() {
3858                    prop_assert!(!c.logs().is_empty(), "events logged no decisions");
3859                }
3860
3861                let mut previous_to: Option<Regime> = None;
3862                for log in c.logs() {
3863                    if let Some(p) = log.p_burst {
3864                        prop_assert!(
3865                            (0.0..=1.0).contains(&p) && p.is_finite(),
3866                            "p_burst outside [0,1]: {:?}", log
3867                        );
3868                    }
3869                    let Some(reason) = log.transition_reason_code else {
3870                        continue;
3871                    };
3872                    if log.detector == RegimeDetector::Bocpd {
3873                        prop_assert!(
3874                            reason != TransitionReasonCode::HeuristicExitBurstCooldown,
3875                            "heuristic cooldown exit tagged as a bocpd decision: {:?}", log
3876                        );
3877                        prop_assert!(
3878                            log.p_burst.is_some(),
3879                            "a bocpd transition must carry its posterior: {:?}", log
3880                        );
3881                    }
3882                    // A transition that did not change regime is not a
3883                    // transition, and the next one must start where this
3884                    // one left off.
3885                    if let Some(from) = previous_to {
3886                        prop_assert_ne!(
3887                            from, log.regime,
3888                            "self-transition recorded: {:?}", log
3889                        );
3890                    }
3891                    previous_to = Some(log.regime);
3892                }
3893            }
3894
3895            /// Whatever the schedule, the last size the caller asked for is the
3896            /// size the terminal ends up at.
3897            ///
3898            /// Coalescing is allowed to drop intermediate sizes -- that is the
3899            /// point -- but dropping the final one would leave the UI laid out
3900            /// for a window that no longer exists. `latest_wins_never_drops`
3901            /// covers this for uniform gaps; this covers it for the mixed
3902            /// burst/steady schedule BOCPD is actually tuned for.
3903            #[test]
3904            fn proptest_final_size_always_applied(
3905                gaps in mixed_interarrivals(300),
3906                last_w in 1u16..500,
3907                last_h in 1u16..300,
3908            ) {
3909                let mut c = ResizeCoalescer::new(CoalescerConfig::default(), (80, 24));
3910                let base = Instant::now();
3911                let mut elapsed = 0u64;
3912                for (i, gap) in gaps.iter().enumerate() {
3913                    elapsed = elapsed.saturating_add(*gap);
3914                    c.handle_resize_at(
3915                        100 + u16::try_from(i % 200).expect("bounded by modulo"),
3916                        40,
3917                        base + Duration::from_millis(elapsed),
3918                    );
3919                }
3920                elapsed = elapsed.saturating_add(1);
3921                c.handle_resize_at(last_w, last_h, base + Duration::from_millis(elapsed));
3922
3923                // Past the hard deadline, with ticks, nothing may still be held.
3924                for extra in 1..=20u64 {
3925                    c.tick_at(base + Duration::from_millis(elapsed + extra * 10));
3926                }
3927                prop_assert_eq!(
3928                    c.last_applied(), (last_w, last_h),
3929                    "final size was never applied after 200 ms of ticks"
3930                );
3931            }
3932        }
3933    }
3934
3935    // =========================================================================
3936    // Telemetry Hooks Tests (bd-1rz0.7)
3937    // =========================================================================
3938
3939    #[test]
3940    fn telemetry_hooks_fire_on_resize_applied() {
3941        use std::sync::Arc;
3942        use std::sync::atomic::{AtomicU32, Ordering};
3943
3944        let applied_count = Arc::new(AtomicU32::new(0));
3945        let applied_count_clone = applied_count.clone();
3946
3947        let hooks = TelemetryHooks::new().on_resize_applied(move |_entry| {
3948            applied_count_clone.fetch_add(1, Ordering::SeqCst);
3949        });
3950
3951        let mut config = test_config();
3952        config.enable_logging = true;
3953        let mut c = ResizeCoalescer::new(config, (80, 24)).with_telemetry_hooks(hooks);
3954
3955        let base = Instant::now();
3956        c.handle_resize_at(100, 40, base);
3957        c.tick_at(base + Duration::from_millis(50));
3958
3959        assert_eq!(applied_count.load(Ordering::SeqCst), 1);
3960    }
3961
3962    #[test]
3963    fn telemetry_hooks_fire_on_regime_change() {
3964        use std::sync::Arc;
3965        use std::sync::atomic::{AtomicU32, Ordering};
3966
3967        let regime_changes = Arc::new(AtomicU32::new(0));
3968        let regime_changes_clone = regime_changes.clone();
3969
3970        let hooks = TelemetryHooks::new().on_regime_change(move |_from, _to| {
3971            regime_changes_clone.fetch_add(1, Ordering::SeqCst);
3972        });
3973
3974        let config = test_config();
3975        let mut c = ResizeCoalescer::new(config, (80, 24)).with_telemetry_hooks(hooks);
3976
3977        let base = Instant::now();
3978
3979        // Rapid events to trigger burst mode
3980        for i in 0..15 {
3981            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 10));
3982        }
3983
3984        // Should have triggered at least one regime change (Steady -> Burst)
3985        assert!(regime_changes.load(Ordering::SeqCst) >= 1);
3986    }
3987
3988    #[test]
3989    fn regime_transition_count_tracks_changes() {
3990        let config = test_config();
3991        let mut c = ResizeCoalescer::new(config, (80, 24));
3992
3993        assert_eq!(c.regime_transition_count(), 0);
3994
3995        let base = Instant::now();
3996
3997        // Rapid events to trigger burst mode
3998        for i in 0..15 {
3999            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 10));
4000        }
4001
4002        // Should have transitioned to Burst at least once
4003        assert!(c.regime_transition_count() >= 1);
4004    }
4005
4006    #[test]
4007    fn cycle_time_percentiles_calculated() {
4008        let mut config = test_config();
4009        config.enable_logging = true;
4010        let mut c = ResizeCoalescer::new(config, (80, 24));
4011
4012        // Initially no percentiles
4013        assert!(c.cycle_time_percentiles().is_none());
4014
4015        let base = Instant::now();
4016
4017        // Generate multiple applies to get cycle times
4018        for i in 0..5 {
4019            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 100));
4020            c.tick_at(base + Duration::from_millis(i as u64 * 100 + 50));
4021        }
4022
4023        // Now should have percentiles
4024        let percentiles = c.cycle_time_percentiles();
4025        assert!(percentiles.is_some());
4026
4027        let p = percentiles.unwrap();
4028        assert!(p.count >= 1);
4029        assert!(p.mean_ms >= 0.0);
4030        assert!(p.p50_ms >= 0.0);
4031        assert!(p.p95_ms >= p.p50_ms);
4032        assert!(p.p99_ms >= p.p95_ms);
4033    }
4034
4035    #[test]
4036    fn cycle_time_percentiles_jsonl_format() {
4037        let percentiles = CycleTimePercentiles {
4038            p50_ms: 10.5,
4039            p95_ms: 25.3,
4040            p99_ms: 42.1,
4041            count: 100,
4042            mean_ms: 15.2,
4043        };
4044
4045        let jsonl = percentiles.to_jsonl();
4046        assert!(jsonl.contains("\"event\":\"cycle_time_percentiles\""));
4047        assert!(jsonl.contains("\"p50_ms\":10.500"));
4048        assert!(jsonl.contains("\"p95_ms\":25.300"));
4049        assert!(jsonl.contains("\"p99_ms\":42.100"));
4050        assert!(jsonl.contains("\"mean_ms\":15.200"));
4051        assert!(jsonl.contains("\"count\":100"));
4052    }
4053
4054    // =========================================================================
4055    // BOCPD Integration Tests (bd-3e1t.2.2)
4056    // =========================================================================
4057
4058    /// The posterior ships off. It was the default from 2026-09-02 until the
4059    /// differential replay it was waiting on measured it drawing more frames
4060    /// during a drag on 6 of 6 storm patterns, and no better on settling
4061    /// latency — see `enable_bocpd`'s doc and bd-h8l3d. Turning it back on
4062    /// should change this assertion and the evidence together.
4063    #[test]
4064    fn config_default_leaves_bocpd_off_with_heuristic_fallback() {
4065        let config = CoalescerConfig::default();
4066        assert!(!config.enable_bocpd);
4067        assert!(config.heuristic_fallback);
4068        assert!(
4069            config.bocpd_config.is_none(),
4070            "None means BocpdConfig::default()"
4071        );
4072        let jsonl = config.to_jsonl("run", ScreenMode::AltScreen, 80, 24, 0);
4073        assert!(jsonl.contains(r#""enable_bocpd":false"#), "{jsonl}");
4074        assert!(jsonl.contains(r#""heuristic_fallback":true"#), "{jsonl}");
4075
4076        let c = ResizeCoalescer::new(config, (80, 24));
4077        assert!(!c.bocpd_enabled());
4078        assert!(c.bocpd().is_none(), "no posterior is built when it is off");
4079        assert!(c.bocpd_p_burst().is_none());
4080        assert_eq!(
4081            c.last_detector(),
4082            RegimeDetector::Heuristic,
4083            "nothing decided yet"
4084        );
4085        assert_eq!(c.detector_decisions(), DetectorDecisions::default());
4086
4087        // Opting in still works and is what the evidence was gathered under.
4088        let on = ResizeCoalescer::new(CoalescerConfig::default().with_bocpd(), (80, 24));
4089        assert!(on.bocpd_enabled());
4090        assert!(on.bocpd().is_some());
4091        assert!(on.bocpd_p_burst().is_some());
4092    }
4093
4094    /// With defaults the first event has no inter-arrival, so the heuristic
4095    /// decides it; from the second event on the posterior is defined and
4096    /// BOCPD decides. Every `decision` row names its detector.
4097    #[test]
4098    fn first_event_uses_heuristic_then_bocpd() {
4099        let config = CoalescerConfig::default().with_bocpd().with_logging(true);
4100        let mut c = ResizeCoalescer::new(config, (80, 24));
4101        let base = Instant::now();
4102
4103        c.handle_resize_at(81, 24, base);
4104        assert_eq!(c.last_detector(), RegimeDetector::Heuristic);
4105        c.handle_resize_at(82, 24, base + Duration::from_millis(30));
4106        assert_eq!(c.last_detector(), RegimeDetector::Bocpd);
4107        c.handle_resize_at(83, 24, base + Duration::from_millis(60));
4108        assert_eq!(c.last_detector(), RegimeDetector::Bocpd);
4109
4110        let jsonl = c.decision_logs_jsonl();
4111        let decisions: Vec<&str> = jsonl
4112            .lines()
4113            .filter(|line| line.contains(r#""event":"decision""#))
4114            .collect();
4115        assert_eq!(decisions.len(), 3, "{jsonl}");
4116        assert!(
4117            decisions[0].contains(r#""detector":"heuristic""#),
4118            "{}",
4119            decisions[0]
4120        );
4121        assert!(decisions[0].contains(r#""p_burst":"#), "{}", decisions[0]);
4122        assert!(
4123            decisions[1].contains(r#""detector":"bocpd""#),
4124            "{}",
4125            decisions[1]
4126        );
4127        assert!(
4128            decisions[2].contains(r#""detector":"bocpd""#),
4129            "{}",
4130            decisions[2]
4131        );
4132        assert_eq!(
4133            c.detector_decisions(),
4134            DetectorDecisions {
4135                bocpd: 2,
4136                heuristic: 1
4137            }
4138        );
4139    }
4140
4141    /// An inter-arrival beyond `max_observation_ms` (10 s by default) would
4142    /// only reach the posterior clamped, so the heuristic decides that event.
4143    #[test]
4144    fn clamped_observation_falls_back_to_heuristic() {
4145        let config = CoalescerConfig::default().with_bocpd().with_logging(true);
4146        let mut c = ResizeCoalescer::new(config, (80, 24));
4147        let base = Instant::now();
4148
4149        c.handle_resize_at(81, 24, base);
4150        c.handle_resize_at(82, 24, base + Duration::from_millis(30));
4151        assert_eq!(c.last_detector(), RegimeDetector::Bocpd);
4152
4153        c.handle_resize_at(83, 24, base + Duration::from_secs(20));
4154        assert_eq!(c.last_detector(), RegimeDetector::Heuristic);
4155        let last = c
4156            .decision_logs_jsonl()
4157            .lines()
4158            .rfind(|line| line.contains(r#""event":"decision""#))
4159            .map(str::to_owned)
4160            .expect("decision row");
4161        assert!(last.contains(r#""detector":"heuristic""#), "{last}");
4162
4163        // Sub-millisecond inter-arrivals sit below `min_observation_ms`.
4164        c.handle_resize_at(
4165            84,
4166            24,
4167            base + Duration::from_secs(20) + Duration::from_micros(200),
4168        );
4169        assert_eq!(c.last_detector(), RegimeDetector::Heuristic);
4170
4171        // Back in range: the posterior decides again.
4172        c.handle_resize_at(
4173            85,
4174            24,
4175            base + Duration::from_secs(20) + Duration::from_millis(40),
4176        );
4177        assert_eq!(c.last_detector(), RegimeDetector::Bocpd);
4178    }
4179
4180    /// `heuristic_fallback = false` hands every event to the posterior, even
4181    /// the first one.
4182    #[test]
4183    fn fallback_off_lets_bocpd_decide_the_first_event() {
4184        let config = CoalescerConfig::default()
4185            .with_bocpd()
4186            .with_heuristic_fallback(false);
4187        let mut c = ResizeCoalescer::new(config, (80, 24));
4188        c.handle_resize_at(81, 24, Instant::now());
4189        assert_eq!(c.last_detector(), RegimeDetector::Bocpd);
4190        assert_eq!(c.detector_decisions().bocpd, 1);
4191    }
4192
4193    /// `without_bocpd()` builds no detector: every decision is heuristic and
4194    /// tagged as such, and rapid events enter Burst through the rate rule.
4195    #[test]
4196    fn explicit_disable_keeps_heuristic_only() {
4197        let config = CoalescerConfig::default()
4198            .without_bocpd()
4199            .with_logging(true);
4200        assert!(!config.enable_bocpd);
4201        assert!(config.bocpd_config.is_none());
4202        let config_row = config.to_jsonl("run", ScreenMode::AltScreen, 80, 24, 0);
4203        assert!(
4204            config_row.contains(r#""enable_bocpd":false"#),
4205            "{config_row}"
4206        );
4207        let mut c = ResizeCoalescer::new(config, (80, 24));
4208        assert!(c.bocpd().is_none());
4209
4210        let base = Instant::now();
4211        for i in 0..12u64 {
4212            c.handle_resize_at(81 + i as u16, 24, base + Duration::from_millis(i * 20));
4213        }
4214        assert_eq!(c.regime(), Regime::Burst);
4215        assert_eq!(c.detector_decisions().bocpd, 0);
4216        assert_eq!(c.detector_decisions().heuristic, 12);
4217
4218        let jsonl = c.decision_logs_jsonl();
4219        assert!(!jsonl.contains(r#""detector":"bocpd""#), "{jsonl}");
4220        assert!(jsonl.contains(r#""detector":"heuristic""#), "{jsonl}");
4221        assert!(jsonl.contains(r#""p_burst":null"#), "{jsonl}");
4222
4223        let transitions = c.transition_logs();
4224        assert!(
4225            transitions.iter().any(|t| t.to_regime == Regime::Burst
4226                && t.reason_code == TransitionReasonCode::HeuristicEnterBurstRate),
4227            "{transitions:?}"
4228        );
4229        assert!(
4230            transitions
4231                .iter()
4232                .all(|t| t.detector == RegimeDetector::Heuristic),
4233            "{transitions:?}"
4234        );
4235        let row = transitions[0].to_jsonl("run", ScreenMode::AltScreen, 80, 24);
4236        assert!(row.contains(r#""detector":"heuristic""#), "{row}");
4237    }
4238
4239    /// BOCPD mode has no between-event exit from the posterior itself, so a
4240    /// burst followed by silence leaves Burst on a tick once the silence
4241    /// reaches `mu_steady_ms`, tagged `bocpd_idle_exit`.
4242    #[test]
4243    fn bocpd_mode_exits_burst_on_idle_tick() {
4244        let mut c = ResizeCoalescer::new(CoalescerConfig::default().with_bocpd(), (80, 24));
4245        let base = Instant::now();
4246        let mut now = base;
4247        for i in 0..40u16 {
4248            now += Duration::from_millis(5);
4249            let _ = c.handle_resize_at(100 + (i % 7), 40 + (i % 3), now);
4250        }
4251        assert_eq!(c.last_detector(), RegimeDetector::Bocpd);
4252        assert_eq!(
4253            c.regime(),
4254            Regime::Burst,
4255            "40 events at 200/s must be a burst"
4256        );
4257        let mu_steady = c
4258            .bocpd()
4259            .expect("bocpd on by default")
4260            .config()
4261            .mu_steady_ms;
4262
4263        // Quiet ticks shorter than the steady mean inter-arrival keep Burst.
4264        let _ = c.tick_at(now + Duration::from_millis((mu_steady / 2.0) as u64));
4265        assert_eq!(c.regime(), Regime::Burst);
4266
4267        // Once the silence reaches it, the regime returns to Steady.
4268        let _ = c.tick_at(now + Duration::from_millis(mu_steady as u64 + 1));
4269        assert_eq!(c.regime(), Regime::Steady);
4270        let last = c.transition_logs().last().expect("idle exit recorded");
4271        assert_eq!(last.reason_code, TransitionReasonCode::BocpdIdleExit);
4272        assert_eq!(last.detector, RegimeDetector::Bocpd);
4273        assert!(last.confidence > 0.99, "{last:?}");
4274        assert!(last.p_burst.is_some());
4275        let row = last.to_jsonl("run", ScreenMode::AltScreen, 80, 24);
4276        assert!(row.contains(r#""reason_code":"bocpd_idle_exit""#), "{row}");
4277    }
4278
4279    /// The stats snapshot exposes the detector counters the evidence rows
4280    /// are derived from.
4281    #[test]
4282    fn stats_counts_detector_decisions() {
4283        let mut c = ResizeCoalescer::new(CoalescerConfig::default().with_bocpd(), (80, 24));
4284        let base = Instant::now();
4285        c.handle_resize_at(81, 24, base);
4286        c.handle_resize_at(82, 24, base + Duration::from_millis(25));
4287        c.handle_resize_at(83, 24, base + Duration::from_millis(50));
4288        let stats = c.stats();
4289        assert_eq!(stats.detector, RegimeDetector::Bocpd);
4290        assert_eq!(stats.detector_decisions.heuristic, 1);
4291        assert_eq!(stats.detector_decisions.bocpd, 2);
4292        assert_eq!(
4293            stats.detector_decisions.bocpd + stats.detector_decisions.heuristic,
4294            stats.event_count
4295        );
4296    }
4297
4298    #[test]
4299    fn bocpd_enabled_with_config() {
4300        let config = CoalescerConfig::default().with_bocpd();
4301        let c = ResizeCoalescer::new(config, (80, 24));
4302        assert!(c.bocpd_enabled());
4303        assert!(c.bocpd().is_some());
4304    }
4305
4306    #[test]
4307    fn bocpd_posterior_normalized() {
4308        let config = CoalescerConfig::default().with_bocpd();
4309        let mut c = ResizeCoalescer::new(config, (80, 24));
4310
4311        let base = Instant::now();
4312
4313        // Feed events with various inter-arrival times
4314        for i in 0..20 {
4315            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 50));
4316        }
4317
4318        // Check posterior is valid probability
4319        let p_burst = c.bocpd_p_burst().expect("BOCPD should be enabled");
4320        assert!(
4321            (0.0..=1.0).contains(&p_burst),
4322            "P(burst) must be in [0,1], got {}",
4323            p_burst
4324        );
4325
4326        // Check BOCPD internal posterior is normalized
4327        if let Some(bocpd) = c.bocpd() {
4328            let sum: f64 = bocpd.run_length_posterior().iter().sum();
4329            assert!(
4330                (sum - 1.0).abs() < 1e-9,
4331                "Posterior must sum to 1, got {}",
4332                sum
4333            );
4334        }
4335    }
4336
4337    #[test]
4338    fn bocpd_detects_burst_from_rapid_events() {
4339        use crate::bocpd::BocpdConfig;
4340
4341        // Configure BOCPD with clear burst detection
4342        let bocpd_config = BocpdConfig {
4343            mu_steady_ms: 200.0,
4344            mu_burst_ms: 20.0,
4345            burst_threshold: 0.6,
4346            steady_threshold: 0.4,
4347            ..BocpdConfig::default()
4348        };
4349
4350        let config = CoalescerConfig::default().with_bocpd_config(bocpd_config);
4351        let mut c = ResizeCoalescer::new(config, (80, 24));
4352
4353        let base = Instant::now();
4354
4355        // Feed rapid events (10ms intervals = burst-like)
4356        for i in 0..30 {
4357            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 10));
4358        }
4359
4360        // Should have high P(burst) and be in Burst regime
4361        let p_burst = c.bocpd_p_burst().expect("BOCPD should be enabled");
4362        assert!(
4363            p_burst > 0.5,
4364            "Rapid events should yield high P(burst), got {}",
4365            p_burst
4366        );
4367        assert_eq!(
4368            c.regime(),
4369            Regime::Burst,
4370            "Regime should be Burst with rapid events"
4371        );
4372    }
4373
4374    #[test]
4375    fn bocpd_detects_steady_from_slow_events() {
4376        use crate::bocpd::BocpdConfig;
4377
4378        // Configure BOCPD with clear steady detection
4379        let bocpd_config = BocpdConfig {
4380            mu_steady_ms: 200.0,
4381            mu_burst_ms: 20.0,
4382            burst_threshold: 0.7,
4383            steady_threshold: 0.3,
4384            ..BocpdConfig::default()
4385        };
4386
4387        let config = CoalescerConfig::default().with_bocpd_config(bocpd_config);
4388        let mut c = ResizeCoalescer::new(config, (80, 24));
4389
4390        let base = Instant::now();
4391
4392        // Feed slow events (300ms intervals = steady-like)
4393        for i in 0..10 {
4394            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 300));
4395        }
4396
4397        // Should have low P(burst) and be in Steady regime
4398        let p_burst = c.bocpd_p_burst().expect("BOCPD should be enabled");
4399        assert!(
4400            p_burst < 0.5,
4401            "Slow events should yield low P(burst), got {}",
4402            p_burst
4403        );
4404        assert_eq!(
4405            c.regime(),
4406            Regime::Steady,
4407            "Regime should be Steady with slow events"
4408        );
4409    }
4410
4411    #[test]
4412    fn bocpd_recommended_delay_varies_with_regime() {
4413        let config = CoalescerConfig::default().with_bocpd();
4414        let mut c = ResizeCoalescer::new(config, (80, 24));
4415
4416        let base = Instant::now();
4417
4418        // Initial delay (before any events)
4419        c.handle_resize_at(85, 30, base);
4420        let delay_initial = c.bocpd_recommended_delay().expect("BOCPD enabled");
4421
4422        // Feed burst-like events
4423        for i in 1..30 {
4424            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 10));
4425        }
4426        let delay_burst = c.bocpd_recommended_delay().expect("BOCPD enabled");
4427
4428        // Recommended delay should be positive
4429        assert!(delay_initial > 0, "Initial delay should be positive");
4430        assert!(delay_burst > 0, "Burst delay should be positive");
4431    }
4432
4433    #[test]
4434    fn bocpd_update_is_deterministic() {
4435        let config = CoalescerConfig::default().with_bocpd();
4436
4437        let base = Instant::now();
4438
4439        // Run twice with identical inputs
4440        let results: Vec<_> = (0..2)
4441            .map(|_| {
4442                let mut c = ResizeCoalescer::new(config.clone(), (80, 24));
4443                for i in 0..20 {
4444                    c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(i as u64 * 25));
4445                }
4446                (c.regime(), c.bocpd_p_burst())
4447            })
4448            .collect();
4449
4450        assert_eq!(
4451            results[0], results[1],
4452            "BOCPD results must be deterministic"
4453        );
4454    }
4455
4456    #[test]
4457    fn bocpd_memory_bounded() {
4458        use crate::bocpd::BocpdConfig;
4459
4460        // Use a small max_run_length to test memory bounds
4461        let bocpd_config = BocpdConfig {
4462            max_run_length: 50,
4463            ..BocpdConfig::default()
4464        };
4465
4466        let config = CoalescerConfig::default().with_bocpd_config(bocpd_config);
4467        let mut c = ResizeCoalescer::new(config, (80, 24));
4468
4469        let base = Instant::now();
4470
4471        // Feed many events
4472        for i in 0u64..200 {
4473            c.handle_resize_at(
4474                80 + (i as u16 % 100),
4475                24 + (i as u16 % 50),
4476                base + Duration::from_millis(i * 20),
4477            );
4478        }
4479
4480        // Check posterior length is bounded
4481        if let Some(bocpd) = c.bocpd() {
4482            let posterior_len = bocpd.run_length_posterior().len();
4483            assert!(
4484                posterior_len <= 51, // max_run_length + 1
4485                "Posterior length should be bounded, got {}",
4486                posterior_len
4487            );
4488        }
4489    }
4490
4491    #[test]
4492    fn bocpd_stable_under_mixed_traffic() {
4493        let config = CoalescerConfig::default().with_bocpd();
4494        let mut c = ResizeCoalescer::new(config, (80, 24));
4495
4496        let base = Instant::now();
4497        let mut offset = 0u64;
4498
4499        // Steady period
4500        for i in 0..5 {
4501            offset += 200;
4502            c.handle_resize_at(80 + i, 24 + i, base + Duration::from_millis(offset));
4503        }
4504
4505        // Burst period
4506        for i in 0..15 {
4507            offset += 15;
4508            c.handle_resize_at(90 + i, 30 + i, base + Duration::from_millis(offset));
4509        }
4510
4511        // Steady period again
4512        for i in 0..5 {
4513            offset += 250;
4514            c.handle_resize_at(100 + i, 40 + i, base + Duration::from_millis(offset));
4515        }
4516
4517        // Posterior should still be valid
4518        let p_burst = c.bocpd_p_burst().expect("BOCPD enabled");
4519        assert!(
4520            (0.0..=1.0).contains(&p_burst),
4521            "P(burst) must remain valid after mixed traffic"
4522        );
4523
4524        if let Some(bocpd) = c.bocpd() {
4525            let sum: f64 = bocpd.run_length_posterior().iter().sum();
4526            assert!((sum - 1.0).abs() < 1e-9, "Posterior must remain normalized");
4527        }
4528    }
4529
4530    // =========================================================================
4531    // Evidence JSONL field validation tests (bd-plwf)
4532    // =========================================================================
4533
4534    #[test]
4535    fn evidence_decision_jsonl_contains_all_required_fields() {
4536        let log = DecisionLog {
4537            timestamp: Instant::now(),
4538            elapsed_ms: 16.5,
4539            event_idx: 1,
4540            dt_ms: 16.0,
4541            event_rate: 62.5,
4542            regime: Regime::Steady,
4543            action: "apply",
4544            pending_size: Some((100, 40)),
4545            applied_size: Some((100, 40)),
4546            time_since_render_ms: 16.2,
4547            coalesce_ms: Some(16.0),
4548            forced: false,
4549            transition_reason_code: None,
4550            transition_confidence: None,
4551            detector: RegimeDetector::Heuristic,
4552            p_burst: None,
4553        };
4554
4555        let jsonl = log.to_jsonl("test-run-1", ScreenMode::AltScreen, 100, 40);
4556        let parsed: serde_json::Value =
4557            serde_json::from_str(&jsonl).expect("Decision JSONL must be valid JSON");
4558
4559        // Schema fields
4560        assert_eq!(
4561            parsed["schema_version"].as_str().unwrap(),
4562            EVIDENCE_SCHEMA_VERSION
4563        );
4564        assert_eq!(parsed["run_id"].as_str().unwrap(), "test-run-1");
4565        assert_eq!(parsed["event_idx"].as_u64().unwrap(), 1);
4566        assert_eq!(parsed["screen_mode"].as_str().unwrap(), "altscreen");
4567        assert_eq!(parsed["cols"].as_u64().unwrap(), 100);
4568        assert_eq!(parsed["rows"].as_u64().unwrap(), 40);
4569
4570        // Event-specific fields
4571        assert_eq!(parsed["event"].as_str().unwrap(), "decision");
4572        assert!(parsed["elapsed_ms"].as_f64().is_some());
4573        assert!(parsed["dt_ms"].as_f64().is_some());
4574        assert!(parsed["event_rate"].as_f64().is_some());
4575        assert_eq!(parsed["regime"].as_str().unwrap(), "steady");
4576        assert_eq!(parsed["action"].as_str().unwrap(), "apply");
4577        assert_eq!(parsed["pending_w"].as_u64().unwrap(), 100);
4578        assert_eq!(parsed["pending_h"].as_u64().unwrap(), 40);
4579        assert_eq!(parsed["applied_w"].as_u64().unwrap(), 100);
4580        assert_eq!(parsed["applied_h"].as_u64().unwrap(), 40);
4581        assert!(parsed["time_since_render_ms"].as_f64().is_some());
4582        assert!(parsed["coalesce_ms"].as_f64().is_some());
4583        assert!(!parsed["forced"].as_bool().unwrap());
4584        assert!(parsed["transition_reason_code"].is_null());
4585        assert!(parsed["transition_confidence"].is_null());
4586    }
4587
4588    #[test]
4589    fn evidence_decision_jsonl_null_fields_when_no_pending() {
4590        let log = DecisionLog {
4591            timestamp: Instant::now(),
4592            elapsed_ms: 0.0,
4593            event_idx: 0,
4594            dt_ms: 0.0,
4595            event_rate: 0.0,
4596            regime: Regime::Steady,
4597            action: "skip_same_size",
4598            pending_size: None,
4599            applied_size: None,
4600            time_since_render_ms: 0.0,
4601            coalesce_ms: None,
4602            forced: false,
4603            transition_reason_code: None,
4604            transition_confidence: None,
4605            detector: RegimeDetector::Heuristic,
4606            p_burst: None,
4607        };
4608
4609        let jsonl = log.to_jsonl("test-run-2", ScreenMode::AltScreen, 80, 24);
4610        let parsed: serde_json::Value =
4611            serde_json::from_str(&jsonl).expect("Decision JSONL must be valid JSON");
4612
4613        assert!(parsed["pending_w"].is_null());
4614        assert!(parsed["pending_h"].is_null());
4615        assert!(parsed["applied_w"].is_null());
4616        assert!(parsed["applied_h"].is_null());
4617        assert!(parsed["coalesce_ms"].is_null());
4618        assert!(parsed["transition_reason_code"].is_null());
4619        assert!(parsed["transition_confidence"].is_null());
4620    }
4621
4622    #[test]
4623    fn evidence_config_jsonl_contains_all_fields() {
4624        let config = test_config();
4625        let jsonl = config.to_jsonl("cfg-run", ScreenMode::AltScreen, 80, 24, 0);
4626        let parsed: serde_json::Value =
4627            serde_json::from_str(&jsonl).expect("Config JSONL must be valid JSON");
4628
4629        assert_eq!(parsed["event"].as_str().unwrap(), "config");
4630        assert_eq!(
4631            parsed["schema_version"].as_str().unwrap(),
4632            EVIDENCE_SCHEMA_VERSION
4633        );
4634        assert_eq!(parsed["steady_delay_ms"].as_u64().unwrap(), 16);
4635        assert_eq!(parsed["burst_delay_ms"].as_u64().unwrap(), 40);
4636        assert_eq!(parsed["hard_deadline_ms"].as_u64().unwrap(), 100);
4637        assert!(parsed["burst_enter_rate"].as_f64().is_some());
4638        assert!(parsed["burst_exit_rate"].as_f64().is_some());
4639        assert_eq!(parsed["cooldown_frames"].as_u64().unwrap(), 3);
4640        assert_eq!(parsed["rate_window_size"].as_u64().unwrap(), 8);
4641    }
4642
4643    #[test]
4644    fn evidence_inline_screen_mode_string() {
4645        let log = DecisionLog {
4646            timestamp: Instant::now(),
4647            elapsed_ms: 0.0,
4648            event_idx: 0,
4649            dt_ms: 0.0,
4650            event_rate: 0.0,
4651            regime: Regime::Burst,
4652            action: "coalesce",
4653            pending_size: Some((120, 40)),
4654            applied_size: None,
4655            time_since_render_ms: 5.0,
4656            coalesce_ms: None,
4657            forced: false,
4658            transition_reason_code: None,
4659            transition_confidence: None,
4660            detector: RegimeDetector::Heuristic,
4661            p_burst: None,
4662        };
4663
4664        let jsonl = log.to_jsonl("inline-run", ScreenMode::Inline { ui_height: 12 }, 120, 40);
4665        let parsed: serde_json::Value =
4666            serde_json::from_str(&jsonl).expect("JSONL must be valid JSON");
4667
4668        assert_eq!(parsed["screen_mode"].as_str().unwrap(), "inline");
4669        assert_eq!(parsed["regime"].as_str().unwrap(), "burst");
4670    }
4671
4672    #[test]
4673    fn resize_scheduling_steady_applies_within_steady_delay() {
4674        let config = CoalescerConfig {
4675            steady_delay_ms: 20,
4676            burst_delay_ms: 50,
4677            hard_deadline_ms: 200,
4678            enable_logging: true,
4679            ..test_config()
4680        };
4681        let base = Instant::now();
4682        let mut c = ResizeCoalescer::new(config, (80, 24));
4683
4684        // Single resize in steady mode
4685        let action = c.handle_resize_at(100, 40, base);
4686        // First resize may or may not apply immediately depending on implementation
4687        match action {
4688            CoalesceAction::ApplyResize { width, height, .. } => {
4689                assert_eq!(width, 100);
4690                assert_eq!(height, 40);
4691            }
4692            CoalesceAction::None => {
4693                // Tick past steady delay to get the apply
4694                let later = base + Duration::from_millis(25);
4695                let action = c.tick_at(later);
4696                if let CoalesceAction::ApplyResize { width, height, .. } = action {
4697                    assert_eq!(width, 100);
4698                    assert_eq!(height, 40);
4699                }
4700            }
4701        }
4702
4703        // Verify final applied size
4704        assert_eq!(c.last_applied(), (100, 40));
4705    }
4706
4707    #[test]
4708    fn resize_scheduling_burst_regime_coalesces_rapid_events() {
4709        let config = CoalescerConfig {
4710            steady_delay_ms: 16,
4711            burst_delay_ms: 40,
4712            hard_deadline_ms: 100,
4713            burst_enter_rate: 10.0,
4714            enable_logging: true,
4715            ..test_config()
4716        };
4717        let base = Instant::now();
4718        let mut c = ResizeCoalescer::new(config, (80, 24));
4719        let mut apply_count = 0u32;
4720
4721        // Rapid resize events (20 events at 50ms intervals = 20 Hz)
4722        for i in 0..20 {
4723            let t = base + Duration::from_millis(i * 50);
4724            let action = c.handle_resize_at(80 + (i as u16), 24, t);
4725            if matches!(action, CoalesceAction::ApplyResize { .. }) {
4726                apply_count += 1;
4727            }
4728            // Tick between events
4729            let tick_t = t + Duration::from_millis(10);
4730            let tick_action = c.tick_at(tick_t);
4731            if matches!(tick_action, CoalesceAction::ApplyResize { .. }) {
4732                apply_count += 1;
4733            }
4734        }
4735
4736        // Should have coalesced: fewer applies than events
4737        assert!(
4738            apply_count < 20,
4739            "Expected coalescing: {apply_count} applies for 20 events"
4740        );
4741        // But should still have rendered at least once
4742        assert!(apply_count > 0, "Should have at least one apply");
4743    }
4744
4745    #[test]
4746    fn evidence_summary_jsonl_includes_checksum() {
4747        let config = CoalescerConfig {
4748            enable_logging: true,
4749            ..test_config()
4750        };
4751        let base = Instant::now();
4752        let mut c = ResizeCoalescer::new(config, (80, 24));
4753
4754        // Generate some events
4755        c.handle_resize_at(100, 40, base + Duration::from_millis(10));
4756        c.tick_at(base + Duration::from_millis(30));
4757
4758        let all_lines = c.evidence_to_jsonl();
4759        let summary_line = all_lines.lines().last().expect("Should have summary line");
4760        let parsed: serde_json::Value =
4761            serde_json::from_str(summary_line).expect("Summary JSONL line must be valid JSON");
4762
4763        assert_eq!(parsed["event"].as_str().unwrap(), "summary");
4764        assert!(parsed["decisions"].as_u64().is_some());
4765        assert!(parsed["applies"].as_u64().is_some());
4766        assert!(parsed["forced_applies"].as_u64().is_some());
4767        assert!(parsed["coalesces"].as_u64().is_some());
4768        assert!(parsed["skips"].as_u64().is_some());
4769        assert!(parsed["regime"].as_str().is_some());
4770        assert!(parsed["checksum"].as_str().is_some());
4771    }
4772
4773    // =========================================================================
4774    // DecisionEvidence tests (bd-dionl)
4775    // =========================================================================
4776
4777    #[test]
4778    fn decision_evidence_favor_apply_steady() {
4779        let ev = DecisionEvidence::favor_apply(Regime::Steady, 80.0, 2.0);
4780        // Steady regime contrib = 1.0, timing = min(80/50, 2) = 1.6, rate<5 = 0.5
4781        assert!(ev.log_bayes_factor > 0.0, "Should favor apply");
4782        assert_eq!(ev.regime_contribution, 1.0);
4783        assert!((ev.timing_contribution - 1.6).abs() < 0.01);
4784        assert_eq!(ev.rate_contribution, 0.5);
4785        assert!(ev.is_strong());
4786        assert!(ev.is_decisive());
4787    }
4788
4789    #[test]
4790    fn decision_evidence_favor_apply_burst_regime() {
4791        let ev = DecisionEvidence::favor_apply(Regime::Burst, 10.0, 20.0);
4792        // Burst regime contrib = -0.5, timing = min(10/50, 2) = 0.2, rate>=5 = -0.3
4793        assert_eq!(ev.regime_contribution, -0.5);
4794        assert!((ev.timing_contribution - 0.2).abs() < 0.01);
4795        assert_eq!(ev.rate_contribution, -0.3);
4796        // LBF = -0.5 + 0.2 + (-0.3) = -0.6, so not strong
4797        assert!(!ev.is_strong());
4798    }
4799
4800    #[test]
4801    fn decision_evidence_favor_coalesce_burst() {
4802        let ev = DecisionEvidence::favor_coalesce(Regime::Burst, 5.0, 15.0);
4803        // Burst regime contrib = 1.0, timing = min(20/5, 2) = 2.0, rate>10 = 0.5
4804        // LBF = -(1.0 + 2.0 + 0.5) = -3.5
4805        assert!(ev.log_bayes_factor < 0.0, "Should favor coalesce");
4806        assert_eq!(ev.regime_contribution, 1.0);
4807        assert!((ev.timing_contribution - 2.0).abs() < 0.01);
4808        assert_eq!(ev.rate_contribution, 0.5);
4809        assert!(ev.is_strong());
4810        assert!(ev.is_decisive());
4811    }
4812
4813    #[test]
4814    fn decision_evidence_favor_coalesce_steady_regime() {
4815        let ev = DecisionEvidence::favor_coalesce(Regime::Steady, 100.0, 3.0);
4816        // Steady regime contrib = -0.5, timing = min(20/100, 2) = 0.2, rate<=10 = -0.3
4817        assert_eq!(ev.regime_contribution, -0.5);
4818        assert!((ev.timing_contribution - 0.2).abs() < 0.01);
4819        assert_eq!(ev.rate_contribution, -0.3);
4820    }
4821
4822    #[test]
4823    fn decision_evidence_forced_deadline() {
4824        let ev = DecisionEvidence::forced_deadline(100.0);
4825        assert!(ev.log_bayes_factor.is_infinite());
4826        assert_eq!(ev.regime_contribution, 0.0);
4827        assert!((ev.timing_contribution - 100.0).abs() < 0.01);
4828        assert_eq!(ev.rate_contribution, 0.0);
4829        assert!(ev.is_strong());
4830        assert!(ev.is_decisive());
4831        assert!(ev.explanation.contains("100.0ms"));
4832    }
4833
4834    #[test]
4835    fn decision_evidence_is_strong_boundary() {
4836        // Exactly 1.0 is NOT strong (need >1.0)
4837        let ev = DecisionEvidence {
4838            log_bayes_factor: 1.0,
4839            regime_contribution: 0.0,
4840            timing_contribution: 0.0,
4841            rate_contribution: 0.0,
4842            explanation: String::new(),
4843        };
4844        assert!(!ev.is_strong());
4845
4846        let ev2 = DecisionEvidence {
4847            log_bayes_factor: 1.001,
4848            ..ev.clone()
4849        };
4850        assert!(ev2.is_strong());
4851
4852        // Negative values also count
4853        let ev3 = DecisionEvidence {
4854            log_bayes_factor: -1.5,
4855            ..ev
4856        };
4857        assert!(ev3.is_strong());
4858    }
4859
4860    #[test]
4861    fn decision_evidence_is_decisive_boundary() {
4862        let ev = DecisionEvidence {
4863            log_bayes_factor: 2.0,
4864            regime_contribution: 0.0,
4865            timing_contribution: 0.0,
4866            rate_contribution: 0.0,
4867            explanation: String::new(),
4868        };
4869        assert!(!ev.is_decisive()); // need >2.0
4870
4871        let ev2 = DecisionEvidence {
4872            log_bayes_factor: 2.001,
4873            ..ev
4874        };
4875        assert!(ev2.is_decisive());
4876    }
4877
4878    #[test]
4879    fn decision_evidence_to_jsonl_valid() {
4880        let ev = DecisionEvidence::favor_apply(Regime::Steady, 50.0, 3.0);
4881        let jsonl = ev.to_jsonl("test-run", ScreenMode::AltScreen, 80, 24, 5);
4882        let parsed: serde_json::Value =
4883            serde_json::from_str(&jsonl).expect("DecisionEvidence JSONL must be valid JSON");
4884
4885        assert_eq!(parsed["event"].as_str().unwrap(), "decision_evidence");
4886        assert!(parsed["log_bayes_factor"].as_f64().is_some());
4887        assert!(parsed["regime_contribution"].as_f64().is_some());
4888        assert!(parsed["timing_contribution"].as_f64().is_some());
4889        assert!(parsed["rate_contribution"].as_f64().is_some());
4890        assert!(parsed["explanation"].as_str().is_some());
4891    }
4892
4893    #[test]
4894    fn decision_evidence_to_jsonl_infinity() {
4895        let ev = DecisionEvidence::forced_deadline(100.0);
4896        let jsonl = ev.to_jsonl("test-run", ScreenMode::AltScreen, 80, 24, 0);
4897        // Infinity serialized as "inf" string
4898        assert!(jsonl.contains("\"inf\""));
4899    }
4900
4901    // =========================================================================
4902    // Edge case tests (bd-dionl)
4903    // =========================================================================
4904
4905    #[test]
4906    fn hard_deadline_zero_applies_immediately() {
4907        let config = CoalescerConfig {
4908            hard_deadline_ms: 0,
4909            enable_logging: true,
4910            ..test_config()
4911        };
4912        let mut c = ResizeCoalescer::new(config, (80, 24));
4913        let base = Instant::now();
4914
4915        // Any resize should apply immediately since deadline is 0
4916        let action = c.handle_resize_at(100, 40, base);
4917        assert!(
4918            matches!(action, CoalesceAction::ApplyResize { .. }),
4919            "hard_deadline_ms=0 should force immediate apply, got {action:?}"
4920        );
4921    }
4922
4923    #[test]
4924    fn rate_window_size_zero_returns_zero_rate() {
4925        let config = CoalescerConfig {
4926            rate_window_size: 0,
4927            enable_logging: true,
4928            ..test_config()
4929        };
4930        let mut c = ResizeCoalescer::new(config, (80, 24));
4931        let base = Instant::now();
4932
4933        for i in 0..5 {
4934            c.handle_resize_at(80 + i, 24, base + Duration::from_millis(i as u64 * 10));
4935        }
4936        // With window=0, only 1 event kept, so < 2 elements → rate=0
4937        let rate = c.calculate_event_rate(base + Duration::from_millis(50));
4938        assert_eq!(rate, 0.0, "rate_window_size=0 should yield 0 rate");
4939    }
4940
4941    #[test]
4942    fn tick_no_pending_returns_none() {
4943        let config = test_config();
4944        let mut c = ResizeCoalescer::new(config, (80, 24));
4945        let base = Instant::now();
4946
4947        // No resize events, tick should return None
4948        let action = c.tick_at(base);
4949        assert_eq!(action, CoalesceAction::None);
4950        let action = c.tick_at(base + Duration::from_millis(500));
4951        assert_eq!(action, CoalesceAction::None);
4952    }
4953
4954    #[test]
4955    fn time_until_apply_none_when_no_pending() {
4956        let c = ResizeCoalescer::new(test_config(), (80, 24));
4957        assert!(c.time_until_apply(Instant::now()).is_none());
4958    }
4959
4960    #[test]
4961    fn time_until_apply_zero_when_past_delay() {
4962        let config = test_config();
4963        let mut c = ResizeCoalescer::new(config, (80, 24));
4964        let base = Instant::now();
4965
4966        c.handle_resize_at(100, 40, base);
4967        // Well past the steady_delay_ms of 16ms
4968        let result = c.time_until_apply(base + Duration::from_millis(500));
4969        assert_eq!(result, Some(Duration::ZERO));
4970    }
4971
4972    // =========================================================================
4973    // json_escape tests (bd-dionl)
4974    // =========================================================================
4975
4976    #[test]
4977    fn json_escape_special_characters() {
4978        assert_eq!(json_escape("hello"), "hello");
4979        assert_eq!(json_escape("a\"b"), "a\\\"b");
4980        assert_eq!(json_escape("a\\b"), "a\\\\b");
4981        assert_eq!(json_escape("a\nb"), "a\\nb");
4982        assert_eq!(json_escape("a\rb"), "a\\rb");
4983        assert_eq!(json_escape("a\tb"), "a\\tb");
4984    }
4985
4986    #[test]
4987    fn json_escape_control_characters() {
4988        // Control char \x01 should be escaped as \u0001
4989        let input = "a\x01b";
4990        let escaped = json_escape(input);
4991        assert_eq!(escaped, "a\\u0001b");
4992    }
4993
4994    #[test]
4995    fn json_escape_empty_string() {
4996        assert_eq!(json_escape(""), "");
4997    }
4998
4999    // =========================================================================
5000    // clear_logs and decision_logs_jsonl tests (bd-dionl)
5001    // =========================================================================
5002
5003    #[test]
5004    fn clear_logs_resets_state() {
5005        let mut config = test_config();
5006        config.enable_logging = true;
5007        let mut c = ResizeCoalescer::new(config, (80, 24));
5008
5009        c.handle_resize_at(100, 40, Instant::now());
5010        c.tick_at(Instant::now() + Duration::from_millis(50));
5011
5012        assert!(!c.logs().is_empty());
5013
5014        c.clear_logs();
5015        assert!(c.logs().is_empty());
5016
5017        // After clearing, new logs should work
5018        c.handle_resize_at(120, 50, Instant::now());
5019        c.tick_at(Instant::now() + Duration::from_millis(50));
5020        assert!(!c.logs().is_empty());
5021    }
5022
5023    #[test]
5024    fn decision_logs_jsonl_each_line_valid() {
5025        let mut config = test_config();
5026        config.enable_logging = true;
5027        let base = Instant::now();
5028        let mut c = ResizeCoalescer::new(config, (80, 24))
5029            .with_evidence_run_id("jsonl-test")
5030            .with_screen_mode(ScreenMode::AltScreen);
5031
5032        c.handle_resize_at(100, 40, base);
5033        c.handle_resize_at(110, 50, base + Duration::from_millis(5));
5034        c.tick_at(base + Duration::from_millis(50));
5035
5036        let jsonl = c.decision_logs_jsonl();
5037        assert!(!jsonl.is_empty());
5038        for line in jsonl.lines() {
5039            let _: serde_json::Value =
5040                serde_json::from_str(line).expect("Each JSONL line must be valid JSON");
5041        }
5042    }
5043
5044    // =========================================================================
5045    // TelemetryHooks tests (bd-dionl)
5046    // =========================================================================
5047
5048    #[test]
5049    fn telemetry_hooks_has_methods() {
5050        let hooks = TelemetryHooks::new();
5051        assert!(!hooks.has_resize_applied());
5052        assert!(!hooks.has_regime_change());
5053        assert!(!hooks.has_decision());
5054
5055        let hooks = hooks.on_resize_applied(|_| {});
5056        assert!(hooks.has_resize_applied());
5057        assert!(!hooks.has_regime_change());
5058        assert!(!hooks.has_decision());
5059    }
5060
5061    #[test]
5062    fn telemetry_hooks_with_tracing() {
5063        let hooks = TelemetryHooks::new().with_tracing(true);
5064        let debug_str = format!("{:?}", hooks);
5065        assert!(debug_str.contains("emit_tracing: true"));
5066    }
5067
5068    #[test]
5069    fn telemetry_hooks_default_equals_new() {
5070        let h1 = TelemetryHooks::default();
5071        let h2 = TelemetryHooks::new();
5072        assert!(!h1.has_resize_applied());
5073        assert!(!h2.has_resize_applied());
5074    }
5075
5076    #[test]
5077    fn telemetry_hooks_on_decision_fires() {
5078        use std::sync::Arc;
5079        use std::sync::atomic::{AtomicU32, Ordering};
5080
5081        let count = Arc::new(AtomicU32::new(0));
5082        let count_clone = count.clone();
5083
5084        let hooks = TelemetryHooks::new().on_decision(move |_entry| {
5085            count_clone.fetch_add(1, Ordering::SeqCst);
5086        });
5087
5088        let mut config = test_config();
5089        config.enable_logging = true;
5090        let mut c = ResizeCoalescer::new(config, (80, 24)).with_telemetry_hooks(hooks);
5091
5092        let base = Instant::now();
5093        c.handle_resize_at(100, 40, base);
5094
5095        // The coalesce decision should fire the on_decision hook
5096        assert!(count.load(Ordering::SeqCst) >= 1);
5097    }
5098
5099    // =========================================================================
5100    // Regime::as_str tests (bd-dionl)
5101    // =========================================================================
5102
5103    #[test]
5104    fn regime_as_str_values() {
5105        assert_eq!(Regime::Steady.as_str(), "steady");
5106        assert_eq!(Regime::Burst.as_str(), "burst");
5107    }
5108
5109    #[test]
5110    fn regime_default_is_steady() {
5111        assert_eq!(Regime::default(), Regime::Steady);
5112    }
5113
5114    // =========================================================================
5115    // DecisionSummary tests (bd-dionl)
5116    // =========================================================================
5117
5118    #[test]
5119    fn decision_summary_checksum_hex_format() {
5120        let summary = DecisionSummary {
5121            checksum: 0x0123456789ABCDEF,
5122            ..DecisionSummary::default()
5123        };
5124        assert_eq!(summary.checksum_hex(), "0123456789abcdef");
5125    }
5126
5127    #[test]
5128    fn decision_summary_default_values() {
5129        let summary = DecisionSummary::default();
5130        assert_eq!(summary.decision_count, 0);
5131        assert_eq!(summary.apply_count, 0);
5132        assert_eq!(summary.forced_apply_count, 0);
5133        assert_eq!(summary.coalesce_count, 0);
5134        assert_eq!(summary.skip_count, 0);
5135        assert_eq!(summary.regime, Regime::Steady);
5136        assert_eq!(summary.last_applied, (0, 0));
5137        assert_eq!(summary.checksum, 0);
5138    }
5139
5140    #[test]
5141    fn decision_summary_to_jsonl_valid() {
5142        let summary = DecisionSummary {
5143            decision_count: 5,
5144            apply_count: 2,
5145            forced_apply_count: 1,
5146            coalesce_count: 2,
5147            skip_count: 1,
5148            regime: Regime::Burst,
5149            last_applied: (120, 40),
5150            checksum: 0xDEADBEEF,
5151        };
5152        let jsonl = summary.to_jsonl("run-1", ScreenMode::AltScreen, 120, 40, 5);
5153        let parsed: serde_json::Value =
5154            serde_json::from_str(&jsonl).expect("Summary JSONL must be valid JSON");
5155
5156        assert_eq!(parsed["event"].as_str().unwrap(), "summary");
5157        assert_eq!(parsed["decisions"].as_u64().unwrap(), 5);
5158        assert_eq!(parsed["applies"].as_u64().unwrap(), 2);
5159        assert_eq!(parsed["forced_applies"].as_u64().unwrap(), 1);
5160        assert_eq!(parsed["coalesces"].as_u64().unwrap(), 2);
5161        assert_eq!(parsed["skips"].as_u64().unwrap(), 1);
5162        assert_eq!(parsed["regime"].as_str().unwrap(), "burst");
5163        assert_eq!(parsed["last_w"].as_u64().unwrap(), 120);
5164        assert_eq!(parsed["last_h"].as_u64().unwrap(), 40);
5165        assert!(parsed["checksum"].as_str().unwrap().contains("deadbeef"));
5166    }
5167
5168    // =========================================================================
5169    // screen_mode_str tests (bd-dionl)
5170    // =========================================================================
5171
5172    #[test]
5173    fn screen_mode_str_all_variants() {
5174        assert_eq!(screen_mode_str(ScreenMode::AltScreen), "altscreen");
5175        assert_eq!(
5176            screen_mode_str(ScreenMode::Inline { ui_height: 10 }),
5177            "inline"
5178        );
5179        assert_eq!(
5180            screen_mode_str(ScreenMode::InlineAuto {
5181                min_height: 5,
5182                max_height: 20,
5183            }),
5184            "inline_auto"
5185        );
5186    }
5187
5188    // =========================================================================
5189    // Config builder chaining tests (bd-dionl)
5190    // =========================================================================
5191
5192    #[test]
5193    fn config_with_logging_chaining() {
5194        let config = CoalescerConfig::default().with_logging(true);
5195        assert!(config.enable_logging);
5196
5197        let config2 = config.with_logging(false);
5198        assert!(!config2.enable_logging);
5199    }
5200
5201    #[test]
5202    fn config_with_bocpd_chaining() {
5203        let config = CoalescerConfig::default().with_bocpd();
5204        assert!(config.enable_bocpd);
5205        assert!(config.bocpd_config.is_some());
5206    }
5207
5208    #[test]
5209    fn config_with_bocpd_config_chaining() {
5210        let bocpd_cfg = BocpdConfig {
5211            max_run_length: 42,
5212            ..BocpdConfig::default()
5213        };
5214        let config = CoalescerConfig::default().with_bocpd_config(bocpd_cfg);
5215        assert!(config.enable_bocpd);
5216        assert_eq!(config.bocpd_config.as_ref().unwrap().max_run_length, 42);
5217    }
5218
5219    // =========================================================================
5220    // Coalescer builder chaining tests (bd-dionl)
5221    // =========================================================================
5222
5223    #[test]
5224    fn coalescer_with_evidence_run_id() {
5225        let c = ResizeCoalescer::new(test_config(), (80, 24)).with_evidence_run_id("custom-run-id");
5226        // Verify via evidence JSONL output
5227        let jsonl = c.evidence_to_jsonl();
5228        assert!(jsonl.contains("custom-run-id"));
5229    }
5230
5231    #[test]
5232    fn coalescer_with_screen_mode() {
5233        let mut config = test_config();
5234        config.enable_logging = true;
5235        let mut c = ResizeCoalescer::new(config, (80, 24))
5236            .with_screen_mode(ScreenMode::Inline { ui_height: 8 });
5237
5238        c.handle_resize(100, 40);
5239        let jsonl = c.evidence_to_jsonl();
5240        assert!(jsonl.contains("\"screen_mode\":\"inline\""));
5241    }
5242
5243    #[test]
5244    fn coalescer_set_evidence_sink_clears_config_logged() {
5245        let mut config = test_config();
5246        config.enable_logging = true;
5247        let mut c = ResizeCoalescer::new(config, (80, 24));
5248
5249        // Generate some events so config is logged
5250        c.handle_resize(100, 40);
5251
5252        // Setting evidence sink to None should reset config_logged
5253        c.set_evidence_sink(None);
5254
5255        // Evidence JSONL should still have config line since it rebuilds from config
5256        let jsonl = c.evidence_to_jsonl();
5257        assert!(jsonl.contains("\"event\":\"config\""));
5258    }
5259
5260    // =========================================================================
5261    // duration_since_or_zero tests (bd-dionl)
5262    // =========================================================================
5263
5264    #[test]
5265    fn duration_since_or_zero_normal() {
5266        let earlier = Instant::now();
5267        std::thread::sleep(Duration::from_millis(1));
5268        let now = Instant::now();
5269        let result = duration_since_or_zero(now, earlier);
5270        assert!(result >= Duration::from_millis(1));
5271    }
5272
5273    #[test]
5274    fn duration_since_or_zero_same_instant() {
5275        let now = Instant::now();
5276        let result = duration_since_or_zero(now, now);
5277        assert_eq!(result, Duration::ZERO);
5278    }
5279
5280    // =========================================================================
5281    // ResizeAppliedEvent and RegimeChangeEvent struct tests (bd-dionl)
5282    // =========================================================================
5283
5284    #[test]
5285    fn resize_applied_event_fields() {
5286        let event = ResizeAppliedEvent {
5287            new_size: (100, 40),
5288            old_size: (80, 24),
5289            elapsed: Duration::from_millis(42),
5290            forced: true,
5291        };
5292        assert_eq!(event.new_size, (100, 40));
5293        assert_eq!(event.old_size, (80, 24));
5294        assert_eq!(event.elapsed, Duration::from_millis(42));
5295        assert!(event.forced);
5296    }
5297
5298    #[test]
5299    fn regime_change_event_fields() {
5300        let event = RegimeChangeEvent {
5301            from: Regime::Steady,
5302            to: Regime::Burst,
5303            event_idx: 42,
5304            reason_code: TransitionReasonCode::HeuristicEnterBurstRate,
5305            confidence: 0.91,
5306        };
5307        assert_eq!(event.from, Regime::Steady);
5308        assert_eq!(event.to, Regime::Burst);
5309        assert_eq!(event.event_idx, 42);
5310        assert_eq!(
5311            event.reason_code,
5312            TransitionReasonCode::HeuristicEnterBurstRate
5313        );
5314        assert!((event.confidence - 0.91).abs() < f64::EPSILON);
5315    }
5316
5317    // =========================================================================
5318    // CoalesceAction equality edge cases (bd-dionl)
5319    // =========================================================================
5320
5321    #[test]
5322    fn coalesce_action_none_eq() {
5323        assert_eq!(CoalesceAction::None, CoalesceAction::None);
5324        assert_ne!(
5325            CoalesceAction::None,
5326            CoalesceAction::ApplyResize {
5327                width: 1,
5328                height: 1,
5329                coalesce_time: Duration::ZERO,
5330                forced_by_deadline: false,
5331            }
5332        );
5333    }
5334
5335    /// CONTRACT (bd-1za0z item 2, pinned): in BOCPD mode the posterior owns
5336    /// regime changes; the heuristic cooldown exit must never fire, and the
5337    /// transition log must alternate regimes (no `Burst -> Burst` pairs).
5338    #[test]
5339    fn bocpd_mode_never_emits_heuristic_cooldown_exit() {
5340        let mut c = ResizeCoalescer::new(test_config().with_bocpd(), (80, 24));
5341        let base = Instant::now();
5342        let mut now = base;
5343        // 200 events at 200 events/s (well above the 10/s burst threshold).
5344        for i in 0..200u16 {
5345            now += Duration::from_millis(5);
5346            let _ = c.handle_resize_at(100 + (i % 7), 40 + (i % 3), now);
5347        }
5348        // Then 100 quiet ticks (one per 16 ms frame).
5349        for _ in 0..100 {
5350            now += Duration::from_millis(16);
5351            let _ = c.tick_at(now);
5352        }
5353        let logs = c.transition_logs();
5354        assert!(
5355            logs.iter()
5356                .all(|t| t.reason_code != TransitionReasonCode::HeuristicExitBurstCooldown),
5357            "heuristic cooldown exit fired in BOCPD mode: {logs:?}"
5358        );
5359        for window in logs.windows(2) {
5360            assert_ne!(
5361                window[0].from_regime, window[0].to_regime,
5362                "a transition must change regime: {logs:?}"
5363            );
5364            assert_eq!(
5365                window[0].to_regime, window[1].from_regime,
5366                "consecutive transitions must chain: {logs:?}"
5367            );
5368        }
5369        assert_eq!(c.regime_transition_count(), logs.len() as u64);
5370    }
5371
5372    /// CONTRACT (bd-1za0z item 2, regression): the immediate path
5373    /// (`record_external_apply`, used by `ResizeBehavior::Immediate`) must not
5374    /// leave `stats().regime` pinned to `Burst` once the burst is over.
5375    #[test]
5376    fn immediate_mode_regime_is_not_pinned_to_burst() {
5377        let mut c = ResizeCoalescer::new(test_config(), (80, 24));
5378        let mut now = Instant::now();
5379        assert_eq!(c.stats().regime, Regime::Steady);
5380        // A burst of externally applied resizes (5 ms apart = 200/s).
5381        for i in 0..30u16 {
5382            now += Duration::from_millis(5);
5383            c.record_external_apply(100 + i, 40, now);
5384        }
5385        assert_eq!(c.stats().regime, Regime::Burst, "burst detected");
5386        let transitions_after_burst = c.regime_transition_count();
5387        // The immediate path is never ticked by the frame loop, so the next
5388        // observation is the next resize: an isolated apply after a quiet gap
5389        // must bring the regime back to Steady instead of leaving it pinned.
5390        now += Duration::from_secs(2);
5391        c.record_external_apply(90, 30, now);
5392        assert_eq!(
5393            c.stats().regime,
5394            Regime::Steady,
5395            "regime pinned to Burst after the burst ended"
5396        );
5397        assert_eq!(c.stats().last_applied, (90, 30));
5398        assert_eq!(c.regime_transition_count(), transitions_after_burst + 1);
5399        let last = c.transition_logs().last().expect("exit transition logged");
5400        assert_eq!(
5401            last.reason_code,
5402            TransitionReasonCode::HeuristicExitBurstRate
5403        );
5404        assert_eq!(
5405            (last.from_regime, last.to_regime),
5406            (Regime::Burst, Regime::Steady)
5407        );
5408        assert_eq!(last.reason_code.as_str(), "heuristic_exit_burst_rate");
5409    }
5410
5411    #[test]
5412    fn coalesce_action_apply_resize_eq() {
5413        let a = CoalesceAction::ApplyResize {
5414            width: 100,
5415            height: 40,
5416            coalesce_time: Duration::from_millis(16),
5417            forced_by_deadline: false,
5418        };
5419        let b = CoalesceAction::ApplyResize {
5420            width: 100,
5421            height: 40,
5422            coalesce_time: Duration::from_millis(16),
5423            forced_by_deadline: false,
5424        };
5425        assert_eq!(a, b);
5426
5427        let c = CoalesceAction::ApplyResize {
5428            width: 100,
5429            height: 40,
5430            coalesce_time: Duration::from_millis(16),
5431            forced_by_deadline: true,
5432        };
5433        assert_ne!(a, c);
5434    }
5435
5436    // =========================================================================
5437    // FNV hash consistency (bd-dionl)
5438    // =========================================================================
5439
5440    #[test]
5441    fn fnv_hash_deterministic() {
5442        let mut h1 = FNV_OFFSET_BASIS;
5443        fnv_hash_bytes(&mut h1, b"hello world");
5444
5445        let mut h2 = FNV_OFFSET_BASIS;
5446        fnv_hash_bytes(&mut h2, b"hello world");
5447
5448        assert_eq!(h1, h2);
5449    }
5450
5451    #[test]
5452    fn fnv_hash_different_inputs_different_hashes() {
5453        let mut h1 = FNV_OFFSET_BASIS;
5454        fnv_hash_bytes(&mut h1, b"hello");
5455
5456        let mut h2 = FNV_OFFSET_BASIS;
5457        fnv_hash_bytes(&mut h2, b"world");
5458
5459        assert_ne!(h1, h2);
5460    }
5461
5462    #[test]
5463    fn fnv_hash_empty_input_returns_basis() {
5464        let mut hash = FNV_OFFSET_BASIS;
5465        fnv_hash_bytes(&mut hash, b"");
5466        assert_eq!(hash, FNV_OFFSET_BASIS);
5467    }
5468}