1use std::collections::HashMap;
7use std::time::{Duration, Instant};
8
9#[derive(Debug)]
11pub struct AdvancedScirS2Features {
12 pub ml_models: HashMap<String, MLModel>,
14
15 pub predictive_engine: PredictiveAllocationEngine,
17
18 pub auto_optimization: AutoOptimizationSystem,
20
21 pub anomaly_detector: AnomalyDetector,
23}
24
25#[derive(Debug, Clone)]
27pub struct MLModel {
28 pub model_id: String,
30
31 pub model_type: String,
33
34 pub accuracy: f64,
36
37 pub last_training: Instant,
39
40 pub training_samples: usize,
42
43 pub parameters: ModelParameters,
45
46 pub state: ModelState,
48}
49
50#[derive(Debug, Clone)]
52pub struct ModelParameters {
53 pub weights: Vec<f64>,
55
56 pub bias: f64,
58
59 pub learning_rate: f64,
61
62 pub regularization: f64,
64}
65
66#[derive(Debug, Clone, PartialEq)]
68pub enum ModelState {
69 Untrained,
70 Training,
71 Trained,
72 Deprecated,
73}
74
75#[derive(Debug)]
77pub struct PredictiveAllocationEngine {
78 pub enabled: bool,
80
81 pub prediction_horizon: Duration,
83
84 pub model_accuracy: f64,
86
87 prediction_history: Vec<AllocationPrediction>,
89
90 feature_extractors: Vec<FeatureExtractor>,
92
93 prediction_cache: HashMap<String, CachedPrediction>,
95}
96
97#[derive(Debug, Clone)]
99pub struct AllocationPrediction {
100 pub timestamp: Instant,
102
103 pub size: usize,
105
106 pub confidence: f64,
108
109 pub allocator: String,
111
112 pub features: Vec<f64>,
114
115 pub actual_outcome: Option<AllocationOutcome>,
117}
118
119#[derive(Debug, Clone)]
121pub struct AllocationOutcome {
122 pub actual_size: usize,
124
125 pub actual_allocator: String,
127
128 pub timestamp: Instant,
130
131 pub success: bool,
133}
134
135#[derive(Debug, Clone)]
137pub struct FeatureExtractor {
138 pub name: String,
140
141 pub dimensions: usize,
143
144 pub extractor_type: FeatureType,
146
147 pub last_extraction: Instant,
149}
150
151#[derive(Debug, Clone)]
153pub enum FeatureType {
154 Temporal,
156 Statistical,
158 Pattern,
160 SystemState,
162}
163
164#[derive(Debug, Clone)]
166pub struct CachedPrediction {
167 pub prediction: AllocationPrediction,
169
170 pub cached_at: Instant,
172
173 pub expires_at: Instant,
175
176 pub hit_count: u32,
178}
179
180#[derive(Debug)]
182pub struct AutoOptimizationSystem {
183 pub enabled: bool,
185
186 pub optimization_queue: Vec<OptimizationTask>,
188
189 pub last_optimization: Option<Instant>,
191
192 strategies: Vec<OptimizationStrategy>,
194
195 history: Vec<OptimizationResult>,
197}
198
199#[derive(Debug, Clone)]
201pub struct OptimizationTask {
202 pub task_id: String,
204
205 pub task_type: String,
207
208 pub priority: u32,
210
211 pub estimated_benefit: f64,
213
214 pub created_at: Instant,
216
217 pub target_component: String,
219
220 pub parameters: HashMap<String, String>,
222
223 pub dependencies: Vec<String>,
225}
226
227#[derive(Debug, Clone)]
229pub struct OptimizationStrategy {
230 pub name: String,
232
233 pub strategy_type: StrategyType,
235
236 pub conditions: Vec<OptimizationCondition>,
238
239 pub expected_impact: f64,
241
242 pub complexity: OptimizationComplexity,
244}
245
246#[derive(Debug, Clone)]
248pub enum StrategyType {
249 CacheOptimization,
251 FragmentationReduction,
253 AllocationOptimization,
255 ContentionReduction,
257 ParameterTuning,
259}
260
261#[derive(Debug, Clone)]
263pub struct OptimizationCondition {
264 pub description: String,
266
267 pub metric: String,
269
270 pub threshold: f64,
272
273 pub operator: ComparisonOperator,
275}
276
277#[derive(Debug, Clone)]
279pub enum ComparisonOperator {
280 GreaterThan,
281 LessThan,
282 Equal,
283 NotEqual,
284 Between(f64, f64),
285}
286
287#[derive(Debug, Clone, PartialEq, PartialOrd)]
289pub enum OptimizationComplexity {
290 Low,
291 Medium,
292 High,
293 Expert,
294}
295
296#[derive(Debug, Clone)]
298pub struct OptimizationResult {
299 pub timestamp: Instant,
301
302 pub task_id: String,
304
305 pub optimization_type: String,
307
308 pub success: bool,
310
311 pub performance_improvement: f64,
313
314 pub duration: Duration,
316
317 pub resource_cost: f64,
319
320 pub error_message: Option<String>,
322}
323
324#[derive(Debug)]
326pub struct AnomalyDetector {
327 pub enabled: bool,
329
330 pub sensitivity: f64,
332
333 pub detected_anomalies: u64,
335
336 detection_models: Vec<AnomalyModel>,
338
339 anomaly_history: Vec<DetectedAnomaly>,
341
342 baseline_metrics: HashMap<String, BaselineMetric>,
344}
345
346#[derive(Debug, Clone)]
348pub struct AnomalyModel {
349 pub name: String,
351
352 pub model_type: AnomalyModelType,
354
355 pub threshold: f64,
357
358 pub parameters: AnomalyModelParameters,
360
361 pub last_update: Instant,
363}
364
365#[derive(Debug, Clone)]
367pub enum AnomalyModelType {
368 StatisticalOutlier,
370 IsolationForest,
372 LocalOutlierFactor,
374 OneClassSVM,
376 Autoencoder,
378}
379
380#[derive(Debug, Clone)]
382pub struct AnomalyModelParameters {
383 pub window_size: usize,
385
386 pub custom_params: HashMap<String, f64>,
388}
389
390#[derive(Debug, Clone)]
392pub struct DetectedAnomaly {
393 pub timestamp: Instant,
395
396 pub anomaly_type: AnomalyType,
398
399 pub metric_name: String,
401
402 pub score: f64,
404
405 pub expected_value: f64,
407
408 pub actual_value: f64,
410
411 pub confidence: f64,
413
414 pub suggested_action: Option<String>,
416}
417
418#[derive(Debug, Clone)]
420pub enum AnomalyType {
421 HighOutlier,
423 LowOutlier,
425 PatternAnomaly,
427 BehaviorChange,
429 PerformanceDegradation,
431}
432
433#[derive(Debug, Clone)]
435pub struct BaselineMetric {
436 pub name: String,
438
439 pub mean: f64,
441
442 pub std_dev: f64,
444
445 pub min_value: f64,
447
448 pub max_value: f64,
450
451 pub sample_count: usize,
453
454 pub last_update: Instant,
456}
457
458#[derive(Debug)]
460pub struct ScirS2OptimizationEngine {
461 pub optimization_history: Vec<OptimizationResult>,
463
464 pub active_optimizations: HashMap<String, ActiveOptimization>,
466
467 pub optimization_metrics: OptimizationMetrics,
469
470 pub config: OptimizationConfig,
472
473 pub baselines: HashMap<String, PerformanceBaseline>,
475}
476
477#[derive(Debug, Clone)]
479pub struct ActiveOptimization {
480 pub id: String,
482
483 pub start_time: Instant,
485
486 pub target: String,
488
489 pub expected_completion: Instant,
491
492 pub progress: f64,
494
495 pub strategy: OptimizationStrategy,
497
498 pub intermediate_results: Vec<IntermediateResult>,
500}
501
502#[derive(Debug, Clone)]
504pub struct IntermediateResult {
505 pub timestamp: Instant,
507
508 pub progress: f64,
510
511 pub metrics: HashMap<String, f64>,
513
514 pub status: String,
516}
517
518#[derive(Debug, Clone)]
520pub struct OptimizationMetrics {
521 pub total_optimizations: u64,
523
524 pub successful_optimizations: u64,
526
527 pub average_improvement: f64,
529
530 pub optimization_efficiency: f64,
532
533 pub total_optimization_time: Duration,
535}
536
537#[derive(Debug, Clone)]
539pub struct OptimizationConfig {
540 pub auto_optimize: bool,
542
543 pub aggressiveness: f64,
545
546 pub max_concurrent: usize,
548
549 pub timeout: Duration,
551
552 pub min_improvement: f64,
554}
555
556#[derive(Debug, Clone)]
558pub struct PerformanceBaseline {
559 pub name: String,
561
562 pub metrics: HashMap<String, f64>,
564
565 pub established_at: Instant,
567
568 pub confidence: f64,
570}
571
572impl AdvancedScirS2Features {
573 pub fn new() -> Self {
575 Self {
576 ml_models: HashMap::new(),
577 predictive_engine: PredictiveAllocationEngine::new(),
578 auto_optimization: AutoOptimizationSystem::new(),
579 anomaly_detector: AnomalyDetector::new(),
580 }
581 }
582
583 pub fn initialize_ml_models(&mut self) {
585 let allocation_model = MLModel {
587 model_id: "allocation_predictor".to_string(),
588 model_type: "neural_network".to_string(),
589 accuracy: 0.0,
590 last_training: Instant::now(),
591 training_samples: 0,
592 parameters: ModelParameters {
593 weights: vec![0.0; 10], bias: 0.0,
595 learning_rate: 0.01,
596 regularization: 0.001,
597 },
598 state: ModelState::Untrained,
599 };
600
601 self.ml_models
602 .insert("allocation_predictor".to_string(), allocation_model);
603
604 let performance_model = MLModel {
606 model_id: "performance_optimizer".to_string(),
607 model_type: "decision_tree".to_string(),
608 accuracy: 0.0,
609 last_training: Instant::now(),
610 training_samples: 0,
611 parameters: ModelParameters {
612 weights: vec![0.0; 5],
613 bias: 0.0,
614 learning_rate: 0.05,
615 regularization: 0.0,
616 },
617 state: ModelState::Untrained,
618 };
619
620 self.ml_models
621 .insert("performance_optimizer".to_string(), performance_model);
622 }
623
624 pub fn train_model(
626 &mut self,
627 model_id: &str,
628 training_data: &[TrainingExample],
629 ) -> Result<(), String> {
630 if let Some(model) = self.ml_models.get_mut(model_id) {
631 model.state = ModelState::Training;
632
633 let improvement = Self::simulate_training(model, training_data);
635
636 model.accuracy = improvement;
637 model.training_samples = training_data.len();
638 model.last_training = Instant::now();
639 model.state = ModelState::Trained;
640
641 Ok(())
642 } else {
643 Err(format!("Model '{}' not found", model_id))
644 }
645 }
646
647 pub fn predict(&self, model_id: &str, features: &[f64]) -> Option<ModelPrediction> {
649 if let Some(model) = self.ml_models.get(model_id) {
650 if model.state != ModelState::Trained {
651 return None;
652 }
653
654 let prediction_value = self.compute_prediction(model, features);
656 let confidence = model.accuracy;
657
658 Some(ModelPrediction {
659 value: prediction_value,
660 confidence,
661 model_id: model_id.to_string(),
662 timestamp: Instant::now(),
663 })
664 } else {
665 None
666 }
667 }
668
669 fn simulate_training(model: &mut MLModel, training_data: &[TrainingExample]) -> f64 {
672 let data_quality = if training_data.len() > 100 { 0.8 } else { 0.5 };
674 let model_complexity = match model.model_type.as_str() {
675 "linear_regression" => 0.6,
676 "neural_network" => 0.8,
677 "decision_tree" => 0.7,
678 _ => 0.5,
679 };
680
681 (data_quality + model_complexity) / 2.0
682 }
683
684 fn compute_prediction(&self, model: &MLModel, features: &[f64]) -> f64 {
685 let prediction = features
687 .iter()
688 .zip(model.parameters.weights.iter())
689 .map(|(f, w)| f * w)
690 .sum::<f64>()
691 + model.parameters.bias;
692
693 prediction
694 }
695}
696
697impl PredictiveAllocationEngine {
698 pub fn new() -> Self {
700 Self {
701 enabled: false,
702 prediction_horizon: Duration::from_secs(60),
703 model_accuracy: 0.0,
704 prediction_history: Vec::new(),
705 feature_extractors: Vec::new(),
706 prediction_cache: HashMap::new(),
707 }
708 }
709
710 pub fn enable(&mut self) {
712 self.enabled = true;
713 self.initialize_feature_extractors();
714 }
715
716 pub fn predict_allocation(
718 &mut self,
719 context: &AllocationContext,
720 ) -> Option<AllocationPrediction> {
721 if !self.enabled {
722 return None;
723 }
724
725 let features = self.extract_features(context);
727
728 let prediction = AllocationPrediction {
730 timestamp: Instant::now(),
731 size: self.predict_size(&features),
732 confidence: self.model_accuracy,
733 allocator: self.predict_allocator(&features),
734 features,
735 actual_outcome: None,
736 };
737
738 let cache_key = format!("{}_{}", prediction.allocator, prediction.size);
740 self.prediction_cache.insert(
741 cache_key,
742 CachedPrediction {
743 prediction: prediction.clone(),
744 cached_at: Instant::now(),
745 expires_at: Instant::now() + self.prediction_horizon,
746 hit_count: 0,
747 },
748 );
749
750 self.prediction_history.push(prediction.clone());
752
753 if self.prediction_history.len() > 1000 {
755 self.prediction_history.remove(0);
756 }
757
758 Some(prediction)
759 }
760
761 pub fn update_accuracy(&mut self, prediction_id: usize, outcome: AllocationOutcome) {
763 if let Some(prediction) = self.prediction_history.get_mut(prediction_id) {
764 prediction.actual_outcome = Some(outcome.clone());
765
766 let prediction_error = (prediction.size as f64 - outcome.actual_size as f64).abs();
768 let relative_error = prediction_error / outcome.actual_size.max(1) as f64;
769 let accuracy = 1.0 - relative_error.min(1.0);
770
771 self.model_accuracy = (self.model_accuracy + accuracy) / 2.0;
773 }
774 }
775
776 pub fn get_prediction_stats(&self) -> PredictionStats {
778 let total_predictions = self.prediction_history.len();
779 let predictions_with_outcomes = self
780 .prediction_history
781 .iter()
782 .filter(|p| p.actual_outcome.is_some())
783 .count();
784
785 let accuracy_sum = self
786 .prediction_history
787 .iter()
788 .filter_map(|p| p.actual_outcome.as_ref())
789 .zip(self.prediction_history.iter())
790 .map(|(outcome, prediction)| {
791 let error = (prediction.size as f64 - outcome.actual_size as f64).abs();
792 1.0 - (error / outcome.actual_size.max(1) as f64).min(1.0)
793 })
794 .sum::<f64>();
795
796 let average_accuracy = if predictions_with_outcomes > 0 {
797 accuracy_sum / predictions_with_outcomes as f64
798 } else {
799 0.0
800 };
801
802 PredictionStats {
803 total_predictions,
804 validated_predictions: predictions_with_outcomes,
805 average_accuracy,
806 cache_hit_rate: self.calculate_cache_hit_rate(),
807 }
808 }
809
810 fn initialize_feature_extractors(&mut self) {
813 self.feature_extractors = vec![
814 FeatureExtractor {
815 name: "temporal".to_string(),
816 dimensions: 3,
817 extractor_type: FeatureType::Temporal,
818 last_extraction: Instant::now(),
819 },
820 FeatureExtractor {
821 name: "statistical".to_string(),
822 dimensions: 4,
823 extractor_type: FeatureType::Statistical,
824 last_extraction: Instant::now(),
825 },
826 FeatureExtractor {
827 name: "pattern".to_string(),
828 dimensions: 2,
829 extractor_type: FeatureType::Pattern,
830 last_extraction: Instant::now(),
831 },
832 ];
833 }
834
835 fn extract_features(&self, context: &AllocationContext) -> Vec<f64> {
836 let mut features = Vec::new();
837
838 for extractor in &self.feature_extractors {
839 match extractor.extractor_type {
840 FeatureType::Temporal => {
841 let now = Instant::now();
842 features.push(context.timestamp.elapsed().as_secs_f64());
843 features.push(
844 (now.duration_since(context.timestamp).as_secs_f64() % 86400.0) / 86400.0,
845 ); features.push(
847 (now.duration_since(context.timestamp).as_secs_f64() % (86400.0 * 7.0))
848 / (86400.0 * 7.0),
849 ); }
851 FeatureType::Statistical => {
852 features.push(
853 context.recent_allocation_sizes.iter().sum::<f64>()
854 / context.recent_allocation_sizes.len().max(1) as f64,
855 );
856 features.push(context.current_memory_pressure);
857 features.push(context.thread_count as f64);
858 features.push(context.available_memory as f64);
859 }
860 FeatureType::Pattern => {
861 features.push(context.allocation_frequency);
862 features.push(context.fragmentation_level);
863 }
864 FeatureType::SystemState => {
865 }
867 }
868 }
869
870 features
871 }
872
873 fn predict_size(&self, features: &[f64]) -> usize {
874 let base_size = features.get(0).unwrap_or(&1024.0);
876 (base_size * 1.2) as usize
877 }
878
879 fn predict_allocator(&self, features: &[f64]) -> String {
880 let memory_pressure = features.get(1).unwrap_or(&0.5);
882 if *memory_pressure > 0.7 {
883 "high_pressure_allocator".to_string()
884 } else {
885 "default_allocator".to_string()
886 }
887 }
888
889 fn calculate_cache_hit_rate(&self) -> f64 {
890 let total_hits: u32 = self.prediction_cache.values().map(|c| c.hit_count).sum();
891 let total_predictions = self.prediction_cache.len() as u32;
892
893 if total_predictions > 0 {
894 total_hits as f64 / total_predictions as f64
895 } else {
896 0.0
897 }
898 }
899}
900
901impl AutoOptimizationSystem {
902 pub fn new() -> Self {
904 Self {
905 enabled: false,
906 optimization_queue: Vec::new(),
907 last_optimization: None,
908 strategies: Vec::new(),
909 history: Vec::new(),
910 }
911 }
912
913 pub fn enable(&mut self) {
915 self.enabled = true;
916 self.initialize_strategies();
917 }
918
919 pub fn add_task(&mut self, task: OptimizationTask) {
921 self.optimization_queue.push(task);
922 self.optimization_queue
923 .sort_by_key(|t| std::cmp::Reverse(t.priority));
924 }
925
926 pub fn process_queue(&mut self) -> Vec<OptimizationResult> {
928 if !self.enabled || self.optimization_queue.is_empty() {
929 return Vec::new();
930 }
931
932 let mut results = Vec::new();
933 let max_concurrent = 3; for _ in 0..max_concurrent {
936 if let Some(task) = self.optimization_queue.pop() {
937 let result = self.execute_optimization_task(&task);
938 results.push(result);
939 } else {
940 break;
941 }
942 }
943
944 self.last_optimization = Some(Instant::now());
945 results
946 }
947
948 fn initialize_strategies(&mut self) {
951 self.strategies = vec![
952 OptimizationStrategy {
953 name: "Cache Optimization".to_string(),
954 strategy_type: StrategyType::CacheOptimization,
955 conditions: vec![OptimizationCondition {
956 description: "Low cache hit rate".to_string(),
957 metric: "cache_hit_rate".to_string(),
958 threshold: 0.8,
959 operator: ComparisonOperator::LessThan,
960 }],
961 expected_impact: 0.3,
962 complexity: OptimizationComplexity::Medium,
963 },
964 OptimizationStrategy {
965 name: "Fragmentation Reduction".to_string(),
966 strategy_type: StrategyType::FragmentationReduction,
967 conditions: vec![OptimizationCondition {
968 description: "High fragmentation level".to_string(),
969 metric: "fragmentation_level".to_string(),
970 threshold: 0.3,
971 operator: ComparisonOperator::GreaterThan,
972 }],
973 expected_impact: 0.4,
974 complexity: OptimizationComplexity::High,
975 },
976 ];
977 }
978
979 fn execute_optimization_task(&mut self, task: &OptimizationTask) -> OptimizationResult {
980 let start_time = Instant::now();
981
982 let success = task.estimated_benefit > 0.3; let improvement = if success { task.estimated_benefit } else { 0.0 };
985
986 let result = OptimizationResult {
987 timestamp: Instant::now(),
988 task_id: task.task_id.clone(),
989 optimization_type: task.task_type.clone(),
990 success,
991 performance_improvement: improvement,
992 duration: start_time.elapsed(),
993 resource_cost: task.estimated_benefit * 100.0, error_message: if success {
995 None
996 } else {
997 Some("Optimization failed to meet threshold".to_string())
998 },
999 };
1000
1001 self.history.push(result.clone());
1002 result
1003 }
1004}
1005
1006impl AnomalyDetector {
1007 pub fn new() -> Self {
1009 Self {
1010 enabled: false,
1011 sensitivity: 0.5,
1012 detected_anomalies: 0,
1013 detection_models: Vec::new(),
1014 anomaly_history: Vec::new(),
1015 baseline_metrics: HashMap::new(),
1016 }
1017 }
1018
1019 pub fn enable(&mut self, sensitivity: f64) {
1021 self.enabled = true;
1022 self.sensitivity = sensitivity.clamp(0.0, 1.0);
1023 self.initialize_detection_models();
1024 }
1025
1026 pub fn detect_anomalies(&mut self, metrics: &HashMap<String, f64>) -> Vec<DetectedAnomaly> {
1028 if !self.enabled {
1029 return Vec::new();
1030 }
1031
1032 let mut anomalies = Vec::new();
1033
1034 for (metric_name, &value) in metrics {
1035 if let Some(baseline) = self.baseline_metrics.get(metric_name) {
1036 if let Some(anomaly) = self.check_statistical_anomaly(metric_name, value, baseline)
1037 {
1038 anomalies.push(anomaly);
1039 self.detected_anomalies += 1;
1040 }
1041 } else {
1042 self.baseline_metrics.insert(
1044 metric_name.clone(),
1045 BaselineMetric {
1046 name: metric_name.clone(),
1047 mean: value,
1048 std_dev: 0.0,
1049 min_value: value,
1050 max_value: value,
1051 sample_count: 1,
1052 last_update: Instant::now(),
1053 },
1054 );
1055 }
1056 }
1057
1058 self.anomaly_history.extend(anomalies.clone());
1060 if self.anomaly_history.len() > 1000 {
1061 self.anomaly_history.truncate(1000);
1062 }
1063
1064 anomalies
1065 }
1066
1067 pub fn update_baselines(&mut self, metrics: &HashMap<String, f64>) {
1069 for (metric_name, &value) in metrics {
1070 if let Some(baseline) = self.baseline_metrics.get_mut(metric_name) {
1071 let new_count = baseline.sample_count + 1;
1073 let delta = value - baseline.mean;
1074 let new_mean = baseline.mean + delta / new_count as f64;
1075
1076 let delta2 = value - new_mean;
1077 let new_variance = (baseline.std_dev.powi(2) * (baseline.sample_count - 1) as f64
1078 + delta * delta2)
1079 / new_count as f64;
1080
1081 baseline.mean = new_mean;
1082 baseline.std_dev = new_variance.sqrt();
1083 baseline.min_value = baseline.min_value.min(value);
1084 baseline.max_value = baseline.max_value.max(value);
1085 baseline.sample_count = new_count;
1086 baseline.last_update = Instant::now();
1087 }
1088 }
1089 }
1090
1091 fn initialize_detection_models(&mut self) {
1094 self.detection_models = vec![AnomalyModel {
1095 name: "Statistical Outlier".to_string(),
1096 model_type: AnomalyModelType::StatisticalOutlier,
1097 threshold: 3.0, parameters: AnomalyModelParameters {
1099 window_size: 100,
1100 custom_params: HashMap::new(),
1101 },
1102 last_update: Instant::now(),
1103 }];
1104 }
1105
1106 fn check_statistical_anomaly(
1107 &self,
1108 metric_name: &str,
1109 value: f64,
1110 baseline: &BaselineMetric,
1111 ) -> Option<DetectedAnomaly> {
1112 if baseline.sample_count < 10 || baseline.std_dev == 0.0 {
1113 return None; }
1115
1116 let z_score = (value - baseline.mean).abs() / baseline.std_dev;
1117 let threshold = 3.0 * self.sensitivity; if z_score > threshold {
1120 let anomaly_type = if value > baseline.mean {
1121 AnomalyType::HighOutlier
1122 } else {
1123 AnomalyType::LowOutlier
1124 };
1125
1126 Some(DetectedAnomaly {
1127 timestamp: Instant::now(),
1128 anomaly_type,
1129 metric_name: metric_name.to_string(),
1130 score: z_score,
1131 expected_value: baseline.mean,
1132 actual_value: value,
1133 confidence: (z_score / (threshold + 1.0)).min(1.0),
1134 suggested_action: Some(format!("Investigate {} metric", metric_name)),
1135 })
1136 } else {
1137 None
1138 }
1139 }
1140}
1141
1142#[derive(Debug, Clone)]
1146pub struct TrainingExample {
1147 pub features: Vec<f64>,
1148 pub target: f64,
1149 pub weight: f64,
1150}
1151
1152#[derive(Debug, Clone)]
1154pub struct ModelPrediction {
1155 pub value: f64,
1156 pub confidence: f64,
1157 pub model_id: String,
1158 pub timestamp: Instant,
1159}
1160
1161#[derive(Debug, Clone)]
1163pub struct AllocationContext {
1164 pub timestamp: Instant,
1165 pub thread_count: usize,
1166 pub available_memory: usize,
1167 pub current_memory_pressure: f64,
1168 pub recent_allocation_sizes: Vec<f64>,
1169 pub allocation_frequency: f64,
1170 pub fragmentation_level: f64,
1171}
1172
1173#[derive(Debug, Clone)]
1175pub struct PredictionStats {
1176 pub total_predictions: usize,
1177 pub validated_predictions: usize,
1178 pub average_accuracy: f64,
1179 pub cache_hit_rate: f64,
1180}
1181
1182impl Default for OptimizationConfig {
1183 fn default() -> Self {
1184 Self {
1185 auto_optimize: false,
1186 aggressiveness: 0.5,
1187 max_concurrent: 2,
1188 timeout: Duration::from_secs(300),
1189 min_improvement: 0.1,
1190 }
1191 }
1192}