trustformers-models 0.1.1

Model implementations 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
//! Tests for memory profiling functionality
//!
//! Comprehensive test suite covering all memory profiling components
//! including profiler creation, metrics collection, analytics, and reporting.

#![cfg(test)]

use super::*;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

#[tokio::test]
async fn test_profiler_creation() {
    let config = types::ProfilerConfig::default();
    let profiler = profiler::MemoryProfiler::new(config).expect("failed to create profiler");
    assert!(profiler.get_current_summary().is_none());
}

#[tokio::test]
async fn test_metrics_collection() {
    let metrics = profiler::MemoryProfiler::collect_memory_metrics()
        .await
        .expect("operation failed");
    assert!(metrics.total_memory_mb > 0.0);
    assert!(metrics.timestamp > UNIX_EPOCH);
}

#[test]
fn test_fragmentation_calculation() {
    let info = system::ProcessMemoryInfo {
        total_mb: 1000.0,
        heap_mb: 800.0,
        stack_mb: 64.0,
        peak_mb: 1200.0,
        allocated_objects: 1000,
        deallocated_objects: 500,
        active_allocations: 500,
        gc_collections: 10,
        gc_time_ms: 150.0,
    };

    let fragmentation = profiler::MemoryProfiler::calculate_fragmentation_ratio(&info);
    assert!((0.0..=1.0).contains(&fragmentation));
}

#[tokio::test]
async fn test_report_generation() {
    let config = types::ProfilerConfig::default();
    let profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    let report = profiler.generate_report().await.expect("operation failed");
    assert!(report.summary.peak_memory_mb >= 0.0);
    assert!(!report.recommendations.is_empty());
}

#[tokio::test]
async fn test_atomic_monitoring_control() {
    let config = types::ProfilerConfig::default();
    let mut profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Test initial state
    assert!(!profiler.is_monitoring());

    // Test atomic start
    profiler.start_monitoring().await.expect("operation failed");
    assert!(profiler.is_monitoring());

    // Test double start doesn't fail
    profiler.start_monitoring().await.expect("operation failed");
    assert!(profiler.is_monitoring());

    // Test atomic stop
    profiler.stop_monitoring().await.expect("operation failed");
    assert!(!profiler.is_monitoring());
}

#[test]
fn test_cached_recommendations_performance() {
    let config = types::ProfilerConfig::default();
    let profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Verify cached recommendations are pre-allocated
    let cached = profiler.get_cached_recommendations();
    assert!(!cached.high_memory.is_empty());
    assert!(!cached.rapid_growth.is_empty());
    assert!(!cached.fragmentation.is_empty());

    // Test recommendations contain expected content
    assert!(cached.high_memory.iter().any(|r| r.contains("batch size")));
    assert!(cached.rapid_growth.iter().any(|r| r.contains("memory leaks")));
    assert!(cached.fragmentation.iter().any(|r| r.contains("memory pools")));
}

#[tokio::test]
async fn test_alert_analysis_optimization() {
    let config = types::ProfilerConfig::default();
    let alerts = Arc::new(Mutex::new(Vec::new()));
    let cached_recommendations = analytics::AlertRecommendations::new();
    let adaptive_thresholds = Arc::new(Mutex::new(analytics::AdaptiveThresholds::default()));

    // Test metrics that should trigger alerts
    let high_memory_metrics = types::MemoryMetrics {
        timestamp: SystemTime::now(),
        total_memory_mb: 2000.0, // Above default threshold of 1024
        heap_memory_mb: 1800.0,
        stack_memory_mb: 64.0,
        gpu_memory_mb: None,
        peak_memory_mb: 2000.0,
        allocated_objects: 1000,
        deallocated_objects: 500,
        active_allocations: 500,
        memory_fragmentation_ratio: 0.1,
        gc_collections: 10,
        gc_time_ms: 100.0,
        memory_growth_rate_mb_per_sec: 60.0, // Above default threshold of 50.0
    };

    // Call the optimized alert analysis
    profiler::MemoryProfiler::analyze_for_alerts_adaptive(
        &high_memory_metrics,
        &None,
        &alerts,
        &config,
        &cached_recommendations,
        &adaptive_thresholds,
    )
    .await;

    // Verify alerts were generated efficiently
    let alerts_vec = alerts.lock().expect("operation failed");
    assert!(alerts_vec.len() >= 2); // High memory + rapid growth alerts

    // Verify cached recommendations were used
    let high_mem_alert = alerts_vec
        .iter()
        .find(|a| matches!(a.alert_type, types::MemoryAlertType::HighMemoryUsage))
        .expect("operation failed");
    assert_eq!(
        high_mem_alert.recommendations,
        cached_recommendations.high_memory
    );
}

#[tokio::test]
async fn test_concurrent_monitoring() {
    let config = types::ProfilerConfig {
        collection_interval_ms: 20, // Slightly slower to reduce load
        max_data_points: 10,        // Reduced from 100
        ..types::ProfilerConfig::default()
    };
    let mut profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Start monitoring
    profiler.start_monitoring().await.expect("operation failed");

    // Let it run for a shorter time
    tokio::time::sleep(Duration::from_millis(30)).await;

    // Check that metrics were collected
    let summary = profiler.get_current_summary();
    assert!(summary.is_some());

    // Stop monitoring
    profiler.stop_monitoring().await.expect("operation failed");

    // Verify it stops cleanly
    tokio::time::sleep(Duration::from_millis(10)).await;
    assert!(!profiler.is_monitoring());

    // Explicit cleanup
    drop(profiler);
    std::hint::black_box(());
}

#[test]
fn test_metrics_history_bounded() {
    let config = types::ProfilerConfig {
        max_data_points: 5,
        ..types::ProfilerConfig::default()
    };
    let profiler = profiler::MemoryProfiler::new(config).expect("operation failed");
    let mut history = profiler.get_metrics_history().lock().expect("operation failed");

    // Add more than max_data_points
    for i in 0..10 {
        history.push_back(types::MemoryMetrics {
            timestamp: SystemTime::now(),
            total_memory_mb: i as f64,
            heap_memory_mb: i as f64,
            stack_memory_mb: 64.0,
            gpu_memory_mb: None,
            peak_memory_mb: i as f64,
            allocated_objects: i,
            deallocated_objects: 0,
            active_allocations: i,
            memory_fragmentation_ratio: 0.1,
            gc_collections: 0,
            gc_time_ms: 0.0,
            memory_growth_rate_mb_per_sec: 0.0,
        });

        // Simulate the bounded behavior
        while history.len() > 5 {
            history.pop_front();
        }
    }

    // Verify it's bounded correctly
    assert_eq!(history.len(), 5);
    assert_eq!(
        history.back().expect("operation failed").total_memory_mb,
        9.0
    );
}

#[tokio::test]
async fn test_adaptive_thresholds_system() {
    let config = types::ProfilerConfig::default();
    let profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Test initial adaptive thresholds
    let initial_thresholds = profiler.get_adaptive_thresholds().await.expect("operation failed");
    assert_eq!(initial_thresholds.base_memory_threshold, 1024.0);
    assert_eq!(initial_thresholds.growth_rate_threshold, 50.0);
    assert_eq!(initial_thresholds.fragmentation_threshold, 0.3);
    assert_eq!(initial_thresholds.adaptation_factor, 0.1);

    // Test adaptive threshold updates
    // Use timestamp 6 minutes in future to trigger update (requires > 300 seconds)
    let high_memory_metrics = types::MemoryMetrics {
        timestamp: SystemTime::now() + std::time::Duration::from_secs(360),
        total_memory_mb: 2000.0, // Much higher than base threshold
        heap_memory_mb: 1800.0,
        stack_memory_mb: 64.0,
        gpu_memory_mb: None,
        peak_memory_mb: 2000.0,
        allocated_objects: 1000,
        deallocated_objects: 500,
        active_allocations: 500,
        memory_fragmentation_ratio: 0.5, // High fragmentation
        gc_collections: 10,
        gc_time_ms: 100.0,
        memory_growth_rate_mb_per_sec: 25.0, // Very high growth
    };

    // Simulate threshold adaptation
    profiler::MemoryProfiler::update_adaptive_thresholds(
        &high_memory_metrics,
        profiler.get_adaptive_thresholds_internal(),
    )
    .await;

    // Verify thresholds adapted upward
    let updated_thresholds = profiler.get_adaptive_thresholds().await.expect("operation failed");
    assert!(updated_thresholds.base_memory_threshold > initial_thresholds.base_memory_threshold);
    assert!(
        updated_thresholds.fragmentation_threshold > initial_thresholds.fragmentation_threshold
    );
    assert!(updated_thresholds.last_updated > initial_thresholds.last_updated);
}

#[tokio::test]
async fn test_memory_prediction_system() {
    let config = types::ProfilerConfig::default();
    let profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Test no prediction with insufficient data
    let initial_prediction = profiler.predict_memory_usage(300).await.expect("operation failed"); // 5 minutes ahead
    assert!(initial_prediction.is_none());

    // Simulate a trend by adding metrics with increasing memory usage
    let base_time = SystemTime::now();
    {
        let mut history = profiler.get_metrics_history().lock().expect("operation failed");

        for i in 0..70 {
            // More than trend_window (60) for good prediction
            let metrics = types::MemoryMetrics {
                timestamp: base_time + Duration::from_secs(i * 10),
                total_memory_mb: 1000.0 + (i as f64 * 2.0), // Steadily increasing
                heap_memory_mb: 900.0 + (i as f64 * 1.8),
                stack_memory_mb: 64.0,
                gpu_memory_mb: None,
                peak_memory_mb: 1000.0 + (i as f64 * 2.0),
                allocated_objects: 1000 + i * 10,
                deallocated_objects: 500,
                active_allocations: 500 + i * 10,
                memory_fragmentation_ratio: 0.1,
                gc_collections: 10,
                gc_time_ms: 100.0,
                memory_growth_rate_mb_per_sec: 2.0,
            };
            history.push_back(metrics);
        }
    }

    // Update memory prediction with trend data
    let latest_metrics = types::MemoryMetrics {
        timestamp: base_time + Duration::from_secs(700),
        total_memory_mb: 1140.0,
        heap_memory_mb: 1026.0,
        stack_memory_mb: 64.0,
        gpu_memory_mb: None,
        peak_memory_mb: 1140.0,
        allocated_objects: 1700,
        deallocated_objects: 500,
        active_allocations: 1200,
        memory_fragmentation_ratio: 0.1,
        gc_collections: 10,
        gc_time_ms: 100.0,
        memory_growth_rate_mb_per_sec: 2.0,
    };

    profiler::MemoryProfiler::update_memory_prediction(
        &latest_metrics,
        profiler.get_memory_predictor_internal(),
        profiler.get_metrics_history(),
    )
    .await;

    // Test prediction with sufficient data
    let prediction = profiler.predict_memory_usage(300).await.expect("operation failed"); // 5 minutes ahead
    assert!(prediction.is_some());

    let pred = prediction.expect("operation failed");
    assert!(pred.predicted_memory_mb > 1140.0); // Should predict growth
    assert!(pred.confidence > 0.0 && pred.confidence <= 1.0);
    assert_eq!(pred.horizon_secs, 300);
    assert!(pred.trend_slope > 0.0); // Positive growth trend
}

#[tokio::test]
async fn test_memory_leak_detection() {
    let config = types::ProfilerConfig {
        enable_leak_detection: true,
        ..types::ProfilerConfig::default()
    };
    let profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Test leak detection configuration
    let initial_config = profiler.get_leak_detection_config().await.expect("operation failed");
    assert_eq!(initial_config.growth_threshold, 10.0);
    assert_eq!(initial_config.duration_secs, 300);
    assert_eq!(initial_config.allocation_threshold, 1000);
    assert_eq!(initial_config.confidence_threshold, 0.8);

    // Test configuration update
    let new_config = profiler::LeakDetectionConfig {
        growth_threshold: 15.0,
        duration_secs: 600,
        allocation_threshold: 2000,
        confidence_threshold: 0.9,
    };
    profiler
        .configure_leak_detection(new_config.clone())
        .await
        .expect("operation failed");

    let updated_config = profiler.get_leak_detection_config().await.expect("operation failed");
    assert_eq!(updated_config.growth_threshold, 15.0);
    assert_eq!(updated_config.duration_secs, 600);
    assert_eq!(updated_config.allocation_threshold, 2000);
    assert_eq!(updated_config.confidence_threshold, 0.9);
}

#[tokio::test]
async fn test_monitoring_performance_stats() {
    let config = types::ProfilerConfig {
        collection_interval_ms: 20, // Slower collection to reduce load
        max_data_points: 5,         // Reduced data points
        ..types::ProfilerConfig::default()
    };
    let mut profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Initial stats should be zero
    let initial_stats = profiler.get_monitoring_stats().await.expect("operation failed");
    assert_eq!(initial_stats.total_collections, 0);
    assert_eq!(initial_stats.average_overhead_us, 0);
    assert_eq!(initial_stats.uptime_secs, 0);

    // Start monitoring and let it collect some data for shorter time
    profiler.start_monitoring().await.expect("operation failed");
    tokio::time::sleep(Duration::from_millis(30)).await;

    // Check stats after some collections
    let stats = profiler.get_monitoring_stats().await.expect("operation failed");
    assert!(stats.total_collections > 0);
    assert!(stats.average_overhead_us > 0);
    // uptime_secs may be 0 since we only slept 30ms (< 1 second)
    // Just verify it's a valid value (stats is collected correctly)
    let _ = stats.uptime_secs;

    profiler.stop_monitoring().await.expect("operation failed");

    // Explicit cleanup
    drop(profiler);
    std::hint::black_box(());
}

#[test]
fn test_linear_regression_calculation() {
    // Test the linear regression implementation used in memory prediction
    let data_points: Vec<(f64, f64)> = vec![
        (1.0, 100.0), // time, memory
        (2.0, 102.0),
        (3.0, 104.0),
        (4.0, 106.0),
        (5.0, 108.0),
    ];

    // Calculate linear regression manually to verify
    let n = data_points.len() as f64;
    let sum_x: f64 = data_points.iter().map(|(x, _)| *x).sum();
    let sum_y: f64 = data_points.iter().map(|(_, y)| *y).sum();
    let sum_xy: f64 = data_points.iter().map(|(x, y)| x * y).sum();
    let sum_x2: f64 = data_points.iter().map(|(x, _)| x * x).sum();

    let slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x);
    let intercept = (sum_y - slope * sum_x) / n;

    // For this data, slope should be approximately 2.0 (2 MB per time unit)
    assert!((slope - 2.0).abs() < 0.1);
    assert!((intercept - 98.0).abs() < 0.1);

    // Test correlation calculation
    let y_mean = sum_y / n;
    let ss_tot: f64 = data_points.iter().map(|(_, y)| (y - y_mean).powi(2)).sum();
    let ss_res: f64 = data_points.iter().map(|(x, y)| (y - (slope * x + intercept)).powi(2)).sum();
    let r_squared = 1.0 - (ss_res / ss_tot);

    // For perfect linear data, R² should be very close to 1.0
    assert!(r_squared > 0.99);
}

#[tokio::test]
async fn test_adaptive_threshold_edge_cases() {
    let config = types::ProfilerConfig::default();
    let profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Test with extremely high memory usage
    // Use a timestamp 6 minutes in the future to trigger threshold update (requires > 300 seconds)
    let extreme_metrics = types::MemoryMetrics {
        timestamp: SystemTime::now() + std::time::Duration::from_secs(360),
        total_memory_mb: 100000.0, // 100 GB
        heap_memory_mb: 95000.0,
        stack_memory_mb: 64.0,
        gpu_memory_mb: None,
        peak_memory_mb: 100000.0,
        allocated_objects: 1000000,
        deallocated_objects: 500000,
        active_allocations: 500000,
        memory_fragmentation_ratio: 0.8, // Very high fragmentation
        gc_collections: 100,
        gc_time_ms: 5000.0,                    // 5 seconds of GC
        memory_growth_rate_mb_per_sec: 1000.0, // Extremely rapid growth
    };

    profiler::MemoryProfiler::update_adaptive_thresholds(
        &extreme_metrics,
        profiler.get_adaptive_thresholds_internal(),
    )
    .await;

    let updated_thresholds = profiler.get_adaptive_thresholds().await.expect("operation failed");

    // Thresholds should adapt but remain reasonable
    assert!(updated_thresholds.base_memory_threshold > 1024.0);
    assert!(updated_thresholds.base_memory_threshold < 50000.0); // Not too extreme
    assert!(updated_thresholds.fragmentation_threshold > 0.3);
    assert!(updated_thresholds.fragmentation_threshold < 1.0); // Must stay under 1.0

    // Test with zero/minimal memory usage
    let minimal_metrics = types::MemoryMetrics {
        timestamp: SystemTime::now(),
        total_memory_mb: 1.0, // Very low
        heap_memory_mb: 0.5,
        stack_memory_mb: 0.5,
        gpu_memory_mb: None,
        peak_memory_mb: 1.0,
        allocated_objects: 1,
        deallocated_objects: 0,
        active_allocations: 1,
        memory_fragmentation_ratio: 0.0, // No fragmentation
        gc_collections: 0,
        gc_time_ms: 0.0,
        memory_growth_rate_mb_per_sec: 0.0,
    };

    profiler::MemoryProfiler::update_adaptive_thresholds(
        &minimal_metrics,
        profiler.get_adaptive_thresholds_internal(),
    )
    .await;

    let minimal_thresholds = profiler.get_adaptive_thresholds().await.expect("operation failed");

    // Thresholds should adapt downward but remain usable
    assert!(minimal_thresholds.base_memory_threshold > 10.0); // Not too low
    assert!(minimal_thresholds.fragmentation_threshold > 0.1); // Reasonable minimum
}

#[tokio::test]
async fn test_comprehensive_analytics_integration() {
    let config = types::ProfilerConfig {
        enable_leak_detection: true,
        enable_pattern_analysis: true,
        collection_interval_ms: 25,       // Slower collection
        memory_alert_threshold_mb: 500.0, // Lower threshold for testing
        max_data_points: 5,               // Reduced data points
        ..types::ProfilerConfig::default()
    };
    let mut profiler = profiler::MemoryProfiler::new(config).expect("operation failed");

    // Start monitoring
    profiler.start_monitoring().await.expect("operation failed");

    // Let it run for much shorter time
    tokio::time::sleep(Duration::from_millis(40)).await;

    // Test all analytics features work together
    let thresholds = profiler.get_adaptive_thresholds().await.expect("operation failed");
    let stats = profiler.get_monitoring_stats().await.expect("operation failed");
    let leak_config = profiler.get_leak_detection_config().await.expect("operation failed");

    // Verify basic functioning
    assert!(thresholds.base_memory_threshold > 0.0);
    assert!(stats.total_collections > 0);
    assert!(leak_config.growth_threshold > 0.0);

    // Test analytics summary
    let summary = profiler.get_analytics_summary().await.expect("operation failed");
    assert!(summary.adaptive_thresholds.base_memory_threshold > 0.0);
    assert!(summary.monitoring_stats.total_collections > 0);

    profiler.stop_monitoring().await.expect("operation failed");

    // Explicit cleanup
    drop(profiler);
    std::hint::black_box(());
}

#[test]
fn test_statistical_analyzer() {
    let analyzer = analytics::StatisticalAnalyzer::new(0.95);

    // Create test metrics with known values
    let mut metrics = Vec::new();
    for i in 0..50 {
        let memory_mb = 100.0 + (i as f64) * 2.0; // Linear growth from 100MB to 198MB
        metrics.push(types::MemoryMetrics {
            timestamp: SystemTime::now(),
            total_memory_mb: memory_mb,
            heap_memory_mb: memory_mb * 0.8,
            stack_memory_mb: memory_mb * 0.1,
            gpu_memory_mb: Some(memory_mb * 0.5),
            peak_memory_mb: memory_mb * 1.2,
            allocated_objects: (1000 + i) as u64,
            deallocated_objects: (900 + i) as u64,
            active_allocations: 100,
            memory_fragmentation_ratio: 0.15,
            gc_collections: 10,
            gc_time_ms: 5.0,
            memory_growth_rate_mb_per_sec: 2.0,
        });
    }

    // Test statistical calculations
    let stats = analyzer.calculate_usage_statistics(&metrics);
    assert!(stats.mean > 100.0);
    assert!(stats.mean < 200.0);
    assert!(stats.std_dev > 0.0);
    assert!(stats.trend_slope > 0.0); // Should have positive trend
    assert!(stats.coefficient_of_variation > 0.0);
    assert_eq!(stats.outlier_count, 0); // Linear data should have no outliers
}

#[test]
fn test_anomaly_detection() {
    let analyzer = analytics::StatisticalAnalyzer::new(0.95);

    // Create test metrics with an anomaly
    let mut metrics = Vec::new();
    for i in 0..20 {
        let memory_mb = if i == 15 {
            500.0 // Sudden spike
        } else {
            100.0 + (i as f64)
        };

        metrics.push(types::MemoryMetrics {
            timestamp: SystemTime::now(),
            total_memory_mb: memory_mb,
            heap_memory_mb: memory_mb * 0.8,
            stack_memory_mb: memory_mb * 0.1,
            gpu_memory_mb: Some(memory_mb * 0.5),
            peak_memory_mb: memory_mb * 1.2,
            allocated_objects: (1000 + i) as u64,
            deallocated_objects: (900 + i) as u64,
            active_allocations: 100,
            memory_fragmentation_ratio: 0.15,
            gc_collections: 10,
            gc_time_ms: 5.0,
            memory_growth_rate_mb_per_sec: 2.0,
        });
    }

    // Test anomaly detection
    let anomalies = analyzer.detect_anomalies(&metrics);
    assert!(!anomalies.is_empty());
    assert_eq!(
        anomalies[0].anomaly_type,
        analytics::AnomalyType::SuddenSpike
    );
    assert!(anomalies[0].confidence_score > 0.0);
    assert!(anomalies[0].description.contains("spike"));
}

#[test]
fn test_sustained_growth_detection() {
    let analyzer = analytics::StatisticalAnalyzer::new(0.95);

    // Create test metrics with sustained growth
    let mut metrics = Vec::new();
    for i in 0..30 {
        let memory_mb = if i < 20 {
            100.0 + (i as f64) // Gradual growth
        } else {
            100.0 + 20.0 + (i as f64 - 20.0) * 5.0 // Faster growth in later part
        };

        metrics.push(types::MemoryMetrics {
            timestamp: SystemTime::now(),
            total_memory_mb: memory_mb,
            heap_memory_mb: memory_mb * 0.8,
            stack_memory_mb: memory_mb * 0.1,
            gpu_memory_mb: Some(memory_mb * 0.5),
            peak_memory_mb: memory_mb * 1.2,
            allocated_objects: (1000 + i) as u64,
            deallocated_objects: (900 + i) as u64,
            active_allocations: 100,
            memory_fragmentation_ratio: 0.15,
            gc_collections: 10,
            gc_time_ms: 5.0,
            memory_growth_rate_mb_per_sec: 2.0,
        });
    }

    // Test sustained growth detection
    let anomalies = analyzer.detect_anomalies(&metrics);
    let growth_anomalies: Vec<_> = anomalies
        .iter()
        .filter(|a| matches!(a.anomaly_type, analytics::AnomalyType::SustainedGrowth))
        .collect();

    assert!(!growth_anomalies.is_empty());
    assert!(growth_anomalies[0].confidence_score > 0.0);
    assert!(growth_anomalies[0].description.contains("growth"));
}

#[test]
fn test_statistical_analyzer_empty_data() {
    let analyzer = analytics::StatisticalAnalyzer::new(0.95);
    let metrics = Vec::new();

    let stats = analyzer.calculate_usage_statistics(&metrics);
    assert_eq!(stats.mean, 0.0);
    assert_eq!(stats.std_dev, 0.0);

    let anomalies = analyzer.detect_anomalies(&metrics);
    assert!(anomalies.is_empty());
}

#[test]
fn test_memory_statistics_default() {
    let stats = analytics::MemoryStatistics::default();
    assert_eq!(stats.mean, 0.0);
    assert_eq!(stats.median, 0.0);
    assert_eq!(stats.outlier_count, 0);
    assert_eq!(stats.trend_slope, 0.0);
}