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