Skip to main content

trustformers_mobile/lifecycle/
stats.rs

1//! Lifecycle Statistics and Monitoring
2//!
3//! This module contains types for tracking and analyzing lifecycle statistics,
4//! performance metrics, and system monitoring.
5
6use crate::lifecycle::config::{TaskPriority, TaskType};
7use crate::lifecycle::state::AppState;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11/// Lifecycle statistics tracker
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct LifecycleStats {
14    /// Statistics collection start time
15    pub start_timestamp: u64,
16    /// App state statistics
17    pub app_state_stats: AppStateStats,
18    /// Task execution statistics
19    pub task_execution_stats: HashMap<TaskType, TaskExecutionStats>,
20    /// Resource usage statistics
21    pub resource_usage_stats: ResourceUsageStats,
22    /// Performance statistics
23    pub performance_stats: PerformanceStats,
24    /// Error statistics
25    pub error_stats: ErrorStats,
26    /// User interaction statistics
27    pub user_interaction_stats: UserInteractionStats,
28    /// System health statistics
29    pub system_health_stats: SystemHealthStats,
30}
31
32/// App state transition statistics
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct AppStateStats {
35    /// Time spent in each state (seconds)
36    pub time_in_state: HashMap<AppState, u64>,
37    /// Transition counts between states
38    pub transition_counts: HashMap<String, u32>, // "FromState->ToState" format
39    /// Average time between transitions (seconds)
40    pub avg_transition_interval_seconds: f64,
41    /// Total transitions recorded
42    pub total_transitions: u64,
43    /// Last state change timestamp
44    pub last_state_change_timestamp: u64,
45    /// State change frequency (transitions/hour)
46    pub state_change_frequency_per_hour: f32,
47}
48
49/// Task execution statistics
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct TaskExecutionStats {
52    /// Total tasks executed
53    pub total_executed: u64,
54    /// Successful executions
55    pub successful_executions: u64,
56    /// Failed executions
57    pub failed_executions: u64,
58    /// Cancelled executions
59    pub cancelled_executions: u64,
60    /// Average execution time (seconds)
61    pub avg_execution_time_seconds: f64,
62    /// Minimum execution time (seconds)
63    pub min_execution_time_seconds: f64,
64    /// Maximum execution time (seconds)
65    pub max_execution_time_seconds: f64,
66    /// Success rate percentage
67    pub success_rate_percent: f32,
68    /// Average resource consumption
69    pub avg_resource_consumption: AvgResourceConsumption,
70    /// Priority distribution
71    pub priority_distribution: HashMap<TaskPriority, u32>,
72    /// Queue wait time statistics
73    pub queue_wait_stats: QueueWaitStats,
74}
75
76/// Average resource consumption statistics
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct AvgResourceConsumption {
79    /// Average CPU usage (%)
80    pub avg_cpu_percent: f32,
81    /// Average memory usage (MB)
82    pub avg_memory_mb: f32,
83    /// Average network usage (MB)
84    pub avg_network_mb: f32,
85    /// Average battery consumption (mAh)
86    pub avg_battery_mah: f32,
87    /// Average execution time (seconds)
88    pub avg_execution_time_seconds: f32,
89}
90
91/// Queue wait time statistics
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct QueueWaitStats {
94    /// Average wait time (seconds)
95    pub avg_wait_time_seconds: f64,
96    /// Minimum wait time (seconds)
97    pub min_wait_time_seconds: f64,
98    /// Maximum wait time (seconds)
99    pub max_wait_time_seconds: f64,
100    /// 95th percentile wait time (seconds)
101    pub p95_wait_time_seconds: f64,
102}
103
104/// Resource usage statistics
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct ResourceUsageStats {
107    /// CPU usage statistics
108    pub cpu_stats: UsageStats,
109    /// Memory usage statistics
110    pub memory_stats: UsageStats,
111    /// Network usage statistics
112    pub network_stats: UsageStats,
113    /// Battery usage statistics
114    pub battery_stats: BatteryUsageStats,
115    /// GPU usage statistics (if available)
116    pub gpu_stats: Option<UsageStats>,
117    /// Storage I/O statistics
118    pub storage_stats: StorageStats,
119    /// Thermal statistics
120    pub thermal_stats: ThermalStats,
121}
122
123/// Generic usage statistics
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct UsageStats {
126    /// Current usage value
127    pub current: f32,
128    /// Average usage
129    pub average: f32,
130    /// Minimum usage recorded
131    pub minimum: f32,
132    /// Maximum usage recorded
133    pub maximum: f32,
134    /// 95th percentile usage
135    pub p95: f32,
136    /// Standard deviation
137    pub std_deviation: f32,
138    /// Total samples collected
139    pub sample_count: u64,
140}
141
142/// Battery usage statistics
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct BatteryUsageStats {
145    /// Current battery level (%)
146    pub current_level_percent: u8,
147    /// Battery drain rate (%/hour)
148    pub drain_rate_percent_per_hour: f32,
149    /// Average battery level
150    pub avg_battery_level_percent: f32,
151    /// Time since last charge (hours)
152    pub time_since_last_charge_hours: f32,
153    /// Charging cycles in session
154    pub charging_cycles: u32,
155    /// Low battery events
156    pub low_battery_events: u32,
157    /// Critical battery events
158    pub critical_battery_events: u32,
159}
160
161/// Storage I/O statistics
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct StorageStats {
164    /// Read operations count
165    pub read_operations: u64,
166    /// Write operations count
167    pub write_operations: u64,
168    /// Total bytes read
169    pub bytes_read: u64,
170    /// Total bytes written
171    pub bytes_written: u64,
172    /// Average read speed (MB/s)
173    pub avg_read_speed_mbps: f32,
174    /// Average write speed (MB/s)
175    pub avg_write_speed_mbps: f32,
176    /// Storage space usage (MB)
177    pub storage_usage_mb: u64,
178    /// Available storage space (MB)
179    pub available_storage_mb: u64,
180}
181
182/// Thermal statistics
183#[derive(Debug, Clone, Serialize, Deserialize)]
184pub struct ThermalStats {
185    /// Current temperature (°C)
186    pub current_temperature_celsius: f32,
187    /// Average temperature (°C)
188    pub avg_temperature_celsius: f32,
189    /// Maximum temperature recorded (°C)
190    pub max_temperature_celsius: f32,
191    /// Thermal events count
192    pub thermal_events: u32,
193    /// Throttling events count
194    pub throttling_events: u32,
195    /// Time spent in thermal warning (seconds)
196    pub time_in_thermal_warning_seconds: u64,
197    /// Temperature trend
198    pub temperature_trend: TemperatureTrend,
199}
200
201/// Temperature trend analysis
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203pub enum TemperatureTrend {
204    Stable,
205    Rising,
206    Falling,
207    Oscillating,
208}
209
210/// Performance statistics
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct PerformanceStats {
213    /// Inference performance statistics
214    pub inference_stats: InferencePerformanceStats,
215    /// Memory performance statistics
216    pub memory_performance_stats: MemoryPerformanceStats,
217    /// Network performance statistics
218    pub network_performance_stats: NetworkPerformanceStats,
219    /// Overall system performance score (0-100)
220    pub overall_performance_score: f32,
221    /// Performance degradation events
222    pub performance_degradation_events: u32,
223    /// Performance optimization events
224    pub performance_optimization_events: u32,
225}
226
227/// Inference performance statistics
228#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct InferencePerformanceStats {
230    /// Total inferences performed
231    pub total_inferences: u64,
232    /// Average inference time (ms)
233    pub avg_inference_time_ms: f32,
234    /// Inference throughput (inferences/second)
235    pub throughput_per_second: f32,
236    /// Accuracy statistics
237    pub accuracy_stats: AccuracyStats,
238    /// Model loading time statistics
239    pub model_loading_stats: ModelLoadingStats,
240    /// Queue backlog statistics
241    pub queue_backlog_stats: QueueBacklogStats,
242}
243
244/// Accuracy tracking statistics
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct AccuracyStats {
247    /// Average accuracy score (0-100)
248    pub avg_accuracy_score: f32,
249    /// Accuracy trend over time
250    pub accuracy_trend: AccuracyTrend,
251    /// Model drift detection events
252    pub model_drift_events: u32,
253    /// Accuracy degradation events
254    pub accuracy_degradation_events: u32,
255}
256
257/// Accuracy trend analysis
258#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
259pub enum AccuracyTrend {
260    Stable,
261    Improving,
262    Degrading,
263    Fluctuating,
264}
265
266/// Model loading statistics
267#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct ModelLoadingStats {
269    /// Total model loads
270    pub total_loads: u32,
271    /// Average loading time (seconds)
272    pub avg_loading_time_seconds: f32,
273    /// Cache hit rate (%)
274    pub cache_hit_rate_percent: f32,
275    /// Failed loads count
276    pub failed_loads: u32,
277    /// Memory usage for loaded models (MB)
278    pub loaded_models_memory_mb: usize,
279}
280
281/// Queue backlog statistics
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct QueueBacklogStats {
284    /// Current queue size
285    pub current_queue_size: usize,
286    /// Average queue size
287    pub avg_queue_size: f32,
288    /// Maximum queue size recorded
289    pub max_queue_size: usize,
290    /// Queue overflow events
291    pub queue_overflow_events: u32,
292    /// Average processing time per item (ms)
293    pub avg_processing_time_ms: f32,
294}
295
296/// Memory performance statistics
297#[derive(Debug, Clone, Serialize, Deserialize)]
298pub struct MemoryPerformanceStats {
299    /// Memory allocation rate (MB/s)
300    pub allocation_rate_mbps: f32,
301    /// Memory deallocation rate (MB/s)
302    pub deallocation_rate_mbps: f32,
303    /// Garbage collection events
304    pub gc_events: u32,
305    /// Average GC pause time (ms)
306    pub avg_gc_pause_time_ms: f32,
307    /// Memory fragmentation percentage
308    pub fragmentation_percent: f32,
309    /// Out of memory events
310    pub oom_events: u32,
311    /// Memory pressure events
312    pub memory_pressure_events: u32,
313}
314
315/// Network performance statistics
316#[derive(Debug, Clone, Serialize, Deserialize)]
317pub struct NetworkPerformanceStats {
318    /// Data transfer rate (MB/s)
319    pub transfer_rate_mbps: f32,
320    /// Connection success rate (%)
321    pub connection_success_rate_percent: f32,
322    /// Average latency (ms)
323    pub avg_latency_ms: f32,
324    /// Timeout events
325    pub timeout_events: u32,
326    /// Retry events
327    pub retry_events: u32,
328    /// Data usage statistics
329    pub data_usage: DataUsageStats,
330}
331
332/// Data usage statistics
333#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct DataUsageStats {
335    /// Total data sent (MB)
336    pub total_sent_mb: f32,
337    /// Total data received (MB)
338    pub total_received_mb: f32,
339    /// Data usage by task type
340    pub usage_by_task_type: HashMap<TaskType, f32>,
341    /// Peak bandwidth usage (MB/s)
342    pub peak_bandwidth_mbps: f32,
343}
344
345/// Error statistics tracking
346#[derive(Debug, Clone, Serialize, Deserialize)]
347pub struct ErrorStats {
348    /// Total errors recorded
349    pub total_errors: u64,
350    /// Errors by category
351    pub errors_by_category: HashMap<String, u32>,
352    /// Errors by severity
353    pub errors_by_severity: HashMap<ErrorSeverity, u32>,
354    /// Recent error patterns
355    pub recent_error_patterns: Vec<ErrorPattern>,
356    /// Error rate (errors/hour)
357    pub error_rate_per_hour: f32,
358    /// Error resolution statistics
359    pub error_resolution_stats: ErrorResolutionStats,
360}
361
362/// Error severity levels
363#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
364pub enum ErrorSeverity {
365    Low,
366    Medium,
367    High,
368    Critical,
369}
370
371/// Error pattern detection
372#[derive(Debug, Clone, Serialize, Deserialize)]
373pub struct ErrorPattern {
374    /// Pattern identifier
375    pub pattern_id: String,
376    /// Error message pattern
377    pub message_pattern: String,
378    /// Occurrence count
379    pub occurrence_count: u32,
380    /// First occurrence timestamp
381    pub first_occurrence_timestamp: u64,
382    /// Last occurrence timestamp
383    pub last_occurrence_timestamp: u64,
384    /// Affected components
385    pub affected_components: Vec<String>,
386}
387
388/// Error resolution statistics
389#[derive(Debug, Clone, Serialize, Deserialize)]
390pub struct ErrorResolutionStats {
391    /// Automatically resolved errors
392    pub auto_resolved_errors: u32,
393    /// Manually resolved errors
394    pub manually_resolved_errors: u32,
395    /// Unresolved errors
396    pub unresolved_errors: u32,
397    /// Average resolution time (minutes)
398    pub avg_resolution_time_minutes: f32,
399    /// Resolution success rate (%)
400    pub resolution_success_rate_percent: f32,
401}
402
403/// User interaction statistics
404#[derive(Debug, Clone, Serialize, Deserialize)]
405pub struct UserInteractionStats {
406    /// Total interactions
407    pub total_interactions: u64,
408    /// Interactions by type
409    pub interactions_by_type: HashMap<String, u32>,
410    /// Average session duration (minutes)
411    pub avg_session_duration_minutes: f32,
412    /// User engagement score (0-100)
413    pub engagement_score: f32,
414    /// Feature usage statistics
415    pub feature_usage_stats: FeatureUsageStats,
416    /// User satisfaction metrics
417    pub satisfaction_metrics: UserSatisfactionMetrics,
418}
419
420/// Feature usage statistics
421#[derive(Debug, Clone, Serialize, Deserialize)]
422pub struct FeatureUsageStats {
423    /// Feature usage counts
424    pub feature_usage_counts: HashMap<String, u32>,
425    /// Feature popularity ranking
426    pub popularity_ranking: Vec<String>,
427    /// Unused features list
428    pub unused_features: Vec<String>,
429    /// Feature adoption rate (%)
430    pub adoption_rate_percent: f32,
431}
432
433/// User satisfaction metrics
434#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct UserSatisfactionMetrics {
436    /// Overall satisfaction score (0-100)
437    pub overall_satisfaction_score: f32,
438    /// Performance satisfaction score (0-100)
439    pub performance_satisfaction_score: f32,
440    /// User feedback count
441    pub feedback_count: u32,
442    /// Positive feedback percentage
443    pub positive_feedback_percent: f32,
444    /// App crashes experienced by user
445    pub user_experienced_crashes: u32,
446}
447
448/// System health monitoring statistics
449#[derive(Debug, Clone, Serialize, Deserialize)]
450pub struct SystemHealthStats {
451    /// Overall health score (0-100)
452    pub overall_health_score: f32,
453    /// Component health scores
454    pub component_health_scores: HashMap<String, f32>,
455    /// Health trend over time
456    pub health_trend: HealthTrend,
457    /// Critical issues count
458    pub critical_issues_count: u32,
459    /// Warning issues count
460    pub warning_issues_count: u32,
461    /// System uptime (hours)
462    pub system_uptime_hours: f32,
463    /// Stability metrics
464    pub stability_metrics: StabilityMetrics,
465}
466
467/// Health trend analysis
468#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
469pub enum HealthTrend {
470    Excellent,
471    Good,
472    Fair,
473    Poor,
474    Critical,
475}
476
477/// System stability metrics
478#[derive(Debug, Clone, Serialize, Deserialize)]
479pub struct StabilityMetrics {
480    /// Crash-free sessions percentage
481    pub crash_free_sessions_percent: f32,
482    /// Mean time between failures (hours)
483    pub mtbf_hours: f32,
484    /// System availability percentage
485    pub availability_percent: f32,
486    /// Recovery time statistics
487    pub recovery_time_stats: RecoveryTimeStats,
488}
489
490/// Recovery time statistics
491#[derive(Debug, Clone, Serialize, Deserialize)]
492pub struct RecoveryTimeStats {
493    /// Average recovery time (minutes)
494    pub avg_recovery_time_minutes: f32,
495    /// Fastest recovery time (minutes)
496    pub fastest_recovery_minutes: f32,
497    /// Slowest recovery time (minutes)
498    pub slowest_recovery_minutes: f32,
499    /// Successful recoveries count
500    pub successful_recoveries: u32,
501    /// Failed recovery attempts
502    pub failed_recovery_attempts: u32,
503}
504
505impl LifecycleStats {
506    /// Create new lifecycle statistics tracker
507    pub fn new() -> Self {
508        let start_timestamp = std::time::SystemTime::now()
509            .duration_since(std::time::UNIX_EPOCH)
510            .expect("SystemTime should be after UNIX_EPOCH")
511            .as_secs();
512
513        Self {
514            start_timestamp,
515            app_state_stats: AppStateStats::new(),
516            task_execution_stats: HashMap::new(),
517            resource_usage_stats: ResourceUsageStats::new(),
518            performance_stats: PerformanceStats::new(),
519            error_stats: ErrorStats::new(),
520            user_interaction_stats: UserInteractionStats::new(),
521            system_health_stats: SystemHealthStats::new(),
522        }
523    }
524
525    /// Update statistics with new data point
526    pub fn update_stats(&mut self, update: StatsUpdate) {
527        match update {
528            StatsUpdate::AppStateTransition {
529                from,
530                to,
531                timestamp,
532            } => {
533                self.app_state_stats.record_transition(from, to, timestamp);
534            },
535            StatsUpdate::TaskExecution {
536                task_type,
537                execution_stats,
538            } => {
539                self.task_execution_stats
540                    .entry(task_type)
541                    .or_insert_with(TaskExecutionStats::new)
542                    .update(execution_stats);
543            },
544            StatsUpdate::ResourceUsage {
545                cpu,
546                memory,
547                network,
548                battery,
549            } => {
550                self.resource_usage_stats.update(cpu, memory, network, battery);
551            },
552            StatsUpdate::Performance {
553                inference_time,
554                accuracy,
555                throughput,
556            } => {
557                self.performance_stats
558                    .update_inference_stats(inference_time, accuracy, throughput);
559            },
560            StatsUpdate::Error {
561                severity,
562                category,
563                message,
564            } => {
565                self.error_stats.record_error(severity, category, message);
566            },
567            StatsUpdate::UserInteraction {
568                interaction_type,
569                duration,
570            } => {
571                self.user_interaction_stats.record_interaction(interaction_type, duration);
572            },
573            StatsUpdate::SystemHealth {
574                component,
575                health_score,
576            } => {
577                self.system_health_stats.update_component_health(component, health_score);
578            },
579        }
580    }
581
582    /// Generate statistics summary report
583    pub fn generate_summary_report(&self) -> StatsSummaryReport {
584        StatsSummaryReport {
585            collection_period_hours: self.get_collection_period_hours(),
586            overall_performance_score: self.performance_stats.overall_performance_score,
587            system_health_score: self.system_health_stats.overall_health_score,
588            error_rate_per_hour: self.error_stats.error_rate_per_hour,
589            user_engagement_score: self.user_interaction_stats.engagement_score,
590            resource_efficiency_score: self.calculate_resource_efficiency_score(),
591            key_metrics: self.extract_key_metrics(),
592            recommendations: self.generate_recommendations(),
593        }
594    }
595
596    /// Get collection period in hours
597    pub fn get_collection_period_hours(&self) -> f32 {
598        let current_timestamp = std::time::SystemTime::now()
599            .duration_since(std::time::UNIX_EPOCH)
600            .expect("SystemTime should be after UNIX_EPOCH")
601            .as_secs();
602        (current_timestamp - self.start_timestamp) as f32 / 3600.0
603    }
604
605    /// Calculate overall resource efficiency score
606    fn calculate_resource_efficiency_score(&self) -> f32 {
607        let cpu_efficiency = 100.0 - self.resource_usage_stats.cpu_stats.average;
608        let memory_efficiency =
609            (1.0 - (self.resource_usage_stats.memory_stats.average / 100.0)) * 100.0;
610        let battery_efficiency =
611            100.0 - self.resource_usage_stats.battery_stats.drain_rate_percent_per_hour;
612
613        (cpu_efficiency + memory_efficiency + battery_efficiency) / 3.0
614    }
615
616    /// Extract key performance metrics
617    fn extract_key_metrics(&self) -> Vec<KeyMetric> {
618        vec![
619            KeyMetric {
620                name: "Average Inference Time".to_string(),
621                value: self.performance_stats.inference_stats.avg_inference_time_ms,
622                unit: "ms".to_string(),
623                trend: MetricTrend::Stable,
624            },
625            KeyMetric {
626                name: "Success Rate".to_string(),
627                value: self.calculate_overall_success_rate(),
628                unit: "%".to_string(),
629                trend: MetricTrend::Stable,
630            },
631            KeyMetric {
632                name: "Memory Usage".to_string(),
633                value: self.resource_usage_stats.memory_stats.average,
634                unit: "MB".to_string(),
635                trend: MetricTrend::Stable,
636            },
637        ]
638    }
639
640    /// Calculate overall success rate
641    fn calculate_overall_success_rate(&self) -> f32 {
642        if self.task_execution_stats.is_empty() {
643            return 100.0;
644        }
645
646        let total_tasks: u64 = self.task_execution_stats.values().map(|s| s.total_executed).sum();
647        let successful_tasks: u64 =
648            self.task_execution_stats.values().map(|s| s.successful_executions).sum();
649
650        if total_tasks == 0 {
651            100.0
652        } else {
653            (successful_tasks as f32 / total_tasks as f32) * 100.0
654        }
655    }
656
657    /// Generate performance recommendations
658    fn generate_recommendations(&self) -> Vec<String> {
659        let mut recommendations = Vec::new();
660
661        if self.resource_usage_stats.memory_stats.average > 80.0 {
662            recommendations.push(
663                "Consider enabling aggressive memory cleanup to reduce memory usage".to_string(),
664            );
665        }
666
667        if self.resource_usage_stats.battery_stats.drain_rate_percent_per_hour > 20.0 {
668            recommendations
669                .push("High battery drain detected. Enable battery optimization mode".to_string());
670        }
671
672        if self.error_stats.error_rate_per_hour > 5.0 {
673            recommendations
674                .push("Error rate is high. Review error patterns and implement fixes".to_string());
675        }
676
677        if self.performance_stats.inference_stats.avg_inference_time_ms > 1000.0 {
678            recommendations.push(
679                "Inference time is high. Consider model optimization or hardware acceleration"
680                    .to_string(),
681            );
682        }
683
684        recommendations
685    }
686}
687
688/// Statistics update events
689#[derive(Debug, Clone)]
690pub enum StatsUpdate {
691    AppStateTransition {
692        from: AppState,
693        to: AppState,
694        timestamp: u64,
695    },
696    TaskExecution {
697        task_type: TaskType,
698        execution_stats: TaskExecutionUpdate,
699    },
700    ResourceUsage {
701        cpu: f32,
702        memory: f32,
703        network: f32,
704        battery: f32,
705    },
706    Performance {
707        inference_time: f32,
708        accuracy: f32,
709        throughput: f32,
710    },
711    Error {
712        severity: ErrorSeverity,
713        category: String,
714        message: String,
715    },
716    UserInteraction {
717        interaction_type: String,
718        duration: u64,
719    },
720    SystemHealth {
721        component: String,
722        health_score: f32,
723    },
724}
725
726/// Task execution update data
727#[derive(Debug, Clone)]
728pub struct TaskExecutionUpdate {
729    pub execution_time_seconds: f64,
730    pub success: bool,
731    pub priority: TaskPriority,
732    pub resource_usage: AvgResourceConsumption,
733    pub wait_time_seconds: f64,
734}
735
736/// Statistics summary report
737#[derive(Debug, Clone, Serialize, Deserialize)]
738pub struct StatsSummaryReport {
739    pub collection_period_hours: f32,
740    pub overall_performance_score: f32,
741    pub system_health_score: f32,
742    pub error_rate_per_hour: f32,
743    pub user_engagement_score: f32,
744    pub resource_efficiency_score: f32,
745    pub key_metrics: Vec<KeyMetric>,
746    pub recommendations: Vec<String>,
747}
748
749/// Key metric representation
750#[derive(Debug, Clone, Serialize, Deserialize)]
751pub struct KeyMetric {
752    pub name: String,
753    pub value: f32,
754    pub unit: String,
755    pub trend: MetricTrend,
756}
757
758/// Metric trend analysis
759#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
760pub enum MetricTrend {
761    Improving,
762    Stable,
763    Degrading,
764    Volatile,
765}
766
767// Implementation blocks for default constructors
768impl AppStateStats {
769    fn new() -> Self {
770        Self {
771            time_in_state: HashMap::new(),
772            transition_counts: HashMap::new(),
773            avg_transition_interval_seconds: 0.0,
774            total_transitions: 0,
775            last_state_change_timestamp: 0,
776            state_change_frequency_per_hour: 0.0,
777        }
778    }
779
780    fn record_transition(&mut self, from: AppState, to: AppState, timestamp: u64) {
781        let transition_key = format!("{:?}->{:?}", from, to);
782        *self.transition_counts.entry(transition_key).or_insert(0) += 1;
783        self.total_transitions += 1;
784        self.last_state_change_timestamp = timestamp;
785    }
786}
787
788impl TaskExecutionStats {
789    fn new() -> Self {
790        Self {
791            total_executed: 0,
792            successful_executions: 0,
793            failed_executions: 0,
794            cancelled_executions: 0,
795            avg_execution_time_seconds: 0.0,
796            min_execution_time_seconds: f64::MAX,
797            max_execution_time_seconds: 0.0,
798            success_rate_percent: 100.0,
799            avg_resource_consumption: AvgResourceConsumption::default(),
800            priority_distribution: HashMap::new(),
801            queue_wait_stats: QueueWaitStats::default(),
802        }
803    }
804
805    fn update(&mut self, update: TaskExecutionUpdate) {
806        self.total_executed += 1;
807        if update.success {
808            self.successful_executions += 1;
809        } else {
810            self.failed_executions += 1;
811        }
812
813        // Update timing statistics
814        self.min_execution_time_seconds =
815            self.min_execution_time_seconds.min(update.execution_time_seconds);
816        self.max_execution_time_seconds =
817            self.max_execution_time_seconds.max(update.execution_time_seconds);
818
819        // Update running average
820        let alpha = 0.1;
821        self.avg_execution_time_seconds =
822            alpha * update.execution_time_seconds + (1.0 - alpha) * self.avg_execution_time_seconds;
823
824        // Update success rate
825        self.success_rate_percent =
826            (self.successful_executions as f32 / self.total_executed as f32) * 100.0;
827
828        // Update priority distribution
829        *self.priority_distribution.entry(update.priority).or_insert(0) += 1;
830    }
831}
832
833impl Default for AvgResourceConsumption {
834    fn default() -> Self {
835        Self {
836            avg_cpu_percent: 0.0,
837            avg_memory_mb: 0.0,
838            avg_network_mb: 0.0,
839            avg_battery_mah: 0.0,
840            avg_execution_time_seconds: 0.0,
841        }
842    }
843}
844
845impl Default for QueueWaitStats {
846    fn default() -> Self {
847        Self {
848            avg_wait_time_seconds: 0.0,
849            min_wait_time_seconds: 0.0,
850            max_wait_time_seconds: 0.0,
851            p95_wait_time_seconds: 0.0,
852        }
853    }
854}
855
856impl ResourceUsageStats {
857    fn new() -> Self {
858        Self {
859            cpu_stats: UsageStats::new(),
860            memory_stats: UsageStats::new(),
861            network_stats: UsageStats::new(),
862            battery_stats: BatteryUsageStats::new(),
863            gpu_stats: None,
864            storage_stats: StorageStats::new(),
865            thermal_stats: ThermalStats::new(),
866        }
867    }
868
869    fn update(&mut self, cpu: f32, memory: f32, network: f32, battery: f32) {
870        self.cpu_stats.update(cpu);
871        self.memory_stats.update(memory);
872        self.network_stats.update(network);
873        self.battery_stats.update(battery);
874    }
875}
876
877impl UsageStats {
878    fn new() -> Self {
879        Self {
880            current: 0.0,
881            average: 0.0,
882            minimum: f32::MAX,
883            maximum: 0.0,
884            p95: 0.0,
885            std_deviation: 0.0,
886            sample_count: 0,
887        }
888    }
889
890    fn update(&mut self, value: f32) {
891        self.current = value;
892        self.minimum = self.minimum.min(value);
893        self.maximum = self.maximum.max(value);
894        self.sample_count += 1;
895
896        // Update running average
897        let alpha = 1.0 / self.sample_count as f32;
898        self.average = alpha * value + (1.0 - alpha) * self.average;
899    }
900}
901
902impl BatteryUsageStats {
903    fn new() -> Self {
904        Self {
905            current_level_percent: 100,
906            drain_rate_percent_per_hour: 0.0,
907            avg_battery_level_percent: 100.0,
908            time_since_last_charge_hours: 0.0,
909            charging_cycles: 0,
910            low_battery_events: 0,
911            critical_battery_events: 0,
912        }
913    }
914
915    fn update(&mut self, battery_level: f32) {
916        self.current_level_percent = battery_level as u8;
917
918        // Update running average
919        let alpha = 0.1;
920        self.avg_battery_level_percent =
921            alpha * battery_level + (1.0 - alpha) * self.avg_battery_level_percent;
922    }
923}
924
925impl StorageStats {
926    fn new() -> Self {
927        Self {
928            read_operations: 0,
929            write_operations: 0,
930            bytes_read: 0,
931            bytes_written: 0,
932            avg_read_speed_mbps: 0.0,
933            avg_write_speed_mbps: 0.0,
934            storage_usage_mb: 0,
935            available_storage_mb: 1000, // Default value
936        }
937    }
938}
939
940impl ThermalStats {
941    fn new() -> Self {
942        Self {
943            current_temperature_celsius: 25.0,
944            avg_temperature_celsius: 25.0,
945            max_temperature_celsius: 25.0,
946            thermal_events: 0,
947            throttling_events: 0,
948            time_in_thermal_warning_seconds: 0,
949            temperature_trend: TemperatureTrend::Stable,
950        }
951    }
952}
953
954impl PerformanceStats {
955    fn new() -> Self {
956        Self {
957            inference_stats: InferencePerformanceStats::new(),
958            memory_performance_stats: MemoryPerformanceStats::new(),
959            network_performance_stats: NetworkPerformanceStats::new(),
960            overall_performance_score: 100.0,
961            performance_degradation_events: 0,
962            performance_optimization_events: 0,
963        }
964    }
965
966    fn update_inference_stats(&mut self, inference_time: f32, accuracy: f32, throughput: f32) {
967        self.inference_stats.update(inference_time, accuracy, throughput);
968    }
969}
970
971impl InferencePerformanceStats {
972    fn new() -> Self {
973        Self {
974            total_inferences: 0,
975            avg_inference_time_ms: 0.0,
976            throughput_per_second: 0.0,
977            accuracy_stats: AccuracyStats::new(),
978            model_loading_stats: ModelLoadingStats::new(),
979            queue_backlog_stats: QueueBacklogStats::new(),
980        }
981    }
982
983    fn update(&mut self, inference_time: f32, accuracy: f32, throughput: f32) {
984        self.total_inferences += 1;
985
986        // Update running averages
987        let alpha = 0.1;
988        self.avg_inference_time_ms =
989            alpha * inference_time + (1.0 - alpha) * self.avg_inference_time_ms;
990        self.throughput_per_second =
991            alpha * throughput + (1.0 - alpha) * self.throughput_per_second;
992
993        self.accuracy_stats.update(accuracy);
994    }
995}
996
997impl AccuracyStats {
998    fn new() -> Self {
999        Self {
1000            avg_accuracy_score: 100.0,
1001            accuracy_trend: AccuracyTrend::Stable,
1002            model_drift_events: 0,
1003            accuracy_degradation_events: 0,
1004        }
1005    }
1006
1007    fn update(&mut self, accuracy: f32) {
1008        let alpha = 0.1;
1009        self.avg_accuracy_score = alpha * accuracy + (1.0 - alpha) * self.avg_accuracy_score;
1010    }
1011}
1012
1013impl ModelLoadingStats {
1014    fn new() -> Self {
1015        Self {
1016            total_loads: 0,
1017            avg_loading_time_seconds: 0.0,
1018            cache_hit_rate_percent: 100.0,
1019            failed_loads: 0,
1020            loaded_models_memory_mb: 0,
1021        }
1022    }
1023}
1024
1025impl QueueBacklogStats {
1026    fn new() -> Self {
1027        Self {
1028            current_queue_size: 0,
1029            avg_queue_size: 0.0,
1030            max_queue_size: 0,
1031            queue_overflow_events: 0,
1032            avg_processing_time_ms: 0.0,
1033        }
1034    }
1035}
1036
1037impl MemoryPerformanceStats {
1038    fn new() -> Self {
1039        Self {
1040            allocation_rate_mbps: 0.0,
1041            deallocation_rate_mbps: 0.0,
1042            gc_events: 0,
1043            avg_gc_pause_time_ms: 0.0,
1044            fragmentation_percent: 0.0,
1045            oom_events: 0,
1046            memory_pressure_events: 0,
1047        }
1048    }
1049}
1050
1051impl NetworkPerformanceStats {
1052    fn new() -> Self {
1053        Self {
1054            transfer_rate_mbps: 0.0,
1055            connection_success_rate_percent: 100.0,
1056            avg_latency_ms: 0.0,
1057            timeout_events: 0,
1058            retry_events: 0,
1059            data_usage: DataUsageStats::new(),
1060        }
1061    }
1062}
1063
1064impl DataUsageStats {
1065    fn new() -> Self {
1066        Self {
1067            total_sent_mb: 0.0,
1068            total_received_mb: 0.0,
1069            usage_by_task_type: HashMap::new(),
1070            peak_bandwidth_mbps: 0.0,
1071        }
1072    }
1073}
1074
1075impl ErrorStats {
1076    fn new() -> Self {
1077        Self {
1078            total_errors: 0,
1079            errors_by_category: HashMap::new(),
1080            errors_by_severity: HashMap::new(),
1081            recent_error_patterns: Vec::new(),
1082            error_rate_per_hour: 0.0,
1083            error_resolution_stats: ErrorResolutionStats::new(),
1084        }
1085    }
1086
1087    fn record_error(&mut self, severity: ErrorSeverity, category: String, _message: String) {
1088        self.total_errors += 1;
1089        *self.errors_by_category.entry(category).or_insert(0) += 1;
1090        *self.errors_by_severity.entry(severity).or_insert(0) += 1;
1091    }
1092}
1093
1094impl ErrorResolutionStats {
1095    fn new() -> Self {
1096        Self {
1097            auto_resolved_errors: 0,
1098            manually_resolved_errors: 0,
1099            unresolved_errors: 0,
1100            avg_resolution_time_minutes: 0.0,
1101            resolution_success_rate_percent: 100.0,
1102        }
1103    }
1104}
1105
1106impl UserInteractionStats {
1107    fn new() -> Self {
1108        Self {
1109            total_interactions: 0,
1110            interactions_by_type: HashMap::new(),
1111            avg_session_duration_minutes: 0.0,
1112            engagement_score: 100.0,
1113            feature_usage_stats: FeatureUsageStats::new(),
1114            satisfaction_metrics: UserSatisfactionMetrics::new(),
1115        }
1116    }
1117
1118    fn record_interaction(&mut self, interaction_type: String, _duration: u64) {
1119        self.total_interactions += 1;
1120        *self.interactions_by_type.entry(interaction_type).or_insert(0) += 1;
1121    }
1122}
1123
1124impl FeatureUsageStats {
1125    fn new() -> Self {
1126        Self {
1127            feature_usage_counts: HashMap::new(),
1128            popularity_ranking: Vec::new(),
1129            unused_features: Vec::new(),
1130            adoption_rate_percent: 100.0,
1131        }
1132    }
1133}
1134
1135impl UserSatisfactionMetrics {
1136    fn new() -> Self {
1137        Self {
1138            overall_satisfaction_score: 100.0,
1139            performance_satisfaction_score: 100.0,
1140            feedback_count: 0,
1141            positive_feedback_percent: 100.0,
1142            user_experienced_crashes: 0,
1143        }
1144    }
1145}
1146
1147impl SystemHealthStats {
1148    fn new() -> Self {
1149        Self {
1150            overall_health_score: 100.0,
1151            component_health_scores: HashMap::new(),
1152            health_trend: HealthTrend::Excellent,
1153            critical_issues_count: 0,
1154            warning_issues_count: 0,
1155            system_uptime_hours: 0.0,
1156            stability_metrics: StabilityMetrics::new(),
1157        }
1158    }
1159
1160    fn update_component_health(&mut self, component: String, health_score: f32) {
1161        self.component_health_scores.insert(component, health_score);
1162
1163        // Recalculate overall health score
1164        if !self.component_health_scores.is_empty() {
1165            let total_score: f32 = self.component_health_scores.values().sum();
1166            self.overall_health_score = total_score / self.component_health_scores.len() as f32;
1167        }
1168    }
1169}
1170
1171impl StabilityMetrics {
1172    fn new() -> Self {
1173        Self {
1174            crash_free_sessions_percent: 100.0,
1175            mtbf_hours: 24.0,
1176            availability_percent: 100.0,
1177            recovery_time_stats: RecoveryTimeStats::new(),
1178        }
1179    }
1180}
1181
1182impl RecoveryTimeStats {
1183    fn new() -> Self {
1184        Self {
1185            avg_recovery_time_minutes: 0.0,
1186            fastest_recovery_minutes: 0.0,
1187            slowest_recovery_minutes: 0.0,
1188            successful_recoveries: 0,
1189            failed_recovery_attempts: 0,
1190        }
1191    }
1192}
1193
1194impl Default for LifecycleStats {
1195    fn default() -> Self {
1196        Self::new()
1197    }
1198}