torsh-backend 0.1.2

Backend abstraction layer for ToRSh
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! Performance Tuning Coordination
//!
//! This module contains the main coordination logic for the performance tuning system,
//! including the PerformanceTuningCoordinator implementation and supporting components
//! for global monitoring, workload classification, adaptive control, and optimization caching.

use super::strategies::{
    CpuTuningStrategy, CudaTuningStrategy, MetalTuningStrategy, WebGpuTuningStrategy,
};
use super::types::*;
use crate::backend::BackendType;
use crate::error::BackendResult;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};
use torsh_core::error::TorshError;

// ================================================================================================
// PerformanceTuningCoordinator Implementation
// ================================================================================================

impl PerformanceTuningCoordinator {
    /// Create a new performance tuning coordinator
    pub fn new() -> BackendResult<Self> {
        let mut strategies = HashMap::new();

        // Initialize backend-specific strategies
        strategies.insert(
            BackendType::Cpu,
            Box::new(CpuTuningStrategy::new()?) as Box<dyn BackendTuningStrategy + Send + Sync>,
        );
        strategies.insert(
            BackendType::Cuda,
            Box::new(CudaTuningStrategy::new()?) as Box<dyn BackendTuningStrategy + Send + Sync>,
        );
        strategies.insert(
            BackendType::Metal,
            Box::new(MetalTuningStrategy::new()?) as Box<dyn BackendTuningStrategy + Send + Sync>,
        );
        strategies.insert(
            BackendType::WebGpu,
            Box::new(WebGpuTuningStrategy::new()?) as Box<dyn BackendTuningStrategy + Send + Sync>,
        );

        Ok(Self {
            strategies: Arc::new(RwLock::new(strategies)),
            global_monitor: Arc::new(Mutex::new(GlobalPerformanceMonitor::new())),
            workload_classifier: WorkloadClassifier::new()?,
            adaptive_controller: AdaptiveTuningController::new(),
            optimization_cache: Arc::new(RwLock::new(OptimizationCache::new(1000))),
        })
    }

    /// Get tuning recommendation for a workload
    pub fn get_tuning_recommendation(
        &self,
        backend_type: BackendType,
        workload: &WorkloadCharacteristics,
        system_state: &SystemState,
        constraints: &TuningConstraints,
    ) -> BackendResult<TuningRecommendation> {
        // Check cache first
        let cache_key = self.compute_cache_key(backend_type, workload, system_state);
        if let Some(cached) = self.get_cached_optimization(cache_key)? {
            if cached.confidence > 0.8 && cached.timestamp.elapsed() < Duration::from_secs(300) {
                return Ok(TuningRecommendation {
                    parameters: cached.parameters,
                    expected_performance: cached.prediction,
                    confidence_score: cached.confidence,
                    alternative_configs: Vec::new(),
                    reasoning: "Retrieved from optimization cache".to_string(),
                });
            }
        }

        // Classify workload
        let workload_class = self.workload_classifier.classify(workload)?;

        // Get backend-specific strategy
        let strategies = self.strategies.read().map_err(|_| {
            TorshError::BackendError("Failed to acquire strategies lock".to_string())
        })?;

        let strategy = strategies.get(&backend_type).ok_or_else(|| {
            TorshError::BackendError(format!("No strategy for backend {:?}", backend_type))
        })?;

        // Get tuning recommendation
        let mut recommendation = strategy.tune_for_workload(workload, system_state, constraints)?;

        // Apply adaptive controller suggestions
        let adaptive_params = self
            .adaptive_controller
            .suggest_parameters(workload_class, &recommendation.parameters)?;
        if let Some(params) = adaptive_params {
            recommendation.alternative_configs.push(params);
        }

        // Cache the result
        let cached_opt = CachedOptimization {
            parameters: recommendation.parameters.clone(),
            prediction: recommendation.expected_performance.clone(),
            timestamp: Instant::now(),
            hit_count: 1,
            confidence: recommendation.confidence_score,
        };
        self.cache_optimization(cache_key, cached_opt)?;

        Ok(recommendation)
    }

    /// Provide performance feedback for learning
    pub fn provide_feedback(&mut self, feedback: PerformanceFeedback) -> BackendResult<()> {
        // Update backend strategy
        let backend_type = self.determine_backend_from_feedback(&feedback);
        {
            let mut strategies = self.strategies.write().map_err(|_| {
                TorshError::BackendError("Failed to acquire strategies lock".to_string())
            })?;

            if let Some(strategy) = strategies.get_mut(&backend_type) {
                strategy.update_from_feedback(&feedback)?;
            }
        }

        // Update adaptive controller
        self.adaptive_controller.update_from_feedback(&feedback)?;

        // Update workload classifier
        let workload_class = self.workload_classifier.classify(&feedback.workload)?;
        self.workload_classifier
            .update_classification(&feedback.workload, workload_class)?;

        // Update global monitor
        {
            let mut monitor = self.global_monitor.lock().map_err(|_| {
                TorshError::BackendError("Failed to acquire global monitor lock".to_string())
            })?;
            monitor.update_performance_stats(backend_type, &feedback)?;
        }

        Ok(())
    }

    /// Get global performance statistics with enhanced analytics
    pub fn get_global_stats(&self) -> BackendResult<GlobalPerformanceStats> {
        let monitor = self.global_monitor.lock().map_err(|_| {
            TorshError::BackendError("Failed to acquire global monitor lock".to_string())
        })?;

        let mut stats = monitor.compute_global_stats();

        // Enhance with advanced analytics
        self.enhance_stats_with_analytics(&mut stats)?;

        Ok(stats)
    }

    /// Enhance performance statistics with advanced analytics
    fn enhance_stats_with_analytics(
        &self,
        stats: &mut GlobalPerformanceStats,
    ) -> BackendResult<()> {
        // Calculate performance trends
        let trend_analysis = self.analyze_performance_trends()?;

        // Add trend data to stats
        stats.efficiency_trend = trend_analysis.efficiency_trend;
        stats.throughput_trend = trend_analysis.throughput_trend;
        stats.latency_trend = trend_analysis.latency_trend;

        // Calculate predictive metrics
        let predictions = self.generate_performance_predictions(&stats)?;
        stats.predicted_efficiency = predictions.next_efficiency;
        stats.predicted_bottlenecks = predictions.likely_bottlenecks;

        // Add optimization recommendations
        stats.optimization_recommendations = self.generate_optimization_recommendations(&stats)?;

        Ok(())
    }

    /// Analyze performance trends over time
    fn analyze_performance_trends(&self) -> BackendResult<PerformanceTrendAnalysis> {
        // Simplified trend analysis - generate synthetic data for now
        // In a real implementation, this would analyze historical performance data

        // Return insufficient data to indicate trends need more historical data
        Ok(PerformanceTrendAnalysis::insufficient_data())
    }

    /// Calculate efficiency trend using simple linear regression
    fn calculate_efficiency_trend(&self, metrics: &[PerformanceMetric]) -> TrendDirection {
        if metrics.len() < 2 {
            return TrendDirection::Stable;
        }

        let n = metrics.len() as f64;
        let mut sum_x = 0.0;
        let mut sum_y = 0.0;
        let mut sum_xy = 0.0;
        let mut sum_x2 = 0.0;

        for (i, metric) in metrics.iter().enumerate() {
            let x = i as f64;
            let y = metric.efficiency_score;

            sum_x += x;
            sum_y += y;
            sum_xy += x * y;
            sum_x2 += x * x;
        }

        // Calculate slope of linear regression line
        let slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x);

        if slope > 0.01 {
            TrendDirection::Improving
        } else if slope < -0.01 {
            TrendDirection::Declining
        } else {
            TrendDirection::Stable
        }
    }

    /// Calculate throughput trend
    fn calculate_throughput_trend(&self, metrics: &[PerformanceMetric]) -> TrendDirection {
        if metrics.len() < 5 {
            return TrendDirection::Stable;
        }

        let recent_avg = metrics
            .iter()
            .rev()
            .take(5)
            .map(|m| m.throughput_ops_per_sec)
            .sum::<f64>()
            / 5.0;

        let older_avg = metrics
            .iter()
            .rev()
            .skip(5)
            .take(5)
            .map(|m| m.throughput_ops_per_sec)
            .sum::<f64>()
            / 5.0;

        let change_ratio = (recent_avg - older_avg) / older_avg;

        if change_ratio > 0.05 {
            TrendDirection::Improving
        } else if change_ratio < -0.05 {
            TrendDirection::Declining
        } else {
            TrendDirection::Stable
        }
    }

    /// Calculate latency trend
    fn calculate_latency_trend(&self, metrics: &[PerformanceMetric]) -> TrendDirection {
        if metrics.len() < 5 {
            return TrendDirection::Stable;
        }

        let recent_avg = metrics
            .iter()
            .rev()
            .take(5)
            .map(|m| m.average_latency_ms)
            .sum::<f64>()
            / 5.0;

        let older_avg = metrics
            .iter()
            .rev()
            .skip(5)
            .take(5)
            .map(|m| m.average_latency_ms)
            .sum::<f64>()
            / 5.0;

        let change_ratio = (recent_avg - older_avg) / older_avg;

        // For latency, lower is better, so trend is inverted
        if change_ratio < -0.05 {
            TrendDirection::Improving
        } else if change_ratio > 0.05 {
            TrendDirection::Declining
        } else {
            TrendDirection::Stable
        }
    }

    /// Calculate confidence level for trend analysis
    fn calculate_trend_confidence(&self, sample_size: usize) -> f64 {
        match sample_size {
            0..=10 => 0.3,
            11..=30 => 0.6,
            31..=60 => 0.8,
            61..=100 => 0.9,
            _ => 0.95,
        }
    }

    /// Generate performance predictions
    fn generate_performance_predictions(
        &self,
        stats: &GlobalPerformanceStats,
    ) -> BackendResult<PerformancePredictions> {
        let current_efficiency = stats.average_efficiency;

        // Simple prediction based on trends
        let next_efficiency = match stats.efficiency_trend {
            TrendDirection::Improving => current_efficiency * 1.05,
            TrendDirection::Declining => current_efficiency * 0.95,
            TrendDirection::Stable => current_efficiency,
        };

        // Predict likely bottlenecks based on current performance patterns
        let likely_bottlenecks = self.predict_bottlenecks(stats)?;

        Ok(PerformancePredictions {
            next_efficiency: next_efficiency.clamp(0.0, 1.0),
            likely_bottlenecks,
            prediction_confidence: 0.75, // Fixed confidence for simplicity
        })
    }

    /// Predict likely performance bottlenecks
    fn predict_bottlenecks(&self, stats: &GlobalPerformanceStats) -> BackendResult<Vec<String>> {
        let mut bottlenecks = Vec::new();

        if stats.average_efficiency < 0.7 {
            bottlenecks.push("Low overall efficiency detected".to_string());
        }

        if stats.memory_utilization > 0.9 {
            bottlenecks.push("High memory utilization - potential memory bottleneck".to_string());
        }

        if stats.average_latency_ms > 100.0 {
            bottlenecks.push("High latency detected - potential I/O bottleneck".to_string());
        }

        if stats.throughput_ops_per_sec < 1000.0 {
            bottlenecks.push("Low throughput - potential CPU or compute bottleneck".to_string());
        }

        if bottlenecks.is_empty() {
            bottlenecks.push("No significant bottlenecks detected".to_string());
        }

        Ok(bottlenecks)
    }

    /// Generate optimization recommendations
    fn generate_optimization_recommendations(
        &self,
        stats: &GlobalPerformanceStats,
    ) -> BackendResult<Vec<String>> {
        let mut recommendations = Vec::new();

        // Memory-based recommendations
        if stats.memory_utilization > 0.85 {
            recommendations.push(
                "Consider increasing memory pool size or implementing memory compression"
                    .to_string(),
            );
        }

        if stats.fragmentation_ratio > 0.3 {
            recommendations
                .push("Run memory defragmentation to improve allocation efficiency".to_string());
        }

        // Performance-based recommendations
        if stats.average_efficiency < 0.8 {
            recommendations.push(
                "Enable aggressive optimization strategies for better performance".to_string(),
            );
        }

        if stats.cache_hit_ratio < 0.9 {
            recommendations.push(
                "Tune cache parameters or increase cache size for better hit rates".to_string(),
            );
        }

        // Throughput-based recommendations
        if stats.throughput_ops_per_sec < 5000.0 {
            recommendations
                .push("Consider parallel processing or batch optimization techniques".to_string());
        }

        // Trend-based recommendations
        match stats.efficiency_trend {
            TrendDirection::Declining => {
                recommendations.push(
                    "Performance declining - investigate recent changes or increase monitoring"
                        .to_string(),
                );
            }
            TrendDirection::Improving => {
                recommendations.push(
                    "Performance improving - maintain current optimization strategies".to_string(),
                );
            }
            TrendDirection::Stable => {
                recommendations.push(
                    "Performance stable - consider experimenting with new optimization techniques"
                        .to_string(),
                );
            }
        }

        if recommendations.is_empty() {
            recommendations
                .push("Performance is optimal - no specific recommendations".to_string());
        }

        Ok(recommendations)
    }

    /// Get strategy metrics for specific backend
    pub fn get_strategy_metrics(
        &self,
        backend_type: BackendType,
    ) -> BackendResult<StrategyMetrics> {
        let strategies = self.strategies.read().map_err(|_| {
            TorshError::BackendError("Failed to acquire strategies lock".to_string())
        })?;

        let strategy = strategies.get(&backend_type).ok_or_else(|| {
            TorshError::BackendError(format!("No strategy for backend {:?}", backend_type))
        })?;

        strategy.get_strategy_metrics()
    }

    /// Compute cache key for optimization
    pub fn compute_cache_key(
        &self,
        backend_type: BackendType,
        workload: &WorkloadCharacteristics,
        system_state: &SystemState,
    ) -> u64 {
        let mut hasher = DefaultHasher::new();
        backend_type.hash(&mut hasher);
        workload.operation_type.hash(&mut hasher);
        workload.data_size.hash(&mut hasher);
        workload.data_type.hash(&mut hasher);
        workload.access_pattern.hash(&mut hasher);
        ((system_state.cpu_utilization * 100.0) as u32).hash(&mut hasher);
        ((system_state.memory_utilization * 100.0) as u32).hash(&mut hasher);
        hasher.finish()
    }

    /// Get cached optimization
    fn get_cached_optimization(&self, cache_key: u64) -> BackendResult<Option<CachedOptimization>> {
        let cache = self.optimization_cache.read().map_err(|_| {
            TorshError::BackendError("Failed to acquire optimization cache lock".to_string())
        })?;

        Ok(cache.cache.get(&cache_key).cloned())
    }

    /// Cache optimization result
    fn cache_optimization(
        &self,
        cache_key: u64,
        optimization: CachedOptimization,
    ) -> BackendResult<()> {
        let mut cache = self.optimization_cache.write().map_err(|_| {
            TorshError::BackendError("Failed to acquire optimization cache lock".to_string())
        })?;

        cache.cache.insert(cache_key, optimization);

        // Evict old entries if cache is full
        if cache.cache.len() > cache.max_entries {
            let eviction_count = cache.max_entries / 4;
            cache.evict_lru_entries(eviction_count)?;
        }

        Ok(())
    }

    /// Determine backend type from feedback
    fn determine_backend_from_feedback(&self, _feedback: &PerformanceFeedback) -> BackendType {
        // This would analyze the feedback to determine which backend was used
        // For now, we'll default to CPU
        BackendType::Cpu
    }
}

// ================================================================================================
// GlobalPerformanceMonitor Implementation
// ================================================================================================

impl GlobalPerformanceMonitor {
    pub fn new() -> Self {
        Self {
            backend_performance: HashMap::new(),
            cross_backend_analysis: CrossBackendAnalysis {
                backend_selection_recommendations: HashMap::new(),
                workload_migration_opportunities: Vec::new(),
                hybrid_execution_strategies: Vec::new(),
            },
            system_health_monitor: SystemHealthMonitor {
                thermal_history: Vec::new(),
                power_history: Vec::new(),
                performance_degradation_events: Vec::new(),
            },
        }
    }

    pub fn update_performance_stats(
        &mut self,
        backend_type: BackendType,
        feedback: &PerformanceFeedback,
    ) -> BackendResult<()> {
        let stats = self
            .backend_performance
            .entry(backend_type)
            .or_insert_with(BackendPerformanceStats::default);
        stats.total_operations += 1;
        stats.total_execution_time += feedback.actual_performance.execution_time;
        stats.average_throughput =
            (stats.average_throughput + feedback.actual_performance.throughput) / 2.0;
        stats.peak_memory_usage = stats
            .peak_memory_usage
            .max(feedback.actual_performance.memory_usage_peak);
        Ok(())
    }

    pub fn compute_global_stats(&self) -> GlobalPerformanceStats {
        let total_ops: usize = self
            .backend_performance
            .values()
            .map(|s| s.total_operations)
            .sum();
        let total_time: Duration = self
            .backend_performance
            .values()
            .map(|s| s.total_execution_time)
            .sum();

        GlobalPerformanceStats {
            total_operations: total_ops,
            average_execution_time: total_time / total_ops.max(1) as u32,
            overall_throughput: 1e6, // Placeholder
            energy_efficiency: 0.8,
            cache_hit_ratio: 0.85,
            thermal_efficiency: 0.9,
            backend_utilization: HashMap::new(),

            // Enhanced analytics fields - initialized with default values
            average_efficiency: 0.8,
            memory_utilization: 0.6,
            fragmentation_ratio: 0.2,
            average_latency_ms: 50.0,
            throughput_ops_per_sec: 1000.0,

            // Trend analysis - initialized as stable
            efficiency_trend: TrendDirection::Stable,
            throughput_trend: TrendDirection::Stable,
            latency_trend: TrendDirection::Stable,

            // Predictions - empty initially
            predicted_efficiency: 0.8,
            predicted_bottlenecks: Vec::new(),

            // Recommendations - empty initially
            optimization_recommendations: Vec::new(),
        }
    }
}

// ================================================================================================
// WorkloadClassifier Implementation
// ================================================================================================

impl WorkloadClassifier {
    pub fn new() -> BackendResult<Self> {
        Ok(Self {
            classification_models: HashMap::new(),
            feature_extractors: Vec::new(),
            classification_cache: HashMap::new(),
        })
    }

    pub fn classify(&self, _workload: &WorkloadCharacteristics) -> BackendResult<WorkloadClass> {
        // Simple classification logic - would be replaced with ML models in practice
        Ok(WorkloadClass::ComputeBound)
    }

    pub fn update_classification(
        &mut self,
        _workload: &WorkloadCharacteristics,
        _class: WorkloadClass,
    ) -> BackendResult<()> {
        // Update classification models based on feedback
        Ok(())
    }
}

// ================================================================================================
// AdaptiveTuningController Implementation
// ================================================================================================

impl AdaptiveTuningController {
    pub fn new() -> Self {
        Self {
            exploration_rate: 0.1,
            learning_rate: 0.01,
            discount_factor: 0.9,
            state_action_values: HashMap::new(),
            experience_replay: Vec::new(),
            performance_baseline: HashMap::new(),
        }
    }

    pub fn suggest_parameters(
        &self,
        _workload_class: WorkloadClass,
        _current_params: &TuningParameters,
    ) -> BackendResult<Option<TuningParameters>> {
        // Reinforcement learning-based parameter suggestion
        // For now, return None (no alternative parameters)
        Ok(None)
    }

    pub fn update_from_feedback(&mut self, _feedback: &PerformanceFeedback) -> BackendResult<()> {
        // Update reinforcement learning models based on performance feedback
        Ok(())
    }
}

// ================================================================================================
// OptimizationCache Implementation
// ================================================================================================

impl OptimizationCache {
    pub fn new(max_entries: usize) -> Self {
        Self {
            cache: HashMap::new(),
            hit_count: 0,
            miss_count: 0,
            max_entries,
        }
    }

    pub fn evict_lru_entries(&mut self, _count: usize) -> BackendResult<()> {
        // Simple eviction implementation - would implement proper LRU in practice
        // For now, just clear some entries randomly
        if self.cache.len() > self.max_entries {
            let keys_to_remove: Vec<_> = self.cache.keys().take(_count).cloned().collect();
            for key in keys_to_remove {
                self.cache.remove(&key);
            }
        }
        Ok(())
    }

    pub fn get_hit_rate(&self) -> f64 {
        let total_requests = self.hit_count + self.miss_count;
        if total_requests == 0 {
            0.0
        } else {
            self.hit_count as f64 / total_requests as f64
        }
    }

    pub fn clear(&mut self) {
        self.cache.clear();
        self.hit_count = 0;
        self.miss_count = 0;
    }
}

// ================================================================================================
// Default Implementations
// ================================================================================================

impl Default for PerformanceTuningCoordinator {
    fn default() -> Self {
        Self::new().expect("Failed to create default PerformanceTuningCoordinator")
    }
}

impl Default for GlobalPerformanceMonitor {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for AdaptiveTuningController {
    fn default() -> Self {
        Self::new()
    }
}

// ================================================================================================
// Helper Functions
// ================================================================================================

/// Create a default system state for testing
pub fn create_default_system_state() -> SystemState {
    SystemState {
        cpu_utilization: 0.5,
        memory_utilization: 0.6,
        thermal_state: ThermalState {
            cpu_temperature: 65.0,
            gpu_temperature: None,
            thermal_throttling_active: false,
            cooling_efficiency: 0.8,
        },
        power_state: PowerState {
            power_limit: None,
            current_power_draw: 50.0,
            battery_level: None,
            power_efficiency_mode: PowerEfficiencyMode::Balanced,
        },
        concurrent_workloads: 2,
        available_memory_bandwidth: 0.7,
        cache_pressure: 0.4,
        numa_topology: NumaTopologyState {
            node_count: 1,
            current_node: 0,
            memory_distribution: vec![1.0],
            cross_node_traffic: 0.0,
        },
    }
}

/// Create default tuning constraints
pub fn create_default_constraints() -> TuningConstraints {
    TuningConstraints {
        max_memory_usage: None,
        max_power_draw: None,
        max_temperature: None,
        latency_requirement: None,
        throughput_requirement: None,
        energy_budget: None,
        real_time_constraints: false,
    }
}

/// Create a sample workload for testing
pub fn create_sample_workload(op_type: OperationType, data_size: usize) -> WorkloadCharacteristics {
    WorkloadCharacteristics {
        operation_type: op_type,
        data_size,
        data_shape: vec![(data_size as f64).sqrt() as usize; 2],
        data_type: DataType::F32,
        access_pattern: AccessPattern::Sequential,
        compute_intensity: 0.8,
        memory_bandwidth_requirement: 0.6,
        parallelization_potential: 0.9,
        cache_locality: 0.7,
        branch_predictability: 0.95,
        vectorization_potential: 0.85,
    }
}