scirs2-autograd 0.3.2

Automatic differentiation module for SciRS2 (scirs2-autograd)
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
//! Error mapping utilities for SciRS2 module integration
//!
//! This module provides consistent error handling and mapping between
//! different SciRS2 modules, allowing for unified error reporting
//! and recovery strategies across the ecosystem.

use super::IntegrationError;
use std::collections::HashMap;

/// Error mapping registry for cross-module error handling
pub struct ErrorMapper {
    /// Registered error mappings
    mappings: HashMap<String, Box<dyn ErrorMapping>>,
    /// Error context stack
    context_stack: Vec<ErrorContext>,
    /// Error recovery strategies
    recovery_strategies: HashMap<String, Box<dyn ErrorRecovery>>,
}

impl ErrorMapper {
    /// Create new error mapper
    pub fn new() -> Self {
        let mut mapper = Self {
            mappings: HashMap::new(),
            context_stack: Vec::new(),
            recovery_strategies: HashMap::new(),
        };

        // Register built-in mappings
        mapper.register_builtin_mappings();
        mapper.register_builtin_recovery_strategies();

        mapper
    }

    /// Register an error mapping
    pub fn register_mapping<M: ErrorMapping + 'static>(
        &mut self,
        source_module: String,
        mapping: M,
    ) {
        self.mappings.insert(source_module, Box::new(mapping));
    }

    /// Register error recovery strategy
    pub fn register_recovery<R: ErrorRecovery + 'static>(
        &mut self,
        error_type: String,
        recovery: R,
    ) {
        self.recovery_strategies
            .insert(error_type, Box::new(recovery));
    }

    /// Map error from source module to integration error
    pub fn map_error(
        &self,
        source_module: &str,
        source_error: &dyn std::error::Error,
    ) -> IntegrationError {
        if let Some(mapping) = self.mappings.get(source_module) {
            mapping.map_error(source_error)
        } else {
            IntegrationError::ModuleCompatibility(format!(
                "Unmapped _error from {source_module}: {source_error}"
            ))
        }
    }

    /// Push error context
    pub fn push_context(&mut self, context: ErrorContext) {
        self.context_stack.push(context);
    }

    /// Pop error context
    pub fn pop_context(&mut self) -> Option<ErrorContext> {
        self.context_stack.pop()
    }

    /// Get current error context
    pub fn current_context(&self) -> Option<&ErrorContext> {
        self.context_stack.last()
    }

    /// Attempt error recovery
    pub fn attempt_recovery(
        &self,
        error: &IntegrationError,
    ) -> Result<RecoveryAction, IntegrationError> {
        let error_type = self.classify_error(error);

        if let Some(recovery) = self.recovery_strategies.get(&error_type) {
            recovery.attempt_recovery(error)
        } else {
            Err(IntegrationError::ModuleCompatibility(format!(
                "No recovery strategy for error type: {error_type}"
            )))
        }
    }

    /// Create enriched error with context
    pub fn enrich_error(&self, error: IntegrationError) -> EnrichedError {
        let suggestions = self.generate_suggestions(&error);
        EnrichedError {
            original_error: error,
            context_stack: self.context_stack.clone(),
            module_trace: self.build_module_trace(),
            suggestions,
            related_errors: Vec::new(),
        }
    }

    /// Aggregate multiple errors into a single report
    pub fn aggregate_errors(&self, errors: Vec<IntegrationError>) -> AggregatedError {
        let mut by_category = HashMap::new();
        let mut by_module = HashMap::new();

        for (index, error) in errors.iter().enumerate() {
            let category = self.classify_error(error);
            by_category
                .entry(category.clone())
                .or_insert_with(Vec::new)
                .push(index);

            if let Some(module) = self.extract_module_from_error(error) {
                by_module.entry(module).or_insert_with(Vec::new).push(index);
            }
        }

        let summary = ErrorMapper::generate_error_summary_from_indices(&errors, &by_category);

        AggregatedError {
            errors,
            by_category,
            by_module,
            summary,
        }
    }

    /// Generate error report
    pub fn generate_report(&self, error: &IntegrationError) -> ErrorReport {
        let enriched = self.enrich_error(error.clone());

        ErrorReport {
            error_id: ErrorMapper::generate_error_id(&enriched),
            timestamp: std::time::SystemTime::now(),
            error_type: self.classify_error(error),
            severity: self.assess_severity(error),
            enriched_error: enriched,
            recovery_suggestions: self.generate_recovery_suggestions(error),
            related_documentation: self.find_related_documentation(error),
        }
    }

    // Helper methods
    fn register_builtin_mappings(&mut self) {
        // Register neural module error mapping
        self.mappings
            .insert("scirs2-neural".to_string(), Box::new(NeuralErrorMapping));

        // Register optimization module error mapping
        self.mappings
            .insert("scirs2-optim".to_string(), Box::new(OptimErrorMapping));

        // Register linear algebra module error mapping
        self.mappings
            .insert("scirs2-linalg".to_string(), Box::new(LinalgErrorMapping));

        // Register core module error mapping
        self.mappings
            .insert("scirs2-core".to_string(), Box::new(CoreErrorMapping));
    }

    fn register_builtin_recovery_strategies(&mut self) {
        // Register tensor conversion recovery
        self.recovery_strategies.insert(
            "tensor_conversion".to_string(),
            Box::new(TensorConversionRecovery),
        );

        // Register module compatibility recovery
        self.recovery_strategies.insert(
            "module_compatibility".to_string(),
            Box::new(CompatibilityRecovery),
        );

        // Register configuration recovery
        self.recovery_strategies
            .insert("configuration".to_string(), Box::new(ConfigurationRecovery));
    }

    fn classify_error(&self, error: &IntegrationError) -> String {
        match error {
            IntegrationError::TensorConversion(_) => "tensor_conversion".to_string(),
            IntegrationError::ModuleCompatibility(_) => "module_compatibility".to_string(),
            IntegrationError::ConfigMismatch(_) => "configuration".to_string(),
            IntegrationError::VersionIncompatibility(_) => "version_compatibility".to_string(),
            IntegrationError::ApiBoundary(_) => "api_boundary".to_string(),
        }
    }

    fn assess_severity(&self, error: &IntegrationError) -> ErrorSeverity {
        match error {
            IntegrationError::TensorConversion(_) => ErrorSeverity::Medium,
            IntegrationError::ModuleCompatibility(_) => ErrorSeverity::High,
            IntegrationError::ConfigMismatch(_) => ErrorSeverity::Low,
            IntegrationError::VersionIncompatibility(_) => ErrorSeverity::High,
            IntegrationError::ApiBoundary(_) => ErrorSeverity::Medium,
        }
    }

    fn extract_module_from_error(&self, error: &IntegrationError) -> Option<String> {
        // Extract module name from error message or context
        match error {
            IntegrationError::ModuleCompatibility(msg)
            | IntegrationError::TensorConversion(msg)
            | IntegrationError::ConfigMismatch(msg)
            | IntegrationError::VersionIncompatibility(msg)
            | IntegrationError::ApiBoundary(msg) => {
                // Simple extraction based on known module names
                if msg.contains("scirs2-neural") {
                    Some("scirs2-neural".to_string())
                } else if msg.contains("scirs2-optim") {
                    Some("scirs2-optim".to_string())
                } else if msg.contains("scirs2-linalg") {
                    Some("scirs2-linalg".to_string())
                } else {
                    None
                }
            }
        }
    }

    fn build_module_trace(&self) -> Vec<String> {
        self.context_stack
            .iter()
            .map(|ctx| ctx.module_name.clone())
            .collect()
    }

    fn generate_suggestions(&self, error: &IntegrationError) -> Vec<String> {
        match error {
            IntegrationError::TensorConversion(_) => vec![
                "Check tensor shapes and data types".to_string(),
                "Ensure compatible precision levels".to_string(),
                "Verify memory layout compatibility".to_string(),
            ],
            IntegrationError::ModuleCompatibility(_) => vec![
                "Check module versions".to_string(),
                "Verify required features are enabled".to_string(),
                "Update module dependencies".to_string(),
            ],
            IntegrationError::ConfigMismatch(_) => vec![
                "Check configuration file syntax".to_string(),
                "Verify environment variables".to_string(),
                "Reset to default configuration".to_string(),
            ],
            IntegrationError::VersionIncompatibility(_) => vec![
                "Update to compatible versions".to_string(),
                "Check version compatibility matrix".to_string(),
                "Use version pinning in dependencies".to_string(),
            ],
            IntegrationError::ApiBoundary(_) => vec![
                "Check API documentation".to_string(),
                "Verify function signatures".to_string(),
                "Update integration code".to_string(),
            ],
        }
    }

    #[allow(dead_code)]
    fn generate_error_summary(
        &self,
        by_category: &HashMap<String, Vec<&IntegrationError>>,
    ) -> String {
        let mut summary = String::new();
        summary.push_str(&format!("Found {} error categories:\n", by_category.len()));

        for (category, errors) in by_category {
            summary.push_str(&format!("  {}: {} errors\n", category, errors.len()));
        }

        summary
    }

    fn generate_error_summary_from_indices(
        self_errors: &[IntegrationError],
        by_category: &HashMap<String, Vec<usize>>,
    ) -> String {
        let mut summary = String::new();
        summary.push_str(&format!("Found {} error categories:\n", by_category.len()));

        for (category, error_indices) in by_category {
            summary.push_str(&format!(
                "  {}: {} _errors\n",
                category,
                error_indices.len()
            ));
        }

        summary
    }

    fn generate_error_id(selfenriched: &EnrichedError) -> String {
        // Generate unique error ID
        format!(
            "ERR_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis()
        )
    }

    fn generate_recovery_suggestions(&self, error: &IntegrationError) -> Vec<RecoverySuggestion> {
        let base_suggestions = self.generate_suggestions(error);

        base_suggestions
            .into_iter()
            .enumerate()
            .map(|(i, suggestion)| RecoverySuggestion {
                priority: if i == 0 {
                    Priority::High
                } else {
                    Priority::Medium
                },
                action: suggestion,
                estimated_success_rate: 0.7 - (i as f64 * 0.1),
                requires_restart: false,
            })
            .collect()
    }

    fn find_related_documentation(&self, error: &IntegrationError) -> Vec<DocumentationLink> {
        match error {
            IntegrationError::TensorConversion(_) => vec![DocumentationLink {
                title: "Tensor Conversion Guide".to_string(),
                url: "https://scirs2.dev/docs/tensor-conversion".to_string(),
                section: Some("Basic Conversion".to_string()),
            }],
            IntegrationError::ModuleCompatibility(_) => vec![DocumentationLink {
                title: "Module Compatibility Matrix".to_string(),
                url: "https://scirs2.dev/docs/compatibility".to_string(),
                section: None,
            }],
            _ => Vec::new(),
        }
    }
}

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

/// Trait for error mapping between modules
pub trait ErrorMapping: Send {
    fn map_error(&self, sourceerror: &dyn std::error::Error) -> IntegrationError;
}

/// Trait for error recovery strategies
pub trait ErrorRecovery: Send {
    fn attempt_recovery(
        &self,
        error: &IntegrationError,
    ) -> Result<RecoveryAction, IntegrationError>;
}

/// Error context for tracking error origins
#[derive(Debug, Clone)]
pub struct ErrorContext {
    pub module_name: String,
    pub function_name: Option<String>,
    pub operation: Option<String>,
    pub additional_info: HashMap<String, String>,
}

impl ErrorContext {
    /// Create new error context
    pub fn new(module_name: String) -> Self {
        Self {
            module_name,
            function_name: None,
            operation: None,
            additional_info: HashMap::new(),
        }
    }

    /// Add function name
    pub fn with_function(mut self, function_name: String) -> Self {
        self.function_name = Some(function_name);
        self
    }

    /// Add operation name
    pub fn with_operation(mut self, operation: String) -> Self {
        self.operation = Some(operation);
        self
    }

    /// Add additional information
    pub fn with_info(mut self, key: String, value: String) -> Self {
        self.additional_info.insert(key, value);
        self
    }
}

/// Enriched error with additional context
#[derive(Debug, Clone)]
pub struct EnrichedError {
    pub original_error: IntegrationError,
    pub context_stack: Vec<ErrorContext>,
    pub module_trace: Vec<String>,
    pub suggestions: Vec<String>,
    pub related_errors: Vec<IntegrationError>,
}

/// Aggregated error report
#[derive(Debug)]
pub struct AggregatedError {
    pub errors: Vec<IntegrationError>,
    pub by_category: HashMap<String, Vec<usize>>,
    pub by_module: HashMap<String, Vec<usize>>,
    pub summary: String,
}

/// Comprehensive error report
#[derive(Debug)]
pub struct ErrorReport {
    pub error_id: String,
    pub timestamp: std::time::SystemTime,
    pub error_type: String,
    pub severity: ErrorSeverity,
    pub enriched_error: EnrichedError,
    pub recovery_suggestions: Vec<RecoverySuggestion>,
    pub related_documentation: Vec<DocumentationLink>,
}

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

/// Recovery actions
#[derive(Debug, Clone)]
pub enum RecoveryAction {
    Retry,
    RetryWithConfig(HashMap<String, String>),
    Fallback(String),
    ManualIntervention(String),
    Abort,
}

/// Recovery suggestion
#[derive(Debug, Clone)]
pub struct RecoverySuggestion {
    pub priority: Priority,
    pub action: String,
    pub estimated_success_rate: f64,
    pub requires_restart: bool,
}

/// Priority levels
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Priority {
    Low,
    Medium,
    High,
    Critical,
}

/// Documentation link
#[derive(Debug, Clone)]
pub struct DocumentationLink {
    pub title: String,
    pub url: String,
    pub section: Option<String>,
}

// Built-in error mappings

/// Neural module error mapping
struct NeuralErrorMapping;

impl ErrorMapping for NeuralErrorMapping {
    fn map_error(&self, source_error: &dyn std::error::Error) -> IntegrationError {
        let error_str = source_error.to_string().to_lowercase();

        if error_str.contains("tensor") || error_str.contains("shape") {
            IntegrationError::TensorConversion(format!(
                "Neural module tensor _error: {source_error}"
            ))
        } else if error_str.contains("gradient") {
            IntegrationError::ApiBoundary(format!("Neural module gradient error: {source_error}"))
        } else {
            IntegrationError::ModuleCompatibility(format!("Neural module error: {source_error}"))
        }
    }
}

/// Optimization module error mapping
struct OptimErrorMapping;

impl ErrorMapping for OptimErrorMapping {
    fn map_error(&self, source_error: &dyn std::error::Error) -> IntegrationError {
        let error_str = source_error.to_string().to_lowercase();

        if error_str.contains("parameter") || error_str.contains("optimizer") {
            IntegrationError::ConfigMismatch(format!(
                "Optimizer configuration _error: {source_error}"
            ))
        } else if error_str.contains("learning_rate") {
            IntegrationError::ConfigMismatch(format!("Learning rate error: {source_error}"))
        } else {
            IntegrationError::ModuleCompatibility(format!(
                "Optimization module _error: {source_error}"
            ))
        }
    }
}

/// Linear algebra module error mapping
struct LinalgErrorMapping;

impl ErrorMapping for LinalgErrorMapping {
    fn map_error(&self, source_error: &dyn std::error::Error) -> IntegrationError {
        let error_str = source_error.to_string().to_lowercase();

        if error_str.contains("matrix") || error_str.contains("dimension") {
            IntegrationError::TensorConversion(format!("Matrix dimension error: {source_error}"))
        } else if error_str.contains("singular") || error_str.contains("decomposition") {
            IntegrationError::ApiBoundary(format!(
                "Linear algebra operation _error: {source_error}"
            ))
        } else {
            IntegrationError::ModuleCompatibility(format!(
                "Linear algebra module _error: {source_error}"
            ))
        }
    }
}

/// Core module error mapping
struct CoreErrorMapping;

impl ErrorMapping for CoreErrorMapping {
    fn map_error(&self, source_error: &dyn std::error::Error) -> IntegrationError {
        let error_str = source_error.to_string().to_lowercase();

        if error_str.contains("config") {
            IntegrationError::ConfigMismatch(format!("Core configuration error: {source_error}"))
        } else if error_str.contains("type") || error_str.contains("conversion") {
            IntegrationError::TensorConversion(format!(
                "Core type conversion _error: {source_error}"
            ))
        } else {
            IntegrationError::ModuleCompatibility(format!("Core module error: {source_error}"))
        }
    }
}

// Built-in recovery strategies

/// Tensor conversion recovery strategy
struct TensorConversionRecovery;

impl ErrorRecovery for TensorConversionRecovery {
    fn attempt_recovery(
        &self,
        error: &IntegrationError,
    ) -> Result<RecoveryAction, IntegrationError> {
        match error {
            IntegrationError::TensorConversion(msg) => {
                if msg.contains("shape") {
                    Ok(RecoveryAction::RetryWithConfig(
                        [("auto_reshape".to_string(), "true".to_string())].into(),
                    ))
                } else if msg.contains("precision") {
                    Ok(RecoveryAction::RetryWithConfig(
                        [("auto_convert_precision".to_string(), "true".to_string())].into(),
                    ))
                } else {
                    Ok(RecoveryAction::Fallback(
                        "Use manual conversion".to_string(),
                    ))
                }
            }
            _ => Err(IntegrationError::ModuleCompatibility(
                "Cannot recover from non-tensor-conversion error".to_string(),
            )),
        }
    }
}

/// Module compatibility recovery strategy
struct CompatibilityRecovery;

impl ErrorRecovery for CompatibilityRecovery {
    fn attempt_recovery(
        &self,
        error: &IntegrationError,
    ) -> Result<RecoveryAction, IntegrationError> {
        match error {
            IntegrationError::ModuleCompatibility(_) => Ok(RecoveryAction::ManualIntervention(
                "Check module versions and update dependencies".to_string(),
            )),
            IntegrationError::VersionIncompatibility(_) => Ok(RecoveryAction::ManualIntervention(
                "Update to compatible module versions".to_string(),
            )),
            _ => Err(IntegrationError::ModuleCompatibility(
                "Cannot recover from non-compatibility error".to_string(),
            )),
        }
    }
}

/// Configuration recovery strategy
struct ConfigurationRecovery;

impl ErrorRecovery for ConfigurationRecovery {
    fn attempt_recovery(
        &self,
        error: &IntegrationError,
    ) -> Result<RecoveryAction, IntegrationError> {
        match error {
            IntegrationError::ConfigMismatch(_) => Ok(RecoveryAction::RetryWithConfig(
                [("use_defaults".to_string(), "true".to_string())].into(),
            )),
            _ => Err(IntegrationError::ConfigMismatch(
                "Cannot recover from non-configuration error".to_string(),
            )),
        }
    }
}

/// Global error mapper instance
static GLOBAL_ERROR_MAPPER: std::sync::OnceLock<std::sync::Mutex<ErrorMapper>> =
    std::sync::OnceLock::new();

/// Initialize global error mapper
#[allow(dead_code)]
pub fn init_error_mapper() -> &'static std::sync::Mutex<ErrorMapper> {
    GLOBAL_ERROR_MAPPER.get_or_init(|| std::sync::Mutex::new(ErrorMapper::new()))
}

/// Map error using global mapper
#[allow(dead_code)]
pub fn map_module_error(
    source_module: &str,
    source_error: &dyn std::error::Error,
) -> IntegrationError {
    let mapper = init_error_mapper();
    if let Ok(mapper_guard) = mapper.lock() {
        mapper_guard.map_error(source_module, source_error)
    } else {
        IntegrationError::ModuleCompatibility(format!(
            "Failed to acquire _error mapper lock for {source_module}: {source_error}"
        ))
    }
}

/// Push error context
#[allow(dead_code)]
pub fn push_error_context(context: ErrorContext) -> Result<(), IntegrationError> {
    let mapper = init_error_mapper();
    let mut mapper_guard = mapper.lock().map_err(|_| {
        IntegrationError::ModuleCompatibility("Failed to acquire error mapper lock".to_string())
    })?;
    mapper_guard.push_context(context);
    Ok(())
}

/// Pop error context
#[allow(dead_code)]
pub fn pop_error_context() -> Result<Option<ErrorContext>, IntegrationError> {
    let mapper = init_error_mapper();
    let mut mapper_guard = mapper.lock().map_err(|_| {
        IntegrationError::ModuleCompatibility("Failed to acquire error mapper lock".to_string())
    })?;
    Ok(mapper_guard.pop_context())
}

/// Generate error report
#[allow(dead_code)]
pub fn generate_error_report(error: &IntegrationError) -> Result<ErrorReport, IntegrationError> {
    let mapper = init_error_mapper();
    let mapper_guard = mapper.lock().map_err(|_| {
        IntegrationError::ModuleCompatibility("Failed to acquire error mapper lock".to_string())
    })?;
    Ok(mapper_guard.generate_report(error))
}

/// Attempt error recovery
#[allow(dead_code)]
pub fn attempt_error_recovery(
    error: &IntegrationError,
) -> Result<RecoveryAction, IntegrationError> {
    let mapper = init_error_mapper();
    let mapper_guard = mapper.lock().map_err(|_| {
        IntegrationError::ModuleCompatibility("Failed to acquire error mapper lock".to_string())
    })?;
    mapper_guard.attempt_recovery(error)
}

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

    #[test]
    fn test_error_mapper_creation() {
        let mapper = ErrorMapper::new();
        assert_eq!(mapper.mappings.len(), 4); // neural, optim, linalg, core
        assert_eq!(mapper.recovery_strategies.len(), 3);
    }

    #[test]
    fn test_error_context() {
        let context = ErrorContext::new("test_module".to_string())
            .with_function("test_function".to_string())
            .with_operation("test_operation".to_string())
            .with_info("key".to_string(), "value".to_string());

        assert_eq!(context.module_name, "test_module");
        assert_eq!(context.function_name, Some("test_function".to_string()));
        assert_eq!(context.operation, Some("test_operation".to_string()));
        assert_eq!(
            context.additional_info.get("key"),
            Some(&"value".to_string())
        );
    }

    #[test]
    fn test_neural_error_mapping() {
        let mapping = NeuralErrorMapping;

        // Create a dummy error
        let dummy_error = IntegrationError::TensorConversion("tensor shape mismatch".to_string());
        let mapped = mapping.map_error(&dummy_error);

        assert!(matches!(mapped, IntegrationError::TensorConversion(_)));
    }

    #[test]
    fn test_error_classification() {
        let mapper = ErrorMapper::new();

        let tensor_error = IntegrationError::TensorConversion("test".to_string());
        assert_eq!(mapper.classify_error(&tensor_error), "tensor_conversion");

        let compat_error = IntegrationError::ModuleCompatibility("test".to_string());
        assert_eq!(mapper.classify_error(&compat_error), "module_compatibility");
    }

    #[test]
    fn test_error_severity() {
        let mapper = ErrorMapper::new();

        let config_error = IntegrationError::ConfigMismatch("test".to_string());
        assert_eq!(mapper.assess_severity(&config_error), ErrorSeverity::Low);

        let compat_error = IntegrationError::ModuleCompatibility("test".to_string());
        assert_eq!(mapper.assess_severity(&compat_error), ErrorSeverity::High);
    }

    #[test]
    fn test_recovery_strategy() {
        let recovery = TensorConversionRecovery;

        let shape_error = IntegrationError::TensorConversion("shape mismatch".to_string());
        let result = recovery
            .attempt_recovery(&shape_error)
            .expect("Operation failed");

        assert!(matches!(result, RecoveryAction::RetryWithConfig(_)));
    }

    #[test]
    fn test_context_stack() {
        let mut mapper = ErrorMapper::new();

        let context1 = ErrorContext::new("module1".to_string());
        let context2 = ErrorContext::new("module2".to_string());

        mapper.push_context(context1);
        mapper.push_context(context2);

        assert_eq!(mapper.context_stack.len(), 2);
        assert_eq!(
            mapper
                .current_context()
                .expect("Operation failed")
                .module_name,
            "module2"
        );

        let popped = mapper.pop_context().expect("Operation failed");
        assert_eq!(popped.module_name, "module2");
        assert_eq!(mapper.context_stack.len(), 1);
    }

    #[test]
    fn test_global_error_mapping() {
        let dummy_error = IntegrationError::TensorConversion("test error".to_string());
        let mapped = map_module_error("scirs2-neural", &dummy_error);

        // Should successfully map without panicking
        assert!(matches!(mapped, IntegrationError::TensorConversion(_)));
    }

    #[test]
    fn test_global_context_management() {
        let context = ErrorContext::new("test_module".to_string());

        push_error_context(context).expect("Operation failed");
        let popped = pop_error_context().expect("Operation failed");

        assert!(popped.is_some());
        assert_eq!(popped.expect("Operation failed").module_name, "test_module");
    }
}