Skip to main content

euv_core/render/adaptive/
impl.rs

1use super::*;
2
3/// Wire-label and mode conversion helpers for `RenderBackendCandidate`.
4impl RenderBackendCandidate {
5    /// Returns the canonical snake_case wire label for this candidate.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Candidate reference.
10    ///
11    /// # Returns
12    ///
13    /// - `&'static str` - Canonical candidate label.
14    #[must_use]
15    pub const fn as_str(&self) -> &'static str {
16        match *self {
17            Self::GpuDirect => CANDIDATE_LABEL_GPU_DIRECT,
18            Self::GpuUpload => CANDIDATE_LABEL_GPU_UPLOAD,
19            Self::Hybrid => CANDIDATE_LABEL_HYBRID,
20            Self::Software => CANDIDATE_LABEL_SOFTWARE,
21            Self::Terminal => CANDIDATE_LABEL_TERMINAL,
22        }
23    }
24
25    /// Maps this adaptive candidate to the corresponding concrete `RenderMode`.
26    ///
27    /// # Arguments
28    ///
29    /// - `&Self` - Candidate reference.
30    ///
31    /// # Returns
32    ///
33    /// - `RenderMode` - Concrete render mode.
34    #[must_use]
35    pub const fn to_render_mode(&self) -> RenderMode {
36        match *self {
37            Self::GpuDirect | Self::GpuUpload => RenderMode::Hardware,
38            Self::Hybrid => RenderMode::Hybrid,
39            Self::Software | Self::Terminal => RenderMode::Software,
40        }
41    }
42
43    /// Returns `true` when this candidate executes direct GPU rendering with zero CPU mirror.
44    ///
45    /// # Arguments
46    ///
47    /// - `&Self` - Candidate reference.
48    ///
49    /// # Returns
50    ///
51    /// - `bool` - `true` only for `GpuDirect`.
52    #[must_use]
53    pub const fn is_direct_gpu(&self) -> bool {
54        matches!(*self, Self::GpuDirect)
55    }
56}
57
58/// Wire-label helpers for `AdaptiveSwitchMode`.
59impl AdaptiveSwitchMode {
60    /// Returns the canonical snake_case wire label for this rollout switch mode.
61    ///
62    /// # Arguments
63    ///
64    /// - `&Self` - Switch mode reference.
65    ///
66    /// # Returns
67    ///
68    /// - `&'static str` - Canonical switch mode label.
69    #[must_use]
70    pub const fn as_str(&self) -> &'static str {
71        match *self {
72            Self::RecommendOnly => SWITCH_MODE_RECOMMEND_ONLY,
73            Self::AutoSwitch => SWITCH_MODE_AUTO_SWITCH,
74        }
75    }
76}
77
78/// Wire-label helpers for `FaultEventKind`.
79impl FaultEventKind {
80    /// Returns the canonical snake_case wire label for this fault kind.
81    ///
82    /// # Arguments
83    ///
84    /// - `&Self` - Fault kind reference.
85    ///
86    /// # Returns
87    ///
88    /// - `&'static str` - Canonical fault label.
89    #[must_use]
90    pub const fn as_str(&self) -> &'static str {
91        match *self {
92            Self::DeviceLost => FAULT_LABEL_DEVICE_LOST,
93            Self::SurfaceDestroyed => FAULT_LABEL_SURFACE_DESTROYED,
94            Self::DriverSuspended => FAULT_LABEL_DRIVER_SUSPENDED,
95            Self::ThermalThrottled => FAULT_LABEL_THERMAL_THROTTLED,
96        }
97    }
98}
99
100/// Default strict baseline requiring full visual equivalence across every quality invariant.
101impl Default for VisualEquivalenceContract {
102    /// Creates the canonical strict visual-equivalence contract with all invariants enabled.
103    ///
104    /// # Returns
105    ///
106    /// - `Self` - Strict visual-equivalence baseline.
107    fn default() -> Self {
108        Self::strict()
109    }
110}
111
112/// Strict contract constructors and equivalence checks for `VisualEquivalenceContract`.
113impl VisualEquivalenceContract {
114    /// Creates a visual-equivalence contract where fonts, layout, color, AA, shadow, blur, visible tiles, and media quality are all invariant.
115    ///
116    /// # Returns
117    ///
118    /// - `Self` - Strict visual-equivalence contract.
119    #[must_use]
120    pub const fn strict() -> Self {
121        Self {
122            fonts_identical: true,
123            layout_identical: true,
124            color_identical: true,
125            antialiasing_identical: true,
126            shadows_identical: true,
127            blur_identical: true,
128            visible_tiles_identical: true,
129            media_quality_identical: true,
130        }
131    }
132
133    /// Validates that `candidate` satisfies every invariant required by `self`.
134    ///
135    /// # Arguments
136    ///
137    /// - `&Self` - Required baseline contract.
138    /// - `&Self` - Candidate visual contract.
139    ///
140    /// # Returns
141    ///
142    /// - `Result<(), VisualEquivalenceFailure>` - `Ok(())` when visually equivalent, or the first violated invariant.
143    pub const fn check_equivalence(
144        &self,
145        candidate: &Self,
146    ) -> Result<(), VisualEquivalenceFailure> {
147        let Self {
148            fonts_identical,
149            layout_identical,
150            color_identical,
151            antialiasing_identical,
152            shadows_identical,
153            blur_identical,
154            visible_tiles_identical,
155            media_quality_identical,
156        } = *self;
157        if fonts_identical && !candidate.fonts_identical {
158            return Err(VisualEquivalenceFailure::FontMismatch);
159        }
160        if layout_identical && !candidate.layout_identical {
161            return Err(VisualEquivalenceFailure::LayoutMismatch);
162        }
163        if color_identical && !candidate.color_identical {
164            return Err(VisualEquivalenceFailure::ColorSpaceMismatch);
165        }
166        if antialiasing_identical && !candidate.antialiasing_identical {
167            return Err(VisualEquivalenceFailure::AntialiasingMismatch);
168        }
169        if shadows_identical && !candidate.shadows_identical {
170            return Err(VisualEquivalenceFailure::ShadowMismatch);
171        }
172        if blur_identical && !candidate.blur_identical {
173            return Err(VisualEquivalenceFailure::BackdropBlurMismatch);
174        }
175        if visible_tiles_identical && !candidate.visible_tiles_identical {
176            return Err(VisualEquivalenceFailure::VisibleTileMismatch);
177        }
178        if media_quality_identical && !candidate.media_quality_identical {
179            return Err(VisualEquivalenceFailure::MediaQualityMismatch);
180        }
181        Ok(())
182    }
183
184    /// Returns `true` when `candidate` satisfies all required visual invariants.
185    ///
186    /// # Arguments
187    ///
188    /// - `&Self` - Required baseline contract.
189    /// - `&Self` - Candidate visual contract.
190    ///
191    /// # Returns
192    ///
193    /// - `bool` - `true` when visually equivalent.
194    #[must_use]
195    pub const fn is_equivalent(&self, candidate: &Self) -> bool {
196        self.check_equivalence(candidate).is_ok()
197    }
198}
199
200/// Constructors and gate checks for `CandidateCapabilities`.
201impl CandidateCapabilities {
202    /// Creates a supported visually-equivalent candidate capability declaration.
203    ///
204    /// # Arguments
205    ///
206    /// - `RenderBackendCandidate` - Candidate kind.
207    /// - `GraphicsBackend` - Underlying graphics backend.
208    /// - `bool` - Whether warmup work must execute on UI/render thread.
209    ///
210    /// # Returns
211    ///
212    /// - `Self` - Verified visually-equivalent candidate capabilities.
213    #[must_use]
214    pub const fn supported_equivalent(
215        candidate: RenderBackendCandidate,
216        graphics_backend: GraphicsBackend,
217        requires_ui_thread_warmup: bool,
218    ) -> Self {
219        Self {
220            candidate,
221            supported: true,
222            visual_contract: VisualEquivalenceContract::strict(),
223            requires_ui_thread_warmup,
224            is_simulated_profile: false,
225            direct_gpu_verified_on_device: matches!(candidate, RenderBackendCandidate::GpuDirect),
226            graphics_backend,
227        }
228    }
229
230    /// Evaluates whether this candidate passes platform support, device honesty, and visual-equivalence gates.
231    ///
232    /// # Arguments
233    ///
234    /// - `&Self` - Candidate capability record.
235    /// - `&VisualEquivalenceContract` - Required baseline contract.
236    ///
237    /// # Returns
238    ///
239    /// - `Result<(), VisualEquivalenceFailure>` - `Ok(())` when eligible, or exact disqualification reason.
240    pub fn passes_gate(
241        &self,
242        baseline: &VisualEquivalenceContract,
243    ) -> Result<(), VisualEquivalenceFailure> {
244        if !self.get_supported() {
245            return Err(VisualEquivalenceFailure::BackendUnsupported);
246        }
247        if self.get_candidate() == RenderBackendCandidate::GpuDirect
248            && self.get_is_simulated_profile()
249            && !self.get_direct_gpu_verified_on_device()
250        {
251            return Err(VisualEquivalenceFailure::UnverifiedSimulatedGpu);
252        }
253        let contract: VisualEquivalenceContract = self.get_visual_contract();
254        baseline.check_equivalence(&contract)
255    }
256}
257
258/// Default host capability profile for headless software execution.
259impl Default for HostCapabilityProfile {
260    /// Creates a deterministic single-channel software host profile.
261    ///
262    /// # Returns
263    ///
264    /// - `Self` - Default headless host profile.
265    fn default() -> Self {
266        Self::from_platform(
267            PlatformKind::Headless,
268            PlatformCapabilities::for_platform(PlatformKind::Headless),
269        )
270    }
271}
272
273/// Platform capability synthesis and gate helpers for `HostCapabilityProfile`.
274impl HostCapabilityProfile {
275    /// Builds a truthful `HostCapabilityProfile` from `platform` and `capabilities`.
276    ///
277    /// # Arguments
278    ///
279    /// - `PlatformKind` - Target execution platform.
280    /// - `PlatformCapabilities` - Reported hardware capabilities.
281    ///
282    /// # Returns
283    ///
284    /// - `Self` - Host capability profile with visual-equivalence baseline.
285    #[must_use]
286    pub fn from_platform(platform: PlatformKind, capabilities: PlatformCapabilities) -> Self {
287        let baseline_contract: VisualEquivalenceContract = VisualEquivalenceContract::strict();
288        if matches!(
289            platform,
290            PlatformKind::Terminal
291                | PlatformKind::TerminalCli
292                | PlatformKind::MiniApp
293                | PlatformKind::QuickApp
294        ) {
295            let (cand, backend): (RenderBackendCandidate, GraphicsBackend) =
296                if matches!(platform, PlatformKind::Terminal | PlatformKind::TerminalCli) {
297                    (RenderBackendCandidate::Terminal, GraphicsBackend::Headless)
298                } else {
299                    (RenderBackendCandidate::Software, GraphicsBackend::Canvas2d)
300                };
301            return Self {
302                platform,
303                candidates: vec![CandidateCapabilities::supported_equivalent(
304                    cand, backend, true,
305                )],
306                single_channel_only: true,
307                baseline_contract,
308            };
309        }
310        let default_gpu: GraphicsBackend = platform.default_graphics_backend();
311        let sw_backend: GraphicsBackend = if platform == PlatformKind::Web {
312            GraphicsBackend::Canvas2d
313        } else {
314            GraphicsBackend::SoftwareCpu
315        };
316        let mut candidates: Vec<CandidateCapabilities> = Vec::new();
317        if capabilities.get_hardware_gpu() {
318            let ui_thread_req: bool = matches!(
319                platform,
320                PlatformKind::Web | PlatformKind::MacOs | PlatformKind::Ios | PlatformKind::IpadOs
321            );
322            candidates.push(CandidateCapabilities::supported_equivalent(
323                RenderBackendCandidate::GpuDirect,
324                default_gpu,
325                ui_thread_req,
326            ));
327            candidates.push(CandidateCapabilities::supported_equivalent(
328                RenderBackendCandidate::GpuUpload,
329                default_gpu,
330                ui_thread_req,
331            ));
332            candidates.push(CandidateCapabilities::supported_equivalent(
333                RenderBackendCandidate::Hybrid,
334                default_gpu,
335                ui_thread_req,
336            ));
337        }
338        candidates.push(CandidateCapabilities::supported_equivalent(
339            RenderBackendCandidate::Software,
340            sw_backend,
341            false,
342        ));
343        let single_channel_only: bool = candidates.len() <= 1;
344        Self {
345            platform,
346            candidates,
347            single_channel_only,
348            baseline_contract,
349        }
350    }
351
352    /// Creates a single-channel host profile locked strictly to `candidate` with probing permanently disabled.
353    ///
354    /// # Arguments
355    ///
356    /// - `PlatformKind` - Target platform.
357    /// - `RenderBackendCandidate` - Sole supported channel.
358    /// - `GraphicsBackend` - Graphics backend bound to that channel.
359    ///
360    /// # Returns
361    ///
362    /// - `Self` - Single-channel locked profile.
363    #[must_use]
364    pub fn single_channel(
365        platform: PlatformKind,
366        candidate: RenderBackendCandidate,
367        backend: GraphicsBackend,
368    ) -> Self {
369        Self {
370            platform,
371            candidates: vec![CandidateCapabilities::supported_equivalent(
372                candidate, backend, true,
373            )],
374            single_channel_only: true,
375            baseline_contract: VisualEquivalenceContract::strict(),
376        }
377    }
378
379    /// Converts host-declared `HostChannelCapabilities` (HarmonyOS, Wearables, MiniApps, QuickApps) into a unified `HostCapabilityProfile` enforcing single-channel locking and simulated-profile honesty.
380    ///
381    /// # Arguments
382    ///
383    /// - `PlatformKind` - Target execution platform.
384    /// - `&HostChannelCapabilities` - Host-declared channel capability matrix.
385    ///
386    /// # Returns
387    ///
388    /// - `Self` - Unified capability profile ready for `AdaptiveRenderRouter`.
389    #[must_use]
390    pub fn from_host_channel_capabilities(
391        platform: PlatformKind,
392        caps: &HostChannelCapabilities,
393    ) -> Self {
394        let gate: HostVisualEquivalenceGate = caps.get_visual_equivalence();
395        let visual_contract: VisualEquivalenceContract = VisualEquivalenceContract {
396            fonts_identical: gate.get_fonts_equivalent(),
397            layout_identical: gate.get_layout_equivalent(),
398            color_identical: gate.get_color_equivalent(),
399            antialiasing_identical: gate.get_aa_equivalent(),
400            shadows_identical: gate.get_shadow_equivalent(),
401            blur_identical: gate.get_blur_equivalent(),
402            visible_tiles_identical: gate.get_visible_tiles_equivalent(),
403            media_quality_identical: gate.get_media_quality_equivalent(),
404        };
405        let is_sim: bool = caps.get_simulated_profile();
406        let verified_gpu: bool = !is_sim && caps.get_direct_gpu_verified_on_device();
407        let default_gpu: GraphicsBackend = platform.default_graphics_backend();
408        let mut candidates: Vec<CandidateCapabilities> = Vec::new();
409        for channel in caps.get_supported_channels() {
410            let (candidate, graphics_backend): (RenderBackendCandidate, GraphicsBackend) =
411                match *channel {
412                    HostRenderChannel::GpuDirect => {
413                        (RenderBackendCandidate::GpuDirect, default_gpu)
414                    }
415                    HostRenderChannel::GpuUpload => {
416                        (RenderBackendCandidate::GpuUpload, default_gpu)
417                    }
418                    HostRenderChannel::SoftwareBuffer => (
419                        RenderBackendCandidate::Software,
420                        GraphicsBackend::SoftwareCpu,
421                    ),
422                    HostRenderChannel::Canvas2d => {
423                        (RenderBackendCandidate::Software, GraphicsBackend::Canvas2d)
424                    }
425                    HostRenderChannel::WebGl | HostRenderChannel::WebGl2 => {
426                        (RenderBackendCandidate::GpuUpload, GraphicsBackend::WebGl2)
427                    }
428                };
429            let direct_verified: bool =
430                candidate == RenderBackendCandidate::GpuDirect && verified_gpu;
431            candidates.push(CandidateCapabilities {
432                candidate,
433                supported: true,
434                visual_contract,
435                requires_ui_thread_warmup: true,
436                is_simulated_profile: is_sim,
437                direct_gpu_verified_on_device: direct_verified,
438                graphics_backend,
439            });
440        }
441        let single_channel_only: bool = caps.get_supported_channels().len() <= 1;
442        Self {
443            platform,
444            candidates,
445            single_channel_only,
446            baseline_contract: VisualEquivalenceContract::strict(),
447        }
448    }
449
450    /// Returns `true` when this host exposes at most one eligible rendering channel and MUST NOT probe others.
451    ///
452    /// # Arguments
453    ///
454    /// - `&Self` - Host profile reference.
455    ///
456    /// # Returns
457    ///
458    /// - `bool` - `true` for single-channel hosts.
459    #[must_use]
460    pub fn is_single_channel(&self) -> bool {
461        if self.get_single_channel_only() {
462            return true;
463        }
464        let eligible: usize = self
465            .get_candidates()
466            .iter()
467            .filter(|cap: &&CandidateCapabilities| {
468                cap.passes_gate(&self.get_baseline_contract()).is_ok()
469            })
470            .count();
471        eligible <= 1
472    }
473
474    /// Evaluates whether `candidate` passes this host's capability and visual-equivalence gate.
475    ///
476    /// # Arguments
477    ///
478    /// - `&Self` - Host profile reference.
479    /// - `RenderBackendCandidate` - Candidate to verify.
480    ///
481    /// # Returns
482    ///
483    /// - `Result<(), VisualEquivalenceFailure>` - `Ok(())` if eligible, or exact failure reason.
484    pub fn candidate_passes_gate(
485        &self,
486        candidate: RenderBackendCandidate,
487    ) -> Result<(), VisualEquivalenceFailure> {
488        let baseline: VisualEquivalenceContract = self.get_baseline_contract();
489        let found: Option<&CandidateCapabilities> = self
490            .get_candidates()
491            .iter()
492            .find(|cap: &&CandidateCapabilities| cap.get_candidate() == candidate);
493        match found {
494            Some(cap) => cap.passes_gate(&baseline),
495            None => Err(VisualEquivalenceFailure::BackendUnsupported),
496        }
497    }
498
499    /// Returns the first eligible visually-equivalent candidate matching priority order (`GpuDirect` first, excluding `exclude`).
500    ///
501    /// # Arguments
502    ///
503    /// - `&Self` - Host profile reference.
504    /// - `Option<RenderBackendCandidate>` - Optional candidate to skip (e.g., a failed startup or faulted backend).
505    ///
506    /// # Returns
507    ///
508    /// - `RenderBackendCandidate` - Highest-priority eligible fallback candidate.
509    #[must_use]
510    pub fn best_available_candidate(
511        &self,
512        exclude: Option<RenderBackendCandidate>,
513    ) -> RenderBackendCandidate {
514        let priority: [RenderBackendCandidate; 5] = [
515            RenderBackendCandidate::GpuDirect,
516            RenderBackendCandidate::GpuUpload,
517            RenderBackendCandidate::Software,
518            RenderBackendCandidate::Hybrid,
519            RenderBackendCandidate::Terminal,
520        ];
521        for cand in priority {
522            if Some(cand) == exclude {
523                continue;
524            }
525            if self.candidate_passes_gate(cand).is_ok() {
526                return cand;
527            }
528        }
529        if self.get_platform() == PlatformKind::Terminal {
530            RenderBackendCandidate::Terminal
531        } else {
532            RenderBackendCandidate::Software
533        }
534    }
535
536    /// Resolves the concrete `GraphicsBackend` declared for `candidate` on this host.
537    ///
538    /// # Arguments
539    ///
540    /// - `&Self` - Host profile reference.
541    /// - `RenderBackendCandidate` - Target candidate.
542    ///
543    /// # Returns
544    ///
545    /// - `GraphicsBackend` - Declared graphics backend.
546    #[must_use]
547    pub fn graphics_backend_for(&self, candidate: RenderBackendCandidate) -> GraphicsBackend {
548        if let Some(cap) = self
549            .get_candidates()
550            .iter()
551            .find(|cap: &&CandidateCapabilities| cap.get_candidate() == candidate)
552        {
553            return cap.get_graphics_backend();
554        }
555        match candidate {
556            RenderBackendCandidate::Software => GraphicsBackend::SoftwareCpu,
557            RenderBackendCandidate::Terminal => GraphicsBackend::Headless,
558            RenderBackendCandidate::GpuDirect
559            | RenderBackendCandidate::GpuUpload
560            | RenderBackendCandidate::Hybrid => self.get_platform().default_graphics_backend(),
561        }
562    }
563}
564
565/// Default bounded `WinnerCache`.
566impl Default for WinnerCache {
567    /// Creates an empty `WinnerCache` with `DEFAULT_WINNER_CACHE_CAPACITY`.
568    ///
569    /// # Returns
570    ///
571    /// - `Self` - Empty bounded winner cache.
572    fn default() -> Self {
573        Self::with_capacity(DEFAULT_WINNER_CACHE_CAPACITY)
574    }
575}
576
577/// Lookup, recording, and environment invalidation helpers for `WinnerCache`.
578impl WinnerCache {
579    /// Creates an empty `WinnerCache` retaining up to `max_entries` verified records.
580    ///
581    /// # Arguments
582    ///
583    /// - `usize` - Maximum entry capacity (clamped to `>= 1`).
584    ///
585    /// # Returns
586    ///
587    /// - `Self` - Empty bounded winner cache.
588    #[must_use]
589    pub fn with_capacity(max_entries: usize) -> Self {
590        let cap: usize = max_entries.max(1);
591        Self {
592            entries: HashMap::with_capacity(cap),
593            max_entries: cap,
594        }
595    }
596
597    /// Looks up a previously verified startup winner matching exact `(device_id, driver_version, display_mode_hz, build_id, scene_profile)`.
598    ///
599    /// # Arguments
600    ///
601    /// - `&Self` - Cache reference.
602    /// - `&WinnerCacheKey` - Composite environment and scene key.
603    ///
604    /// # Returns
605    ///
606    /// - `Option<WinnerCacheEntry>` - Cached verified winner if present.
607    #[must_use]
608    pub fn lookup(&self, key: &WinnerCacheKey) -> Option<WinnerCacheEntry> {
609        self.get_entries().get(key).copied()
610    }
611
612    /// Stores a verified winner entry, evicting the oldest record if the cache is full.
613    ///
614    /// # Arguments
615    ///
616    /// - `&Self` - Mutable cache reference.
617    /// - `WinnerCacheKey` - Composite environment and scene key.
618    /// - `WinnerCacheEntry` - Verified winner metrics.
619    pub fn record(&mut self, key: WinnerCacheKey, entry: WinnerCacheEntry) {
620        let limit: usize = self.get_max_entries();
621        if !self.get_entries().contains_key(&key) && self.get_entries().len() >= limit {
622            let oldest_key: Option<WinnerCacheKey> = self
623                .get_entries()
624                .iter()
625                .min_by_key(|(_, val): &(&WinnerCacheKey, &WinnerCacheEntry)| {
626                    val.get_verified_at_ms()
627                })
628                .map(|(k, _): (&WinnerCacheKey, &WinnerCacheEntry)| k.clone());
629            if let Some(evict) = oldest_key {
630                let _: Option<WinnerCacheEntry> = self.get_mut_entries().remove(&evict);
631            }
632        }
633        let _: Option<WinnerCacheEntry> = self.get_mut_entries().insert(key, entry);
634    }
635
636    /// Invalidates every cached entry for `device_id` whose driver version, display mode, or build ID no longer matches.
637    ///
638    /// # Arguments
639    ///
640    /// - `&Self` - Mutable cache reference.
641    /// - `&str` - Active device identifier.
642    /// - `&str` - Current graphics driver version.
643    /// - `u32` - Current display mode in millihertz.
644    /// - `&str` - Current build identifier.
645    ///
646    /// # Returns
647    ///
648    /// - `usize` - Number of invalidated stale entries removed.
649    pub fn invalidate_stale_environment(
650        &mut self,
651        device_id: &str,
652        driver_version: &str,
653        display_mode_hz_millihz: u32,
654        build_id: &str,
655    ) -> usize {
656        let before: usize = self.get_entries().len();
657        self.get_mut_entries()
658            .retain(|k: &WinnerCacheKey, _: &mut WinnerCacheEntry| {
659                if k.get_device_id().as_str() != device_id {
660                    return true;
661                }
662                k.get_driver_version().as_str() == driver_version
663                    && k.get_display_mode_hz_millihz() == display_mode_hz_millihz
664                    && k.get_build_id().as_str() == build_id
665            });
666        before.saturating_sub(self.get_entries().len())
667    }
668
669    /// Returns the number of cached verified winner entries.
670    ///
671    /// # Arguments
672    ///
673    /// - `&Self` - Cache reference.
674    ///
675    /// # Returns
676    ///
677    /// - `usize` - Entry count.
678    #[must_use]
679    pub fn len(&self) -> usize {
680        self.get_entries().len()
681    }
682
683    /// Returns `true` when no verified winners are cached.
684    ///
685    /// # Arguments
686    ///
687    /// - `&Self` - Cache reference.
688    ///
689    /// # Returns
690    ///
691    /// - `bool` - `true` when empty.
692    #[must_use]
693    pub fn is_empty(&self) -> bool {
694        self.get_entries().is_empty()
695    }
696}
697
698/// Default pre-allocated `BoundedTelemetryQueue`.
699impl Default for BoundedTelemetryQueue {
700    /// Creates a pre-allocated ring queue with `DEFAULT_TELEMETRY_QUEUE_CAPACITY` slots.
701    ///
702    /// # Returns
703    ///
704    /// - `Self` - Pre-allocated telemetry queue.
705    fn default() -> Self {
706        Self::with_capacity(DEFAULT_TELEMETRY_QUEUE_CAPACITY)
707    }
708}
709
710/// Zero-allocation hot-path push and low-frequency aggregation helpers for `BoundedTelemetryQueue`.
711impl BoundedTelemetryQueue {
712    /// Pre-allocates a fixed-capacity ring buffer (`>= 1`) so subsequent `push` calls perform zero heap allocation.
713    ///
714    /// # Arguments
715    ///
716    /// - `usize` - Fixed slot capacity.
717    ///
718    /// # Returns
719    ///
720    /// - `Self` - Ready ring queue.
721    #[must_use]
722    pub fn with_capacity(capacity: usize) -> Self {
723        let cap: usize = capacity.max(1);
724        let slots: Vec<TelemetrySample> = vec![TelemetrySample::default(); cap];
725        Self {
726            slots,
727            head: 0,
728            len: 0,
729            capacity: cap,
730            dropped_oldest_count: 0,
731        }
732    }
733
734    /// Pushes `sample` without blocking or heap allocation, overwriting the oldest sample when full.
735    ///
736    /// # Arguments
737    ///
738    /// - `&Self` - Mutable telemetry queue.
739    /// - `TelemetrySample` - Sample capturing reused callback/present timestamps.
740    ///
741    /// # Returns
742    ///
743    /// - `bool` - `true` when stored without dropping; `false` when the oldest sample was evicted.
744    pub fn push(&mut self, sample: TelemetrySample) -> bool {
745        let cap: usize = self.get_capacity();
746        let len: usize = self.get_len();
747        let head: usize = self.get_head();
748        if len < cap {
749            let tail: usize = (head + len) % cap;
750            self.get_mut_slots()[tail] = sample;
751            self.set_len(len + 1);
752            true
753        } else {
754            self.get_mut_slots()[head] = sample;
755            self.set_head((head + 1) % cap);
756            let next_drops: u64 = self.get_dropped_oldest_count().saturating_add(1);
757            self.set_dropped_oldest_count(next_drops);
758            false
759        }
760    }
761
762    /// Drains all currently queued samples in FIFO order into `out` and resets the ring cursor.
763    ///
764    /// # Arguments
765    ///
766    /// - `&Self` - Mutable telemetry queue.
767    /// - `&mut Vec<TelemetrySample>` - Destination vector.
768    ///
769    /// # Returns
770    ///
771    /// - `usize` - Number of samples drained.
772    pub fn drain_into(&mut self, out: &mut Vec<TelemetrySample>) -> usize {
773        let count: usize = self.get_len();
774        let head: usize = self.get_head();
775        let cap: usize = self.get_capacity();
776        for offset in 0..count {
777            let idx: usize = (head + offset) % cap;
778            out.push(self.get_slots()[idx]);
779        }
780        self.set_head(0);
781        self.set_len(0);
782        count
783    }
784
785    /// Aggregates all queued samples in a single low-frequency batch without pixel readback or GPU wait.
786    ///
787    /// # Arguments
788    ///
789    /// - `&Self` - Mutable telemetry queue.
790    ///
791    /// # Returns
792    ///
793    /// - `AggregatedTelemetryWindow` - Aggregated presentation interval and latency percentiles.
794    pub fn aggregate_and_drain(&mut self) -> AggregatedTelemetryWindow {
795        let mut drained: Vec<TelemetrySample> = Vec::with_capacity(self.get_len());
796        let count: usize = self.drain_into(&mut drained);
797        if count == 0 {
798            return AggregatedTelemetryWindow::default();
799        }
800        let mut present_intervals: Vec<f64> = Vec::with_capacity(count);
801        let mut input_latencies: Vec<f64> = Vec::new();
802        let mut presented: u64 = 0;
803        let mut skipped: u64 = 0;
804        let mut failed: u64 = 0;
805        let mut missed: u64 = 0;
806        let mut compositor_hits: u64 = 0;
807        let last_sample: TelemetrySample = drained[count - 1];
808        for sample in drained.iter() {
809            match sample.get_present_outcome() {
810                SurfacePresentOutcome::Submitted => {
811                    presented = presented.saturating_add(1);
812                    if sample.get_missed_deadline() {
813                        missed = missed.saturating_add(1);
814                    }
815                    if sample.get_present_interval_ms() > 0.0 {
816                        present_intervals.push(sample.get_present_interval_ms());
817                    }
818                    if sample.get_present_timing_source() == PresentTimingSource::CompositorMeasured
819                    {
820                        compositor_hits = compositor_hits.saturating_add(1);
821                    }
822                }
823                SurfacePresentOutcome::SkippedUnchanged => {
824                    skipped = skipped.saturating_add(1);
825                }
826                SurfacePresentOutcome::Failed => {
827                    failed = failed.saturating_add(1);
828                }
829            }
830            if sample.get_input_latency_measured() {
831                input_latencies.push(sample.get_input_to_present_ms());
832            }
833        }
834        present_intervals.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
835        input_latencies.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
836        AggregatedTelemetryWindow {
837            sample_count: count as u64,
838            presented_frames: presented,
839            skipped_unchanged_frames: skipped,
840            failed_frames: failed,
841            missed_deadline_frames: missed,
842            present_p50_ms: sorted_percentile_f64(&present_intervals, 0.50),
843            present_p95_ms: sorted_percentile_f64(&present_intervals, 0.95),
844            present_p99_ms: sorted_percentile_f64(&present_intervals, 0.99),
845            input_to_present_p95_ms: sorted_percentile_f64(&input_latencies, 0.95),
846            has_input_latency: !input_latencies.is_empty(),
847            has_compositor_timing: compositor_hits > 0 && compositor_hits == presented,
848            scene_profile: last_sample.get_scene_profile(),
849            display_mode_hz: last_sample.get_display_mode_hz(),
850            candidate: last_sample.get_candidate(),
851        }
852    }
853}
854
855/// Constructors and builders for `CandidateScore`.
856impl CandidateScore {
857    /// Creates a comparable `CandidateScore` for `(candidate, scene_profile, display_mode_hz_millihz)` and latency metrics `(missed_ratio, p95_ms, p99_ms, input_to_present_ms)`.
858    ///
859    /// # Arguments
860    ///
861    /// - `RenderBackendCandidate` - Candidate backend being scored.
862    /// - `SceneProfile` - Active workload scene profile.
863    /// - `u32` - Display refresh mode in millihertz.
864    /// - `(f64, f64, f64, f64)` - Tuple `(missed_frame_ratio, p95_frame_ms, p99_frame_ms, input_to_present_ms)`.
865    /// - `u64` - Number of real presented frames backing this score.
866    ///
867    /// # Returns
868    ///
869    /// - `Self` - Comparable candidate score (`hybrid_net_gain_ms` defaults to `0.0`).
870    #[must_use]
871    pub const fn from_metrics(
872        candidate: RenderBackendCandidate,
873        scene_profile: SceneProfile,
874        display_mode_hz_millihz: u32,
875        latency: (f64, f64, f64, f64),
876        sample_count: u64,
877    ) -> Self {
878        let (missed_frame_ratio, p95_frame_ms, p99_frame_ms, input_to_present_ms): (
879            f64,
880            f64,
881            f64,
882            f64,
883        ) = latency;
884        Self {
885            candidate,
886            scene_profile,
887            display_mode_hz_millihz,
888            missed_frame_ratio,
889            p95_frame_ms,
890            p99_frame_ms,
891            input_to_present_ms,
892            hybrid_net_gain_ms: 0.0,
893            sample_count,
894        }
895    }
896
897    /// Attaches the measured sparse-effect `Hybrid` net gain in milliseconds over pure GPU and pure CPU.
898    ///
899    /// # Arguments
900    ///
901    /// - `Self` - Base candidate score.
902    /// - `f64` - Net gain in milliseconds (`<= 0.0` disqualifies `Hybrid`).
903    ///
904    /// # Returns
905    ///
906    /// - `Self` - Updated candidate score.
907    #[must_use]
908    pub fn with_hybrid_net_gain_ms(mut self, net_gain_ms: f64) -> Self {
909        self.set_hybrid_net_gain_ms(net_gain_ms);
910        self
911    }
912}
913
914/// Default budget-sliced warmup and deferred-release settings for `HandoffBudgetConfig`.
915impl Default for HandoffBudgetConfig {
916    /// Creates the default handoff budget configuration.
917    ///
918    /// # Returns
919    ///
920    /// - `Self` - Default `HandoffBudgetConfig`.
921    fn default() -> Self {
922        Self {
923            warmup_steps_required: DEFAULT_HANDOFF_WARMUP_STEPS,
924            per_frame_budget_ms: DEFAULT_HANDOFF_PER_FRAME_BUDGET_MS,
925            max_warmup_timeout_ms: DEFAULT_HANDOFF_TIMEOUT_MS,
926            post_commit_fence_frames: DEFAULT_POST_COMMIT_FENCE_FRAMES,
927        }
928    }
929}
930
931/// Invariance checks for `RuntimeStateSnapshot`.
932impl RuntimeStateSnapshot {
933    /// Verifies that scroll, gesture, focus, page state, animation timeline, and target refresh rate are completely preserved.
934    ///
935    /// # Arguments
936    ///
937    /// - `&Self` - Pre-switch runtime state snapshot.
938    /// - `&Self` - Post-switch runtime state snapshot.
939    ///
940    /// # Returns
941    ///
942    /// - `bool` - `true` when zero user/animation state was reset and target refresh rate did not drop.
943    #[must_use]
944    pub fn is_preserved_by(&self, after: &Self) -> bool {
945        self.get_scroll_offset_x().to_bits() == after.get_scroll_offset_x().to_bits()
946            && self.get_scroll_offset_y().to_bits() == after.get_scroll_offset_y().to_bits()
947            && self.get_active_gesture_id() == after.get_active_gesture_id()
948            && self.get_focused_node_id() == after.get_focused_node_id()
949            && self.get_page_state_revision() == after.get_page_state_revision()
950            && self.get_animation_timeline_ns() == after.get_animation_timeline_ns()
951            && after.get_target_refresh_hz() >= self.get_target_refresh_hz()
952    }
953}
954
955/// Default idle state for `HandoffCoordinator`.
956impl Default for HandoffCoordinator {
957    /// Creates an idle `HandoffCoordinator`.
958    ///
959    /// # Returns
960    ///
961    /// - `Self` - Idle handoff coordinator.
962    fn default() -> Self {
963        Self {
964            stage: HandoffStage::Idle,
965            old_candidate: RenderBackendCandidate::Software,
966            target_candidate: RenderBackendCandidate::Software,
967            target_width: 0,
968            target_height: 0,
969            target_scale_factor: 1.0,
970            target_scene_version: 0,
971            started_at_ms: 0,
972            warmup_steps_completed: 0,
973            budget_config: HandoffBudgetConfig::default(),
974            old_resources_retained: false,
975            commit_fence_id: 0,
976            completed_fence_id: 0,
977            post_handoff_present_confirmed: false,
978            last_abort_reason: None,
979            seamless_success_count: 0,
980            abort_count: 0,
981            preserved_state: RuntimeStateSnapshot::default(),
982        }
983    }
984}
985
986/// Frame-boundary handoff lifecycle methods for `HandoffCoordinator`.
987impl HandoffCoordinator {
988    /// Returns the most recent abort reason, if any handoff aborted.
989    ///
990    /// # Arguments
991    ///
992    /// - `&Self` - Coordinator reference.
993    ///
994    /// # Returns
995    ///
996    /// - `Option<HandoffAbortReason>` - Last abort reason.
997    #[must_use]
998    pub fn last_abort_reason_value(&self) -> Option<HandoffAbortReason> {
999        let Self {
1000            last_abort_reason, ..
1001        } = *self;
1002        last_abort_reason
1003    }
1004
1005    /// Returns `true` when a handoff is warming up, boundary-ready, or awaiting post-handoff present confirmation.
1006    ///
1007    /// # Arguments
1008    ///
1009    /// - `&Self` - Coordinator reference.
1010    ///
1011    /// # Returns
1012    ///
1013    /// - `bool` - `true` when in flight.
1014    #[must_use]
1015    pub fn is_in_flight(&self) -> bool {
1016        matches!(
1017            self.get_stage(),
1018            HandoffStage::WarmingUp
1019                | HandoffStage::ReadyForBoundary
1020                | HandoffStage::AwaitingPresentConfirmation
1021        )
1022    }
1023
1024    /// Starts warming up `target` on exact `(width, height, scale_factor, scene_version)` while `old` continues presenting uninterrupted.
1025    ///
1026    /// # Arguments
1027    ///
1028    /// - `&Self` - Mutable handoff coordinator.
1029    /// - `RenderBackendCandidate` - Currently presenting backend that remains active during warmup.
1030    /// - `RenderBackendCandidate` - Candidate backend to warm up.
1031    /// - `(u32, u32, f32, u64)` - Tuple `(width, height, scale_factor, scene_version)`.
1032    /// - `u64` - Monotonic start timestamp in milliseconds.
1033    /// - `RuntimeStateSnapshot` - Interactive state snapshot that MUST remain invariant across takeover.
1034    pub fn begin_handoff(
1035        &mut self,
1036        old: RenderBackendCandidate,
1037        target: RenderBackendCandidate,
1038        frame_identity: (u32, u32, f32, u64),
1039        now_ms: u64,
1040        state: RuntimeStateSnapshot,
1041    ) {
1042        let (width, height, scale_factor, scene_version): (u32, u32, f32, u64) = frame_identity;
1043        self.set_stage(HandoffStage::WarmingUp);
1044        self.set_old_candidate(old);
1045        self.set_target_candidate(target);
1046        self.set_target_width(width);
1047        self.set_target_height(height);
1048        self.set_target_scale_factor(scale_factor);
1049        self.set_target_scene_version(scene_version);
1050        self.set_started_at_ms(now_ms);
1051        self.set_warmup_steps_completed(0);
1052        self.set_old_resources_retained(true);
1053        self.set_commit_fence_id(0);
1054        self.set_completed_fence_id(0);
1055        self.set_post_handoff_present_confirmed(false);
1056        self.set_last_abort_reason(None);
1057        self.set_preserved_state(state);
1058    }
1059
1060    /// Executes one budget-sliced UI/render-thread warmup step, aborting cleanly if warmup times out or init fails.
1061    ///
1062    /// # Arguments
1063    ///
1064    /// - `&Self` - Mutable handoff coordinator.
1065    /// - `f64` - Elapsed work slice duration in milliseconds for this frame.
1066    /// - `bool` - `true` if this warmup step succeeded without error.
1067    /// - `u64` - Current monotonic timestamp in milliseconds.
1068    ///
1069    /// # Returns
1070    ///
1071    /// - `Result<HandoffStage, HandoffAbortReason>` - Updated handoff stage or clean abort reason.
1072    pub fn step_warmup(
1073        &mut self,
1074        step_elapsed_ms: f64,
1075        step_ok: bool,
1076        now_ms: u64,
1077    ) -> Result<HandoffStage, HandoffAbortReason> {
1078        if self.get_stage() != HandoffStage::WarmingUp {
1079            return Ok(self.get_stage());
1080        }
1081        let budget: HandoffBudgetConfig = self.get_budget_config();
1082        let elapsed_total_ms: u64 = now_ms.saturating_sub(self.get_started_at_ms());
1083        if elapsed_total_ms > budget.get_max_warmup_timeout_ms() {
1084            self.abort_internal(HandoffAbortReason::TimedOut);
1085            return Err(HandoffAbortReason::TimedOut);
1086        }
1087        if !step_ok {
1088            self.abort_internal(HandoffAbortReason::InitFailed);
1089            return Err(HandoffAbortReason::InitFailed);
1090        }
1091        if step_elapsed_ms <= budget.get_per_frame_budget_ms()
1092            || self.get_warmup_steps_completed() == 0
1093        {
1094            let next_steps: u32 = self.get_warmup_steps_completed().saturating_add(1);
1095            self.set_warmup_steps_completed(next_steps);
1096        }
1097        if self.get_warmup_steps_completed() >= budget.get_warmup_steps_required().max(1) {
1098            self.set_stage(HandoffStage::ReadyForBoundary);
1099        }
1100        Ok(self.get_stage())
1101    }
1102
1103    /// Attempts atomic takeover at a frame boundary ONLY when candidate first frame matches `(width, height, scale_factor, scene_version)` and meets deadline.
1104    ///
1105    /// # Arguments
1106    ///
1107    /// - `&Self` - Mutable handoff coordinator.
1108    /// - `HandoffFrameDescriptor` - Candidate's verified first frame descriptor.
1109    /// - `(u32, u32, f32, u64)` - Current live `(width, height, scale_factor, scene_version)` at the frame boundary.
1110    /// - `u64` - Sync fence ID associated with the takeover frame.
1111    /// - `u64` - Current monotonic timestamp in milliseconds.
1112    ///
1113    /// # Returns
1114    ///
1115    /// - `Result<RenderBackendCandidate, HandoffAbortReason>` - New active candidate on boundary commit, or abort reason keeping old backend active.
1116    pub fn try_commit_at_frame_boundary(
1117        &mut self,
1118        first_frame: HandoffFrameDescriptor,
1119        current_frame: (u32, u32, f32, u64),
1120        commit_fence_id: u64,
1121        now_ms: u64,
1122    ) -> Result<RenderBackendCandidate, HandoffAbortReason> {
1123        let (cur_w, cur_h, cur_scale, cur_scene_ver): (u32, u32, f32, u64) = current_frame;
1124        let budget: HandoffBudgetConfig = self.get_budget_config();
1125        if now_ms.saturating_sub(self.get_started_at_ms()) > budget.get_max_warmup_timeout_ms() {
1126            self.abort_internal(HandoffAbortReason::TimedOut);
1127            return Err(HandoffAbortReason::TimedOut);
1128        }
1129        if !first_frame.get_first_frame_ok() {
1130            self.abort_internal(HandoffAbortReason::FirstFrameFailed);
1131            return Err(HandoffAbortReason::FirstFrameFailed);
1132        }
1133        if first_frame.get_width() != cur_w
1134            || first_frame.get_height() != cur_h
1135            || first_frame.get_width() != self.get_target_width()
1136            || first_frame.get_height() != self.get_target_height()
1137        {
1138            self.abort_internal(HandoffAbortReason::DimensionMismatch);
1139            return Err(HandoffAbortReason::DimensionMismatch);
1140        }
1141        if (first_frame.get_scale_factor() - cur_scale).abs() > 0.001
1142            || (first_frame.get_scale_factor() - self.get_target_scale_factor()).abs() > 0.001
1143        {
1144            self.abort_internal(HandoffAbortReason::ScaleFactorMismatch);
1145            return Err(HandoffAbortReason::ScaleFactorMismatch);
1146        }
1147        if first_frame.get_scene_version() != cur_scene_ver
1148            || first_frame.get_scene_version() != self.get_target_scene_version()
1149        {
1150            self.abort_internal(HandoffAbortReason::StaleSceneVersion);
1151            return Err(HandoffAbortReason::StaleSceneVersion);
1152        }
1153        if first_frame.get_frame_time_ms() > first_frame.get_deadline_ms() {
1154            self.abort_internal(HandoffAbortReason::MissedDeadline);
1155            return Err(HandoffAbortReason::MissedDeadline);
1156        }
1157        self.set_stage(HandoffStage::AwaitingPresentConfirmation);
1158        self.set_commit_fence_id(commit_fence_id.max(1));
1159        self.set_old_resources_retained(true);
1160        self.set_post_handoff_present_confirmed(false);
1161        Ok(self.get_target_candidate())
1162    }
1163
1164    /// Confirms post-handoff presentation and sync fence completion, releasing old backend resources ONLY once both succeed.
1165    ///
1166    /// # Arguments
1167    ///
1168    /// - `&Self` - Mutable handoff coordinator.
1169    /// - `bool` - `true` when the post-handoff frame was confirmed presented on the new backend.
1170    /// - `u64` - Highest completed GPU/surface sync fence identifier.
1171    ///
1172    /// # Returns
1173    ///
1174    /// - `bool` - `true` when old backend resources are now safe to release and the handoff is finalized as a seamless success.
1175    pub fn confirm_post_handoff_present(
1176        &mut self,
1177        present_confirmed: bool,
1178        completed_fence_id: u64,
1179    ) -> bool {
1180        if self.get_stage() != HandoffStage::AwaitingPresentConfirmation {
1181            return false;
1182        }
1183        if present_confirmed {
1184            self.set_post_handoff_present_confirmed(true);
1185        }
1186        let latest_fence: u64 = self.get_completed_fence_id().max(completed_fence_id);
1187        self.set_completed_fence_id(latest_fence);
1188        if self.get_post_handoff_present_confirmed() && latest_fence >= self.get_commit_fence_id() {
1189            self.set_old_resources_retained(false);
1190            self.set_stage(HandoffStage::Committed);
1191            let next_ok: u64 = self.get_seamless_success_count().saturating_add(1);
1192            self.set_seamless_success_count(next_ok);
1193            true
1194        } else {
1195            false
1196        }
1197    }
1198
1199    /// Aborts any in-flight handoff because of an external fault without crediting `seamless_success_count`.
1200    ///
1201    /// # Arguments
1202    ///
1203    /// - `&Self` - Mutable handoff coordinator.
1204    pub fn abort_for_fault(&mut self) {
1205        if self.is_in_flight() {
1206            self.abort_internal(HandoffAbortReason::FaultInterrupted);
1207        }
1208    }
1209
1210    /// Marks the handoff aborted while preserving the old backend and incrementing `abort_count`.
1211    ///
1212    /// # Arguments
1213    ///
1214    /// - `&Self` - Mutable handoff coordinator.
1215    /// - `HandoffAbortReason` - Structured abort cause.
1216    fn abort_internal(&mut self, reason: HandoffAbortReason) {
1217        self.set_stage(HandoffStage::Aborted);
1218        self.set_last_abort_reason(Some(reason));
1219        self.set_old_resources_retained(true);
1220        let next_aborts: u64 = self.get_abort_count().saturating_add(1);
1221        self.set_abort_count(next_aborts);
1222    }
1223}
1224
1225/// Default shadow-first adaptive router policy (`RecommendOnly`).
1226impl Default for AdaptiveRouterConfig {
1227    /// Creates the conservative default `AdaptiveRouterConfig` starting in `RecommendOnly` shadow mode.
1228    ///
1229    /// # Returns
1230    ///
1231    /// - `Self` - Default router config.
1232    fn default() -> Self {
1233        Self {
1234            switch_mode: AdaptiveSwitchMode::RecommendOnly,
1235            sustained_miss_threshold: DEFAULT_SUSTAINED_MISS_THRESHOLD,
1236            input_latency_degrade_ratio: DEFAULT_INPUT_LATENCY_DEGRADE_RATIO,
1237            consecutive_wins_required: DEFAULT_CONSECUTIVE_WINS_REQUIRED,
1238            switch_cost_ms: DEFAULT_SWITCH_COST_MS,
1239            min_dwell_ms: DEFAULT_MIN_DWELL_MS,
1240            cooldown_ms: DEFAULT_COOLDOWN_MS,
1241            probe_min_headroom_ratio: DEFAULT_PROBE_MIN_HEADROOM_RATIO,
1242            telemetry_queue_capacity: DEFAULT_TELEMETRY_QUEUE_CAPACITY,
1243        }
1244    }
1245}
1246
1247/// Fault-tag inspection helper for `AdaptiveDecision`.
1248impl AdaptiveDecision {
1249    /// Returns the optional explicit fault classification attached to this decision.
1250    ///
1251    /// # Arguments
1252    ///
1253    /// - `&Self` - Decision reference.
1254    ///
1255    /// # Returns
1256    ///
1257    /// - `Option<FaultEventKind>` - Fault tag when this decision originated from a fault.
1258    #[must_use]
1259    pub fn fault_tag_value(&self) -> Option<FaultEventKind> {
1260        let Self { fault_tag, .. } = *self;
1261        fault_tag
1262    }
1263}
1264
1265/// Default adaptive router initialized for a headless software host in shadow `RecommendOnly` mode.
1266impl Default for AdaptiveRenderRouter {
1267    /// Creates a default headless `AdaptiveRenderRouter`.
1268    ///
1269    /// # Returns
1270    ///
1271    /// - `Self` - Default adaptive render router.
1272    fn default() -> Self {
1273        Self::new(
1274            AdaptiveRouterConfig::default(),
1275            HostCapabilityProfile::default(),
1276            60.0,
1277        )
1278    }
1279}
1280
1281/// Unified 5-stage routing, probing, selection, handoff, and fault handling implementation for `AdaptiveRenderRouter`.
1282impl AdaptiveRenderRouter {
1283    /// Creates a new 5-stage `AdaptiveRenderRouter` bound to `config`, `host_profile`, and `display_mode_hz`.
1284    ///
1285    /// # Arguments
1286    ///
1287    /// - `AdaptiveRouterConfig` - Policy thresholds and rollout switch mode.
1288    /// - `HostCapabilityProfile` - Host channel capabilities and visual-equivalence baseline.
1289    /// - `f64` - Initial display mode refresh rate in Hertz.
1290    ///
1291    /// # Returns
1292    ///
1293    /// - `Self` - Initialized adaptive render router.
1294    #[must_use]
1295    pub fn new(
1296        config: AdaptiveRouterConfig,
1297        host_profile: HostCapabilityProfile,
1298        display_mode_hz: f64,
1299    ) -> Self {
1300        let initial_candidate: RenderBackendCandidate = host_profile.best_available_candidate(None);
1301        let queue_cap: usize = config.get_telemetry_queue_capacity();
1302        Self {
1303            config,
1304            host_profile,
1305            winner_cache: WinnerCache::default(),
1306            telemetry_queue: BoundedTelemetryQueue::with_capacity(queue_cap),
1307            handoff: HandoffCoordinator::default(),
1308            active_candidate: initial_candidate,
1309            recommended_candidate: initial_candidate,
1310            active_scene_profile: SceneProfile::StaticUi,
1311            display_mode_hz: if display_mode_hz.is_finite() && display_mode_hz > 0.0 {
1312                display_mode_hz
1313            } else {
1314                60.0
1315            },
1316            device_id: DEFAULT_DEVICE_ID.to_string(),
1317            driver_version: DEFAULT_DRIVER_VERSION.to_string(),
1318            build_id: DEFAULT_BUILD_ID.to_string(),
1319            last_switch_ms: 0,
1320            has_switched_once: false,
1321            cooldown_until_ms: 0,
1322            sustained_miss_streak: 0,
1323            input_latency_degraded: false,
1324            streak_candidate: None,
1325            streak_wins: 0,
1326            last_valid_frame_retained: false,
1327            fault_failover_count: 0,
1328            tagged_fault_events: Vec::new(),
1329            probe_runs: 0,
1330            probe_skips_no_headroom: 0,
1331            cache_hits: 0,
1332            recommendations_logged: 0,
1333            last_decision_reason: REASON_KEEP_CURRENT,
1334        }
1335    }
1336
1337    /// Updates environment identity `(device_id, driver_version, display_mode_hz, build_id)` and invalidates stale cached winners.
1338    ///
1339    /// # Arguments
1340    ///
1341    /// - `&Self` - Mutable router reference.
1342    /// - `&str` - Device identifier.
1343    /// - `&str` - Graphics driver version.
1344    /// - `f64` - Display mode refresh rate in Hertz.
1345    /// - `&str` - Build identifier.
1346    ///
1347    /// # Returns
1348    ///
1349    /// - `usize` - Number of stale winner cache entries invalidated.
1350    pub fn update_environment(
1351        &mut self,
1352        device_id: &str,
1353        driver_version: &str,
1354        display_mode_hz: f64,
1355        build_id: &str,
1356    ) -> usize {
1357        self.set_device_id(device_id.to_string());
1358        self.set_driver_version(driver_version.to_string());
1359        if display_mode_hz.is_finite() && display_mode_hz > 0.0 {
1360            self.set_display_mode_hz(display_mode_hz);
1361        }
1362        self.set_build_id(build_id.to_string());
1363        let millihz: u32 = hz_to_millihz(self.get_display_mode_hz());
1364        self.get_mut_winner_cache().invalidate_stale_environment(
1365            device_id,
1366            driver_version,
1367            millihz,
1368            build_id,
1369        )
1370    }
1371
1372    /// Builds the current `WinnerCacheKey` for `scene_profile` using active device, driver, display mode, and build identity.
1373    ///
1374    /// # Arguments
1375    ///
1376    /// - `&Self` - Router reference.
1377    /// - `SceneProfile` - Target scene profile.
1378    ///
1379    /// # Returns
1380    ///
1381    /// - `WinnerCacheKey` - Exact composite cache key.
1382    #[must_use]
1383    pub fn cache_key_for(&self, scene_profile: SceneProfile) -> WinnerCacheKey {
1384        WinnerCacheKey::new(
1385            self.get_device_id().clone(),
1386            self.get_driver_version().clone(),
1387            hz_to_millihz(self.get_display_mode_hz()),
1388            self.get_build_id().clone(),
1389            scene_profile,
1390        )
1391    }
1392
1393    /// Stage 1 (Startup): selects a verified cached winner if valid, otherwise tries visually-equivalent `GpuDirect` first (locking single-channel hosts).
1394    ///
1395    /// # Arguments
1396    ///
1397    /// - `&Self` - Mutable router reference.
1398    /// - `SceneProfile` - Initial scene workload profile.
1399    ///
1400    /// # Returns
1401    ///
1402    /// - `AdaptiveDecision` - Startup backend selection decision.
1403    pub fn select_startup_candidate(&mut self, scene_profile: SceneProfile) -> AdaptiveDecision {
1404        self.set_active_scene_profile(scene_profile);
1405        if self.get_host_profile().is_single_channel() {
1406            let sole: RenderBackendCandidate =
1407                self.get_host_profile().best_available_candidate(None);
1408            self.set_active_candidate(sole);
1409            self.set_recommended_candidate(sole);
1410            self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
1411            return AdaptiveDecision {
1412                kind: AdaptiveDecisionKind::LockedSingleChannel,
1413                active_candidate: sole,
1414                recommended_candidate: sole,
1415                applied: true,
1416                reason: REASON_SINGLE_CHANNEL_LOCKED,
1417                preserve_last_valid_frame: false,
1418                fault_tag: None,
1419            };
1420        }
1421        let key: WinnerCacheKey = self.cache_key_for(scene_profile);
1422        if let Some(entry) = self.get_winner_cache().lookup(&key)
1423            && self
1424                .get_host_profile()
1425                .candidate_passes_gate(entry.get_winner())
1426                .is_ok()
1427        {
1428            let winner: RenderBackendCandidate = entry.get_winner();
1429            let next_hits: u64 = self.get_cache_hits().saturating_add(1);
1430            self.set_cache_hits(next_hits);
1431            self.set_active_candidate(winner);
1432            self.set_recommended_candidate(winner);
1433            self.set_last_decision_reason(REASON_CACHE_HIT_VERIFIED);
1434            return AdaptiveDecision {
1435                kind: AdaptiveDecisionKind::UseCachedWinner,
1436                active_candidate: winner,
1437                recommended_candidate: winner,
1438                applied: true,
1439                reason: REASON_CACHE_HIT_VERIFIED,
1440                preserve_last_valid_frame: false,
1441                fault_tag: None,
1442            };
1443        }
1444        if self
1445            .get_host_profile()
1446            .candidate_passes_gate(RenderBackendCandidate::GpuDirect)
1447            .is_ok()
1448        {
1449            self.set_active_candidate(RenderBackendCandidate::GpuDirect);
1450            self.set_recommended_candidate(RenderBackendCandidate::GpuDirect);
1451            self.set_last_decision_reason(REASON_STARTUP_GPU_DIRECT);
1452            return AdaptiveDecision {
1453                kind: AdaptiveDecisionKind::StartupGpuDirect,
1454                active_candidate: RenderBackendCandidate::GpuDirect,
1455                recommended_candidate: RenderBackendCandidate::GpuDirect,
1456                applied: true,
1457                reason: REASON_STARTUP_GPU_DIRECT,
1458                preserve_last_valid_frame: false,
1459                fault_tag: None,
1460            };
1461        }
1462        let fallback: RenderBackendCandidate =
1463            self.get_host_profile().best_available_candidate(None);
1464        self.set_active_candidate(fallback);
1465        self.set_recommended_candidate(fallback);
1466        self.set_last_decision_reason(REASON_STARTUP_FALLBACK_READY);
1467        AdaptiveDecision {
1468            kind: AdaptiveDecisionKind::KeepCurrent,
1469            active_candidate: fallback,
1470            recommended_candidate: fallback,
1471            applied: true,
1472            reason: REASON_STARTUP_FALLBACK_READY,
1473            preserve_last_valid_frame: false,
1474            fault_tag: None,
1475        }
1476    }
1477
1478    /// Stage 1 (Startup failover): immediately switches from a failed startup candidate to a known-working visually-equivalent path.
1479    ///
1480    /// # Arguments
1481    ///
1482    /// - `&Self` - Mutable router reference.
1483    /// - `RenderBackendCandidate` - Candidate that failed initialization or first-frame submission.
1484    /// - `u64` - Current monotonic timestamp in milliseconds.
1485    ///
1486    /// # Returns
1487    ///
1488    /// - `AdaptiveDecision` - Immediate failover decision.
1489    pub fn on_startup_candidate_failed(
1490        &mut self,
1491        failed: RenderBackendCandidate,
1492        now_ms: u64,
1493    ) -> AdaptiveDecision {
1494        let next: RenderBackendCandidate = self
1495            .get_host_profile()
1496            .best_available_candidate(Some(failed));
1497        self.set_active_candidate(next);
1498        self.set_recommended_candidate(next);
1499        self.set_last_switch_ms(now_ms);
1500        self.set_has_switched_once(true);
1501        let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
1502        self.set_cooldown_until_ms(cooldown_end);
1503        self.set_last_decision_reason(REASON_STARTUP_FAILOVER);
1504        AdaptiveDecision {
1505            kind: AdaptiveDecisionKind::StartupFailover,
1506            active_candidate: next,
1507            recommended_candidate: next,
1508            applied: true,
1509            reason: REASON_STARTUP_FAILOVER,
1510            preserve_last_valid_frame: false,
1511            fault_tag: None,
1512        }
1513    }
1514
1515    /// Stage 2 (Runtime): records a zero-allocation hot-path telemetry sample into `BoundedTelemetryQueue` and updates degradation triggers.
1516    ///
1517    /// # Arguments
1518    ///
1519    /// - `&Self` - Mutable router reference.
1520    /// - `TelemetrySample` - Frame sample reusing existing callback/present timestamps.
1521    ///
1522    /// # Returns
1523    ///
1524    /// - `bool` - `true` when enqueued without overwriting an unread sample; `false` when drop-oldest triggered.
1525    pub fn record_runtime_sample(&mut self, sample: TelemetrySample) -> bool {
1526        let target_ms: f64 =
1527            AdaptiveFrameMetrics::target_frame_interval_ms_for_hz(sample.get_display_mode_hz());
1528        if sample.get_present_outcome() == SurfacePresentOutcome::Submitted {
1529            if sample.get_missed_deadline() {
1530                let next_streak: u32 = self.get_sustained_miss_streak().saturating_add(1);
1531                self.set_sustained_miss_streak(next_streak);
1532            } else {
1533                self.set_sustained_miss_streak(0);
1534            }
1535        }
1536        if sample.get_input_latency_measured() {
1537            let degrade_limit: f64 =
1538                target_ms * self.get_config().get_input_latency_degrade_ratio();
1539            self.set_input_latency_degraded(sample.get_input_to_present_ms() > degrade_limit);
1540        }
1541        self.get_mut_telemetry_queue().push(sample)
1542    }
1543
1544    /// Returns `true` ONLY when the runtime is idle OR explicit frame headroom exceeds the configured threshold.
1545    ///
1546    /// # Arguments
1547    ///
1548    /// - `&Self` - Router reference.
1549    /// - `bool` - `true` when the app is currently idle.
1550    /// - `f64` - Recent active frame duration in milliseconds.
1551    /// - `f64` - Target frame interval in milliseconds.
1552    ///
1553    /// # Returns
1554    ///
1555    /// - `bool` - `true` when probing has sufficient headroom.
1556    #[must_use]
1557    pub fn has_probe_headroom(
1558        &self,
1559        is_idle: bool,
1560        recent_frame_ms: f64,
1561        target_interval_ms: f64,
1562    ) -> bool {
1563        if is_idle {
1564            return true;
1565        }
1566        if !target_interval_ms.is_finite() || target_interval_ms <= 0.0 {
1567            return false;
1568        }
1569        let remaining_ms: f64 = target_interval_ms - recent_frame_ms.max(0.0);
1570        let required_ms: f64 = target_interval_ms
1571            * self
1572                .get_config()
1573                .get_probe_min_headroom_ratio()
1574                .clamp(0.0, 1.0);
1575        remaining_ms >= required_ms
1576    }
1577
1578    /// Stage 2 (Runtime): gates short candidate probing strictly on sustained degradation AND idle/explicit headroom (never probing single-channel hosts).
1579    ///
1580    /// # Arguments
1581    ///
1582    /// - `&Self` - Mutable router reference.
1583    /// - `bool` - `true` when the UI/render loop is currently idle.
1584    /// - `f64` - Recent active frame time in milliseconds.
1585    /// - `f64` - Target frame interval in milliseconds.
1586    /// - `u64` - Current monotonic timestamp in milliseconds.
1587    ///
1588    /// # Returns
1589    ///
1590    /// - `Result<ProbeTriggerReason, &'static str>` - `Ok(reason)` when a short probe is authorized, or static suppression reason.
1591    pub fn should_trigger_probe(
1592        &mut self,
1593        is_idle: bool,
1594        recent_frame_ms: f64,
1595        target_interval_ms: f64,
1596        now_ms: u64,
1597    ) -> Result<ProbeTriggerReason, &'static str> {
1598        if self.get_host_profile().is_single_channel() {
1599            self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
1600            return Err(REASON_SINGLE_CHANNEL_LOCKED);
1601        }
1602        if now_ms < self.get_cooldown_until_ms() {
1603            self.set_last_decision_reason(REASON_PROBE_COOLDOWN);
1604            return Err(REASON_PROBE_COOLDOWN);
1605        }
1606        if self.get_handoff().is_in_flight() {
1607            self.set_last_decision_reason(REASON_PROBE_HANDOFF_ACTIVE);
1608            return Err(REASON_PROBE_HANDOFF_ACTIVE);
1609        }
1610        let trigger: Option<ProbeTriggerReason> = if self.get_sustained_miss_streak()
1611            >= self.get_config().get_sustained_miss_threshold()
1612        {
1613            Some(ProbeTriggerReason::SustainedDeadlineMiss)
1614        } else if self.get_input_latency_degraded() {
1615            Some(ProbeTriggerReason::InputLatencyDegraded)
1616        } else {
1617            None
1618        };
1619        let Some(reason) = trigger else {
1620            self.set_last_decision_reason(REASON_PROBE_NO_TRIGGER);
1621            return Err(REASON_PROBE_NO_TRIGGER);
1622        };
1623        if !self.has_probe_headroom(is_idle, recent_frame_ms, target_interval_ms) {
1624            let next_skips: u64 = self.get_probe_skips_no_headroom().saturating_add(1);
1625            self.set_probe_skips_no_headroom(next_skips);
1626            self.set_last_decision_reason(REASON_PROBE_NO_HEADROOM);
1627            return Err(REASON_PROBE_NO_HEADROOM);
1628        }
1629        let next_probes: u64 = self.get_probe_runs().saturating_add(1);
1630        self.set_probe_runs(next_probes);
1631        self.set_last_decision_reason(REASON_PROBE_STARTED);
1632        Ok(reason)
1633    }
1634
1635    /// Stage 3 (Selection): compares `current` and `candidate` under identical scene profile and refresh rate after quality, capability, and Hybrid net-gain gates.
1636    ///
1637    /// # Arguments
1638    ///
1639    /// - `&Self` - Mutable router reference.
1640    /// - `CandidateScore` - Measured score of the currently active backend.
1641    /// - `CandidateScore` - Measured score of the probed candidate backend.
1642    /// - `u64` - Current monotonic timestamp in milliseconds.
1643    ///
1644    /// # Returns
1645    ///
1646    /// - `AdaptiveDecision` - Selection outcome respecting `RecommendOnly` vs `AutoSwitch`, consecutive wins, dwell time, and cooldown.
1647    pub fn evaluate_candidates(
1648        &mut self,
1649        current: CandidateScore,
1650        candidate: CandidateScore,
1651        now_ms: u64,
1652    ) -> AdaptiveDecision {
1653        let active: RenderBackendCandidate = self.get_active_candidate();
1654        if self.get_host_profile().is_single_channel() {
1655            self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
1656            return AdaptiveDecision {
1657                kind: AdaptiveDecisionKind::LockedSingleChannel,
1658                active_candidate: active,
1659                recommended_candidate: active,
1660                applied: false,
1661                reason: REASON_SINGLE_CHANNEL_LOCKED,
1662                preserve_last_valid_frame: false,
1663                fault_tag: None,
1664            };
1665        }
1666        if candidate.get_candidate() == active {
1667            self.set_streak_candidate(None);
1668            self.set_streak_wins(0);
1669            self.set_last_decision_reason(REASON_KEEP_CURRENT);
1670            return AdaptiveDecision {
1671                kind: AdaptiveDecisionKind::KeepCurrent,
1672                active_candidate: active,
1673                recommended_candidate: active,
1674                applied: false,
1675                reason: REASON_KEEP_CURRENT,
1676                preserve_last_valid_frame: false,
1677                fault_tag: None,
1678            };
1679        }
1680        if self
1681            .get_host_profile()
1682            .candidate_passes_gate(candidate.get_candidate())
1683            .is_err()
1684        {
1685            self.set_streak_candidate(None);
1686            self.set_streak_wins(0);
1687            self.set_last_decision_reason(REASON_VISUAL_GATE_FAILED);
1688            return AdaptiveDecision {
1689                kind: AdaptiveDecisionKind::KeepCurrent,
1690                active_candidate: active,
1691                recommended_candidate: active,
1692                applied: false,
1693                reason: REASON_VISUAL_GATE_FAILED,
1694                preserve_last_valid_frame: false,
1695                fault_tag: None,
1696            };
1697        }
1698        if current.get_scene_profile() != candidate.get_scene_profile()
1699            || current.get_display_mode_hz_millihz() != candidate.get_display_mode_hz_millihz()
1700        {
1701            self.set_last_decision_reason(REASON_CONTEXT_MISMATCH);
1702            return AdaptiveDecision {
1703                kind: AdaptiveDecisionKind::KeepCurrent,
1704                active_candidate: active,
1705                recommended_candidate: active,
1706                applied: false,
1707                reason: REASON_CONTEXT_MISMATCH,
1708                preserve_last_valid_frame: false,
1709                fault_tag: None,
1710            };
1711        }
1712        if candidate.get_candidate() == RenderBackendCandidate::Hybrid
1713            && candidate.get_hybrid_net_gain_ms() <= 0.0
1714        {
1715            self.set_streak_candidate(None);
1716            self.set_streak_wins(0);
1717            self.set_last_decision_reason(REASON_HYBRID_NO_NET_GAIN);
1718            return AdaptiveDecision {
1719                kind: AdaptiveDecisionKind::KeepCurrent,
1720                active_candidate: active,
1721                recommended_candidate: active,
1722                applied: false,
1723                reason: REASON_HYBRID_NO_NET_GAIN,
1724                preserve_last_valid_frame: false,
1725                fault_tag: None,
1726            };
1727        }
1728        let current_cost: f64 = compute_candidate_composite_cost_ms(&current);
1729        let candidate_cost: f64 = compute_candidate_composite_cost_ms(&candidate);
1730        let gain_ms: f64 = current_cost - candidate_cost;
1731        let is_tie: bool = gain_ms.abs() <= SCORE_TIE_EPSILON_MS;
1732        let prefer_gpu_on_tie: bool = is_tie
1733            && candidate.get_candidate() == RenderBackendCandidate::GpuDirect
1734            && active != RenderBackendCandidate::GpuDirect;
1735        let gpu_wins_tie_stay: bool = is_tie && active == RenderBackendCandidate::GpuDirect;
1736        if gpu_wins_tie_stay {
1737            self.set_streak_candidate(None);
1738            self.set_streak_wins(0);
1739            self.set_last_decision_reason(REASON_TIE_PREFER_GPU_DIRECT);
1740            return AdaptiveDecision {
1741                kind: AdaptiveDecisionKind::KeepCurrent,
1742                active_candidate: active,
1743                recommended_candidate: active,
1744                applied: false,
1745                reason: REASON_TIE_PREFER_GPU_DIRECT,
1746                preserve_last_valid_frame: false,
1747                fault_tag: None,
1748            };
1749        }
1750        let cfg: AdaptiveRouterConfig = self.get_config();
1751        let beats_switch_cost: bool = prefer_gpu_on_tie || gain_ms > cfg.get_switch_cost_ms();
1752        if !beats_switch_cost {
1753            self.set_streak_candidate(None);
1754            self.set_streak_wins(0);
1755            self.set_last_decision_reason(REASON_BELOW_SWITCH_COST);
1756            return AdaptiveDecision {
1757                kind: AdaptiveDecisionKind::KeepCurrent,
1758                active_candidate: active,
1759                recommended_candidate: active,
1760                applied: false,
1761                reason: REASON_BELOW_SWITCH_COST,
1762                preserve_last_valid_frame: false,
1763                fault_tag: None,
1764            };
1765        }
1766        let prev_cand: Option<RenderBackendCandidate> = self.streak_candidate_value();
1767        let next_wins: u32 = if prev_cand == Some(candidate.get_candidate()) {
1768            self.get_streak_wins().saturating_add(1)
1769        } else {
1770            1
1771        };
1772        self.set_streak_candidate(Some(candidate.get_candidate()));
1773        self.set_streak_wins(next_wins);
1774        if next_wins < cfg.get_consecutive_wins_required().max(1) {
1775            self.set_last_decision_reason(REASON_AWAITING_CONSECUTIVE_WINS);
1776            return AdaptiveDecision {
1777                kind: AdaptiveDecisionKind::KeepCurrent,
1778                active_candidate: active,
1779                recommended_candidate: active,
1780                applied: false,
1781                reason: REASON_AWAITING_CONSECUTIVE_WINS,
1782                preserve_last_valid_frame: false,
1783                fault_tag: None,
1784            };
1785        }
1786        let dwell_blocked: bool = self.get_has_switched_once()
1787            && now_ms.saturating_sub(self.get_last_switch_ms()) < cfg.get_min_dwell_ms();
1788        let cooldown_blocked: bool = now_ms < self.get_cooldown_until_ms();
1789        if dwell_blocked || cooldown_blocked {
1790            self.set_last_decision_reason(REASON_DWELL_OR_COOLDOWN_ACTIVE);
1791            return AdaptiveDecision {
1792                kind: AdaptiveDecisionKind::KeepCurrent,
1793                active_candidate: active,
1794                recommended_candidate: candidate.get_candidate(),
1795                applied: false,
1796                reason: REASON_DWELL_OR_COOLDOWN_ACTIVE,
1797                preserve_last_valid_frame: false,
1798                fault_tag: None,
1799            };
1800        }
1801        self.set_recommended_candidate(candidate.get_candidate());
1802        match cfg.get_switch_mode() {
1803            AdaptiveSwitchMode::RecommendOnly => {
1804                let next_recs: u64 = self.get_recommendations_logged().saturating_add(1);
1805                self.set_recommendations_logged(next_recs);
1806                self.set_last_decision_reason(REASON_RECOMMEND_ONLY_SHADOW);
1807                AdaptiveDecision {
1808                    kind: AdaptiveDecisionKind::RecommendSwitch,
1809                    active_candidate: active,
1810                    recommended_candidate: candidate.get_candidate(),
1811                    applied: false,
1812                    reason: REASON_RECOMMEND_ONLY_SHADOW,
1813                    preserve_last_valid_frame: false,
1814                    fault_tag: None,
1815                }
1816            }
1817            AdaptiveSwitchMode::AutoSwitch => {
1818                self.set_last_decision_reason(REASON_AUTO_SWITCH_HANDOFF);
1819                AdaptiveDecision {
1820                    kind: AdaptiveDecisionKind::BeginHandoff,
1821                    active_candidate: active,
1822                    recommended_candidate: candidate.get_candidate(),
1823                    applied: true,
1824                    reason: REASON_AUTO_SWITCH_HANDOFF,
1825                    preserve_last_valid_frame: false,
1826                    fault_tag: None,
1827                }
1828            }
1829        }
1830    }
1831
1832    /// Stage 4 (Handoff): initiates budget-sliced candidate warmup while keeping the current backend presenting uninterrupted.
1833    ///
1834    /// # Arguments
1835    ///
1836    /// - `&Self` - Mutable router reference.
1837    /// - `RenderBackendCandidate` - Candidate backend to warm up.
1838    /// - `(u32, u32, f32, u64)` - Tuple `(width, height, scale_factor, scene_version)`.
1839    /// - `u64` - Monotonic start timestamp in milliseconds.
1840    /// - `RuntimeStateSnapshot` - Interactive runtime state snapshot that must stay invariant.
1841    ///
1842    /// # Returns
1843    ///
1844    /// - `Result<(), VisualEquivalenceFailure>` - `Ok(())` when warmup started, or visual-equivalence gate failure.
1845    pub fn begin_seamless_handoff(
1846        &mut self,
1847        target: RenderBackendCandidate,
1848        frame_identity: (u32, u32, f32, u64),
1849        now_ms: u64,
1850        state: RuntimeStateSnapshot,
1851    ) -> Result<(), VisualEquivalenceFailure> {
1852        self.get_host_profile().candidate_passes_gate(target)?;
1853        let old: RenderBackendCandidate = self.get_active_candidate();
1854        self.get_mut_handoff()
1855            .begin_handoff(old, target, frame_identity, now_ms, state);
1856        Ok(())
1857    }
1858
1859    /// Stage 4 (Handoff): attempts atomic takeover at a frame boundary and updates active candidate on success (or aborts cleanly).
1860    ///
1861    /// # Arguments
1862    ///
1863    /// - `&Self` - Mutable router reference.
1864    /// - `HandoffFrameDescriptor` - Candidate first-frame verification descriptor.
1865    /// - `(u32, u32, f32, u64)` - Live frame-boundary `(width, height, scale_factor, scene_version)`.
1866    /// - `u64` - Sync fence ID for deferred old-resource reclamation.
1867    /// - `u64` - Current monotonic timestamp in milliseconds.
1868    /// - `CandidateScore` - Verified score of the winning candidate for cache recording.
1869    ///
1870    /// # Returns
1871    ///
1872    /// - `AdaptiveDecision` - `CommitHandoff` on exact boundary match or `AbortHandoff` leaving old backend active.
1873    pub fn commit_handoff_at_boundary(
1874        &mut self,
1875        first_frame: HandoffFrameDescriptor,
1876        current_frame: (u32, u32, f32, u64),
1877        commit_fence_id: u64,
1878        now_ms: u64,
1879        verified_score: CandidateScore,
1880    ) -> AdaptiveDecision {
1881        let old_active: RenderBackendCandidate = self.get_active_candidate();
1882        match self.get_mut_handoff().try_commit_at_frame_boundary(
1883            first_frame,
1884            current_frame,
1885            commit_fence_id,
1886            now_ms,
1887        ) {
1888            Ok(next_candidate) => {
1889                self.set_active_candidate(next_candidate);
1890                self.set_recommended_candidate(next_candidate);
1891                self.set_last_switch_ms(now_ms);
1892                self.set_has_switched_once(true);
1893                let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
1894                self.set_cooldown_until_ms(cooldown_end);
1895                self.set_streak_candidate(None);
1896                self.set_streak_wins(0);
1897                self.set_sustained_miss_streak(0);
1898                let key: WinnerCacheKey = self.cache_key_for(verified_score.get_scene_profile());
1899                let entry: WinnerCacheEntry = WinnerCacheEntry::new(
1900                    next_candidate,
1901                    now_ms,
1902                    verified_score.get_p95_frame_ms(),
1903                    verified_score.get_p99_frame_ms(),
1904                    verified_score.get_missed_frame_ratio(),
1905                    verified_score.get_input_to_present_ms(),
1906                );
1907                self.get_mut_winner_cache().record(key, entry);
1908                self.set_last_decision_reason(REASON_HANDOFF_COMMITTED);
1909                AdaptiveDecision {
1910                    kind: AdaptiveDecisionKind::CommitHandoff,
1911                    active_candidate: next_candidate,
1912                    recommended_candidate: next_candidate,
1913                    applied: true,
1914                    reason: REASON_HANDOFF_COMMITTED,
1915                    preserve_last_valid_frame: false,
1916                    fault_tag: None,
1917                }
1918            }
1919            Err(_) => {
1920                self.set_streak_candidate(None);
1921                self.set_streak_wins(0);
1922                self.set_last_decision_reason(REASON_HANDOFF_ABORTED);
1923                AdaptiveDecision {
1924                    kind: AdaptiveDecisionKind::AbortHandoff,
1925                    active_candidate: old_active,
1926                    recommended_candidate: old_active,
1927                    applied: false,
1928                    reason: REASON_HANDOFF_ABORTED,
1929                    preserve_last_valid_frame: true,
1930                    fault_tag: None,
1931                }
1932            }
1933        }
1934    }
1935
1936    /// Stage 5 (Fault Handling): handles hardware/surface/driver/thermal faults explicitly, excluding them from seamless-handoff success counts.
1937    ///
1938    /// # Arguments
1939    ///
1940    /// - `&Self` - Mutable router reference.
1941    /// - `FaultEventKind` - Explicit fault classification (`DeviceLost`, `SurfaceDestroyed`, `DriverSuspended`, `ThermalThrottled`).
1942    /// - `bool` - `true` when the host window remains valid and the last valid frame MUST be retained (never submitting a blank frame).
1943    /// - `u64` - Current monotonic timestamp in milliseconds.
1944    ///
1945    /// # Returns
1946    ///
1947    /// - `AdaptiveDecision` - Tagged fault response with immediate failover on `DeviceLost`.
1948    pub fn handle_fault(
1949        &mut self,
1950        fault: FaultEventKind,
1951        window_valid: bool,
1952        now_ms: u64,
1953    ) -> AdaptiveDecision {
1954        self.get_mut_handoff().abort_for_fault();
1955        self.get_mut_tagged_fault_events().push((now_ms, fault));
1956        self.set_streak_candidate(None);
1957        self.set_streak_wins(0);
1958        let retain_frame: bool = window_valid && fault != FaultEventKind::SurfaceDestroyed;
1959        self.set_last_valid_frame_retained(retain_frame);
1960        match fault {
1961            FaultEventKind::DeviceLost => {
1962                let current: RenderBackendCandidate = self.get_active_candidate();
1963                let next: RenderBackendCandidate = self
1964                    .get_host_profile()
1965                    .best_available_candidate(Some(current));
1966                self.set_active_candidate(next);
1967                self.set_recommended_candidate(next);
1968                self.set_last_switch_ms(now_ms);
1969                self.set_has_switched_once(true);
1970                let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
1971                self.set_cooldown_until_ms(cooldown_end);
1972                let next_faults: u64 = self.get_fault_failover_count().saturating_add(1);
1973                self.set_fault_failover_count(next_faults);
1974                self.set_last_decision_reason(REASON_FAULT_DEVICE_LOST);
1975                AdaptiveDecision {
1976                    kind: AdaptiveDecisionKind::FaultFailover,
1977                    active_candidate: next,
1978                    recommended_candidate: next,
1979                    applied: true,
1980                    reason: REASON_FAULT_DEVICE_LOST,
1981                    preserve_last_valid_frame: retain_frame,
1982                    fault_tag: Some(fault),
1983                }
1984            }
1985            FaultEventKind::SurfaceDestroyed
1986            | FaultEventKind::DriverSuspended
1987            | FaultEventKind::ThermalThrottled => {
1988                let active: RenderBackendCandidate = self.get_active_candidate();
1989                let reason: &'static str = match fault {
1990                    FaultEventKind::SurfaceDestroyed => REASON_FAULT_SURFACE_DESTROYED,
1991                    FaultEventKind::DriverSuspended => REASON_FAULT_DRIVER_SUSPENDED,
1992                    FaultEventKind::ThermalThrottled => REASON_FAULT_THERMAL_THROTTLED,
1993                    FaultEventKind::DeviceLost => REASON_FAULT_DEVICE_LOST,
1994                };
1995                self.set_last_decision_reason(reason);
1996                AdaptiveDecision {
1997                    kind: AdaptiveDecisionKind::FaultFailover,
1998                    active_candidate: active,
1999                    recommended_candidate: active,
2000                    applied: false,
2001                    reason,
2002                    preserve_last_valid_frame: retain_frame,
2003                    fault_tag: Some(fault),
2004                }
2005            }
2006        }
2007    }
2008
2009    /// Captures a compact serializable telemetry snapshot of the router and handoff coordinator state.
2010    ///
2011    /// # Arguments
2012    ///
2013    /// - `&Self` - Router reference.
2014    ///
2015    /// # Returns
2016    ///
2017    /// - `AdaptiveRouterSnapshot` - Snapshot embedded inside `AdaptiveFrameMetrics`.
2018    #[must_use]
2019    pub fn snapshot(&self) -> AdaptiveRouterSnapshot {
2020        let last_fault: Option<FaultEventKind> = self
2021            .get_tagged_fault_events()
2022            .last()
2023            .map(|(_, kind): &(u64, FaultEventKind)| *kind);
2024        AdaptiveRouterSnapshot {
2025            active_candidate: self.get_active_candidate(),
2026            recommended_candidate: self.get_recommended_candidate(),
2027            switch_mode: self.get_config().get_switch_mode(),
2028            handoff_stage: self.get_handoff().get_stage(),
2029            seamless_handoff_successes: self.get_handoff().get_seamless_success_count(),
2030            handoff_aborts: self.get_handoff().get_abort_count(),
2031            fault_failovers: self.get_fault_failover_count(),
2032            probe_runs: self.get_probe_runs(),
2033            probe_skips_no_headroom: self.get_probe_skips_no_headroom(),
2034            cache_hits: self.get_cache_hits(),
2035            recommendations_logged: self.get_recommendations_logged(),
2036            has_tagged_fault: last_fault.is_some(),
2037            last_fault_kind: last_fault.unwrap_or(FaultEventKind::DeviceLost),
2038        }
2039    }
2040
2041    /// Returns the candidate currently accumulating consecutive wins, if any.
2042    ///
2043    /// # Arguments
2044    ///
2045    /// - `&Self` - Router reference.
2046    ///
2047    /// # Returns
2048    ///
2049    /// - `Option<RenderBackendCandidate>` - Candidate on an active win streak.
2050    #[must_use]
2051    pub fn streak_candidate_value(&self) -> Option<RenderBackendCandidate> {
2052        let Self {
2053            streak_candidate, ..
2054        } = *self;
2055        streak_candidate
2056    }
2057}