trustformers-debug 0.1.1

Advanced debugging tools for TrustformeRS models
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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
//! Comprehensive error recovery mechanisms for debugging sessions

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};
use uuid::Uuid;

/// Comprehensive error recovery system
#[derive(Debug)]
pub struct ErrorRecoverySystem {
    config: ErrorRecoveryConfig,
    recovery_strategies: HashMap<ErrorType, Vec<RecoveryStrategy>>,
    error_history: VecDeque<ErrorEvent>,
    recovery_history: VecDeque<RecoveryEvent>,
    circuit_breaker: CircuitBreaker,
    health_monitor: SystemHealthMonitor,
    failsafe_manager: FailsafeManager,
}

/// Configuration for error recovery
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorRecoveryConfig {
    pub enabled: bool,
    pub max_retry_attempts: usize,
    pub retry_delay_ms: u64,
    pub circuit_breaker_threshold: usize,
    pub health_check_interval_ms: u64,
    pub auto_failsafe_enabled: bool,
    pub error_history_limit: usize,
    pub recovery_timeout_ms: u64,
}

impl Default for ErrorRecoveryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_retry_attempts: 3,
            retry_delay_ms: 100,
            circuit_breaker_threshold: 5,
            health_check_interval_ms: 5000,
            auto_failsafe_enabled: true,
            error_history_limit: 1000,
            recovery_timeout_ms: 30000,
        }
    }
}

/// Types of errors that can occur during debugging
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ErrorType {
    TensorInspectionError,
    GradientDebuggingError,
    ModelDiagnosticsError,
    VisualizationError,
    MemoryProfilingError,
    IOError,
    NetworkError,
    ResourceExhaustion,
    ConfigurationError,
    DataCorruption,
    SystemFailure,
    UserError,
}

/// Recovery strategies for different error types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RecoveryStrategy {
    Retry { max_attempts: usize, delay_ms: u64 },
    Fallback { alternative_method: String },
    GracefulDegradation { reduced_functionality: String },
    ResourceCleanup { cleanup_type: String },
    SystemReset { component: String },
    EmergencyShutdown,
    UserNotification { message: String },
    AutomaticRepair { repair_action: String },
}

/// Error event record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorEvent {
    pub id: Uuid,
    pub error_type: ErrorType,
    pub error_message: String,
    pub component: String,
    pub severity: ErrorSeverity,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub context: ErrorContext,
    pub stack_trace: Option<String>,
}

/// Error severity levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ErrorSeverity {
    Low,
    Medium,
    High,
    Critical,
    Fatal,
}

/// Context information for errors
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorContext {
    pub session_id: Uuid,
    pub operation: String,
    pub parameters: HashMap<String, String>,
    pub system_state: SystemState,
}

/// System state at time of error
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemState {
    pub memory_usage_mb: u64,
    pub cpu_usage_percent: f64,
    pub active_tensors: usize,
    pub active_sessions: usize,
    pub uptime_seconds: u64,
}

/// Recovery event record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecoveryEvent {
    pub id: Uuid,
    pub error_id: Uuid,
    pub strategy: RecoveryStrategy,
    pub start_time: chrono::DateTime<chrono::Utc>,
    pub end_time: Option<chrono::DateTime<chrono::Utc>>,
    pub success: Option<bool>,
    pub result_message: String,
    pub attempts: usize,
}

/// Circuit breaker for preventing cascading failures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CircuitBreaker {
    pub state: CircuitState,
    pub failure_count: usize,
    pub last_failure_time: Option<chrono::DateTime<chrono::Utc>>,
    pub threshold: usize,
    pub timeout_duration: Duration,
}

/// Circuit breaker states
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CircuitState {
    Closed,
    Open,
    HalfOpen,
}

/// System health monitoring
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemHealthMonitor {
    pub overall_health: HealthStatus,
    pub component_health: HashMap<String, HealthStatus>,
    pub last_health_check: chrono::DateTime<chrono::Utc>,
    pub health_metrics: HealthMetrics,
}

/// Health status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HealthStatus {
    Healthy,
    Degraded,
    Unhealthy,
    Critical,
}

/// Health metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthMetrics {
    pub error_rate: f64,
    pub recovery_success_rate: f64,
    pub average_response_time_ms: f64,
    pub memory_health_score: f64,
    pub stability_score: f64,
}

/// Failsafe manager for critical situations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailsafeManager {
    pub enabled: bool,
    pub emergency_protocols: Vec<EmergencyProtocol>,
    pub safe_mode_enabled: bool,
    pub data_backup_enabled: bool,
    pub last_backup: Option<chrono::DateTime<chrono::Utc>>,
}

/// Emergency protocols
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmergencyProtocol {
    pub name: String,
    pub trigger_conditions: Vec<String>,
    pub actions: Vec<String>,
    pub priority: u8,
}

impl ErrorRecoverySystem {
    /// Create a new error recovery system
    pub fn new(config: ErrorRecoveryConfig) -> Self {
        let mut system = Self {
            config,
            recovery_strategies: HashMap::new(),
            error_history: VecDeque::new(),
            recovery_history: VecDeque::new(),
            circuit_breaker: CircuitBreaker {
                state: CircuitState::Closed,
                failure_count: 0,
                last_failure_time: None,
                threshold: 5,
                timeout_duration: Duration::from_secs(60),
            },
            health_monitor: SystemHealthMonitor {
                overall_health: HealthStatus::Healthy,
                component_health: HashMap::new(),
                last_health_check: chrono::Utc::now(),
                health_metrics: HealthMetrics {
                    error_rate: 0.0,
                    recovery_success_rate: 1.0,
                    average_response_time_ms: 0.0,
                    memory_health_score: 1.0,
                    stability_score: 1.0,
                },
            },
            failsafe_manager: FailsafeManager {
                enabled: true,
                emergency_protocols: Vec::new(),
                safe_mode_enabled: false,
                data_backup_enabled: true,
                last_backup: None,
            },
        };

        system.initialize_default_strategies();
        system.initialize_emergency_protocols();
        system
    }

    /// Handle an error event and attempt recovery
    pub async fn handle_error(&mut self, error: ErrorEvent) -> Result<RecoveryResult> {
        // Check circuit breaker
        if matches!(self.circuit_breaker.state, CircuitState::Open) {
            return Ok(RecoveryResult {
                success: false,
                strategy_used: None,
                message: "Circuit breaker is open - recovery attempts suspended".to_string(),
                recovery_time: Duration::from_millis(0),
            });
        }

        // Record error
        self.record_error(error.clone());

        // Check if emergency protocols should be triggered
        if self.should_trigger_emergency_protocol(&error) {
            return self.execute_emergency_protocol(&error).await;
        }

        // Attempt recovery
        let recovery_result = self.attempt_recovery(&error).await?;

        // Update circuit breaker and health monitor
        self.update_circuit_breaker(&recovery_result);
        self.update_health_metrics(&error, &recovery_result);

        Ok(recovery_result)
    }

    /// Record an error event
    pub fn record_error(&mut self, error: ErrorEvent) {
        self.error_history.push_back(error);

        // Maintain history limit
        while self.error_history.len() > self.config.error_history_limit {
            self.error_history.pop_front();
        }
    }

    /// Attempt recovery using appropriate strategies
    pub async fn attempt_recovery(&mut self, error: &ErrorEvent) -> Result<RecoveryResult> {
        let strategies = self.get_recovery_strategies(&error.error_type);

        for (attempt, strategy) in strategies.iter().enumerate() {
            if attempt >= self.config.max_retry_attempts {
                break;
            }

            let recovery_event = RecoveryEvent {
                id: Uuid::new_v4(),
                error_id: error.id,
                strategy: strategy.clone(),
                start_time: chrono::Utc::now(),
                end_time: None,
                success: None,
                result_message: String::new(),
                attempts: attempt + 1,
            };

            let result = self.execute_recovery_strategy(strategy, error).await?;

            let mut updated_event = recovery_event;
            updated_event.end_time = Some(chrono::Utc::now());
            updated_event.success = Some(result.success);
            updated_event.result_message = result.message.clone();

            self.recovery_history.push_back(updated_event);

            if result.success {
                return Ok(result);
            }

            // Wait before next attempt
            if attempt < strategies.len() - 1 {
                tokio::time::sleep(Duration::from_millis(self.config.retry_delay_ms)).await;
            }
        }

        Ok(RecoveryResult {
            success: false,
            strategy_used: None,
            message: "All recovery strategies failed".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    /// Execute a specific recovery strategy
    pub async fn execute_recovery_strategy(
        &self,
        strategy: &RecoveryStrategy,
        error: &ErrorEvent,
    ) -> Result<RecoveryResult> {
        let start_time = Instant::now();

        let result = match strategy {
            RecoveryStrategy::Retry {
                max_attempts,
                delay_ms,
            } => self.execute_retry_strategy(*max_attempts, *delay_ms, error).await,
            RecoveryStrategy::Fallback { alternative_method } => {
                self.execute_fallback_strategy(alternative_method, error).await
            },
            RecoveryStrategy::GracefulDegradation {
                reduced_functionality,
            } => self.execute_degradation_strategy(reduced_functionality, error).await,
            RecoveryStrategy::ResourceCleanup { cleanup_type } => {
                self.execute_cleanup_strategy(cleanup_type, error).await
            },
            RecoveryStrategy::SystemReset { component } => {
                self.execute_reset_strategy(component, error).await
            },
            RecoveryStrategy::EmergencyShutdown => self.execute_shutdown_strategy(error).await,
            RecoveryStrategy::UserNotification { message } => {
                self.execute_notification_strategy(message, error).await
            },
            RecoveryStrategy::AutomaticRepair { repair_action } => {
                self.execute_repair_strategy(repair_action, error).await
            },
        };

        let recovery_time = start_time.elapsed();

        match result {
            Ok(mut recovery_result) => {
                recovery_result.recovery_time = recovery_time;
                recovery_result.strategy_used = Some(strategy.clone());
                Ok(recovery_result)
            },
            Err(e) => Ok(RecoveryResult {
                success: false,
                strategy_used: Some(strategy.clone()),
                message: format!("Recovery strategy failed: {}", e),
                recovery_time,
            }),
        }
    }

    /// Get recovery strategies for an error type
    pub fn get_recovery_strategies(&self, error_type: &ErrorType) -> Vec<RecoveryStrategy> {
        self.recovery_strategies.get(error_type).cloned().unwrap_or_default()
    }

    /// Check system health
    pub async fn check_system_health(&mut self) -> HealthStatus {
        // Update health metrics
        self.health_monitor.last_health_check = chrono::Utc::now();

        // Calculate error rate from recent history
        let recent_errors = self
            .error_history
            .iter()
            .filter(|e| {
                let age = chrono::Utc::now() - e.timestamp;
                age < chrono::Duration::minutes(5)
            })
            .count();

        self.health_monitor.health_metrics.error_rate = recent_errors as f64 / 100.0; // Normalized

        // Calculate recovery success rate
        let recent_recoveries = self
            .recovery_history
            .iter()
            .filter(|r| {
                if let Some(end_time) = r.end_time {
                    let age = chrono::Utc::now() - end_time;
                    age < chrono::Duration::minutes(5)
                } else {
                    false
                }
            })
            .collect::<Vec<_>>();

        if !recent_recoveries.is_empty() {
            let successful_recoveries =
                recent_recoveries.iter().filter(|r| r.success.unwrap_or(false)).count();
            self.health_monitor.health_metrics.recovery_success_rate =
                successful_recoveries as f64 / recent_recoveries.len() as f64;
        }

        // Determine overall health
        self.health_monitor.overall_health = if self.health_monitor.health_metrics.error_rate > 0.5
        {
            HealthStatus::Critical
        } else if self.health_monitor.health_metrics.error_rate > 0.2 {
            HealthStatus::Unhealthy
        } else if self.health_monitor.health_metrics.error_rate > 0.1 {
            HealthStatus::Degraded
        } else {
            HealthStatus::Healthy
        };

        self.health_monitor.overall_health.clone()
    }

    /// Enable safe mode
    pub fn enable_safe_mode(&mut self) {
        self.failsafe_manager.safe_mode_enabled = true;
        tracing::warn!("Safe mode enabled - operating with reduced functionality");
    }

    /// Disable safe mode
    pub fn disable_safe_mode(&mut self) {
        self.failsafe_manager.safe_mode_enabled = false;
        tracing::info!("Safe mode disabled - full functionality restored");
    }

    /// Get error statistics
    pub fn get_error_statistics(&self) -> ErrorStatistics {
        let total_errors = self.error_history.len();
        let error_type_counts = self.error_history.iter().fold(HashMap::new(), |mut acc, error| {
            *acc.entry(error.error_type.clone()).or_insert(0) += 1;
            acc
        });

        let severity_counts = self.error_history.iter().fold(HashMap::new(), |mut acc, error| {
            *acc.entry(format!("{:?}", error.severity)).or_insert(0) += 1;
            acc
        });

        ErrorStatistics {
            total_errors,
            error_type_counts,
            severity_counts,
            recovery_success_rate: self.health_monitor.health_metrics.recovery_success_rate,
            circuit_breaker_state: self.circuit_breaker.state.clone(),
            system_health: self.health_monitor.overall_health.clone(),
        }
    }

    // Private helper methods

    fn initialize_default_strategies(&mut self) {
        // Initialize default recovery strategies for each error type
        self.recovery_strategies.insert(
            ErrorType::TensorInspectionError,
            vec![
                RecoveryStrategy::Retry {
                    max_attempts: 3,
                    delay_ms: 100,
                },
                RecoveryStrategy::ResourceCleanup {
                    cleanup_type: "tensor_cache".to_string(),
                },
                RecoveryStrategy::Fallback {
                    alternative_method: "simplified_inspection".to_string(),
                },
            ],
        );

        self.recovery_strategies.insert(
            ErrorType::GradientDebuggingError,
            vec![
                RecoveryStrategy::Retry {
                    max_attempts: 2,
                    delay_ms: 200,
                },
                RecoveryStrategy::GracefulDegradation {
                    reduced_functionality: "basic_gradient_info".to_string(),
                },
            ],
        );

        self.recovery_strategies.insert(
            ErrorType::MemoryProfilingError,
            vec![
                RecoveryStrategy::ResourceCleanup {
                    cleanup_type: "memory_profiler".to_string(),
                },
                RecoveryStrategy::SystemReset {
                    component: "memory_tracker".to_string(),
                },
            ],
        );

        self.recovery_strategies.insert(
            ErrorType::ResourceExhaustion,
            vec![
                RecoveryStrategy::ResourceCleanup {
                    cleanup_type: "all_caches".to_string(),
                },
                RecoveryStrategy::GracefulDegradation {
                    reduced_functionality: "essential_only".to_string(),
                },
                RecoveryStrategy::EmergencyShutdown,
            ],
        );

        // Add more strategies for other error types...
    }

    fn initialize_emergency_protocols(&mut self) {
        self.failsafe_manager.emergency_protocols = vec![
            EmergencyProtocol {
                name: "Memory Exhaustion Protocol".to_string(),
                trigger_conditions: vec!["memory_usage > 90%".to_string()],
                actions: vec![
                    "clear_all_caches".to_string(),
                    "reduce_tracking".to_string(),
                ],
                priority: 1,
            },
            EmergencyProtocol {
                name: "Critical Error Protocol".to_string(),
                trigger_conditions: vec!["error_severity == Fatal".to_string()],
                actions: vec!["emergency_backup".to_string(), "safe_shutdown".to_string()],
                priority: 0,
            },
        ];
    }

    fn should_trigger_emergency_protocol(&self, error: &ErrorEvent) -> bool {
        matches!(error.severity, ErrorSeverity::Fatal)
            || error.context.system_state.memory_usage_mb > 8192 // > 8GB
    }

    async fn execute_emergency_protocol(&mut self, error: &ErrorEvent) -> Result<RecoveryResult> {
        tracing::error!(
            "Executing emergency protocol for error: {}",
            error.error_message
        );

        // Enable safe mode
        self.enable_safe_mode();

        // Execute emergency backup if enabled
        if self.failsafe_manager.data_backup_enabled {
            self.create_emergency_backup().await?;
        }

        Ok(RecoveryResult {
            success: true,
            strategy_used: Some(RecoveryStrategy::EmergencyShutdown),
            message: "Emergency protocol executed successfully".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    async fn create_emergency_backup(&mut self) -> Result<()> {
        tracing::info!("Creating emergency backup");
        self.failsafe_manager.last_backup = Some(chrono::Utc::now());
        // Implement backup logic here
        Ok(())
    }

    fn update_circuit_breaker(&mut self, result: &RecoveryResult) {
        if result.success {
            self.circuit_breaker.failure_count = 0;
            self.circuit_breaker.state = CircuitState::Closed;
        } else {
            self.circuit_breaker.failure_count += 1;
            self.circuit_breaker.last_failure_time = Some(chrono::Utc::now());

            if self.circuit_breaker.failure_count >= self.circuit_breaker.threshold {
                self.circuit_breaker.state = CircuitState::Open;
            }
        }
    }

    fn update_health_metrics(&mut self, _error: &ErrorEvent, _result: &RecoveryResult) {
        // Update health metrics based on error and recovery result
        // This would include more sophisticated health scoring logic
    }

    // Recovery strategy implementations (simplified)
    async fn execute_retry_strategy(
        &self,
        _max_attempts: usize,
        _delay_ms: u64,
        _error: &ErrorEvent,
    ) -> Result<RecoveryResult> {
        Ok(RecoveryResult {
            success: true,
            strategy_used: None,
            message: "Retry successful".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    async fn execute_fallback_strategy(
        &self,
        _alternative: &str,
        _error: &ErrorEvent,
    ) -> Result<RecoveryResult> {
        Ok(RecoveryResult {
            success: true,
            strategy_used: None,
            message: "Fallback strategy executed".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    async fn execute_degradation_strategy(
        &self,
        _functionality: &str,
        _error: &ErrorEvent,
    ) -> Result<RecoveryResult> {
        Ok(RecoveryResult {
            success: true,
            strategy_used: None,
            message: "Graceful degradation applied".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    async fn execute_cleanup_strategy(
        &self,
        _cleanup_type: &str,
        _error: &ErrorEvent,
    ) -> Result<RecoveryResult> {
        Ok(RecoveryResult {
            success: true,
            strategy_used: None,
            message: "Resource cleanup completed".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    async fn execute_reset_strategy(
        &self,
        _component: &str,
        _error: &ErrorEvent,
    ) -> Result<RecoveryResult> {
        Ok(RecoveryResult {
            success: true,
            strategy_used: None,
            message: "Component reset completed".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    async fn execute_shutdown_strategy(&self, _error: &ErrorEvent) -> Result<RecoveryResult> {
        Ok(RecoveryResult {
            success: true,
            strategy_used: None,
            message: "Emergency shutdown initiated".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    async fn execute_notification_strategy(
        &self,
        message: &str,
        _error: &ErrorEvent,
    ) -> Result<RecoveryResult> {
        tracing::warn!("User notification: {}", message);
        Ok(RecoveryResult {
            success: true,
            strategy_used: None,
            message: "User notified".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }

    async fn execute_repair_strategy(
        &self,
        _repair_action: &str,
        _error: &ErrorEvent,
    ) -> Result<RecoveryResult> {
        Ok(RecoveryResult {
            success: true,
            strategy_used: None,
            message: "Automatic repair completed".to_string(),
            recovery_time: Duration::from_millis(0),
        })
    }
}

/// Result of a recovery attempt
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecoveryResult {
    pub success: bool,
    pub strategy_used: Option<RecoveryStrategy>,
    pub message: String,
    pub recovery_time: Duration,
}

/// Error statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorStatistics {
    pub total_errors: usize,
    pub error_type_counts: HashMap<ErrorType, usize>,
    pub severity_counts: HashMap<String, usize>,
    pub recovery_success_rate: f64,
    pub circuit_breaker_state: CircuitState,
    pub system_health: HealthStatus,
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn make_error_event(error_type: ErrorType) -> ErrorEvent {
        ErrorEvent {
            id: Uuid::new_v4(),
            error_type,
            error_message: "test error".to_string(),
            component: "test_component".to_string(),
            severity: ErrorSeverity::Medium,
            timestamp: chrono::Utc::now(),
            context: ErrorContext {
                session_id: Uuid::new_v4(),
                operation: "test_op".to_string(),
                parameters: HashMap::new(),
                system_state: SystemState {
                    memory_usage_mb: 1024,
                    cpu_usage_percent: 50.0,
                    active_tensors: 4,
                    active_sessions: 1,
                    uptime_seconds: 100,
                },
            },
            stack_trace: None,
        }
    }

    // ── ErrorRecoveryConfig ──────────────────────────────────────────────

    #[test]
    fn test_config_default_fields() {
        let cfg = ErrorRecoveryConfig::default();
        assert!(cfg.enabled);
        assert!(cfg.max_retry_attempts > 0);
        assert!(cfg.circuit_breaker_threshold > 0);
        assert!(cfg.error_history_limit > 0);
    }

    // ── ErrorRecoverySystem creation ──────────────────────────────────────

    #[test]
    fn test_system_new_initializes_strategies() {
        let system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        // Should have strategies initialized for at least TensorInspectionError
        let strategies = system.get_recovery_strategies(&ErrorType::TensorInspectionError);
        assert!(!strategies.is_empty());
    }

    #[test]
    fn test_system_new_circuit_breaker_closed() {
        let system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        assert!(matches!(system.circuit_breaker.state, CircuitState::Closed));
    }

    // ── record_error ─────────────────────────────────────────────────────

    #[test]
    fn test_record_error_adds_to_history() {
        let mut system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        let event = make_error_event(ErrorType::IOError);
        system.record_error(event);
        assert_eq!(system.error_history.len(), 1);
    }

    #[test]
    fn test_record_error_respects_history_limit() {
        let mut cfg = ErrorRecoveryConfig::default();
        cfg.error_history_limit = 3;
        let mut system = ErrorRecoverySystem::new(cfg);
        for _ in 0..5 {
            system.record_error(make_error_event(ErrorType::NetworkError));
        }
        assert_eq!(system.error_history.len(), 3);
    }

    // ── safe_mode ────────────────────────────────────────────────────────

    #[test]
    fn test_enable_disable_safe_mode() {
        let mut system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        assert!(!system.failsafe_manager.safe_mode_enabled);
        system.enable_safe_mode();
        assert!(system.failsafe_manager.safe_mode_enabled);
        system.disable_safe_mode();
        assert!(!system.failsafe_manager.safe_mode_enabled);
    }

    // ── get_error_statistics ──────────────────────────────────────────────

    #[test]
    fn test_error_statistics_empty() {
        let system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        let stats = system.get_error_statistics();
        assert_eq!(stats.total_errors, 0);
        assert!(matches!(stats.circuit_breaker_state, CircuitState::Closed));
        assert!(matches!(stats.system_health, HealthStatus::Healthy));
    }

    #[test]
    fn test_error_statistics_with_errors() {
        let mut system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        system.record_error(make_error_event(ErrorType::IOError));
        system.record_error(make_error_event(ErrorType::NetworkError));
        let stats = system.get_error_statistics();
        assert_eq!(stats.total_errors, 2);
        assert_eq!(
            stats.error_type_counts.get(&ErrorType::IOError).copied().unwrap_or(0),
            1
        );
    }

    // ── ErrorType variants ────────────────────────────────────────────────

    #[test]
    fn test_error_type_variants() {
        let types = [
            ErrorType::TensorInspectionError,
            ErrorType::GradientDebuggingError,
            ErrorType::ModelDiagnosticsError,
            ErrorType::VisualizationError,
            ErrorType::MemoryProfilingError,
            ErrorType::IOError,
            ErrorType::NetworkError,
            ErrorType::ResourceExhaustion,
            ErrorType::ConfigurationError,
            ErrorType::DataCorruption,
            ErrorType::SystemFailure,
            ErrorType::UserError,
        ];
        for t in &types {
            assert!(!format!("{:?}", t).is_empty());
        }
    }

    // ── ErrorSeverity variants ────────────────────────────────────────────

    #[test]
    fn test_error_severity_variants() {
        let severities = [
            ErrorSeverity::Low,
            ErrorSeverity::Medium,
            ErrorSeverity::High,
            ErrorSeverity::Critical,
            ErrorSeverity::Fatal,
        ];
        for s in &severities {
            assert!(!format!("{:?}", s).is_empty());
        }
    }

    // ── RecoveryStrategy variants ─────────────────────────────────────────

    #[test]
    fn test_recovery_strategy_variants() {
        let strats = [
            RecoveryStrategy::Retry {
                max_attempts: 3,
                delay_ms: 100,
            },
            RecoveryStrategy::Fallback {
                alternative_method: "alt".to_string(),
            },
            RecoveryStrategy::GracefulDegradation {
                reduced_functionality: "basic".to_string(),
            },
            RecoveryStrategy::ResourceCleanup {
                cleanup_type: "cache".to_string(),
            },
            RecoveryStrategy::SystemReset {
                component: "comp".to_string(),
            },
            RecoveryStrategy::EmergencyShutdown,
            RecoveryStrategy::UserNotification {
                message: "msg".to_string(),
            },
            RecoveryStrategy::AutomaticRepair {
                repair_action: "repair".to_string(),
            },
        ];
        for s in &strats {
            assert!(!format!("{:?}", s).is_empty());
        }
    }

    // ── CircuitState variants ─────────────────────────────────────────────

    #[test]
    fn test_circuit_state_variants() {
        let states = [
            CircuitState::Closed,
            CircuitState::Open,
            CircuitState::HalfOpen,
        ];
        for s in &states {
            assert!(!format!("{:?}", s).is_empty());
        }
    }

    // ── HealthStatus variants ─────────────────────────────────────────────

    #[test]
    fn test_health_status_variants() {
        let statuses = [
            HealthStatus::Healthy,
            HealthStatus::Degraded,
            HealthStatus::Unhealthy,
            HealthStatus::Critical,
        ];
        for s in &statuses {
            assert!(!format!("{:?}", s).is_empty());
        }
    }

    // ── CircuitBreaker ────────────────────────────────────────────────────

    #[test]
    fn test_circuit_breaker_initial_state() {
        let system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        assert_eq!(system.circuit_breaker.failure_count, 0);
        assert!(system.circuit_breaker.last_failure_time.is_none());
        assert_eq!(system.circuit_breaker.threshold, 5);
    }

    // ── SystemState struct ────────────────────────────────────────────────

    #[test]
    fn test_system_state_construction() {
        let state = SystemState {
            memory_usage_mb: 2048,
            cpu_usage_percent: 75.5,
            active_tensors: 10,
            active_sessions: 2,
            uptime_seconds: 3600,
        };
        assert_eq!(state.memory_usage_mb, 2048);
        assert!((state.cpu_usage_percent - 75.5).abs() < 1e-6);
    }

    // ── HealthMetrics ──────────────────────────────────────────────────────

    #[test]
    fn test_health_metrics_initial_values() {
        let system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        let m = &system.health_monitor.health_metrics;
        assert_eq!(m.error_rate, 0.0);
        assert_eq!(m.recovery_success_rate, 1.0);
    }

    // ── async handle_error with open circuit breaker ──────────────────────

    #[tokio::test]
    async fn test_handle_error_with_open_circuit_breaker() {
        let mut system = ErrorRecoverySystem::new(ErrorRecoveryConfig::default());
        system.circuit_breaker.state = CircuitState::Open;
        let event = make_error_event(ErrorType::IOError);
        let result = system.handle_error(event).await.expect("should succeed");
        assert!(!result.success);
        assert!(result.message.contains("Circuit breaker"));
    }
}