Skip to main content

trustformers_mobile/mobile_performance_profiler/optimization/
engine.rs

1//! Optimization Engine
2//!
3//! This module provides intelligent optimization suggestion generation for mobile
4//! ML inference workloads using machine learning models and expert system rules.
5
6use anyhow::Result;
7use std::collections::{HashMap, VecDeque};
8use std::time::Instant;
9use tracing::debug;
10
11use super::super::types::*;
12use crate::device_info::ThermalState;
13
14/// Intelligent optimization suggestion engine
15#[derive(Debug)]
16pub struct OptimizationEngine {
17    /// Engine configuration
18    config: OptimizationEngineConfig,
19    /// Generated optimization suggestions
20    active_suggestions: HashMap<String, OptimizationSuggestion>,
21    /// Suggestion generation rules
22    optimization_rules: Vec<OptimizationRule>,
23    /// Suggestion ranking system
24    suggestion_ranker: SuggestionRanker,
25    /// Impact estimation models
26    impact_estimator: ImpactEstimator,
27    /// Suggestion history and tracking
28    suggestion_history: VecDeque<OptimizationEvent>,
29    /// Engine performance statistics
30    engine_stats: OptimizationEngineStats,
31}
32
33/// Optimization rule for suggestion generation
34#[derive(Debug, Clone)]
35pub struct OptimizationRule {
36    /// Rule identifier
37    pub id: String,
38    /// Human-readable rule name
39    pub name: String,
40    /// Trigger condition
41    pub condition: OptimizationCondition,
42    /// Generated suggestion template
43    pub suggestion_template: OptimizationSuggestion,
44    /// Estimated performance impact
45    pub estimated_impact: ImpactLevel,
46    /// Implementation difficulty
47    pub difficulty: DifficultyLevel,
48    /// Rule confidence score
49    pub confidence: f32,
50    /// Whether the rule is enabled
51    pub enabled: bool,
52}
53
54/// Conditions that trigger optimization suggestions
55#[derive(Debug, Clone)]
56pub enum OptimizationCondition {
57    /// High memory usage pattern
58    HighMemoryUsage {
59        threshold_percent: f32,
60        pattern: MemoryUsagePattern,
61    },
62    /// Low cache hit rate
63    LowCacheHitRate {
64        threshold_percent: f32,
65        cache_type: CacheType,
66    },
67    /// High inference latency
68    InferenceLatencyHigh {
69        threshold_ms: f32,
70        model_type: Option<String>,
71    },
72    /// Thermal throttling events
73    ThermalThrottling {
74        frequency: u32,
75        severity: ThermalState,
76    },
77    /// High battery drain
78    BatteryDrainHigh {
79        threshold_mw: f32,
80        context: BatteryContext,
81    },
82    /// Low network bandwidth utilization
83    NetworkBandwidthLow {
84        threshold_mbps: f32,
85        connection_type: NetworkType,
86    },
87    /// GPU underutilization
88    GPUUnderutilized {
89        threshold_percent: f32,
90        workload_type: WorkloadType,
91    },
92    /// CPU inefficiency patterns
93    CPUInefficiency {
94        pattern: CPUUsagePattern,
95        severity: f32,
96    },
97}
98
99/// Memory usage patterns for optimization
100#[derive(Debug, Clone)]
101pub enum MemoryUsagePattern {
102    /// Steady high usage
103    SteadyHigh,
104    /// Rapid growth
105    RapidGrowth,
106    /// Memory leaks
107    MemoryLeaks,
108    /// Fragmentation
109    Fragmentation,
110    /// Large allocations
111    LargeAllocations,
112}
113
114/// Cache types for optimization analysis
115#[derive(Debug, Clone)]
116pub enum CacheType {
117    /// Model cache
118    Model,
119    /// Tensor cache
120    Tensor,
121    /// Computation cache
122    Computation,
123    /// Network cache
124    Network,
125    /// General purpose cache
126    General,
127}
128
129/// Battery usage context
130#[derive(Debug, Clone)]
131pub enum BatteryContext {
132    /// During inference
133    Inference,
134    /// During model loading
135    ModelLoading,
136    /// During background tasks
137    Background,
138    /// During network operations
139    Network,
140    /// General usage
141    General,
142}
143
144/// Network connection types
145#[derive(Debug, Clone)]
146pub enum NetworkType {
147    /// WiFi connection
148    WiFi,
149    /// Cellular connection
150    Cellular,
151    /// Low power Bluetooth
152    Bluetooth,
153    /// Unknown connection type
154    Unknown,
155}
156
157/// ML workload types
158#[derive(Debug, Clone)]
159pub enum WorkloadType {
160    /// Computer vision workloads
161    ComputerVision,
162    /// Natural language processing
163    NLP,
164    /// Audio processing
165    Audio,
166    /// General ML inference
167    General,
168}
169
170/// CPU usage patterns
171#[derive(Debug, Clone)]
172pub enum CPUUsagePattern {
173    /// High single-core usage
174    SingleCoreHigh,
175    /// Poor multi-core utilization
176    PoorMultiCore,
177    /// Frequent context switching
178    FrequentSwitching,
179    /// Thermal throttling induced
180    ThermalLimited,
181    /// Inefficient algorithms
182    InefficientAlgorithms,
183}
184
185/// Optimization event for historical tracking
186#[derive(Debug, Clone)]
187pub struct OptimizationEvent {
188    pub timestamp: std::time::Instant,
189    pub suggestion_id: String,
190    pub event_type: String,
191    pub performance_impact: f32,
192    pub implementation_status: String,
193    pub metadata: std::collections::HashMap<String, String>,
194}
195
196/// Optimization engine statistics
197#[derive(Debug, Clone, Default)]
198pub struct OptimizationEngineStats {
199    /// Total suggestions generated
200    pub suggestions_generated: u64,
201    /// Suggestions accepted by users
202    pub suggestions_accepted: u64,
203    /// Suggestions that led to improvements
204    pub successful_suggestions: u64,
205    /// Average improvement achieved
206    pub avg_improvement_percent: f32,
207    /// Engine accuracy rate
208    pub accuracy_rate: f32,
209}
210
211/// Suggestion ranking system
212#[derive(Debug)]
213pub struct SuggestionRanker {
214    /// Ranking algorithm
215    algorithm: RankingAlgorithm,
216}
217
218/// Impact estimation models
219#[derive(Debug)]
220pub struct ImpactEstimator {
221    /// Impact models
222    models: Vec<ImpactModel>,
223}
224
225/// Internal ranking algorithm
226#[derive(Debug)]
227struct RankingAlgorithm;
228
229/// Internal impact model
230#[derive(Debug)]
231struct ImpactModel;
232
233impl OptimizationEngine {
234    /// Create a new optimization engine with the given configuration
235    pub fn new(config: OptimizationEngineConfig) -> Result<Self> {
236        let optimization_rules = Self::initialize_default_rules();
237
238        Ok(Self {
239            config,
240            active_suggestions: HashMap::new(),
241            optimization_rules,
242            suggestion_ranker: SuggestionRanker {
243                algorithm: RankingAlgorithm,
244            },
245            impact_estimator: ImpactEstimator { models: Vec::new() },
246            suggestion_history: VecDeque::new(),
247            engine_stats: OptimizationEngineStats::default(),
248        })
249    }
250
251    /// Generate optimization suggestions based on current metrics and bottlenecks
252    pub fn generate_suggestions(
253        &mut self,
254        metrics: &MobileMetricsSnapshot,
255        bottlenecks: &[PerformanceBottleneck],
256    ) -> Result<Vec<OptimizationSuggestion>> {
257        let mut suggestions = Vec::new();
258
259        // Generate suggestions from rules
260        for rule in &self.optimization_rules {
261            if !rule.enabled {
262                continue;
263            }
264
265            if self.evaluate_optimization_condition(&rule.condition, metrics)? {
266                let suggestion = self.create_suggestion_from_rule(rule, metrics)?;
267                suggestions.push(suggestion);
268
269                // Track suggestion generation
270                self.engine_stats.suggestions_generated += 1;
271                debug!("Generated optimization suggestion: {}", rule.name);
272            }
273        }
274
275        // Generate suggestions based on bottlenecks
276        for bottleneck in bottlenecks {
277            let bottleneck_suggestions =
278                self.generate_bottleneck_suggestions(bottleneck, metrics)?;
279            suggestions.extend(bottleneck_suggestions);
280        }
281
282        // Rank and prioritize suggestions
283        let ranked_suggestions = self.rank_suggestions(suggestions, metrics)?;
284
285        // Record them so `get_active_suggestions` / `get_all_suggestions`
286        // report what was generated. Without this the accessors returned an
287        // empty list no matter how many rules fired.
288        self.active_suggestions.clear();
289        for suggestion in &ranked_suggestions {
290            self.active_suggestions.insert(suggestion.title.clone(), suggestion.clone());
291        }
292
293        Ok(ranked_suggestions)
294    }
295
296    /// Initialize default optimization rules
297    fn initialize_default_rules() -> Vec<OptimizationRule> {
298        vec![
299            OptimizationRule {
300                id: "enable_quantization".to_string(),
301                name: "Enable Model Quantization".to_string(),
302                condition: OptimizationCondition::InferenceLatencyHigh {
303                    threshold_ms: 200.0,
304                    model_type: None,
305                },
306                suggestion_template: OptimizationSuggestion {
307                    suggestion_type: SuggestionType::ModelOptimization,
308                    title: "Enable INT8 Quantization".to_string(),
309                    description:
310                        "Reduce model size and inference latency by using 8-bit quantization"
311                            .to_string(),
312                    implementation_steps: vec![
313                        "Configure quantization in model settings".to_string(),
314                        "Test accuracy impact on validation dataset".to_string(),
315                        "Deploy quantized model if accuracy is acceptable".to_string(),
316                    ],
317                    estimated_improvement: String::new(), // filled in from the measurement that triggered the rule
318                    difficulty: DifficultyLevel::Medium,
319                    priority: PriorityLevel::High,
320                },
321                estimated_impact: ImpactLevel::High,
322                difficulty: DifficultyLevel::Medium,
323                confidence: 0.85,
324                enabled: true,
325            },
326            OptimizationRule {
327                id: "enable_gpu_acceleration".to_string(),
328                name: "Enable GPU Acceleration".to_string(),
329                condition: OptimizationCondition::CPUInefficiency {
330                    pattern: CPUUsagePattern::SingleCoreHigh,
331                    severity: 0.8,
332                },
333                suggestion_template: OptimizationSuggestion {
334                    suggestion_type: SuggestionType::HardwareOptimization,
335                    title: "Enable GPU Acceleration".to_string(),
336                    description:
337                        "Offload computation to GPU for better performance and lower CPU usage"
338                            .to_string(),
339                    implementation_steps: vec![
340                        "Check GPU availability and compatibility".to_string(),
341                        "Configure GPU backend in inference settings".to_string(),
342                        "Monitor GPU utilization and performance".to_string(),
343                    ],
344                    estimated_improvement: String::new(), // filled in from the measurement that triggered the rule
345                    difficulty: DifficultyLevel::Low,
346                    priority: PriorityLevel::High,
347                },
348                estimated_impact: ImpactLevel::High,
349                difficulty: DifficultyLevel::Low,
350                confidence: 0.9,
351                enabled: true,
352            },
353            OptimizationRule {
354                id: "reduce_batch_size".to_string(),
355                name: "Reduce Batch Size".to_string(),
356                condition: OptimizationCondition::HighMemoryUsage {
357                    threshold_percent: 85.0,
358                    pattern: MemoryUsagePattern::SteadyHigh,
359                },
360                suggestion_template: OptimizationSuggestion {
361                    suggestion_type: SuggestionType::PerformanceOptimization,
362                    title: "Reduce Inference Batch Size".to_string(),
363                    description: "Lower memory usage by processing smaller batches of data"
364                        .to_string(),
365                    implementation_steps: vec![
366                        "Identify current batch size configuration".to_string(),
367                        "Reduce batch size by 25-50%".to_string(),
368                        "Monitor latency and throughput impact".to_string(),
369                    ],
370                    estimated_improvement: String::new(), // filled in from the measurement that triggered the rule
371                    difficulty: DifficultyLevel::Low,
372                    priority: PriorityLevel::Medium,
373                },
374                estimated_impact: ImpactLevel::Medium,
375                difficulty: DifficultyLevel::Low,
376                confidence: 0.95,
377                enabled: true,
378            },
379        ]
380    }
381
382    /// Evaluate an optimization condition against current metrics
383    fn evaluate_optimization_condition(
384        &self,
385        condition: &OptimizationCondition,
386        metrics: &MobileMetricsSnapshot,
387    ) -> Result<bool> {
388        match condition {
389            OptimizationCondition::HighMemoryUsage {
390                threshold_percent, ..
391            } => Ok(metrics
392                .memory
393                .as_ref()
394                .and_then(|memory| memory.resident_share_percent())
395                .is_some_and(|share| share > *threshold_percent)),
396            OptimizationCondition::InferenceLatencyHigh { threshold_ms, .. } => {
397                Ok(metrics.inference.avg_latency_ms > *threshold_ms as f64)
398            },
399            OptimizationCondition::LowCacheHitRate {
400                threshold_percent, ..
401            } => {
402                // Real hit rate: the collector's inference tracker counts
403                // every recorded hit and miss. This used to compare an
404                // invented constant 50.0 against the threshold, so the rule
405                // fired (or not) regardless of the actual cache.
406                let hit_rate_percent = metrics.inference.cache_hit_rate as f32 * 100.0;
407                Ok(metrics.inference.total_inferences > 0 && hit_rate_percent < *threshold_percent)
408            },
409            OptimizationCondition::CPUInefficiency { severity, .. } => {
410                Ok(metrics.cpu.as_ref().is_some_and(|cpu| cpu.usage_percent > (severity * 100.0)))
411            },
412            _ => Ok(false), // Simplified for other conditions
413        }
414    }
415
416    /// Create an optimization suggestion from a triggered rule
417    fn create_suggestion_from_rule(
418        &self,
419        rule: &OptimizationRule,
420        metrics: &MobileMetricsSnapshot,
421    ) -> Result<OptimizationSuggestion> {
422        let mut suggestion = rule.suggestion_template.clone();
423
424        // State what was actually measured against the rule's threshold. The
425        // previous line reported `"{}% improvement"` from a fixed 30.0 base --
426        // a predicted speedup nothing had measured or modelled.
427        suggestion.estimated_improvement = self.describe_trigger(rule, metrics);
428
429        Ok(suggestion)
430    }
431
432    /// Generate suggestions specifically for detected bottlenecks
433    fn generate_bottleneck_suggestions(
434        &self,
435        bottleneck: &PerformanceBottleneck,
436        _metrics: &MobileMetricsSnapshot,
437    ) -> Result<Vec<OptimizationSuggestion>> {
438        let suggestions = match bottleneck.bottleneck_type {
439            BottleneckType::Memory => vec![OptimizationSuggestion {
440                suggestion_type: SuggestionType::PerformanceOptimization,
441                title: "Memory Optimization".to_string(),
442                description: format!("Address {} memory bottleneck", bottleneck.description),
443                implementation_steps: vec!["Optimize memory usage".to_string()],
444                estimated_improvement: format!(
445                    "memory bottleneck, impact score {:.1}/100",
446                    bottleneck.impact_score
447                ),
448                difficulty: DifficultyLevel::Medium,
449                priority: PriorityLevel::High,
450            }],
451            BottleneckType::CPU => vec![OptimizationSuggestion {
452                suggestion_type: SuggestionType::HardwareOptimization,
453                title: "CPU Optimization".to_string(),
454                description: format!("Address {} CPU bottleneck", bottleneck.description),
455                implementation_steps: vec!["Optimize CPU usage".to_string()],
456                estimated_improvement: format!(
457                    "CPU bottleneck, impact score {:.1}/100",
458                    bottleneck.impact_score
459                ),
460                difficulty: DifficultyLevel::Medium,
461                priority: PriorityLevel::High,
462            }],
463            BottleneckType::Latency => vec![OptimizationSuggestion {
464                suggestion_type: SuggestionType::ModelOptimization,
465                title: "Inference Latency Optimization".to_string(),
466                description: format!("Address {} latency bottleneck", bottleneck.description),
467                implementation_steps: vec![
468                    "Enable INT8 quantization and re-measure".to_string(),
469                    "Route the model through an available hardware backend".to_string(),
470                ],
471                estimated_improvement: format!(
472                    "latency bottleneck, impact score {:.1}/100",
473                    bottleneck.impact_score
474                ),
475                difficulty: DifficultyLevel::Medium,
476                priority: PriorityLevel::High,
477            }],
478            BottleneckType::Cache => vec![OptimizationSuggestion {
479                suggestion_type: SuggestionType::PerformanceOptimization,
480                title: "Cache Effectiveness".to_string(),
481                description: format!("Address {} cache bottleneck", bottleneck.description),
482                implementation_steps: vec![
483                    "Increase the KV/result cache size".to_string(),
484                    "Review the cache key so equivalent requests share an entry".to_string(),
485                ],
486                estimated_improvement: format!(
487                    "cache bottleneck, impact score {:.1}/100",
488                    bottleneck.impact_score
489                ),
490                difficulty: DifficultyLevel::Low,
491                priority: PriorityLevel::Medium,
492            }],
493            // GPU, Network, Thermal and Power bottlenecks cannot be detected
494            // at all today (no measured input -- see
495            // `BottleneckDetector::evaluate_rule`), so there is no suggestion
496            // template for them to reach.
497            BottleneckType::GPU
498            | BottleneckType::Network
499            | BottleneckType::Thermal
500            | BottleneckType::Power => Vec::new(),
501        };
502
503        Ok(suggestions)
504    }
505
506    /// Rank suggestions by priority and relevance
507    fn rank_suggestions(
508        &self,
509        mut suggestions: Vec<OptimizationSuggestion>,
510        metrics: &MobileMetricsSnapshot,
511    ) -> Result<Vec<OptimizationSuggestion>> {
512        // Sort by priority and difficulty
513        suggestions.sort_by(|a, b| {
514            // Higher priority first, then lower difficulty
515            match b.priority.cmp(&a.priority) {
516                std::cmp::Ordering::Equal => a.difficulty.cmp(&b.difficulty),
517                other => other,
518            }
519        });
520
521        // Limit to top suggestions
522        suggestions.truncate(10);
523        Ok(suggestions)
524    }
525
526    /// Calculate estimated improvement for a rule in current context
527    /// Describe the measurement that tripped this rule.
528    ///
529    /// This crate models no relationship between applying a suggestion and the
530    /// speedup that follows, so it reports the observation rather than a
531    /// predicted gain.
532    fn describe_trigger(&self, rule: &OptimizationRule, metrics: &MobileMetricsSnapshot) -> String {
533        match &rule.condition {
534            OptimizationCondition::HighMemoryUsage {
535                threshold_percent, ..
536            } => match metrics.memory.as_ref().and_then(|m| m.resident_share_percent()) {
537                Some(share) => format!(
538                    "resident memory at {:.1}% of usable (rule threshold {:.1}%)",
539                    share, threshold_percent
540                ),
541                None => "resident memory share not yet sampled".to_string(),
542            },
543            OptimizationCondition::InferenceLatencyHigh { threshold_ms, .. } => format!(
544                "mean inference latency {:.1} ms over {} inferences (rule threshold {:.1} ms)",
545                metrics.inference.avg_latency_ms, metrics.inference.total_inferences, threshold_ms
546            ),
547            OptimizationCondition::LowCacheHitRate {
548                threshold_percent, ..
549            } => format!(
550                "cache hit rate {:.1}% (rule threshold {:.1}%)",
551                metrics.inference.cache_hit_rate as f32 * 100.0,
552                threshold_percent
553            ),
554            OptimizationCondition::CPUInefficiency { severity, .. } => match metrics.cpu.as_ref() {
555                Some(cpu) => format!(
556                    "CPU usage {:.1}% (rule threshold {:.1}%)",
557                    cpu.usage_percent,
558                    severity * 100.0
559                ),
560                None => "CPU usage not measured".to_string(),
561            },
562            _ => format!("rule `{}` condition met", rule.id),
563        }
564    }
565
566    /// Adjust confidence based on current context
567    fn adjust_confidence_for_context(
568        &self,
569        base_confidence: f32,
570        _metrics: &MobileMetricsSnapshot,
571    ) -> Result<f32> {
572        // Simplified: could factor in device capabilities, model type, etc.
573        Ok(base_confidence.min(1.0).max(0.0))
574    }
575
576    /// Get engine statistics
577    pub fn get_engine_stats(&self) -> &OptimizationEngineStats {
578        &self.engine_stats
579    }
580
581    /// Get active suggestions
582    pub fn get_active_suggestions(&self) -> Vec<OptimizationSuggestion> {
583        self.active_suggestions.values().cloned().collect()
584    }
585
586    /// Every suggestion generated so far in this session.
587    pub fn get_all_suggestions(&self) -> Vec<OptimizationSuggestion> {
588        self.active_suggestions.values().cloned().collect()
589    }
590
591    /// Hot-reload the engine's configuration from the profiler's own config.
592    pub fn update_config(
593        &mut self,
594        config: crate::mobile_performance_profiler::config::MobileProfilerConfig,
595    ) -> Result<()> {
596        self.config.enabled = config.enabled;
597        self.config.generation_interval_ms = config.sampling.interval_ms;
598        debug!("Updated optimization engine configuration");
599        Ok(())
600    }
601
602    /// Mark a suggestion as implemented
603    pub fn mark_suggestion_implemented(
604        &mut self,
605        suggestion_id: &str,
606        performance_gain: f32,
607    ) -> Result<()> {
608        if let Some(suggestion) = self.active_suggestions.remove(suggestion_id) {
609            // Record the optimization event
610            let event = OptimizationEvent {
611                timestamp: Instant::now(),
612                suggestion_id: suggestion_id.to_string(),
613                event_type: "implemented".to_string(),
614                performance_impact: performance_gain,
615                implementation_status: "completed".to_string(),
616                metadata: HashMap::new(),
617            };
618
619            self.suggestion_history.push_back(event);
620            self.engine_stats.suggestions_accepted += 1;
621
622            if performance_gain > 0.0 {
623                self.engine_stats.successful_suggestions += 1;
624            }
625
626            // Update average improvement
627            let total_improvement = self.engine_stats.avg_improvement_percent
628                * self.engine_stats.successful_suggestions as f32;
629            self.engine_stats.avg_improvement_percent = (total_improvement + performance_gain)
630                / self.engine_stats.successful_suggestions as f32;
631        }
632
633        Ok(())
634    }
635}
636
637impl Default for OptimizationEngine {
638    fn default() -> Self {
639        // reason: built from a known-valid default config; construction is infallible
640        // for the default config and Default cannot return a Result.
641        Self::new(OptimizationEngineConfig::default())
642            .expect("default OptimizationEngineConfig must yield a valid engine")
643    }
644}
645
646#[cfg(test)]
647mod tests {
648    use super::*;
649    use crate::mobile_performance_profiler::types::{
650        BottleneckSeverity, BottleneckType, CpuMetrics, InferenceMetrics, MemoryMetrics,
651        MobileMetricsSnapshot, PerformanceBottleneck,
652    };
653
654    fn bottleneck(bottleneck_type: BottleneckType) -> PerformanceBottleneck {
655        PerformanceBottleneck {
656            bottleneck_type,
657            severity: BottleneckSeverity::Medium,
658            description: "test".to_string(),
659            affected_component: "test".to_string(),
660            impact_score: 42.0,
661            suggestions: Vec::new(),
662            timestamp: 1,
663        }
664    }
665
666    /// Regression: `generate_bottleneck_suggestions` matched only Memory and
667    /// CPU and fell through to `Vec::new()` for everything else, so the
668    /// Latency and Cache bottlenecks the detector reports produced nothing.
669    #[test]
670    fn test_latency_and_cache_bottlenecks_produce_suggestions() {
671        let engine = OptimizationEngine::default();
672        let metrics = MobileMetricsSnapshot::default();
673
674        for kind in [BottleneckType::Latency, BottleneckType::Cache] {
675            let suggestions = engine
676                .generate_bottleneck_suggestions(&bottleneck(kind), &metrics)
677                .expect("suggestion generation");
678            assert!(
679                !suggestions.is_empty(),
680                "{kind:?} bottleneck produced no suggestion"
681            );
682            // The reported figure states the measured impact, not a predicted
683            // "% improvement" from a fixed base.
684            assert!(suggestions[0].estimated_improvement.contains("impact score 42.0/100"));
685        }
686    }
687
688    /// Regression: the `LowCacheHitRate` condition used to be
689    /// `Ok(50.0 < *threshold_percent)` -- an invented constant compared
690    /// against the threshold, so the rule's verdict never depended on the
691    /// actual cache.
692    #[test]
693    fn test_cache_hit_rate_rule_reads_the_measured_rate() {
694        let engine = OptimizationEngine::default();
695        let condition = OptimizationCondition::LowCacheHitRate {
696            threshold_percent: 60.0,
697            cache_type: CacheType::Model,
698        };
699
700        let mut poor = MobileMetricsSnapshot::default();
701        poor.inference = InferenceMetrics {
702            total_inferences: 100,
703            cache_hit_rate: 0.10,
704            ..Default::default()
705        };
706        assert!(engine.evaluate_optimization_condition(&condition, &poor).expect("evaluate"));
707
708        let mut good = poor.clone();
709        good.inference.cache_hit_rate = 0.95;
710        assert!(!engine.evaluate_optimization_condition(&condition, &good).expect("evaluate"));
711    }
712
713    /// Regression: `HighMemoryUsage` divided by `heap_total_mb`, which no
714    /// platform publishes. It now reads the measured resident share, and an
715    /// unmeasured snapshot cannot trip the rule.
716    #[test]
717    fn test_memory_rule_needs_a_real_measurement() {
718        let engine = OptimizationEngine::default();
719        let condition = OptimizationCondition::HighMemoryUsage {
720            threshold_percent: 80.0,
721            pattern: MemoryUsagePattern::SteadyHigh,
722        };
723
724        let unmeasured = MobileMetricsSnapshot::default();
725        assert!(unmeasured.memory.is_none());
726        assert!(!engine
727            .evaluate_optimization_condition(&condition, &unmeasured)
728            .expect("evaluate"));
729
730        let mut pressured = unmeasured.clone();
731        pressured.memory = Some(MemoryMetrics {
732            heap_used_mb: 900.0,
733            available_mb: 100.0,
734            ..Default::default()
735        });
736        assert!(engine
737            .evaluate_optimization_condition(&condition, &pressured)
738            .expect("evaluate"));
739    }
740
741    /// CPU conditions likewise need a measurement.
742    #[test]
743    fn test_cpu_rule_needs_a_real_measurement() {
744        let engine = OptimizationEngine::default();
745        let condition = OptimizationCondition::CPUInefficiency {
746            pattern: CPUUsagePattern::SingleCoreHigh,
747            severity: 0.8,
748        };
749
750        let unmeasured = MobileMetricsSnapshot::default();
751        assert!(!engine
752            .evaluate_optimization_condition(&condition, &unmeasured)
753            .expect("evaluate"));
754
755        let mut busy = unmeasured.clone();
756        busy.cpu = Some(CpuMetrics {
757            usage_percent: 92.0,
758            ..Default::default()
759        });
760        assert!(engine.evaluate_optimization_condition(&condition, &busy).expect("evaluate"));
761    }
762}