trustformers 0.1.1

TrustformeRS - Rust port of Hugging Face Transformers
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
use crate::error::{Result, TrustformersError};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, RwLock};
use std::time::Instant;

/// Configuration for adaptive batch sizing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdaptiveBatchConfig {
    /// Minimum batch size to consider
    pub min_batch_size: usize,
    /// Maximum batch size to test
    pub max_batch_size: usize,
    /// Number of performance samples to collect per batch size
    pub samples_per_size: usize,
    /// Warmup iterations before collecting metrics
    pub warmup_iterations: usize,
    /// Target latency percentile (e.g., 95.0 for 95th percentile)
    pub target_latency_percentile: f64,
    /// Target latency in milliseconds
    pub target_latency_ms: f64,
    /// Throughput weight in optimization (0.0 to 1.0)
    pub throughput_weight: f64,
    /// Latency weight in optimization (0.0 to 1.0)
    pub latency_weight: f64,
    /// Memory weight in optimization (0.0 to 1.0)
    pub memory_weight: f64,
    /// Re-evaluation interval in seconds
    pub reevaluation_interval_secs: u64,
}

impl Default for AdaptiveBatchConfig {
    fn default() -> Self {
        Self {
            min_batch_size: 1,
            max_batch_size: 64,
            samples_per_size: 10,
            warmup_iterations: 3,
            target_latency_percentile: 95.0,
            target_latency_ms: 100.0,
            throughput_weight: 0.4,
            latency_weight: 0.4,
            memory_weight: 0.2,
            reevaluation_interval_secs: 300, // 5 minutes
        }
    }
}

/// Performance sample for a specific batch size
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceSample {
    pub batch_size: usize,
    pub latency_ms: f64,
    pub throughput_rps: f64,
    pub memory_usage_mb: f64,
    pub gpu_memory_mb: f64,
    pub cpu_utilization: f32,
    pub gpu_utilization: f32,
    pub timestamp: std::time::SystemTime,
}

/// Statistics for a batch size over multiple samples
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchSizeStats {
    pub batch_size: usize,
    pub sample_count: usize,
    pub avg_latency_ms: f64,
    pub p95_latency_ms: f64,
    pub p99_latency_ms: f64,
    pub avg_throughput_rps: f64,
    pub max_throughput_rps: f64,
    pub avg_memory_mb: f64,
    pub max_memory_mb: f64,
    pub avg_cpu_utilization: f32,
    pub avg_gpu_utilization: f32,
    pub score: f64, // Combined optimization score
}

/// Adaptive batch sizing optimizer
#[derive(Debug)]
pub struct AdaptiveBatchOptimizer {
    config: AdaptiveBatchConfig,
    performance_data: Arc<RwLock<HashMap<usize, VecDeque<PerformanceSample>>>>,
    batch_stats: Arc<RwLock<HashMap<usize, BatchSizeStats>>>,
    optimal_batch_size: Arc<RwLock<Option<usize>>>,
    last_evaluation: Arc<RwLock<Instant>>,
    current_test_size: Arc<RwLock<Option<usize>>>,
    test_iteration: Arc<RwLock<usize>>,
}

/// Alias for backward compatibility
pub type AdaptiveBatchManager = AdaptiveBatchOptimizer;

impl AdaptiveBatchOptimizer {
    /// Create a new adaptive batch optimizer
    pub fn new(config: AdaptiveBatchConfig) -> Self {
        Self {
            config,
            performance_data: Arc::new(RwLock::new(HashMap::new())),
            batch_stats: Arc::new(RwLock::new(HashMap::new())),
            optimal_batch_size: Arc::new(RwLock::new(None)),
            last_evaluation: Arc::new(RwLock::new(Instant::now())),
            current_test_size: Arc::new(RwLock::new(None)),
            test_iteration: Arc::new(RwLock::new(0)),
        }
    }

    /// Get the current optimal batch size
    pub fn get_optimal_batch_size(&self) -> Option<usize> {
        *self.optimal_batch_size.read().expect("lock should not be poisoned")
    }

    /// Record a performance sample for a given batch size
    pub fn record_sample(&self, sample: PerformanceSample) -> Result<()> {
        let batch_size = sample.batch_size;

        // Add sample to performance data
        {
            let mut data = self.performance_data.write().expect("lock should not be poisoned");
            let samples = data.entry(batch_size).or_default();
            samples.push_back(sample);

            // Keep only recent samples
            while samples.len() > self.config.samples_per_size * 2 {
                samples.pop_front();
            }
        }

        // Update statistics for this batch size
        self.update_batch_stats(batch_size)?;

        // Check if we should re-evaluate optimal size
        let should_reevaluate = {
            let last_eval = self.last_evaluation.read().expect("lock should not be poisoned");
            last_eval.elapsed().as_secs() >= self.config.reevaluation_interval_secs
        };

        if should_reevaluate {
            self.evaluate_optimal_batch_size()?;
        }

        Ok(())
    }

    /// Get the next batch size to test (for exploration)
    pub fn get_next_test_size(&self) -> Option<usize> {
        let mut current_test = self.current_test_size.write().expect("lock should not be poisoned");
        let mut iteration = self.test_iteration.write().expect("lock should not be poisoned");

        match *current_test {
            None => {
                // Start testing from minimum size
                *current_test = Some(self.config.min_batch_size);
                *iteration = 0;
                Some(self.config.min_batch_size)
            },
            Some(size) => {
                *iteration += 1;

                // Check if we've collected enough samples for current size
                let enough_samples = {
                    let data = self.performance_data.read().expect("lock should not be poisoned");
                    data.get(&size)
                        .map(|samples| samples.len() >= self.config.samples_per_size)
                        .unwrap_or(false)
                };

                if enough_samples {
                    // Move to next batch size
                    let next_size = self.get_next_size_to_test(size);
                    *current_test = next_size;
                    *iteration = 0;
                    next_size
                } else {
                    // Continue testing current size
                    Some(size)
                }
            },
        }
    }

    /// Get the next size to test in sequence
    fn get_next_size_to_test(&self, current_size: usize) -> Option<usize> {
        // Exponential progression for testing
        let progression = [1, 2, 4, 8, 16, 32, 64, 128];

        if let Some(pos) = progression.iter().position(|&x| x == current_size) {
            if pos + 1 < progression.len() && progression[pos + 1] <= self.config.max_batch_size {
                Some(progression[pos + 1])
            } else {
                None // Testing complete
            }
        } else {
            // Custom progression if current size not in standard progression
            let next = current_size * 2;
            if next <= self.config.max_batch_size {
                Some(next)
            } else {
                None
            }
        }
    }

    /// Update statistics for a specific batch size
    fn update_batch_stats(&self, batch_size: usize) -> Result<()> {
        let samples = {
            let data = self.performance_data.read().expect("lock should not be poisoned");
            data.get(&batch_size).cloned().unwrap_or_default()
        };

        if samples.len() < 3 {
            return Ok(()); // Need at least 3 samples for meaningful stats
        }

        let sample_vec: Vec<_> = samples.iter().collect();

        // Calculate statistics
        let avg_latency =
            sample_vec.iter().map(|s| s.latency_ms).sum::<f64>() / sample_vec.len() as f64;
        let avg_throughput =
            sample_vec.iter().map(|s| s.throughput_rps).sum::<f64>() / sample_vec.len() as f64;
        let max_throughput = sample_vec.iter().map(|s| s.throughput_rps).fold(0.0, f64::max);
        let avg_memory =
            sample_vec.iter().map(|s| s.memory_usage_mb).sum::<f64>() / sample_vec.len() as f64;
        let max_memory = sample_vec.iter().map(|s| s.memory_usage_mb).fold(0.0, f64::max);
        let avg_cpu =
            sample_vec.iter().map(|s| s.cpu_utilization).sum::<f32>() / sample_vec.len() as f32;
        let avg_gpu =
            sample_vec.iter().map(|s| s.gpu_utilization).sum::<f32>() / sample_vec.len() as f32;

        // Calculate percentiles
        let mut latencies: Vec<f64> = sample_vec.iter().map(|s| s.latency_ms).collect();
        latencies.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let p95_index = ((latencies.len() as f64) * 0.95) as usize;
        let p99_index = ((latencies.len() as f64) * 0.99) as usize;
        let p95_latency = latencies.get(p95_index).copied().unwrap_or(avg_latency);
        let p99_latency = latencies.get(p99_index).copied().unwrap_or(avg_latency);

        // Calculate optimization score
        let score =
            self.calculate_optimization_score(avg_latency, p95_latency, avg_throughput, avg_memory);

        let stats = BatchSizeStats {
            batch_size,
            sample_count: sample_vec.len(),
            avg_latency_ms: avg_latency,
            p95_latency_ms: p95_latency,
            p99_latency_ms: p99_latency,
            avg_throughput_rps: avg_throughput,
            max_throughput_rps: max_throughput,
            avg_memory_mb: avg_memory,
            max_memory_mb: max_memory,
            avg_cpu_utilization: avg_cpu,
            avg_gpu_utilization: avg_gpu,
            score,
        };

        // Store stats
        {
            let mut batch_stats = self.batch_stats.write().expect("lock should not be poisoned");
            batch_stats.insert(batch_size, stats);
        }

        Ok(())
    }

    /// Calculate optimization score for a configuration
    fn calculate_optimization_score(
        &self,
        avg_latency: f64,
        p95_latency: f64,
        avg_throughput: f64,
        avg_memory: f64,
    ) -> f64 {
        // Normalize metrics to 0-1 scale
        let latency_score = if p95_latency <= self.config.target_latency_ms {
            1.0 // Perfect score for meeting target
        } else {
            (self.config.target_latency_ms / p95_latency).max(0.1) // Penalty for exceeding target
        };

        // Throughput score (higher is better)
        let throughput_score = (avg_throughput / 100.0).min(1.0); // Normalize to 100 RPS baseline

        // Memory score (lower is better)
        let memory_score = (1000.0 / (avg_memory + 100.0)).min(1.0); // Normalize with 1GB baseline

        // Weighted combination

        (self.config.latency_weight * latency_score)
            + (self.config.throughput_weight * throughput_score)
            + (self.config.memory_weight * memory_score)
    }

    /// Evaluate and update the optimal batch size
    fn evaluate_optimal_batch_size(&self) -> Result<()> {
        let stats = self.batch_stats.read().expect("lock should not be poisoned");

        if stats.is_empty() {
            return Ok(());
        }

        // Find batch size with highest score
        let optimal = stats
            .values()
            .filter(|s| s.sample_count >= self.config.samples_per_size)
            .max_by(|a, b| a.score.partial_cmp(&b.score).unwrap_or(std::cmp::Ordering::Equal))
            .map(|s| s.batch_size);

        if let Some(optimal_size) = optimal {
            let mut current_optimal =
                self.optimal_batch_size.write().expect("lock should not be poisoned");
            *current_optimal = Some(optimal_size);

            tracing::info!(
                "Updated optimal batch size to {}: score {:.3}",
                optimal_size,
                stats.get(&optimal_size).expect("optimal_size came from stats").score
            );
        }

        // Update last evaluation time
        {
            let mut last_eval = self.last_evaluation.write().expect("lock should not be poisoned");
            *last_eval = Instant::now();
        }

        Ok(())
    }

    /// Get comprehensive performance report
    pub fn get_performance_report(&self) -> PerformanceReport {
        let stats = self.batch_stats.read().expect("lock should not be poisoned");
        let optimal = *self.optimal_batch_size.read().expect("lock should not be poisoned");

        let mut batch_performances: Vec<_> = stats.values().cloned().collect();
        batch_performances.sort_by_key(|s| s.batch_size);

        PerformanceReport {
            optimal_batch_size: optimal,
            batch_performances,
            total_evaluations: stats.len(),
            last_evaluation: *self.last_evaluation.read().expect("lock should not be poisoned"),
        }
    }

    /// Export performance data for analysis
    pub fn export_data(&self) -> Result<String> {
        let stats = self.batch_stats.read().expect("lock should not be poisoned");
        let data = stats.values().collect::<Vec<_>>();
        serde_json::to_string_pretty(&data)
            .map_err(|e| TrustformersError::runtime_error(format!("Failed to export data: {}", e)))
    }

    /// Import performance data from previous runs
    pub fn import_data(&self, data: &str) -> Result<()> {
        let imported_stats: Vec<BatchSizeStats> = serde_json::from_str(data).map_err(|e| {
            TrustformersError::runtime_error(format!("Failed to import data: {}", e))
        })?;

        {
            let mut stats = self.batch_stats.write().expect("lock should not be poisoned");
            for stat in imported_stats {
                stats.insert(stat.batch_size, stat);
            }
        }

        // Re-evaluate optimal batch size with new data
        self.evaluate_optimal_batch_size()?;

        Ok(())
    }
}

/// Performance report containing optimization results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceReport {
    pub optimal_batch_size: Option<usize>,
    pub batch_performances: Vec<BatchSizeStats>,
    pub total_evaluations: usize,
    #[serde(skip, default = "Instant::now")]
    pub last_evaluation: Instant,
}

impl PerformanceReport {
    /// Get the best performing batch sizes (top N)
    pub fn get_top_performers(&self, n: usize) -> Vec<&BatchSizeStats> {
        let mut sorted = self.batch_performances.iter().collect::<Vec<_>>();
        sorted.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
        sorted.into_iter().take(n).collect()
    }

    /// Get performance comparison between two batch sizes
    pub fn compare_batch_sizes(&self, size1: usize, size2: usize) -> Option<BatchComparison> {
        let stats1 = self.batch_performances.iter().find(|s| s.batch_size == size1)?;
        let stats2 = self.batch_performances.iter().find(|s| s.batch_size == size2)?;

        Some(BatchComparison {
            size1,
            size2,
            latency_improvement: stats1.avg_latency_ms / stats2.avg_latency_ms,
            throughput_improvement: stats2.avg_throughput_rps / stats1.avg_throughput_rps,
            memory_difference: stats2.avg_memory_mb - stats1.avg_memory_mb,
            score_difference: stats2.score - stats1.score,
        })
    }
}

/// Comparison between two batch sizes
#[derive(Debug, Clone)]
pub struct BatchComparison {
    pub size1: usize,
    pub size2: usize,
    pub latency_improvement: f64,    // >1.0 means size1 is faster
    pub throughput_improvement: f64, // >1.0 means size2 has higher throughput
    pub memory_difference: f64,      // Positive means size2 uses more memory
    pub score_difference: f64,       // Positive means size2 has better score
}

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

    // ── Helpers ──────────────────────────────────────────────────────────────

    fn make_sample(
        batch_size: usize,
        latency_ms: f64,
        throughput_rps: f64,
        memory_usage_mb: f64,
    ) -> PerformanceSample {
        PerformanceSample {
            batch_size,
            latency_ms,
            throughput_rps,
            memory_usage_mb,
            gpu_memory_mb: memory_usage_mb * 2.0,
            cpu_utilization: 0.6,
            gpu_utilization: 0.7,
            timestamp: SystemTime::now(),
        }
    }

    fn populate_optimizer(optimizer: &AdaptiveBatchOptimizer, batch_size: usize, n: usize) {
        for _ in 0..n {
            let sample = make_sample(batch_size, 60.0, 50.0, 256.0);
            optimizer.record_sample(sample).expect("record_sample should succeed");
        }
    }

    // ── Config defaults ───────────────────────────────────────────────────────

    #[test]
    fn test_config_min_less_than_max() {
        let config = AdaptiveBatchConfig::default();
        assert!(config.min_batch_size < config.max_batch_size);
    }

    #[test]
    fn test_config_weights_sum_to_one() {
        let config = AdaptiveBatchConfig::default();
        let total = config.throughput_weight + config.latency_weight + config.memory_weight;
        assert!((total - 1.0).abs() < 1e-9, "weights must sum to 1.0");
    }

    #[test]
    fn test_config_target_latency_positive() {
        let config = AdaptiveBatchConfig::default();
        assert!(config.target_latency_ms > 0.0);
    }

    // ── Optimizer initial state ───────────────────────────────────────────────

    #[test]
    fn test_optimizer_starts_with_no_optimal() {
        let optimizer = AdaptiveBatchOptimizer::new(AdaptiveBatchConfig::default());
        assert!(
            optimizer.get_optimal_batch_size().is_none(),
            "no optimal batch size before any data"
        );
    }

    #[test]
    fn test_adaptive_batch_optimizer_basic() {
        let config = AdaptiveBatchConfig::default();
        let optimizer = AdaptiveBatchOptimizer::new(config);
        let sample = make_sample(8, 50.0, 160.0, 512.0);
        optimizer.record_sample(sample).expect("record_sample should succeed");
        assert_eq!(optimizer.get_next_test_size(), Some(1));
        assert_eq!(optimizer.get_next_test_size(), Some(1));
    }

    // ── Optimization score ────────────────────────────────────────────────────

    #[test]
    fn test_optimization_score_calculation() {
        let config = AdaptiveBatchConfig::default();
        let optimizer = AdaptiveBatchOptimizer::new(config);
        let score1 = optimizer.calculate_optimization_score(80.0, 95.0, 50.0, 500.0);
        let score2 = optimizer.calculate_optimization_score(120.0, 150.0, 50.0, 500.0);
        assert!(
            score1 > score2,
            "score should be higher when meeting latency target"
        );
    }

    #[test]
    fn test_optimization_score_lower_memory_better() {
        let config = AdaptiveBatchConfig::default();
        let optimizer = AdaptiveBatchOptimizer::new(config);
        let score_low_mem = optimizer.calculate_optimization_score(80.0, 90.0, 50.0, 100.0);
        let score_high_mem = optimizer.calculate_optimization_score(80.0, 90.0, 50.0, 5000.0);
        assert!(
            score_low_mem > score_high_mem,
            "lower memory should yield better score"
        );
    }

    #[test]
    fn test_optimization_score_higher_throughput_better() {
        let config = AdaptiveBatchConfig::default();
        let optimizer = AdaptiveBatchOptimizer::new(config);
        let score_high = optimizer.calculate_optimization_score(80.0, 90.0, 200.0, 500.0);
        let score_low = optimizer.calculate_optimization_score(80.0, 90.0, 5.0, 500.0);
        assert!(
            score_high > score_low,
            "higher throughput should yield better score"
        );
    }

    // ── Batch size decrease on SLO violation ─────────────────────────────────

    #[test]
    fn test_dynamic_batch_size_based_on_throughput() {
        // When batch_size=1 and latency is fast, throughput > target
        // throughput = 1 / (50ms/1000) = 20 rps
        let throughput = 1.0_f64 / (50.0_f64 / 1000.0);
        assert!(
            throughput > 10.0,
            "batch 1 at 50ms latency should exceed 10 rps threshold"
        );
    }

    // ── Batch size increase on spare capacity ─────────────────────────────────

    #[test]
    fn test_batch_size_increase_on_spare_capacity() {
        // Very low latency with large batch → spare capacity
        let batch = 8_usize;
        let latency_ms = 5.0_f64; // well below typical targets
        let throughput = batch as f64 / (latency_ms / 1000.0);
        assert!(
            throughput > 100.0,
            "large batch at low latency should show spare capacity"
        );
    }

    // ── Exponential smoothing of metrics ─────────────────────────────────────

    #[test]
    fn test_exponential_smoothing_formula() {
        // alpha = 0.1; new_ema = old * (1-alpha) + new_val * alpha
        let old_ema = 50.0_f64;
        let alpha = 0.1_f64;
        let new_val = 100.0_f64;
        let new_ema = old_ema * (1.0 - alpha) + new_val * alpha;
        assert!((new_ema - 55.0).abs() < 1e-9, "EMA update should be 55.0");
    }

    // ── Test size progression ─────────────────────────────────────────────────

    #[test]
    fn test_get_next_size_to_test_exponential() {
        let config = AdaptiveBatchConfig {
            min_batch_size: 1,
            max_batch_size: 64,
            ..Default::default()
        };
        let optimizer = AdaptiveBatchOptimizer::new(config);
        // Populate size=1 with enough samples, then check next
        for _ in 0..15 {
            optimizer
                .record_sample(make_sample(1, 50.0, 20.0, 128.0))
                .expect("record_sample should succeed");
        }
        // After enough samples for size=1, next test should be 2
        let next = optimizer.get_next_test_size();
        assert!(
            next == Some(1) || next == Some(2),
            "should transition from 1 to 2 in exponential progression"
        );
    }

    #[test]
    fn test_get_next_size_none_when_exhausted() {
        let config = AdaptiveBatchConfig {
            min_batch_size: 64,
            max_batch_size: 64,
            samples_per_size: 2,
            ..Default::default()
        };
        let optimizer = AdaptiveBatchOptimizer::new(config);
        for _ in 0..5 {
            optimizer
                .record_sample(make_sample(64, 50.0, 50.0, 512.0))
                .expect("record_sample should succeed");
        }
        // Should eventually return None when no more sizes to test
        let _ = optimizer.get_next_test_size(); // may return Some(64) initially
    }

    // ── Performance report ────────────────────────────────────────────────────

    #[test]
    fn test_performance_report() {
        let config = AdaptiveBatchConfig::default();
        let optimizer = AdaptiveBatchOptimizer::new(config);
        for batch_size in [2_usize, 4, 8, 16] {
            for _ in 0..5 {
                let sample = make_sample(
                    batch_size,
                    50.0 + batch_size as f64 * 5.0,
                    batch_size as f64 * 10.0,
                    batch_size as f64 * 64.0,
                );
                optimizer.record_sample(sample).expect("record_sample should succeed");
            }
        }
        let report = optimizer.get_performance_report();
        assert!(!report.batch_performances.is_empty());
        let top_performers = report.get_top_performers(2);
        assert!(top_performers.len() <= 2);
    }

    #[test]
    fn test_performance_report_empty() {
        let config = AdaptiveBatchConfig::default();
        let optimizer = AdaptiveBatchOptimizer::new(config);
        let report = optimizer.get_performance_report();
        assert!(
            report.batch_performances.is_empty(),
            "fresh optimizer has no performance data"
        );
        assert!(report.optimal_batch_size.is_none());
    }

    // ── Comparison between batch sizes ────────────────────────────────────────

    #[test]
    fn test_batch_size_comparison_throughput_improvement() {
        let config = AdaptiveBatchConfig::default();
        let optimizer = AdaptiveBatchOptimizer::new(config);
        for _ in 0..5 {
            optimizer
                .record_sample(make_sample(4, 80.0, 50.0, 256.0))
                .expect("record_sample should succeed");
            optimizer
                .record_sample(make_sample(8, 80.0, 100.0, 512.0))
                .expect("record_sample should succeed");
        }
        let report = optimizer.get_performance_report();
        if let Some(cmp) = report.compare_batch_sizes(4, 8) {
            assert!(
                cmp.throughput_improvement > 1.0,
                "batch 8 should have better throughput than batch 4"
            );
        }
    }

    // ── Export / import data ──────────────────────────────────────────────────

    #[test]
    fn test_export_and_import_data_roundtrip() {
        let config = AdaptiveBatchConfig::default();
        let optimizer = AdaptiveBatchOptimizer::new(config.clone());
        for _ in 0..5 {
            optimizer
                .record_sample(make_sample(4, 60.0, 60.0, 256.0))
                .expect("record_sample should succeed");
        }
        let exported = optimizer.export_data().expect("export_data should succeed");
        // Import into a fresh optimizer
        let optimizer2 = AdaptiveBatchOptimizer::new(config);
        optimizer2.import_data(&exported).expect("import_data should succeed");
        let report = optimizer2.get_performance_report();
        assert!(
            !report.batch_performances.is_empty(),
            "imported data should populate report"
        );
    }

    // ── Alias test ────────────────────────────────────────────────────────────

    #[test]
    fn test_alias_type() {
        let _mgr: AdaptiveBatchManager =
            AdaptiveBatchOptimizer::new(AdaptiveBatchConfig::default());
    }

    // ── Latency target adjustment ─────────────────────────────────────────────

    #[test]
    fn test_latency_target_adjustment_formula() {
        // When p95 > target, score should be reduced by factor target/p95
        let config = AdaptiveBatchConfig {
            target_latency_ms: 100.0,
            ..Default::default()
        };
        let optimizer = AdaptiveBatchOptimizer::new(config);
        // p95=200ms → factor = 100/200 = 0.5
        let score = optimizer.calculate_optimization_score(150.0, 200.0, 30.0, 500.0);
        assert!(
            score < 1.0,
            "exceeding latency target should penalise score"
        );
    }
}