1use crate::lifecycle::config::{TaskPriority, TaskType};
7use crate::lifecycle::state::AppState;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct LifecycleStats {
14 pub start_timestamp: u64,
16 pub app_state_stats: AppStateStats,
18 pub task_execution_stats: HashMap<TaskType, TaskExecutionStats>,
20 pub resource_usage_stats: ResourceUsageStats,
22 pub performance_stats: PerformanceStats,
24 pub error_stats: ErrorStats,
26 pub user_interaction_stats: UserInteractionStats,
28 pub system_health_stats: SystemHealthStats,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct AppStateStats {
35 pub time_in_state: HashMap<AppState, u64>,
37 pub transition_counts: HashMap<String, u32>, pub avg_transition_interval_seconds: f64,
41 pub total_transitions: u64,
43 pub last_state_change_timestamp: u64,
45 pub state_change_frequency_per_hour: f32,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct TaskExecutionStats {
52 pub total_executed: u64,
54 pub successful_executions: u64,
56 pub failed_executions: u64,
58 pub cancelled_executions: u64,
60 pub avg_execution_time_seconds: f64,
62 pub min_execution_time_seconds: f64,
64 pub max_execution_time_seconds: f64,
66 pub success_rate_percent: f32,
68 pub avg_resource_consumption: AvgResourceConsumption,
70 pub priority_distribution: HashMap<TaskPriority, u32>,
72 pub queue_wait_stats: QueueWaitStats,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct AvgResourceConsumption {
79 pub avg_cpu_percent: f32,
81 pub avg_memory_mb: f32,
83 pub avg_network_mb: f32,
85 pub avg_battery_mah: f32,
87 pub avg_execution_time_seconds: f32,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct QueueWaitStats {
94 pub avg_wait_time_seconds: f64,
96 pub min_wait_time_seconds: f64,
98 pub max_wait_time_seconds: f64,
100 pub p95_wait_time_seconds: f64,
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct ResourceUsageStats {
107 pub cpu_stats: UsageStats,
109 pub memory_stats: UsageStats,
111 pub network_stats: UsageStats,
113 pub battery_stats: BatteryUsageStats,
115 pub gpu_stats: Option<UsageStats>,
117 pub storage_stats: StorageStats,
119 pub thermal_stats: ThermalStats,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct UsageStats {
126 pub current: f32,
128 pub average: f32,
130 pub minimum: f32,
132 pub maximum: f32,
134 pub p95: f32,
136 pub std_deviation: f32,
138 pub sample_count: u64,
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct BatteryUsageStats {
145 pub current_level_percent: u8,
147 pub drain_rate_percent_per_hour: f32,
149 pub avg_battery_level_percent: f32,
151 pub time_since_last_charge_hours: f32,
153 pub charging_cycles: u32,
155 pub low_battery_events: u32,
157 pub critical_battery_events: u32,
159}
160
161#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct StorageStats {
164 pub read_operations: u64,
166 pub write_operations: u64,
168 pub bytes_read: u64,
170 pub bytes_written: u64,
172 pub avg_read_speed_mbps: f32,
174 pub avg_write_speed_mbps: f32,
176 pub storage_usage_mb: u64,
178 pub available_storage_mb: u64,
180}
181
182#[derive(Debug, Clone, Serialize, Deserialize)]
184pub struct ThermalStats {
185 pub current_temperature_celsius: f32,
187 pub avg_temperature_celsius: f32,
189 pub max_temperature_celsius: f32,
191 pub thermal_events: u32,
193 pub throttling_events: u32,
195 pub time_in_thermal_warning_seconds: u64,
197 pub temperature_trend: TemperatureTrend,
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203pub enum TemperatureTrend {
204 Stable,
205 Rising,
206 Falling,
207 Oscillating,
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct PerformanceStats {
213 pub inference_stats: InferencePerformanceStats,
215 pub memory_performance_stats: MemoryPerformanceStats,
217 pub network_performance_stats: NetworkPerformanceStats,
219 pub overall_performance_score: f32,
221 pub performance_degradation_events: u32,
223 pub performance_optimization_events: u32,
225}
226
227#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct InferencePerformanceStats {
230 pub total_inferences: u64,
232 pub avg_inference_time_ms: f32,
234 pub throughput_per_second: f32,
236 pub accuracy_stats: AccuracyStats,
238 pub model_loading_stats: ModelLoadingStats,
240 pub queue_backlog_stats: QueueBacklogStats,
242}
243
244#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct AccuracyStats {
247 pub avg_accuracy_score: f32,
249 pub accuracy_trend: AccuracyTrend,
251 pub model_drift_events: u32,
253 pub accuracy_degradation_events: u32,
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
259pub enum AccuracyTrend {
260 Stable,
261 Improving,
262 Degrading,
263 Fluctuating,
264}
265
266#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct ModelLoadingStats {
269 pub total_loads: u32,
271 pub avg_loading_time_seconds: f32,
273 pub cache_hit_rate_percent: f32,
275 pub failed_loads: u32,
277 pub loaded_models_memory_mb: usize,
279}
280
281#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct QueueBacklogStats {
284 pub current_queue_size: usize,
286 pub avg_queue_size: f32,
288 pub max_queue_size: usize,
290 pub queue_overflow_events: u32,
292 pub avg_processing_time_ms: f32,
294}
295
296#[derive(Debug, Clone, Serialize, Deserialize)]
298pub struct MemoryPerformanceStats {
299 pub allocation_rate_mbps: f32,
301 pub deallocation_rate_mbps: f32,
303 pub gc_events: u32,
305 pub avg_gc_pause_time_ms: f32,
307 pub fragmentation_percent: f32,
309 pub oom_events: u32,
311 pub memory_pressure_events: u32,
313}
314
315#[derive(Debug, Clone, Serialize, Deserialize)]
317pub struct NetworkPerformanceStats {
318 pub transfer_rate_mbps: f32,
320 pub connection_success_rate_percent: f32,
322 pub avg_latency_ms: f32,
324 pub timeout_events: u32,
326 pub retry_events: u32,
328 pub data_usage: DataUsageStats,
330}
331
332#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct DataUsageStats {
335 pub total_sent_mb: f32,
337 pub total_received_mb: f32,
339 pub usage_by_task_type: HashMap<TaskType, f32>,
341 pub peak_bandwidth_mbps: f32,
343}
344
345#[derive(Debug, Clone, Serialize, Deserialize)]
347pub struct ErrorStats {
348 pub total_errors: u64,
350 pub errors_by_category: HashMap<String, u32>,
352 pub errors_by_severity: HashMap<ErrorSeverity, u32>,
354 pub recent_error_patterns: Vec<ErrorPattern>,
356 pub error_rate_per_hour: f32,
358 pub error_resolution_stats: ErrorResolutionStats,
360}
361
362#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
364pub enum ErrorSeverity {
365 Low,
366 Medium,
367 High,
368 Critical,
369}
370
371#[derive(Debug, Clone, Serialize, Deserialize)]
373pub struct ErrorPattern {
374 pub pattern_id: String,
376 pub message_pattern: String,
378 pub occurrence_count: u32,
380 pub first_occurrence_timestamp: u64,
382 pub last_occurrence_timestamp: u64,
384 pub affected_components: Vec<String>,
386}
387
388#[derive(Debug, Clone, Serialize, Deserialize)]
390pub struct ErrorResolutionStats {
391 pub auto_resolved_errors: u32,
393 pub manually_resolved_errors: u32,
395 pub unresolved_errors: u32,
397 pub avg_resolution_time_minutes: f32,
399 pub resolution_success_rate_percent: f32,
401}
402
403#[derive(Debug, Clone, Serialize, Deserialize)]
405pub struct UserInteractionStats {
406 pub total_interactions: u64,
408 pub interactions_by_type: HashMap<String, u32>,
410 pub avg_session_duration_minutes: f32,
412 pub engagement_score: f32,
414 pub feature_usage_stats: FeatureUsageStats,
416 pub satisfaction_metrics: UserSatisfactionMetrics,
418}
419
420#[derive(Debug, Clone, Serialize, Deserialize)]
422pub struct FeatureUsageStats {
423 pub feature_usage_counts: HashMap<String, u32>,
425 pub popularity_ranking: Vec<String>,
427 pub unused_features: Vec<String>,
429 pub adoption_rate_percent: f32,
431}
432
433#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct UserSatisfactionMetrics {
436 pub overall_satisfaction_score: f32,
438 pub performance_satisfaction_score: f32,
440 pub feedback_count: u32,
442 pub positive_feedback_percent: f32,
444 pub user_experienced_crashes: u32,
446}
447
448#[derive(Debug, Clone, Serialize, Deserialize)]
450pub struct SystemHealthStats {
451 pub overall_health_score: f32,
453 pub component_health_scores: HashMap<String, f32>,
455 pub health_trend: HealthTrend,
457 pub critical_issues_count: u32,
459 pub warning_issues_count: u32,
461 pub system_uptime_hours: f32,
463 pub stability_metrics: StabilityMetrics,
465}
466
467#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
469pub enum HealthTrend {
470 Excellent,
471 Good,
472 Fair,
473 Poor,
474 Critical,
475}
476
477#[derive(Debug, Clone, Serialize, Deserialize)]
479pub struct StabilityMetrics {
480 pub crash_free_sessions_percent: f32,
482 pub mtbf_hours: f32,
484 pub availability_percent: f32,
486 pub recovery_time_stats: RecoveryTimeStats,
488}
489
490#[derive(Debug, Clone, Serialize, Deserialize)]
492pub struct RecoveryTimeStats {
493 pub avg_recovery_time_minutes: f32,
495 pub fastest_recovery_minutes: f32,
497 pub slowest_recovery_minutes: f32,
499 pub successful_recoveries: u32,
501 pub failed_recovery_attempts: u32,
503}
504
505impl LifecycleStats {
506 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 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 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 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 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 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 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 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#[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#[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#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
760pub enum MetricTrend {
761 Improving,
762 Stable,
763 Degrading,
764 Volatile,
765}
766
767impl 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 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 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 self.success_rate_percent =
826 (self.successful_executions as f32 / self.total_executed as f32) * 100.0;
827
828 *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 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 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, }
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 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 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}