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
//! Statistical analysis and trend tracking for leaderboard data

use super::LeaderboardEntry;
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Leaderboard statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LeaderboardStats {
    /// Total number of entries
    pub total_entries: usize,
    /// Number of unique models
    pub unique_models: usize,
    /// Number of unique submitters
    pub unique_submitters: usize,
    /// Number of entries by category
    pub entries_by_category: HashMap<String, usize>,
    /// Average metrics across all entries
    pub average_metrics: AverageMetrics,
    /// Best metrics across all entries
    pub best_metrics: BestMetrics,
    /// Entries by precision
    pub entries_by_precision: HashMap<String, usize>,
    /// Entries by hardware platform
    pub entries_by_platform: HashMap<String, usize>,
    /// Date range of entries
    pub date_range: DateRange,
    /// Most active submitters
    pub top_submitters: Vec<(String, usize)>,
    /// Most popular benchmarks
    pub top_benchmarks: Vec<(String, usize)>,
}

/// Average metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AverageMetrics {
    pub latency_ms: f64,
    pub throughput: Option<f64>,
    pub tokens_per_second: Option<f64>,
    pub memory_mb: Option<f64>,
    pub gpu_utilization: Option<f64>,
    pub accuracy: Option<f64>,
}

/// Best metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BestMetrics {
    pub lowest_latency: MetricRecord,
    pub highest_throughput: Option<MetricRecord>,
    pub highest_tokens_per_second: Option<MetricRecord>,
    pub lowest_memory: Option<MetricRecord>,
    pub highest_accuracy: Option<MetricRecord>,
    pub lowest_energy: Option<MetricRecord>,
}

/// Record of a metric with associated entry info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricRecord {
    pub value: f64,
    pub model_name: String,
    pub model_version: String,
    pub entry_id: uuid::Uuid,
    pub timestamp: DateTime<Utc>,
}

/// Date range
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DateRange {
    pub start: DateTime<Utc>,
    pub end: DateTime<Utc>,
}

impl LeaderboardStats {
    /// Calculate statistics from entries
    pub fn from_entries(entries: &[LeaderboardEntry]) -> Result<Self> {
        if entries.is_empty() {
            return Ok(Self::empty());
        }

        let total_entries = entries.len();

        // Unique counts
        let unique_models: std::collections::HashSet<_> =
            entries.iter().map(|e| &e.model_name).collect();
        let unique_submitters: std::collections::HashSet<_> =
            entries.iter().map(|e| &e.submitter.name).collect();

        // Entries by category
        let mut entries_by_category = HashMap::new();
        for entry in entries {
            *entries_by_category.entry(entry.category.to_string()).or_insert(0) += 1;
        }

        // Entries by precision
        let mut entries_by_precision = HashMap::new();
        for entry in entries {
            let precision = format!("{:?}", entry.software.precision);
            *entries_by_precision.entry(precision).or_insert(0) += 1;
        }

        // Entries by platform
        let mut entries_by_platform = HashMap::new();
        for entry in entries {
            *entries_by_platform.entry(entry.hardware.platform.clone()).or_insert(0) += 1;
        }

        // Calculate average metrics
        let average_metrics = Self::calculate_averages(entries);

        // Find best metrics
        let best_metrics = Self::find_best_metrics(entries);

        // Date range
        let dates: Vec<_> = entries.iter().map(|e| e.timestamp).collect();
        let date_range = DateRange {
            start: *dates.iter().min().expect("Min failed"),
            end: *dates.iter().max().expect("Max failed"),
        };

        // Top submitters
        let mut submitter_counts: HashMap<String, usize> = HashMap::new();
        for entry in entries {
            *submitter_counts.entry(entry.submitter.name.clone()).or_insert(0) += 1;
        }
        let mut top_submitters: Vec<_> = submitter_counts.into_iter().collect();
        top_submitters.sort_by_key(|item| std::cmp::Reverse(item.1));
        top_submitters.truncate(10);

        // Top benchmarks
        let mut benchmark_counts: HashMap<String, usize> = HashMap::new();
        for entry in entries {
            *benchmark_counts.entry(entry.benchmark_name.clone()).or_insert(0) += 1;
        }
        let mut top_benchmarks: Vec<_> = benchmark_counts.into_iter().collect();
        top_benchmarks.sort_by_key(|item| std::cmp::Reverse(item.1));
        top_benchmarks.truncate(10);

        Ok(Self {
            total_entries,
            unique_models: unique_models.len(),
            unique_submitters: unique_submitters.len(),
            entries_by_category,
            average_metrics,
            best_metrics,
            entries_by_precision,
            entries_by_platform,
            date_range,
            top_submitters,
            top_benchmarks,
        })
    }

    /// Create empty statistics
    fn empty() -> Self {
        Self {
            total_entries: 0,
            unique_models: 0,
            unique_submitters: 0,
            entries_by_category: HashMap::new(),
            average_metrics: AverageMetrics {
                latency_ms: 0.0,
                throughput: None,
                tokens_per_second: None,
                memory_mb: None,
                gpu_utilization: None,
                accuracy: None,
            },
            best_metrics: BestMetrics {
                lowest_latency: MetricRecord {
                    value: f64::MAX,
                    model_name: String::new(),
                    model_version: String::new(),
                    entry_id: uuid::Uuid::nil(),
                    timestamp: Utc::now(),
                },
                highest_throughput: None,
                highest_tokens_per_second: None,
                lowest_memory: None,
                highest_accuracy: None,
                lowest_energy: None,
            },
            entries_by_precision: HashMap::new(),
            entries_by_platform: HashMap::new(),
            date_range: DateRange {
                start: Utc::now(),
                end: Utc::now(),
            },
            top_submitters: Vec::new(),
            top_benchmarks: Vec::new(),
        }
    }

    /// Calculate average metrics
    fn calculate_averages(entries: &[LeaderboardEntry]) -> AverageMetrics {
        let mut latency_sum = 0.0;
        let mut throughput_sum = 0.0;
        let mut throughput_count = 0;
        let mut tps_sum = 0.0;
        let mut tps_count = 0;
        let mut memory_sum = 0.0;
        let mut memory_count = 0;
        let mut gpu_sum = 0.0;
        let mut gpu_count = 0;
        let mut accuracy_sum = 0.0;
        let mut accuracy_count = 0;

        for entry in entries {
            latency_sum += entry.metrics.latency_ms;

            if let Some(throughput) = entry.metrics.throughput {
                throughput_sum += throughput;
                throughput_count += 1;
            }

            if let Some(tps) = entry.metrics.tokens_per_second {
                tps_sum += tps;
                tps_count += 1;
            }

            if let Some(memory) = entry.metrics.memory_mb {
                memory_sum += memory;
                memory_count += 1;
            }

            if let Some(gpu) = entry.metrics.gpu_utilization {
                gpu_sum += gpu;
                gpu_count += 1;
            }

            if let Some(accuracy) = entry.metrics.accuracy {
                accuracy_sum += accuracy;
                accuracy_count += 1;
            }
        }

        AverageMetrics {
            latency_ms: latency_sum / entries.len() as f64,
            throughput: if throughput_count > 0 {
                Some(throughput_sum / throughput_count as f64)
            } else {
                None
            },
            tokens_per_second: if tps_count > 0 { Some(tps_sum / tps_count as f64) } else { None },
            memory_mb: if memory_count > 0 { Some(memory_sum / memory_count as f64) } else { None },
            gpu_utilization: if gpu_count > 0 { Some(gpu_sum / gpu_count as f64) } else { None },
            accuracy: if accuracy_count > 0 {
                Some(accuracy_sum / accuracy_count as f64)
            } else {
                None
            },
        }
    }

    /// Find best metrics
    fn find_best_metrics(entries: &[LeaderboardEntry]) -> BestMetrics {
        let mut best = BestMetrics {
            lowest_latency: MetricRecord {
                value: f64::MAX,
                model_name: String::new(),
                model_version: String::new(),
                entry_id: uuid::Uuid::nil(),
                timestamp: Utc::now(),
            },
            highest_throughput: None,
            highest_tokens_per_second: None,
            lowest_memory: None,
            highest_accuracy: None,
            lowest_energy: None,
        };

        for entry in entries {
            // Lowest latency
            if entry.metrics.latency_ms < best.lowest_latency.value {
                best.lowest_latency = MetricRecord {
                    value: entry.metrics.latency_ms,
                    model_name: entry.model_name.clone(),
                    model_version: entry.model_version.clone(),
                    entry_id: entry.id,
                    timestamp: entry.timestamp,
                };
            }

            // Highest throughput
            if let Some(throughput) = entry.metrics.throughput {
                if best.highest_throughput.is_none()
                    || throughput
                        > best
                            .highest_throughput
                            .as_ref()
                            .expect("highest_throughput must be initialized")
                            .value
                {
                    best.highest_throughput = Some(MetricRecord {
                        value: throughput,
                        model_name: entry.model_name.clone(),
                        model_version: entry.model_version.clone(),
                        entry_id: entry.id,
                        timestamp: entry.timestamp,
                    });
                }
            }

            // Highest tokens per second
            if let Some(tps) = entry.metrics.tokens_per_second {
                if best.highest_tokens_per_second.is_none()
                    || tps
                        > best
                            .highest_tokens_per_second
                            .as_ref()
                            .expect("highest_tokens_per_second must be initialized")
                            .value
                {
                    best.highest_tokens_per_second = Some(MetricRecord {
                        value: tps,
                        model_name: entry.model_name.clone(),
                        model_version: entry.model_version.clone(),
                        entry_id: entry.id,
                        timestamp: entry.timestamp,
                    });
                }
            }

            // Lowest memory
            if let Some(memory) = entry.metrics.memory_mb {
                if best.lowest_memory.is_none()
                    || memory
                        < best
                            .lowest_memory
                            .as_ref()
                            .expect("lowest_memory must be initialized")
                            .value
                {
                    best.lowest_memory = Some(MetricRecord {
                        value: memory,
                        model_name: entry.model_name.clone(),
                        model_version: entry.model_version.clone(),
                        entry_id: entry.id,
                        timestamp: entry.timestamp,
                    });
                }
            }

            // Highest accuracy
            if let Some(accuracy) = entry.metrics.accuracy {
                if best.highest_accuracy.is_none()
                    || accuracy
                        > best
                            .highest_accuracy
                            .as_ref()
                            .expect("highest_accuracy must be initialized")
                            .value
                {
                    best.highest_accuracy = Some(MetricRecord {
                        value: accuracy,
                        model_name: entry.model_name.clone(),
                        model_version: entry.model_version.clone(),
                        entry_id: entry.id,
                        timestamp: entry.timestamp,
                    });
                }
            }

            // Lowest energy
            if let Some(energy) = entry.metrics.energy_watts {
                if best.lowest_energy.is_none()
                    || energy
                        < best
                            .lowest_energy
                            .as_ref()
                            .expect("lowest_energy must be initialized")
                            .value
                {
                    best.lowest_energy = Some(MetricRecord {
                        value: energy,
                        model_name: entry.model_name.clone(),
                        model_version: entry.model_version.clone(),
                        entry_id: entry.id,
                        timestamp: entry.timestamp,
                    });
                }
            }
        }

        best
    }
}

/// Trend analysis for performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrendAnalysis {
    /// Model name
    pub model_name: String,
    /// Metric name
    pub metric_name: String,
    /// Time period
    pub period_days: usize,
    /// Data points
    pub data_points: Vec<TrendDataPoint>,
    /// Overall trend
    pub trend: PerformanceTrend,
    /// Average improvement per day
    pub daily_change_percent: f64,
    /// Statistical significance
    pub r_squared: f64,
}

/// Trend data point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrendDataPoint {
    pub timestamp: DateTime<Utc>,
    pub value: f64,
    pub entry_id: uuid::Uuid,
}

/// Performance trend direction
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum PerformanceTrend {
    /// Performance is improving
    Improving,
    /// Performance is degrading
    Degrading,
    /// Performance is stable
    Stable,
    /// Not enough data
    Insufficient,
}

impl TrendAnalysis {
    /// Analyze trend for a specific metric
    pub fn analyze(entries: &[LeaderboardEntry], metric_name: &str) -> Result<Self> {
        if entries.is_empty() {
            anyhow::bail!("No entries provided for trend analysis");
        }

        let model_name = entries[0].model_name.clone();
        let mut data_points = Vec::new();

        // Extract data points
        for entry in entries {
            let value = match metric_name {
                "latency" => Some(entry.metrics.latency_ms),
                "throughput" => entry.metrics.throughput,
                "tokens_per_second" => entry.metrics.tokens_per_second,
                "memory" => entry.metrics.memory_mb,
                "gpu_utilization" => entry.metrics.gpu_utilization,
                "accuracy" => entry.metrics.accuracy,
                "energy" => entry.metrics.energy_watts,
                _ => entry.metrics.custom_metrics.get(metric_name).copied(),
            };

            if let Some(val) = value {
                data_points.push(TrendDataPoint {
                    timestamp: entry.timestamp,
                    value: val,
                    entry_id: entry.id,
                });
            }
        }

        if data_points.len() < 2 {
            return Ok(Self {
                model_name,
                metric_name: metric_name.to_string(),
                period_days: 0,
                data_points,
                trend: PerformanceTrend::Insufficient,
                daily_change_percent: 0.0,
                r_squared: 0.0,
            });
        }

        // Sort by timestamp
        data_points.sort_by_key(|p| p.timestamp);

        // Calculate period
        let start = data_points
            .first()
            .expect("data_points must have at least one element")
            .timestamp;
        let end = data_points
            .last()
            .expect("data_points must have at least one element")
            .timestamp;
        let period_days = (end - start).num_days() as usize;

        // Calculate linear regression
        let (slope, r_squared) = Self::linear_regression(&data_points);

        // Determine trend
        let trend = if r_squared < 0.3 {
            PerformanceTrend::Stable
        } else if slope > 0.01 {
            // For metrics where higher is better
            if matches!(metric_name, "throughput" | "tokens_per_second" | "accuracy") {
                PerformanceTrend::Improving
            } else {
                PerformanceTrend::Degrading
            }
        } else if slope < -0.01 {
            // For metrics where lower is better
            if matches!(metric_name, "latency" | "memory" | "energy") {
                PerformanceTrend::Improving
            } else {
                PerformanceTrend::Degrading
            }
        } else {
            PerformanceTrend::Stable
        };

        // Calculate daily change percentage
        let first_value =
            data_points.first().expect("data_points must have at least one element").value;
        let last_value =
            data_points.last().expect("data_points must have at least one element").value;
        let total_change_percent = ((last_value - first_value) / first_value) * 100.0;
        let daily_change_percent =
            if period_days > 0 { total_change_percent / period_days as f64 } else { 0.0 };

        Ok(Self {
            model_name,
            metric_name: metric_name.to_string(),
            period_days,
            data_points,
            trend,
            daily_change_percent,
            r_squared,
        })
    }

    /// Calculate linear regression
    fn linear_regression(points: &[TrendDataPoint]) -> (f64, f64) {
        let n = points.len() as f64;
        if n < 2.0 {
            return (0.0, 0.0);
        }

        // Convert timestamps to days since first point
        let first_timestamp = points[0].timestamp;
        let x_values: Vec<f64> = points
            .iter()
            .map(|p| (p.timestamp - first_timestamp).num_seconds() as f64 / 86400.0)
            .collect();

        let y_values: Vec<f64> = points.iter().map(|p| p.value).collect();

        // Calculate means
        let x_mean = x_values.iter().sum::<f64>() / n;
        let y_mean = y_values.iter().sum::<f64>() / n;

        // Calculate slope and intercept
        let mut numerator = 0.0;
        let mut denominator = 0.0;

        for i in 0..points.len() {
            numerator += (x_values[i] - x_mean) * (y_values[i] - y_mean);
            denominator += (x_values[i] - x_mean).powi(2);
        }

        if denominator == 0.0 {
            return (0.0, 0.0);
        }

        let slope = numerator / denominator;

        // Calculate R-squared
        let mut ss_tot = 0.0;
        let mut ss_res = 0.0;

        for i in 0..points.len() {
            let y_pred = slope * (x_values[i] - x_mean) + y_mean;
            ss_tot += (y_values[i] - y_mean).powi(2);
            ss_res += (y_values[i] - y_pred).powi(2);
        }

        let r_squared = if ss_tot == 0.0 { 0.0 } else { 1.0 - (ss_res / ss_tot) };

        (slope, r_squared)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::leaderboard::*;
    use chrono::Duration;
    use std::collections::HashMap;

    fn create_test_entries() -> Vec<LeaderboardEntry> {
        vec![
            LeaderboardEntry {
                id: uuid::Uuid::new_v4(),
                timestamp: Utc::now() - Duration::days(7),
                model_name: "model1".to_string(),
                model_version: "1.0".to_string(),
                benchmark_name: "benchmark1".to_string(),
                category: LeaderboardCategory::Inference,
                hardware: HardwareInfo {
                    cpu: "Intel Xeon".to_string(),
                    cpu_cores: 32,
                    gpu: Some("NVIDIA A100".to_string()),
                    gpu_count: Some(1),
                    memory_gb: 256.0,
                    accelerator: Some(AcceleratorType::CUDA),
                    platform: "x86_64".to_string(),
                },
                software: SoftwareInfo {
                    framework_version: "0.1.0".to_string(),
                    rust_version: "1.75".to_string(),
                    os: "Linux".to_string(),
                    optimization_level: OptimizationLevel::O3,
                    precision: Precision::FP16,
                    quantization: None,
                    compiler_flags: vec![],
                },
                metrics: PerformanceMetrics {
                    latency_ms: 15.0,
                    latency_percentiles: LatencyPercentiles {
                        p50: 14.0,
                        p90: 18.0,
                        p95: 20.0,
                        p99: 25.0,
                        p999: 35.0,
                    },
                    throughput: Some(66.7),
                    tokens_per_second: None,
                    memory_mb: Some(1024.0),
                    peak_memory_mb: Some(1536.0),
                    gpu_utilization: Some(85.0),
                    accuracy: Some(0.90),
                    energy_watts: None,
                    custom_metrics: HashMap::new(),
                },
                metadata: HashMap::new(),
                validated: true,
                submitter: SubmitterInfo {
                    name: "User1".to_string(),
                    organization: None,
                    email: None,
                    github: None,
                },
                tags: vec![],
            },
            LeaderboardEntry {
                id: uuid::Uuid::new_v4(),
                timestamp: Utc::now(),
                model_name: "model1".to_string(),
                model_version: "1.1".to_string(),
                benchmark_name: "benchmark1".to_string(),
                category: LeaderboardCategory::Inference,
                hardware: HardwareInfo {
                    cpu: "Intel Xeon".to_string(),
                    cpu_cores: 32,
                    gpu: Some("NVIDIA A100".to_string()),
                    gpu_count: Some(1),
                    memory_gb: 256.0,
                    accelerator: Some(AcceleratorType::CUDA),
                    platform: "x86_64".to_string(),
                },
                software: SoftwareInfo {
                    framework_version: "0.1.0".to_string(),
                    rust_version: "1.75".to_string(),
                    os: "Linux".to_string(),
                    optimization_level: OptimizationLevel::O3,
                    precision: Precision::FP16,
                    quantization: None,
                    compiler_flags: vec![],
                },
                metrics: PerformanceMetrics {
                    latency_ms: 10.0,
                    latency_percentiles: LatencyPercentiles {
                        p50: 9.0,
                        p90: 12.0,
                        p95: 14.0,
                        p99: 18.0,
                        p999: 25.0,
                    },
                    throughput: Some(100.0),
                    tokens_per_second: None,
                    memory_mb: Some(1024.0),
                    peak_memory_mb: Some(1536.0),
                    gpu_utilization: Some(90.0),
                    accuracy: Some(0.95),
                    energy_watts: None,
                    custom_metrics: HashMap::new(),
                },
                metadata: HashMap::new(),
                validated: true,
                submitter: SubmitterInfo {
                    name: "User1".to_string(),
                    organization: None,
                    email: None,
                    github: None,
                },
                tags: vec![],
            },
        ]
    }

    #[test]
    fn test_leaderboard_stats() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");

        assert_eq!(stats.total_entries, 2);
        assert_eq!(stats.unique_models, 1);
        assert_eq!(stats.unique_submitters, 1);
        assert_eq!(stats.entries_by_category["Inference"], 2);
        assert_eq!(stats.average_metrics.latency_ms, 12.5);
        assert_eq!(stats.best_metrics.lowest_latency.value, 10.0);
    }

    #[test]
    fn test_trend_analysis() {
        let entries = create_test_entries();
        let trend = TrendAnalysis::analyze(&entries, "latency").expect("operation failed in test");

        assert_eq!(trend.model_name, "model1");
        assert_eq!(trend.metric_name, "latency");
        assert_eq!(trend.data_points.len(), 2);

        // Latency improved from 15ms to 10ms
        match trend.trend {
            PerformanceTrend::Improving => {}, // Expected
            _ => panic!("Expected improving trend for latency"),
        }
    }

    // ── LeaderboardStats additional tests ──

    #[test]
    fn test_empty_entries_stats() {
        let entries: Vec<LeaderboardEntry> = Vec::new();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert_eq!(stats.total_entries, 0);
        assert_eq!(stats.unique_models, 0);
        assert_eq!(stats.unique_submitters, 0);
    }

    #[test]
    fn test_stats_unique_submitters() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        // Both entries from "User1"
        assert_eq!(stats.unique_submitters, 1);
    }

    #[test]
    fn test_stats_entries_by_precision() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        // Both entries use FP16
        assert!(stats.entries_by_precision.contains_key("FP16"));
        assert_eq!(stats.entries_by_precision["FP16"], 2);
    }

    #[test]
    fn test_stats_entries_by_platform() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert!(stats.entries_by_platform.contains_key("x86_64"));
        assert_eq!(stats.entries_by_platform["x86_64"], 2);
    }

    #[test]
    fn test_stats_top_submitters() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert!(!stats.top_submitters.is_empty());
        assert_eq!(stats.top_submitters[0].0, "User1");
        assert_eq!(stats.top_submitters[0].1, 2);
    }

    #[test]
    fn test_stats_top_benchmarks() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert!(!stats.top_benchmarks.is_empty());
        assert_eq!(stats.top_benchmarks[0].0, "benchmark1");
    }

    #[test]
    fn test_stats_date_range() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert!(stats.date_range.start < stats.date_range.end);
    }

    #[test]
    fn test_stats_average_latency() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        // Average of 15.0 and 10.0
        assert!((stats.average_metrics.latency_ms - 12.5).abs() < 1e-6);
    }

    #[test]
    fn test_stats_average_throughput() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        // Average of 66.7 and 100.0
        assert!(stats.average_metrics.throughput.is_some());
        let avg = stats.average_metrics.throughput.expect("throughput should exist");
        assert!((avg - 83.35).abs() < 1e-1);
    }

    #[test]
    fn test_stats_average_accuracy() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        // Average of 0.90 and 0.95
        assert!(stats.average_metrics.accuracy.is_some());
        let avg = stats.average_metrics.accuracy.expect("accuracy should exist");
        assert!((avg - 0.925).abs() < 1e-6);
    }

    #[test]
    fn test_stats_best_lowest_latency() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert!((stats.best_metrics.lowest_latency.value - 10.0).abs() < 1e-6);
    }

    #[test]
    fn test_stats_best_highest_throughput() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert!(stats.best_metrics.highest_throughput.is_some());
        let best = stats.best_metrics.highest_throughput.as_ref().expect("should exist");
        assert!((best.value - 100.0).abs() < 1e-6);
    }

    #[test]
    fn test_stats_best_highest_accuracy() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert!(stats.best_metrics.highest_accuracy.is_some());
        let best = stats.best_metrics.highest_accuracy.as_ref().expect("should exist");
        assert!((best.value - 0.95).abs() < 1e-6);
    }

    #[test]
    fn test_stats_best_lowest_memory() {
        let entries = create_test_entries();
        let stats = LeaderboardStats::from_entries(&entries).expect("operation failed in test");
        assert!(stats.best_metrics.lowest_memory.is_some());
        let best = stats.best_metrics.lowest_memory.as_ref().expect("should exist");
        assert!((best.value - 1024.0).abs() < 1e-6);
    }

    // ── TrendAnalysis additional tests ──

    #[test]
    fn test_trend_analysis_empty_entries() {
        let entries: Vec<LeaderboardEntry> = Vec::new();
        let result = TrendAnalysis::analyze(&entries, "latency");
        assert!(result.is_err());
    }

    #[test]
    fn test_trend_analysis_throughput() {
        let entries = create_test_entries();
        let trend =
            TrendAnalysis::analyze(&entries, "throughput").expect("operation failed in test");
        assert_eq!(trend.data_points.len(), 2);
    }

    #[test]
    fn test_trend_analysis_accuracy() {
        let entries = create_test_entries();
        let trend = TrendAnalysis::analyze(&entries, "accuracy").expect("operation failed in test");
        assert_eq!(trend.data_points.len(), 2);
    }

    #[test]
    fn test_trend_analysis_unknown_metric() {
        let entries = create_test_entries();
        let trend = TrendAnalysis::analyze(&entries, "nonexistent_metric")
            .expect("operation failed in test");
        // No data points for unknown metric
        assert!(
            trend.data_points.is_empty() || matches!(trend.trend, PerformanceTrend::Insufficient)
        );
    }

    #[test]
    fn test_trend_analysis_period_days() {
        let entries = create_test_entries();
        let trend = TrendAnalysis::analyze(&entries, "latency").expect("operation failed in test");
        assert!(trend.period_days >= 6); // entries are 7 days apart
    }

    #[test]
    fn test_trend_analysis_daily_change() {
        let entries = create_test_entries();
        let trend = TrendAnalysis::analyze(&entries, "latency").expect("operation failed in test");
        // Latency went from 15 -> 10 (improvement), daily change should be negative
        assert!(trend.daily_change_percent < 0.0);
    }

    // ── AverageMetrics tests ──

    #[test]
    fn test_average_metrics_clone() {
        let avg = AverageMetrics {
            latency_ms: 10.0,
            throughput: Some(100.0),
            tokens_per_second: None,
            memory_mb: Some(512.0),
            gpu_utilization: None,
            accuracy: Some(0.95),
        };
        let cloned = avg.clone();
        assert!((cloned.latency_ms - 10.0).abs() < 1e-6);
        assert_eq!(cloned.throughput, Some(100.0));
    }

    // ── MetricRecord tests ──

    #[test]
    fn test_metric_record_clone() {
        let record = MetricRecord {
            value: 42.0,
            model_name: "test_model".to_string(),
            model_version: "1.0".to_string(),
            entry_id: uuid::Uuid::nil(),
            timestamp: Utc::now(),
        };
        let cloned = record.clone();
        assert!((cloned.value - 42.0).abs() < 1e-6);
        assert_eq!(cloned.model_name, "test_model");
    }

    // ── PerformanceTrend tests ──

    #[test]
    fn test_performance_trend_variants() {
        let _improving = PerformanceTrend::Improving;
        let _degrading = PerformanceTrend::Degrading;
        let _stable = PerformanceTrend::Stable;
        let _insufficient = PerformanceTrend::Insufficient;
    }

    #[test]
    fn test_performance_trend_clone() {
        let trend = PerformanceTrend::Improving;
        let cloned = trend;
        assert!(matches!(cloned, PerformanceTrend::Improving));
    }

    // ── DateRange tests ──

    #[test]
    fn test_date_range_clone() {
        let now = Utc::now();
        let range = DateRange {
            start: now - Duration::days(7),
            end: now,
        };
        let cloned = range.clone();
        assert_eq!(cloned.start, range.start);
        assert_eq!(cloned.end, range.end);
    }

    // ── TrendDataPoint tests ──

    #[test]
    fn test_trend_data_point_clone() {
        let point = TrendDataPoint {
            timestamp: Utc::now(),
            value: 42.0,
            entry_id: uuid::Uuid::nil(),
        };
        let cloned = point.clone();
        assert!((cloned.value - 42.0).abs() < 1e-6);
    }

    // ── Linear regression tests ──

    #[test]
    fn test_linear_regression_single_point() {
        let points = vec![TrendDataPoint {
            timestamp: Utc::now(),
            value: 10.0,
            entry_id: uuid::Uuid::nil(),
        }];
        let (slope, r_squared) = TrendAnalysis::linear_regression(&points);
        assert!((slope).abs() < 1e-6);
        assert!((r_squared).abs() < 1e-6);
    }
}