tenflowers-dataset 0.1.1

Data pipeline and dataset utilities for TenfloweRS
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
//! Adaptive prefetch auto-tuning policy
//!
//! This module provides automatic tuning of prefetch parameters based on
//! runtime performance metrics. It dynamically adjusts prefetch depth,
//! aggressiveness, and strategies to optimize for the current access pattern.

use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Adaptive prefetch tuning policy
#[derive(Debug, Clone)]
pub struct AdaptivePrefetchPolicy {
    /// Current prefetch depth (number of items to prefetch ahead)
    pub prefetch_depth: usize,
    /// Current prefetch aggressiveness (0.0 = conservative, 1.0 = aggressive)
    pub aggressiveness: f64,
    /// Minimum prefetch depth allowed
    pub min_depth: usize,
    /// Maximum prefetch depth allowed
    pub max_depth: usize,
    /// Target hit rate (0.0 - 1.0)
    pub target_hit_rate: f64,
    /// Current adaptation strategy
    pub strategy: AdaptationStrategy,
}

/// Strategy for adapting prefetch parameters
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AdaptationStrategy {
    /// Conservative: Increase prefetch only when high confidence
    Conservative,
    /// Balanced: Moderate adaptation based on metrics
    Balanced,
    /// Aggressive: Rapidly adapt to maximize performance
    Aggressive,
    /// Custom: Use custom thresholds
    Custom,
}

/// Performance metrics for tuning decisions
#[derive(Debug, Clone)]
pub struct PrefetchMetrics {
    /// Hit rate (successful prefetches / total prefetches)
    pub hit_rate: f64,
    /// Miss rate (unsuccessful prefetches / total prefetches)
    pub miss_rate: f64,
    /// Waste rate (prefetched but unused / total prefetches)
    pub waste_rate: f64,
    /// Average latency when data is in cache (microseconds)
    pub cache_hit_latency_us: f64,
    /// Average latency when data must be fetched (microseconds)
    pub cache_miss_latency_us: f64,
    /// Memory pressure (0.0 = low, 1.0 = high)
    pub memory_pressure: f64,
    /// Access pattern predictability (0.0 = random, 1.0 = perfectly predictable)
    pub predictability: f64,
}

impl Default for PrefetchMetrics {
    fn default() -> Self {
        Self {
            hit_rate: 0.0,
            miss_rate: 0.0,
            waste_rate: 0.0,
            cache_hit_latency_us: 0.0,
            cache_miss_latency_us: 0.0,
            memory_pressure: 0.0,
            predictability: 0.0,
        }
    }
}

/// Tuning decision made by the adaptive policy
#[derive(Debug, Clone)]
pub struct TuningDecision {
    /// New prefetch depth
    pub new_depth: usize,
    /// New aggressiveness level
    pub new_aggressiveness: f64,
    /// Reason for the decision
    pub reason: String,
    /// Confidence in this decision (0.0 - 1.0)
    pub confidence: f64,
}

/// Adaptive prefetch tuner that adjusts parameters automatically
pub struct AdaptivePrefetchTuner {
    /// Current policy configuration
    policy: Arc<Mutex<AdaptivePrefetchPolicy>>,
    /// Historical metrics for trend analysis
    metrics_history: Arc<Mutex<VecDeque<(Instant, PrefetchMetrics)>>>,
    /// Maximum history size
    max_history_size: usize,
    /// Tuning interval (how often to adjust parameters)
    tuning_interval: Duration,
    /// Last tuning time
    last_tuning: Arc<Mutex<Instant>>,
}

impl AdaptivePrefetchPolicy {
    /// Create a new adaptive policy with defaults
    pub fn new() -> Self {
        Self {
            prefetch_depth: 4,
            aggressiveness: 0.5,
            min_depth: 1,
            max_depth: 32,
            target_hit_rate: 0.8,
            strategy: AdaptationStrategy::Balanced,
        }
    }

    /// Create a conservative policy
    pub fn conservative() -> Self {
        Self {
            prefetch_depth: 2,
            aggressiveness: 0.3,
            min_depth: 1,
            max_depth: 8,
            target_hit_rate: 0.9,
            strategy: AdaptationStrategy::Conservative,
        }
    }

    /// Create an aggressive policy
    pub fn aggressive() -> Self {
        Self {
            prefetch_depth: 8,
            aggressiveness: 0.8,
            min_depth: 2,
            max_depth: 64,
            target_hit_rate: 0.7,
            strategy: AdaptationStrategy::Aggressive,
        }
    }

    /// Create a custom policy
    pub fn custom(min_depth: usize, max_depth: usize, target_hit_rate: f64) -> Self {
        Self {
            prefetch_depth: (min_depth + max_depth) / 2,
            aggressiveness: 0.5,
            min_depth,
            max_depth,
            target_hit_rate: target_hit_rate.clamp(0.0, 1.0),
            strategy: AdaptationStrategy::Custom,
        }
    }
}

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

impl AdaptivePrefetchTuner {
    /// Create a new adaptive tuner with the given policy
    pub fn new(policy: AdaptivePrefetchPolicy) -> Self {
        Self {
            policy: Arc::new(Mutex::new(policy)),
            metrics_history: Arc::new(Mutex::new(VecDeque::new())),
            max_history_size: 100,
            tuning_interval: Duration::from_secs(5),
            last_tuning: Arc::new(Mutex::new(Instant::now())),
        }
    }

    /// Create with custom tuning interval
    pub fn with_interval(mut self, interval: Duration) -> Self {
        self.tuning_interval = interval;
        self
    }

    /// Create with custom history size
    pub fn with_history_size(mut self, size: usize) -> Self {
        self.max_history_size = size;
        self
    }

    /// Update metrics and potentially trigger retuning
    pub fn update_metrics(&self, metrics: PrefetchMetrics) -> Option<TuningDecision> {
        // Record metrics
        let mut history = self
            .metrics_history
            .lock()
            .expect("lock should not be poisoned");
        history.push_back((Instant::now(), metrics.clone()));

        // Maintain history size
        while history.len() > self.max_history_size {
            history.pop_front();
        }
        drop(history);

        // Check if it's time to retune
        let mut last_tuning = self
            .last_tuning
            .lock()
            .expect("lock should not be poisoned");
        if last_tuning.elapsed() < self.tuning_interval {
            return None;
        }
        *last_tuning = Instant::now();
        drop(last_tuning);

        // Make tuning decision
        let decision = self.make_tuning_decision(&metrics)?;

        // Apply decision
        let mut policy = self.policy.lock().expect("lock should not be poisoned");
        policy.prefetch_depth = decision.new_depth;
        policy.aggressiveness = decision.new_aggressiveness;
        drop(policy);

        Some(decision)
    }

    /// Make a tuning decision based on current metrics
    fn make_tuning_decision(&self, metrics: &PrefetchMetrics) -> Option<TuningDecision> {
        let policy = self.policy.lock().expect("lock should not be poisoned");
        let current_depth = policy.prefetch_depth;
        let current_aggressiveness = policy.aggressiveness;
        let strategy = policy.strategy;
        let target_hit_rate = policy.target_hit_rate;
        let min_depth = policy.min_depth;
        let max_depth = policy.max_depth;
        drop(policy);

        // Calculate how far we are from target hit rate
        let hit_rate_delta = metrics.hit_rate - target_hit_rate;

        // Decision logic based on strategy
        let (depth_adjustment, aggressiveness_adjustment, reason, confidence) = match strategy {
            AdaptationStrategy::Conservative => self.conservative_decision(
                metrics,
                hit_rate_delta,
                current_depth,
                min_depth,
                max_depth,
            ),
            AdaptationStrategy::Balanced => {
                self.balanced_decision(metrics, hit_rate_delta, current_depth, min_depth, max_depth)
            }
            AdaptationStrategy::Aggressive => self.aggressive_decision(
                metrics,
                hit_rate_delta,
                current_depth,
                min_depth,
                max_depth,
            ),
            AdaptationStrategy::Custom => {
                self.balanced_decision(metrics, hit_rate_delta, current_depth, min_depth, max_depth)
            }
        };

        let new_depth = (current_depth as i32 + depth_adjustment)
            .max(min_depth as i32)
            .min(max_depth as i32) as usize;

        let new_aggressiveness =
            (current_aggressiveness + aggressiveness_adjustment).clamp(0.0, 1.0);

        // Only return decision if there's a meaningful change
        if new_depth == current_depth && (new_aggressiveness - current_aggressiveness).abs() < 0.05
        {
            return None;
        }

        Some(TuningDecision {
            new_depth,
            new_aggressiveness,
            reason,
            confidence,
        })
    }

    fn conservative_decision(
        &self,
        metrics: &PrefetchMetrics,
        hit_rate_delta: f64,
        current_depth: usize,
        min_depth: usize,
        max_depth: usize,
    ) -> (i32, f64, String, f64) {
        // Conservative: Only increase if hit rate is very good and predictability is high
        if hit_rate_delta > 0.1 && metrics.predictability > 0.7 {
            (
                1,
                0.05,
                "High hit rate with good predictability".to_string(),
                0.8,
            )
        } else if hit_rate_delta < -0.2 {
            (
                -1,
                -0.1,
                "Significant hit rate degradation".to_string(),
                0.9,
            )
        } else if metrics.memory_pressure > 0.8 {
            (-1, -0.05, "High memory pressure".to_string(), 0.95)
        } else {
            (0, 0.0, "No change needed".to_string(), 0.6)
        }
    }

    fn balanced_decision(
        &self,
        metrics: &PrefetchMetrics,
        hit_rate_delta: f64,
        current_depth: usize,
        min_depth: usize,
        max_depth: usize,
    ) -> (i32, f64, String, f64) {
        // Balanced: Moderate adjustments based on multiple factors
        let mut depth_adj = 0i32;
        let mut aggr_adj = 0.0;
        let mut reasons = Vec::new();
        let mut confidence: f64 = 0.5;

        // Hit rate consideration
        if hit_rate_delta > 0.05 {
            depth_adj += 1;
            aggr_adj += 0.1;
            reasons.push("Good hit rate");
            confidence += 0.1;
        } else if hit_rate_delta < -0.1 {
            depth_adj -= 1;
            aggr_adj -= 0.1;
            reasons.push("Poor hit rate");
            confidence += 0.2;
        }

        // Predictability consideration
        if metrics.predictability > 0.6 {
            depth_adj += 1;
            reasons.push("High predictability");
            confidence += 0.15;
        } else if metrics.predictability < 0.3 {
            depth_adj -= 1;
            reasons.push("Low predictability");
            confidence += 0.1;
        }

        // Memory pressure consideration
        if metrics.memory_pressure > 0.7 {
            depth_adj -= 2;
            aggr_adj -= 0.2;
            reasons.push("High memory pressure");
            confidence += 0.2;
        }

        // Waste rate consideration
        if metrics.waste_rate > 0.3 {
            depth_adj -= 1;
            aggr_adj -= 0.15;
            reasons.push("High waste rate");
            confidence += 0.15;
        }

        let reason = if reasons.is_empty() {
            "Maintaining current settings".to_string()
        } else {
            reasons.join(", ")
        };

        (depth_adj, aggr_adj, reason, confidence.min(1.0))
    }

    fn aggressive_decision(
        &self,
        metrics: &PrefetchMetrics,
        hit_rate_delta: f64,
        current_depth: usize,
        min_depth: usize,
        max_depth: usize,
    ) -> (i32, f64, String, f64) {
        // Aggressive: Rapidly adapt to maximize performance
        let (depth_adj, aggr_adj, reason, confidence) =
            if metrics.predictability > 0.5 && hit_rate_delta > -0.1 {
                // Increase aggressively if there's some predictability
                (
                    2,
                    0.2,
                    "Increasing prefetch for better performance".to_string(),
                    0.7,
                )
            } else if hit_rate_delta < -0.15 || metrics.memory_pressure > 0.8 {
                // Pull back if hitting problems
                (
                    -2,
                    -0.2,
                    "Reducing prefetch due to issues".to_string(),
                    0.85,
                )
            } else {
                // Try increasing by default
                (1, 0.1, "Exploring higher prefetch levels".to_string(), 0.6)
            };

        (depth_adj, aggr_adj, reason, confidence)
    }

    /// Get current policy
    pub fn get_policy(&self) -> AdaptivePrefetchPolicy {
        self.policy
            .lock()
            .expect("lock should not be poisoned")
            .clone()
    }

    /// Get metrics history
    pub fn get_metrics_history(&self) -> Vec<(Instant, PrefetchMetrics)> {
        self.metrics_history
            .lock()
            .expect("metrics_history lock should not be poisoned")
            .iter()
            .cloned()
            .collect()
    }

    /// Get average metrics over recent history
    pub fn get_average_metrics(&self, window: Duration) -> Option<PrefetchMetrics> {
        let history = self
            .metrics_history
            .lock()
            .expect("lock should not be poisoned");
        let cutoff = Instant::now() - window;

        let recent: Vec<_> = history
            .iter()
            .filter(|(time, _)| *time > cutoff)
            .map(|(_, metrics)| metrics)
            .collect();

        if recent.is_empty() {
            return None;
        }

        let count = recent.len() as f64;
        Some(PrefetchMetrics {
            hit_rate: recent.iter().map(|m| m.hit_rate).sum::<f64>() / count,
            miss_rate: recent.iter().map(|m| m.miss_rate).sum::<f64>() / count,
            waste_rate: recent.iter().map(|m| m.waste_rate).sum::<f64>() / count,
            cache_hit_latency_us: recent.iter().map(|m| m.cache_hit_latency_us).sum::<f64>()
                / count,
            cache_miss_latency_us: recent.iter().map(|m| m.cache_miss_latency_us).sum::<f64>()
                / count,
            memory_pressure: recent.iter().map(|m| m.memory_pressure).sum::<f64>() / count,
            predictability: recent.iter().map(|m| m.predictability).sum::<f64>() / count,
        })
    }

    /// Reset tuner state
    pub fn reset(&self) {
        self.metrics_history
            .lock()
            .expect("lock should not be poisoned")
            .clear();
        *self
            .last_tuning
            .lock()
            .expect("lock should not be poisoned") = Instant::now();
    }

    /// Generate tuning report
    pub fn generate_report(&self) -> String {
        let policy = self.policy.lock().expect("lock should not be poisoned");
        let avg_metrics = self
            .get_average_metrics(Duration::from_secs(60))
            .unwrap_or_default();

        let mut report = String::new();
        report.push_str("=== Adaptive Prefetch Tuning Report ===\n\n");

        report.push_str("## Current Policy\n");
        report.push_str(&format!("  Strategy: {:?}\n", policy.strategy));
        report.push_str(&format!("  Prefetch Depth: {}\n", policy.prefetch_depth));
        report.push_str(&format!("  Aggressiveness: {:.2}\n", policy.aggressiveness));
        report.push_str(&format!(
            "  Depth Range: {} - {}\n",
            policy.min_depth, policy.max_depth
        ));
        report.push_str(&format!(
            "  Target Hit Rate: {:.1}%\n\n",
            policy.target_hit_rate * 100.0
        ));

        report.push_str("## Average Metrics (Last 60s)\n");
        report.push_str(&format!(
            "  Hit Rate: {:.1}%\n",
            avg_metrics.hit_rate * 100.0
        ));
        report.push_str(&format!(
            "  Miss Rate: {:.1}%\n",
            avg_metrics.miss_rate * 100.0
        ));
        report.push_str(&format!(
            "  Waste Rate: {:.1}%\n",
            avg_metrics.waste_rate * 100.0
        ));
        report.push_str(&format!(
            "  Predictability: {:.1}%\n",
            avg_metrics.predictability * 100.0
        ));
        report.push_str(&format!(
            "  Memory Pressure: {:.1}%\n",
            avg_metrics.memory_pressure * 100.0
        ));
        report.push_str(&format!(
            "  Cache Hit Latency: {:.2}μs\n",
            avg_metrics.cache_hit_latency_us
        ));
        report.push_str(&format!(
            "  Cache Miss Latency: {:.2}μs\n",
            avg_metrics.cache_miss_latency_us
        ));

        report
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// PID-controlled adaptive prefetch depth controller
// ──────────────────────────────────────────────────────────────────────────────

/// A PID-based controller that adjusts prefetch depth according to cache-hit rate telemetry.
///
/// Each call to [`PidAdaptiveController::tick`] supplies the current hit rate and returns the new recommended
/// prefetch depth.  The controller computes the classical PID update:
///
/// ```text
/// error      = setpoint_hit_rate − current_hit_rate
/// integral   = clamp(integral + error, −integral_cap, +integral_cap)
/// derivative = error − prev_error
/// output     = kp·error + ki·integral + kd·derivative
/// new_depth  = clamp(current_depth + round(output), min_depth, max_depth)
/// ```
///
/// *A positive error* means hit rate is below the setpoint → increase depth.
/// *Anti-windup* is provided via `integral_cap`.
#[derive(Debug, Clone)]
pub struct PidAdaptiveController {
    /// Proportional gain.
    pub kp: f64,
    /// Integral gain.
    pub ki: f64,
    /// Derivative gain.
    pub kd: f64,
    /// Target (setpoint) hit rate in [0, 1].
    pub setpoint_hit_rate: f64,
    /// Accumulated integral term (anti-windup clamped).
    integral: f64,
    /// Previous error (for derivative term).
    prev_error: f64,
    /// Maximum absolute value of the integral accumulator (anti-windup cap).
    pub integral_cap: f64,
    /// Minimum allowed prefetch depth.
    pub min_depth: usize,
    /// Maximum allowed prefetch depth.
    pub max_depth: usize,
    /// Current prefetch depth recommendation.
    current_depth: usize,
}

impl PidAdaptiveController {
    /// Create a new PID controller.
    ///
    /// - `kp`, `ki`, `kd`: PID gains
    /// - `setpoint_hit_rate`: desired cache-hit rate in [0, 1]
    /// - `initial_depth`: starting prefetch depth
    /// - `min_depth`, `max_depth`: hard bounds on depth output
    pub fn new(
        kp: f64,
        ki: f64,
        kd: f64,
        setpoint_hit_rate: f64,
        initial_depth: usize,
        min_depth: usize,
        max_depth: usize,
    ) -> Self {
        let clamped_depth = initial_depth.clamp(min_depth, max_depth);
        Self {
            kp,
            ki,
            kd,
            setpoint_hit_rate: setpoint_hit_rate.clamp(0.0, 1.0),
            integral: 0.0,
            prev_error: 0.0,
            integral_cap: 10.0,
            min_depth,
            max_depth,
            current_depth: clamped_depth,
        }
    }

    /// Update the controller with the latest cache-hit rate and return the new prefetch depth.
    pub fn tick(&mut self, current_hit_rate: f64) -> usize {
        let error = self.setpoint_hit_rate - current_hit_rate.clamp(0.0, 1.0);

        self.integral = (self.integral + error).clamp(-self.integral_cap, self.integral_cap);

        let derivative = error - self.prev_error;
        self.prev_error = error;

        let output = self.kp * error + self.ki * self.integral + self.kd * derivative;

        let delta = output.round() as i64;
        let new_depth = (self.current_depth as i64 + delta)
            .clamp(self.min_depth as i64, self.max_depth as i64) as usize;

        self.current_depth = new_depth;
        new_depth
    }

    /// Return the current recommended prefetch depth without performing a tick.
    pub fn current_depth(&self) -> usize {
        self.current_depth
    }

    /// Reset the controller state (integral and derivative terms).
    pub fn reset(&mut self) {
        self.integral = 0.0;
        self.prev_error = 0.0;
    }
}

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

    #[test]
    fn test_policy_creation() {
        let policy = AdaptivePrefetchPolicy::new();
        assert_eq!(policy.prefetch_depth, 4);
        assert_eq!(policy.strategy, AdaptationStrategy::Balanced);

        let conservative = AdaptivePrefetchPolicy::conservative();
        assert_eq!(conservative.strategy, AdaptationStrategy::Conservative);
        assert!(conservative.prefetch_depth < policy.prefetch_depth);

        let aggressive = AdaptivePrefetchPolicy::aggressive();
        assert_eq!(aggressive.strategy, AdaptationStrategy::Aggressive);
        assert!(aggressive.prefetch_depth > policy.prefetch_depth);
    }

    #[test]
    fn test_tuner_creation() {
        let policy = AdaptivePrefetchPolicy::new();
        let tuner = AdaptivePrefetchTuner::new(policy);

        let current_policy = tuner.get_policy();
        assert_eq!(current_policy.prefetch_depth, 4);
    }

    #[test]
    fn test_metrics_update() {
        let policy = AdaptivePrefetchPolicy::new();
        let tuner = AdaptivePrefetchTuner::new(policy).with_interval(Duration::from_millis(100));

        let metrics = PrefetchMetrics {
            hit_rate: 0.9,
            predictability: 0.8,
            ..Default::default()
        };

        tuner.update_metrics(metrics.clone());

        // Should not retune immediately
        let decision = tuner.update_metrics(metrics);
        assert!(decision.is_none());
    }

    #[test]
    fn test_average_metrics() {
        let policy = AdaptivePrefetchPolicy::new();
        let tuner = AdaptivePrefetchTuner::new(policy);

        for i in 1..=5 {
            let metrics = PrefetchMetrics {
                hit_rate: i as f64 * 0.1,
                ..Default::default()
            };
            tuner.update_metrics(metrics);
        }

        let avg = tuner
            .get_average_metrics(Duration::from_secs(60))
            .expect("test: operation should succeed");
        assert!((avg.hit_rate - 0.3).abs() < 0.01); // Average of 0.1, 0.2, 0.3, 0.4, 0.5
    }

    #[test]
    fn test_high_hit_rate_increases_depth() {
        let policy = AdaptivePrefetchPolicy::new();
        let tuner = AdaptivePrefetchTuner::new(policy).with_interval(Duration::from_millis(1));

        std::thread::sleep(Duration::from_millis(2));

        let metrics = PrefetchMetrics {
            hit_rate: 0.95, // Very high hit rate
            predictability: 0.9,
            memory_pressure: 0.1,
            ..Default::default()
        };

        let decision = tuner.update_metrics(metrics);
        if let Some(d) = decision {
            assert!(d.new_depth > 4, "Should increase depth on high hit rate");
        }
    }

    #[test]
    fn test_high_memory_pressure_reduces_depth() {
        let policy = AdaptivePrefetchPolicy::new();
        let tuner = AdaptivePrefetchTuner::new(policy).with_interval(Duration::from_millis(1));

        std::thread::sleep(Duration::from_millis(2));

        let metrics = PrefetchMetrics {
            hit_rate: 0.5,
            memory_pressure: 0.9, // Very high memory pressure
            ..Default::default()
        };

        let decision = tuner.update_metrics(metrics);
        if let Some(d) = decision {
            assert!(
                d.new_depth < 4,
                "Should reduce depth on high memory pressure"
            );
        }
    }

    #[test]
    fn test_reset() {
        let policy = AdaptivePrefetchPolicy::new();
        let tuner = AdaptivePrefetchTuner::new(policy);

        tuner.update_metrics(PrefetchMetrics::default());
        assert!(!tuner.get_metrics_history().is_empty());

        tuner.reset();
        assert!(tuner.get_metrics_history().is_empty());
    }

    #[test]
    fn test_generate_report() {
        let policy = AdaptivePrefetchPolicy::new();
        let tuner = AdaptivePrefetchTuner::new(policy);

        tuner.update_metrics(PrefetchMetrics {
            hit_rate: 0.85,
            ..Default::default()
        });

        let report = tuner.generate_report();
        assert!(report.contains("Adaptive Prefetch Tuning Report"));
        assert!(report.contains("Prefetch Depth"));
        assert!(report.contains("Hit Rate"));
    }

    #[test]
    fn test_custom_policy() {
        let policy = AdaptivePrefetchPolicy::custom(2, 16, 0.75);
        assert_eq!(policy.min_depth, 2);
        assert_eq!(policy.max_depth, 16);
        assert!((policy.target_hit_rate - 0.75).abs() < 0.01);
        assert_eq!(policy.strategy, AdaptationStrategy::Custom);
    }

    #[test]
    fn test_pid_controller_step_response() {
        // With kp=0.5, ki=0.05, integral_cap=10, error=0.30 per tick:
        // output ≈ 0.15 + (ki * integral).  Integral saturates at 10 in ~34 ticks →
        // output = 0.15 + 0.50 = 0.65 → rounds to 1. Use 50 ticks to guarantee
        // at least one depth increment.
        let mut ctrl = PidAdaptiveController::new(0.5, 0.05, 0.01, 0.80, 4, 1, 32);
        let initial = ctrl.current_depth();
        let mut last_depth = initial;
        for _ in 0..50 {
            last_depth = ctrl.tick(0.50);
        }
        assert!(
            last_depth > initial,
            "depth should increase when hit rate is below setpoint (init={}, last={})",
            initial,
            last_depth
        );
    }

    #[test]
    fn test_pid_controller_steady_state() {
        let mut ctrl = PidAdaptiveController::new(0.3, 0.0, 0.0, 0.80, 4, 1, 32);
        let mut depth = 0;
        for _ in 0..100 {
            depth = ctrl.tick(0.80);
        }
        assert!(
            (1_usize..=32).contains(&depth),
            "depth out of bounds: {}",
            depth
        );
    }

    #[test]
    fn test_pid_controller_boundaries() {
        let mut ctrl = PidAdaptiveController::new(10.0, 1.0, 1.0, 0.80, 4, 1, 8);
        for _ in 0..50 {
            ctrl.tick(0.0);
        }
        assert_eq!(ctrl.current_depth(), 8, "depth should be clamped to max=8");

        let mut ctrl2 = PidAdaptiveController::new(10.0, 1.0, 1.0, 0.80, 4, 2, 16);
        for _ in 0..50 {
            ctrl2.tick(1.0);
        }
        assert_eq!(ctrl2.current_depth(), 2, "depth should be clamped to min=2");
    }
}