trustformers-core 0.1.1

Core traits and utilities for TrustformeRS
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
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
//! Performance regression detection system
//!
//! This module provides automated detection of performance regressions by comparing
//! current benchmark results with historical baselines.

use crate::errors::{performance_error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

/// Performance baseline for a specific benchmark
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceBaseline {
    /// Benchmark name/identifier
    pub benchmark_name: String,
    /// Mean execution time in nanoseconds
    pub mean_time_ns: u64,
    /// Standard deviation in nanoseconds
    pub std_dev_ns: u64,
    /// Throughput in operations per second (if applicable)
    pub throughput_ops_per_sec: Option<f64>,
    /// Memory usage in bytes
    pub memory_usage_bytes: Option<u64>,
    /// Timestamp when baseline was recorded
    pub timestamp: u64,
    /// Git commit hash (if available)
    pub commit_hash: Option<String>,
    /// Hardware configuration when recorded
    pub hardware_config: HardwareConfig,
}

/// Hardware configuration information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareConfig {
    /// CPU model information
    pub cpu_model: Option<String>,
    /// Number of CPU cores
    pub cpu_cores: u32,
    /// Available system memory in bytes
    pub system_memory_bytes: u64,
    /// GPU information (if available)
    pub gpu_info: Option<String>,
    /// Operating system
    pub os: String,
}

/// Performance regression detection result
#[derive(Debug, Clone)]
pub struct RegressionResult {
    /// Whether a regression was detected
    pub is_regression: bool,
    /// Severity of the regression (0.0 = no regression, 1.0 = severe)
    pub severity: f64,
    /// Performance change percentage (negative = improvement, positive = regression)
    pub performance_change_percent: f64,
    /// Current measurement
    pub current_measurement: PerformanceMeasurement,
    /// Baseline used for comparison
    pub baseline: PerformanceBaseline,
    /// Detailed analysis
    pub analysis: String,
}

/// Current performance measurement
#[derive(Debug, Clone)]
pub struct PerformanceMeasurement {
    /// Execution time in nanoseconds
    pub time_ns: u64,
    /// Throughput in operations per second (if applicable)
    pub throughput_ops_per_sec: Option<f64>,
    /// Memory usage in bytes
    pub memory_usage_bytes: Option<u64>,
}

/// Configuration for regression detection
#[derive(Debug, Clone)]
pub struct RegressionConfig {
    /// Threshold for detecting performance regression (e.g., 0.1 = 10% slower)
    pub regression_threshold: f64,
    /// Number of standard deviations to consider significant
    pub std_dev_threshold: f64,
    /// Whether to consider memory regressions
    pub check_memory_regression: bool,
    /// Whether to consider throughput regressions
    pub check_throughput_regression: bool,
    /// Minimum number of measurements needed for reliable detection
    pub min_measurements: usize,
}

impl Default for RegressionConfig {
    fn default() -> Self {
        Self {
            regression_threshold: 0.05, // 5% performance degradation
            std_dev_threshold: 2.0,     // 2 standard deviations
            check_memory_regression: true,
            check_throughput_regression: true,
            min_measurements: 5,
        }
    }
}

/// Performance regression detector
pub struct RegressionDetector {
    /// Configuration for detection
    config: RegressionConfig,
    /// Storage path for baselines
    storage_path: PathBuf,
    /// In-memory cache of baselines
    baselines: HashMap<String, PerformanceBaseline>,
}

impl RegressionDetector {
    /// Create a new regression detector
    pub fn new(storage_path: impl AsRef<Path>, config: RegressionConfig) -> Result<Self> {
        let storage_path = storage_path.as_ref().to_path_buf();

        // Create storage directory if it doesn't exist
        if let Some(parent) = storage_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                performance_error(format!(
                    "Failed to create baseline storage directory: {}",
                    e
                ))
            })?;
        }

        let mut detector = Self {
            config,
            storage_path,
            baselines: HashMap::new(),
        };

        // Load existing baselines
        detector.load_baselines()?;

        Ok(detector)
    }

    /// Record a new baseline measurement
    pub fn record_baseline(
        &mut self,
        benchmark_name: impl Into<String>,
        measurement: PerformanceMeasurement,
    ) -> Result<()> {
        let benchmark_name = benchmark_name.into();
        let hardware_config = Self::detect_hardware_config()?;

        let baseline = PerformanceBaseline {
            benchmark_name: benchmark_name.clone(),
            mean_time_ns: measurement.time_ns,
            std_dev_ns: 0, // Will be updated with multiple measurements
            throughput_ops_per_sec: measurement.throughput_ops_per_sec,
            memory_usage_bytes: measurement.memory_usage_bytes,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("SystemTime should be after UNIX_EPOCH")
                .as_secs(),
            commit_hash: Self::get_git_commit_hash(),
            hardware_config,
        };

        self.baselines.insert(benchmark_name, baseline);
        self.save_baselines()?;

        Ok(())
    }

    /// Check for performance regression against baseline
    pub fn check_regression(
        &self,
        benchmark_name: &str,
        current_measurement: PerformanceMeasurement,
    ) -> Result<Option<RegressionResult>> {
        let baseline = match self.baselines.get(benchmark_name) {
            Some(baseline) => baseline,
            None => return Ok(None), // No baseline available
        };

        let time_change = if baseline.mean_time_ns > 0 {
            (current_measurement.time_ns as f64 - baseline.mean_time_ns as f64)
                / baseline.mean_time_ns as f64
        } else {
            0.0
        };

        let mut is_regression = false;
        let mut severity = 0.0;
        let mut analysis_parts = Vec::new();

        // Check execution time regression
        if time_change > self.config.regression_threshold {
            is_regression = true;
            severity = (time_change / self.config.regression_threshold).min(1.0);
            analysis_parts.push(format!(
                "Execution time increased by {:.1}% (threshold: {:.1}%)",
                time_change * 100.0,
                self.config.regression_threshold * 100.0
            ));
        }

        // Check throughput regression
        if self.config.check_throughput_regression {
            if let (Some(current_throughput), Some(baseline_throughput)) = (
                current_measurement.throughput_ops_per_sec,
                baseline.throughput_ops_per_sec,
            ) {
                let throughput_change =
                    (baseline_throughput - current_throughput) / baseline_throughput;
                if throughput_change > self.config.regression_threshold {
                    is_regression = true;
                    severity = severity
                        .max((throughput_change / self.config.regression_threshold).min(1.0));
                    analysis_parts.push(format!(
                        "Throughput decreased by {:.1}% (threshold: {:.1}%)",
                        throughput_change * 100.0,
                        self.config.regression_threshold * 100.0
                    ));
                }
            }
        }

        // Check memory usage regression
        if self.config.check_memory_regression {
            if let (Some(current_memory), Some(baseline_memory)) = (
                current_measurement.memory_usage_bytes,
                baseline.memory_usage_bytes,
            ) {
                let memory_change = if baseline_memory > 0 {
                    (current_memory as f64 - baseline_memory as f64) / baseline_memory as f64
                } else {
                    0.0
                };

                if memory_change > self.config.regression_threshold {
                    is_regression = true;
                    severity =
                        severity.max((memory_change / self.config.regression_threshold).min(1.0));
                    analysis_parts.push(format!(
                        "Memory usage increased by {:.1}% (threshold: {:.1}%)",
                        memory_change * 100.0,
                        self.config.regression_threshold * 100.0
                    ));
                }
            }
        }

        let analysis = if analysis_parts.is_empty() {
            "No performance regression detected".to_string()
        } else {
            analysis_parts.join("; ")
        };

        Ok(Some(RegressionResult {
            is_regression,
            severity,
            performance_change_percent: time_change * 100.0,
            current_measurement,
            baseline: baseline.clone(),
            analysis,
        }))
    }

    /// Update baseline with new measurement (incremental statistics)
    pub fn update_baseline(
        &mut self,
        benchmark_name: &str,
        measurement: PerformanceMeasurement,
    ) -> Result<()> {
        if let Some(baseline) = self.baselines.get_mut(benchmark_name) {
            // Simple moving average update (could be improved with proper incremental statistics)
            let old_mean = baseline.mean_time_ns as f64;
            let new_value = measurement.time_ns as f64;
            let new_mean = (old_mean + new_value) / 2.0;

            // Update standard deviation (simplified)
            let old_variance = (baseline.std_dev_ns as f64).powi(2);
            let new_variance = (old_variance + (new_value - old_mean).powi(2)) / 2.0;

            baseline.mean_time_ns = new_mean as u64;
            baseline.std_dev_ns = new_variance.sqrt() as u64;
            baseline.timestamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("SystemTime should be after UNIX_EPOCH")
                .as_secs();

            if let Some(throughput) = measurement.throughput_ops_per_sec {
                baseline.throughput_ops_per_sec = Some(throughput);
            }

            if let Some(memory) = measurement.memory_usage_bytes {
                baseline.memory_usage_bytes = Some(memory);
            }

            self.save_baselines()?;
        }

        Ok(())
    }

    /// Get all available baselines
    pub fn get_baselines(&self) -> &HashMap<String, PerformanceBaseline> {
        &self.baselines
    }

    /// Load baselines from storage
    fn load_baselines(&mut self) -> Result<()> {
        if !self.storage_path.exists() {
            return Ok(());
        }

        let content = std::fs::read_to_string(&self.storage_path)
            .map_err(|e| performance_error(format!("Failed to read baselines file: {}", e)))?;

        let baselines: HashMap<String, PerformanceBaseline> = serde_json::from_str(&content)
            .map_err(|e| performance_error(format!("Failed to parse baselines file: {}", e)))?;

        self.baselines = baselines;
        Ok(())
    }

    /// Save baselines to storage
    fn save_baselines(&self) -> Result<()> {
        let content = serde_json::to_string_pretty(&self.baselines)
            .map_err(|e| performance_error(format!("Failed to serialize baselines: {}", e)))?;

        std::fs::write(&self.storage_path, content)
            .map_err(|e| performance_error(format!("Failed to write baselines file: {}", e)))?;

        Ok(())
    }

    /// Detect current hardware configuration
    fn detect_hardware_config() -> Result<HardwareConfig> {
        Ok(HardwareConfig {
            cpu_model: Self::detect_cpu_model(),
            cpu_cores: num_cpus::get() as u32,
            system_memory_bytes: Self::get_system_memory(),
            gpu_info: Self::detect_gpu_info(),
            os: format!("{} {}", std::env::consts::OS, Self::get_os_version()),
        })
    }

    /// Get system memory size with proper detection
    fn get_system_memory() -> u64 {
        #[cfg(target_os = "linux")]
        {
            // Read from /proc/meminfo on Linux
            if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
                for line in meminfo.lines() {
                    if line.starts_with("MemTotal:") {
                        if let Some(kb_str) = line.split_whitespace().nth(1) {
                            if let Ok(kb) = kb_str.parse::<u64>() {
                                return kb * 1024; // Convert KB to bytes
                            }
                        }
                    }
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            // Use sysctl on macOS
            let output = std::process::Command::new("sysctl").args(["-n", "hw.memsize"]).output();

            if let Ok(output) = output {
                if let Ok(memory_str) = String::from_utf8(output.stdout) {
                    if let Ok(memory_bytes) = memory_str.trim().parse::<u64>() {
                        return memory_bytes;
                    }
                }
            }
        }

        #[cfg(target_os = "windows")]
        {
            // On Windows, we can use GlobalMemoryStatusEx
            // For now, fall back to default as we'd need windows-sys crate
        }

        // Fallback: estimate based on num_cpus (rough heuristic)
        let cpu_count = num_cpus::get() as u64;
        match cpu_count {
            1..=2 => 4 * 1024 * 1024 * 1024,  // 4GB for low-end systems
            3..=4 => 8 * 1024 * 1024 * 1024,  // 8GB for mid-range systems
            5..=8 => 16 * 1024 * 1024 * 1024, // 16GB for higher-end systems
            _ => 32 * 1024 * 1024 * 1024,     // 32GB for high-end systems
        }
    }

    /// Detect CPU model information
    fn detect_cpu_model() -> Option<String> {
        #[cfg(target_os = "linux")]
        {
            // Read from /proc/cpuinfo on Linux
            if let Ok(cpuinfo) = std::fs::read_to_string("/proc/cpuinfo") {
                for line in cpuinfo.lines() {
                    if line.starts_with("model name") {
                        if let Some(model) = line.split(':').nth(1) {
                            return Some(model.trim().to_string());
                        }
                    }
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            // Use sysctl on macOS
            let output = std::process::Command::new("sysctl")
                .args(["-n", "machdep.cpu.brand_string"])
                .output();

            if let Ok(output) = output {
                if let Ok(cpu_model) = String::from_utf8(output.stdout) {
                    return Some(cpu_model.trim().to_string());
                }
            }
        }

        #[cfg(target_os = "windows")]
        {
            // Use wmic on Windows
            let output = std::process::Command::new("wmic")
                .args(["cpu", "get", "name", "/format:list"])
                .output();

            if let Ok(output) = output {
                if let Ok(cpu_info) = String::from_utf8(output.stdout) {
                    for line in cpu_info.lines() {
                        if line.starts_with("Name=") {
                            return Some(line[5..].trim().to_string());
                        }
                    }
                }
            }
        }

        None
    }

    /// Detect GPU information
    fn detect_gpu_info() -> Option<String> {
        #[cfg(target_os = "linux")]
        {
            // Try to detect NVIDIA GPU first
            if let Ok(output) = std::process::Command::new("nvidia-smi")
                .args(["--query-gpu=gpu_name", "--format=csv,noheader,nounits"])
                .output()
            {
                if output.status.success() {
                    if let Ok(gpu_name) = String::from_utf8(output.stdout) {
                        let gpu_name = gpu_name.trim();
                        if !gpu_name.is_empty() {
                            return Some(format!("NVIDIA {}", gpu_name));
                        }
                    }
                }
            }

            // Try to detect AMD GPU
            if let Ok(output) =
                std::process::Command::new("rocm-smi").args(["--showproductname"]).output()
            {
                if output.status.success() {
                    if let Ok(gpu_info) = String::from_utf8(output.stdout) {
                        // Parse rocm-smi output
                        for line in gpu_info.lines() {
                            if line.contains("Card series:") {
                                if let Some(series) = line.split(':').nth(1) {
                                    return Some(format!("AMD {}", series.trim()));
                                }
                            }
                        }
                    }
                }
            }

            // Fallback: check lspci for GPU info
            if let Ok(output) = std::process::Command::new("lspci").args(["-nn"]).output() {
                if output.status.success() {
                    if let Ok(pci_info) = String::from_utf8(output.stdout) {
                        for line in pci_info.lines() {
                            if line.contains("VGA compatible controller")
                                || line.contains("3D controller")
                            {
                                return Some(
                                    line.split(':')
                                        .next_back()
                                        .unwrap_or("Unknown GPU")
                                        .trim()
                                        .to_string(),
                                );
                            }
                        }
                    }
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            // Use system_profiler on macOS
            let output = std::process::Command::new("system_profiler")
                .args(["SPDisplaysDataType", "-xml"])
                .output();

            if let Ok(output) = output {
                if let Ok(display_info) = String::from_utf8(output.stdout) {
                    // Simple parsing for GPU name
                    if display_info.contains("Apple") {
                        if display_info.contains("M1") {
                            return Some("Apple M1 GPU".to_string());
                        } else if display_info.contains("M2") {
                            return Some("Apple M2 GPU".to_string());
                        } else if display_info.contains("M3") {
                            return Some("Apple M3 GPU".to_string());
                        } else {
                            return Some("Apple Silicon GPU".to_string());
                        }
                    }
                    // Could add more parsing for discrete GPUs
                }
            }
        }

        #[cfg(target_os = "windows")]
        {
            // Use wmic on Windows
            let output = std::process::Command::new("wmic")
                .args([
                    "path",
                    "win32_VideoController",
                    "get",
                    "name",
                    "/format:list",
                ])
                .output();

            if let Ok(output) = output {
                if let Ok(gpu_info) = String::from_utf8(output.stdout) {
                    for line in gpu_info.lines() {
                        if line.starts_with("Name=") && line.len() > 5 {
                            let name = &line[5..];
                            if !name.trim().is_empty() {
                                return Some(name.trim().to_string());
                            }
                        }
                    }
                }
            }
        }

        None
    }

    /// Get OS version information
    fn get_os_version() -> String {
        #[cfg(target_os = "linux")]
        {
            // Try to read from /etc/os-release
            if let Ok(os_release) = std::fs::read_to_string("/etc/os-release") {
                let mut name = None;
                let mut version = None;

                for line in os_release.lines() {
                    if let Some(rest) = line.strip_prefix("NAME=") {
                        name = Some(rest.trim_matches('"').to_string());
                    } else if let Some(rest) = line.strip_prefix("VERSION=") {
                        version = Some(rest.trim_matches('"').to_string());
                    }
                }

                match (name, version) {
                    (Some(n), Some(v)) => return format!("{} {}", n, v),
                    (Some(n), None) => return n,
                    _ => {},
                }
            }

            // Fallback: try uname
            if let Ok(output) = std::process::Command::new("uname").args(["-r"]).output() {
                if let Ok(version) = String::from_utf8(output.stdout) {
                    return version.trim().to_string();
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            if let Ok(output) =
                std::process::Command::new("sw_vers").args(["-productVersion"]).output()
            {
                if let Ok(version) = String::from_utf8(output.stdout) {
                    return version.trim().to_string();
                }
            }
        }

        #[cfg(target_os = "windows")]
        {
            if let Ok(output) = std::process::Command::new("ver").output() {
                if let Ok(version) = String::from_utf8(output.stdout) {
                    return version.trim().to_string();
                }
            }
        }

        "Unknown".to_string()
    }

    /// Get current git commit hash
    fn get_git_commit_hash() -> Option<String> {
        // Simple implementation - could use git2 crate for better integration
        std::process::Command::new("git")
            .args(["rev-parse", "HEAD"])
            .output()
            .ok()
            .and_then(|output| {
                if output.status.success() {
                    String::from_utf8(output.stdout).ok().map(|s| s.trim().to_string())
                } else {
                    None
                }
            })
    }
}

/// Helper macro for easily recording performance measurements in tests
#[macro_export]
macro_rules! measure_performance {
    ($detector:expr, $benchmark_name:expr, $code:block) => {{
        let start = std::time::Instant::now();
        let result = $code;
        let duration = start.elapsed();

        let measurement = $crate::performance::regression_detector::PerformanceMeasurement {
            time_ns: duration.as_nanos() as u64,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };

        let _ = $detector.record_baseline($benchmark_name, measurement);
        result
    }};
}

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

    #[test]
    fn test_regression_detector_creation() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let detector = RegressionDetector::new(storage_path, RegressionConfig::default());
        assert!(detector.is_ok());
    }

    #[test]
    fn test_baseline_recording() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let measurement = PerformanceMeasurement {
            time_ns: 1_000_000, // 1ms
            throughput_ops_per_sec: Some(1000.0),
            memory_usage_bytes: Some(1024),
        };

        assert!(detector.record_baseline("test_benchmark", measurement).is_ok());
        assert!(detector.baselines.contains_key("test_benchmark"));
    }

    #[test]
    fn test_regression_detection() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        // Record baseline
        let baseline_measurement = PerformanceMeasurement {
            time_ns: 1_000_000, // 1ms
            throughput_ops_per_sec: Some(1000.0),
            memory_usage_bytes: Some(1024),
        };
        detector
            .record_baseline("test_benchmark", baseline_measurement)
            .expect("operation failed in test");

        // Test with faster performance (no regression)
        let faster_measurement = PerformanceMeasurement {
            time_ns: 900_000, // 0.9ms - 10% improvement
            throughput_ops_per_sec: Some(1100.0),
            memory_usage_bytes: Some(1000),
        };

        let result = detector
            .check_regression("test_benchmark", faster_measurement)
            .expect("operation failed in test");
        assert!(result.is_some());
        assert!(!result.expect("operation failed in test").is_regression);

        // Test with slower performance (regression)
        let slower_measurement = PerformanceMeasurement {
            time_ns: 1_200_000, // 1.2ms - 20% slower
            throughput_ops_per_sec: Some(800.0),
            memory_usage_bytes: Some(1200),
        };

        let result = detector
            .check_regression("test_benchmark", slower_measurement)
            .expect("operation failed in test");
        assert!(result.is_some());
        let regression = result.expect("operation failed in test");
        assert!(regression.is_regression);
        assert!(regression.severity > 0.0);
    }

    // ── RegressionConfig tests ──

    #[test]
    fn test_regression_config_default() {
        let config = RegressionConfig::default();
        assert!((config.regression_threshold - 0.05).abs() < 1e-6);
        assert!((config.std_dev_threshold - 2.0).abs() < 1e-6);
        assert!(config.check_memory_regression);
        assert!(config.check_throughput_regression);
        assert_eq!(config.min_measurements, 5);
    }

    #[test]
    fn test_regression_config_custom() {
        let config = RegressionConfig {
            regression_threshold: 0.1,
            std_dev_threshold: 3.0,
            check_memory_regression: false,
            check_throughput_regression: false,
            min_measurements: 10,
        };
        assert!((config.regression_threshold - 0.1).abs() < 1e-6);
        assert!(!config.check_memory_regression);
    }

    // ── HardwareConfig tests ──

    #[test]
    fn test_hardware_config_clone() {
        let config = HardwareConfig {
            cpu_model: Some("TestCPU".to_string()),
            cpu_cores: 8,
            system_memory_bytes: 16_000_000_000,
            gpu_info: None,
            os: "TestOS".to_string(),
        };
        let cloned = config.clone();
        assert_eq!(cloned.cpu_cores, 8);
        assert_eq!(cloned.os, "TestOS");
    }

    // ── PerformanceBaseline tests ──

    #[test]
    fn test_performance_baseline_clone() {
        let baseline = PerformanceBaseline {
            benchmark_name: "test_bench".to_string(),
            mean_time_ns: 1_000_000,
            std_dev_ns: 50_000,
            throughput_ops_per_sec: Some(1000.0),
            memory_usage_bytes: Some(1024),
            timestamp: 0,
            commit_hash: Some("abc123".to_string()),
            hardware_config: HardwareConfig {
                cpu_model: None,
                cpu_cores: 4,
                system_memory_bytes: 8_000_000_000,
                gpu_info: None,
                os: "test".to_string(),
            },
        };
        let cloned = baseline.clone();
        assert_eq!(cloned.benchmark_name, "test_bench");
        assert_eq!(cloned.mean_time_ns, 1_000_000);
    }

    // ── PerformanceMeasurement tests ──

    #[test]
    fn test_performance_measurement_clone() {
        let measurement = PerformanceMeasurement {
            time_ns: 500_000,
            throughput_ops_per_sec: Some(2000.0),
            memory_usage_bytes: Some(2048),
        };
        let cloned = measurement.clone();
        assert_eq!(cloned.time_ns, 500_000);
        assert_eq!(cloned.throughput_ops_per_sec, Some(2000.0));
    }

    // ── Regression detection edge cases ──

    #[test]
    fn test_check_regression_no_baseline() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let measurement = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };

        let result = detector
            .check_regression("nonexistent_benchmark", measurement)
            .expect("operation failed in test");
        assert!(result.is_none());
    }

    #[test]
    fn test_check_regression_identical_performance() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let measurement = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: Some(1000.0),
            memory_usage_bytes: Some(1024),
        };

        detector
            .record_baseline("test", measurement.clone())
            .expect("operation failed in test");

        let result = detector
            .check_regression("test", measurement)
            .expect("operation failed in test");
        assert!(result.is_some());
        assert!(!result.expect("should be present").is_regression);
    }

    #[test]
    fn test_check_regression_memory_increase() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let baseline = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: Some(1024),
        };
        detector.record_baseline("test", baseline).expect("operation failed in test");

        // 50% memory increase
        let current = PerformanceMeasurement {
            time_ns: 1_000_000, // Same time
            throughput_ops_per_sec: None,
            memory_usage_bytes: Some(1536),
        };

        let result = detector.check_regression("test", current).expect("operation failed in test");
        assert!(result.is_some());
        let r = result.expect("should be present");
        assert!(r.is_regression);
        assert!(r.analysis.contains("Memory"));
    }

    #[test]
    fn test_check_regression_throughput_decrease() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let baseline = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: Some(1000.0),
            memory_usage_bytes: None,
        };
        detector.record_baseline("test", baseline).expect("operation failed in test");

        // 50% throughput decrease
        let current = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: Some(500.0),
            memory_usage_bytes: None,
        };

        let result = detector.check_regression("test", current).expect("operation failed in test");
        assert!(result.is_some());
        let r = result.expect("should be present");
        assert!(r.is_regression);
        assert!(r.analysis.contains("Throughput"));
    }

    // ── Baseline update tests ──

    #[test]
    fn test_update_baseline() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let measurement1 = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: Some(1000.0),
            memory_usage_bytes: Some(1024),
        };
        detector
            .record_baseline("test", measurement1)
            .expect("operation failed in test");

        let measurement2 = PerformanceMeasurement {
            time_ns: 2_000_000,
            throughput_ops_per_sec: Some(500.0),
            memory_usage_bytes: Some(2048),
        };
        detector
            .update_baseline("test", measurement2)
            .expect("operation failed in test");

        let baselines = detector.get_baselines();
        let baseline = baselines.get("test").expect("baseline should exist");
        // Moving average: (1_000_000 + 2_000_000) / 2 = 1_500_000
        assert_eq!(baseline.mean_time_ns, 1_500_000);
    }

    #[test]
    fn test_update_nonexistent_baseline() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let measurement = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };
        // Should not fail, just do nothing
        assert!(detector.update_baseline("nonexistent", measurement).is_ok());
    }

    #[test]
    fn test_get_baselines_empty() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        assert!(detector.get_baselines().is_empty());
    }

    #[test]
    fn test_multiple_baselines() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        for i in 0..5 {
            let measurement = PerformanceMeasurement {
                time_ns: (i + 1) * 1_000_000,
                throughput_ops_per_sec: None,
                memory_usage_bytes: None,
            };
            detector
                .record_baseline(format!("bench_{}", i), measurement)
                .expect("operation failed in test");
        }

        assert_eq!(detector.get_baselines().len(), 5);
    }

    #[test]
    fn test_regression_severity_scaling() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(
            storage_path,
            RegressionConfig {
                regression_threshold: 0.1, // 10% threshold
                ..RegressionConfig::default()
            },
        )
        .expect("operation failed in test");

        let baseline = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };
        detector.record_baseline("test", baseline).expect("operation failed in test");

        // 50% slower => severity should be capped at 1.0
        let current = PerformanceMeasurement {
            time_ns: 1_500_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };

        let result = detector.check_regression("test", current).expect("operation failed in test");
        let r = result.expect("should be present");
        assert!(r.severity <= 1.0);
        assert!(r.severity > 0.0);
    }

    #[test]
    fn test_regression_result_analysis_text() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let baseline = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };
        detector.record_baseline("test", baseline).expect("operation failed in test");

        // No regression
        let current = PerformanceMeasurement {
            time_ns: 900_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };

        let result = detector.check_regression("test", current).expect("operation failed in test");
        let r = result.expect("should be present");
        assert!(r.analysis.contains("No performance regression detected"));
    }

    #[test]
    fn test_regression_with_disabled_checks() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(
            storage_path,
            RegressionConfig {
                check_memory_regression: false,
                check_throughput_regression: false,
                ..RegressionConfig::default()
            },
        )
        .expect("operation failed in test");

        let baseline = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: Some(1000.0),
            memory_usage_bytes: Some(1024),
        };
        detector.record_baseline("test", baseline).expect("operation failed in test");

        // Bad throughput and memory but checks disabled
        let current = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: Some(100.0), // 90% drop
            memory_usage_bytes: Some(10240),     // 10x increase
        };

        let result = detector.check_regression("test", current).expect("operation failed in test");
        let r = result.expect("should be present");
        // Only time check active, which shows no regression
        assert!(!r.is_regression);
    }

    // ── Persistence tests ──

    #[test]
    fn test_baselines_persist_and_reload() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        {
            let mut detector =
                RegressionDetector::new(storage_path.clone(), RegressionConfig::default())
                    .expect("operation failed in test");

            let measurement = PerformanceMeasurement {
                time_ns: 1_000_000,
                throughput_ops_per_sec: Some(1000.0),
                memory_usage_bytes: None,
            };
            detector
                .record_baseline("persisted_bench", measurement)
                .expect("operation failed in test");
        }

        // Reload
        let detector2 = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");
        assert!(detector2.get_baselines().contains_key("persisted_bench"));
    }

    #[test]
    fn test_performance_change_percent_positive() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let baseline = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };
        detector.record_baseline("test", baseline).expect("operation failed in test");

        let slower = PerformanceMeasurement {
            time_ns: 1_200_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };

        let result = detector.check_regression("test", slower).expect("operation failed in test");
        let r = result.expect("should be present");
        assert!(r.performance_change_percent > 0.0);
    }

    #[test]
    fn test_performance_change_percent_negative() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let storage_path = temp_dir.path().join("baselines.json");

        let mut detector = RegressionDetector::new(storage_path, RegressionConfig::default())
            .expect("operation failed in test");

        let baseline = PerformanceMeasurement {
            time_ns: 1_000_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };
        detector.record_baseline("test", baseline).expect("operation failed in test");

        let faster = PerformanceMeasurement {
            time_ns: 800_000,
            throughput_ops_per_sec: None,
            memory_usage_bytes: None,
        };

        let result = detector.check_regression("test", faster).expect("operation failed in test");
        let r = result.expect("should be present");
        assert!(r.performance_change_percent < 0.0);
    }
}