1use 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#[derive(Debug)]
16pub struct OptimizationEngine {
17 config: OptimizationEngineConfig,
19 active_suggestions: HashMap<String, OptimizationSuggestion>,
21 optimization_rules: Vec<OptimizationRule>,
23 suggestion_ranker: SuggestionRanker,
25 impact_estimator: ImpactEstimator,
27 suggestion_history: VecDeque<OptimizationEvent>,
29 engine_stats: OptimizationEngineStats,
31}
32
33#[derive(Debug, Clone)]
35pub struct OptimizationRule {
36 pub id: String,
38 pub name: String,
40 pub condition: OptimizationCondition,
42 pub suggestion_template: OptimizationSuggestion,
44 pub estimated_impact: ImpactLevel,
46 pub difficulty: DifficultyLevel,
48 pub confidence: f32,
50 pub enabled: bool,
52}
53
54#[derive(Debug, Clone)]
56pub enum OptimizationCondition {
57 HighMemoryUsage {
59 threshold_percent: f32,
60 pattern: MemoryUsagePattern,
61 },
62 LowCacheHitRate {
64 threshold_percent: f32,
65 cache_type: CacheType,
66 },
67 InferenceLatencyHigh {
69 threshold_ms: f32,
70 model_type: Option<String>,
71 },
72 ThermalThrottling {
74 frequency: u32,
75 severity: ThermalState,
76 },
77 BatteryDrainHigh {
79 threshold_mw: f32,
80 context: BatteryContext,
81 },
82 NetworkBandwidthLow {
84 threshold_mbps: f32,
85 connection_type: NetworkType,
86 },
87 GPUUnderutilized {
89 threshold_percent: f32,
90 workload_type: WorkloadType,
91 },
92 CPUInefficiency {
94 pattern: CPUUsagePattern,
95 severity: f32,
96 },
97}
98
99#[derive(Debug, Clone)]
101pub enum MemoryUsagePattern {
102 SteadyHigh,
104 RapidGrowth,
106 MemoryLeaks,
108 Fragmentation,
110 LargeAllocations,
112}
113
114#[derive(Debug, Clone)]
116pub enum CacheType {
117 Model,
119 Tensor,
121 Computation,
123 Network,
125 General,
127}
128
129#[derive(Debug, Clone)]
131pub enum BatteryContext {
132 Inference,
134 ModelLoading,
136 Background,
138 Network,
140 General,
142}
143
144#[derive(Debug, Clone)]
146pub enum NetworkType {
147 WiFi,
149 Cellular,
151 Bluetooth,
153 Unknown,
155}
156
157#[derive(Debug, Clone)]
159pub enum WorkloadType {
160 ComputerVision,
162 NLP,
164 Audio,
166 General,
168}
169
170#[derive(Debug, Clone)]
172pub enum CPUUsagePattern {
173 SingleCoreHigh,
175 PoorMultiCore,
177 FrequentSwitching,
179 ThermalLimited,
181 InefficientAlgorithms,
183}
184
185#[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#[derive(Debug, Clone, Default)]
198pub struct OptimizationEngineStats {
199 pub suggestions_generated: u64,
201 pub suggestions_accepted: u64,
203 pub successful_suggestions: u64,
205 pub avg_improvement_percent: f32,
207 pub accuracy_rate: f32,
209}
210
211#[derive(Debug)]
213pub struct SuggestionRanker {
214 algorithm: RankingAlgorithm,
216}
217
218#[derive(Debug)]
220pub struct ImpactEstimator {
221 models: Vec<ImpactModel>,
223}
224
225#[derive(Debug)]
227struct RankingAlgorithm;
228
229#[derive(Debug)]
231struct ImpactModel;
232
233impl OptimizationEngine {
234 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 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 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 self.engine_stats.suggestions_generated += 1;
271 debug!("Generated optimization suggestion: {}", rule.name);
272 }
273 }
274
275 for bottleneck in bottlenecks {
277 let bottleneck_suggestions =
278 self.generate_bottleneck_suggestions(bottleneck, metrics)?;
279 suggestions.extend(bottleneck_suggestions);
280 }
281
282 let ranked_suggestions = self.rank_suggestions(suggestions, metrics)?;
284
285 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 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(), 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(), 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(), 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 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 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), }
414 }
415
416 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 suggestion.estimated_improvement = self.describe_trigger(rule, metrics);
428
429 Ok(suggestion)
430 }
431
432 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 BottleneckType::GPU
498 | BottleneckType::Network
499 | BottleneckType::Thermal
500 | BottleneckType::Power => Vec::new(),
501 };
502
503 Ok(suggestions)
504 }
505
506 fn rank_suggestions(
508 &self,
509 mut suggestions: Vec<OptimizationSuggestion>,
510 metrics: &MobileMetricsSnapshot,
511 ) -> Result<Vec<OptimizationSuggestion>> {
512 suggestions.sort_by(|a, b| {
514 match b.priority.cmp(&a.priority) {
516 std::cmp::Ordering::Equal => a.difficulty.cmp(&b.difficulty),
517 other => other,
518 }
519 });
520
521 suggestions.truncate(10);
523 Ok(suggestions)
524 }
525
526 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 fn adjust_confidence_for_context(
568 &self,
569 base_confidence: f32,
570 _metrics: &MobileMetricsSnapshot,
571 ) -> Result<f32> {
572 Ok(base_confidence.min(1.0).max(0.0))
574 }
575
576 pub fn get_engine_stats(&self) -> &OptimizationEngineStats {
578 &self.engine_stats
579 }
580
581 pub fn get_active_suggestions(&self) -> Vec<OptimizationSuggestion> {
583 self.active_suggestions.values().cloned().collect()
584 }
585
586 pub fn get_all_suggestions(&self) -> Vec<OptimizationSuggestion> {
588 self.active_suggestions.values().cloned().collect()
589 }
590
591 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 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 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 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 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 #[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 assert!(suggestions[0].estimated_improvement.contains("impact score 42.0/100"));
685 }
686 }
687
688 #[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 #[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 #[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}