fulgurance 0.2.0

A blazing-fast, adaptive prefetching and caching library for Rust
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
use crate::PrefetchStrategy;
use super::{BenchmarkablePrefetch, PrefetchType};
use std::collections::HashMap;

/// Stride prefetch strategy.
///
/// Detects multiple stride patterns concurrently and dynamically
/// adjusts to the dominant stride based on confidence.
/// Handles interleaved access patterns and switches between stride patterns.
#[derive(Debug, Clone)]
pub struct StridePrefetch<K>
where
    K: Clone + std::hash::Hash + Eq,
{
    /// History of recent accesses
    access_history: Vec<K>,
    /// Map of candidate strides to their statistics
    stride_patterns: HashMap<i64, StridePattern>,
    /// Max number of accesses to track in history
    max_history: usize,
    /// How many keys ahead to prefetch
    prefetch_distance: usize,
    /// Max predicted keys allowed per access
    max_predictions: usize,
    /// Minimum confidence threshold to use a stride prediction
    min_confidence: f64,
    /// Currently dominant stride pattern (highest confidence)
    dominant_stride: Option<i64>,
}

/// Statistics for each detected stride pattern
#[derive(Debug, Clone)]
pub struct StridePattern {
    /// Confidence score from 0.0 to 1.0
    confidence: f64,
    /// How many times this stride has been observed
    occurrences: usize,
}

impl<K> StridePrefetch<K>
where
    K: Clone + std::hash::Hash + Eq,
{
    /// Creates a default stride prefetcher
    pub fn new() -> Self {
        Self::with_config(8, 3, 4, 0.6)
    }

    /// Creates a stride prefetcher with custom configuration
    pub fn with_config(
        max_history: usize,
        prefetch_distance: usize,
        max_predictions: usize,
        min_confidence: f64,
    ) -> Self {
        Self {
            access_history: Vec::with_capacity(max_history),
            stride_patterns: HashMap::new(),
            max_history,
            prefetch_distance,
            max_predictions,
            min_confidence,
            dominant_stride: None,
        }
    }

    /// Update dominant stride: pick the stride with highest confidence
    fn update_dominant_stride(&mut self) {
        self.dominant_stride = self
            .stride_patterns
            .iter()
            .filter(|(_, pattern)| pattern.confidence >= self.min_confidence)
            .max_by(|a, b| a.1.confidence.partial_cmp(&b.1.confidence).unwrap())
            .map(|(stride, _)| *stride);
    }

    /// Remove low-confidence stride patterns to prevent bloat
    fn cleanup_patterns(&mut self) {
        self.stride_patterns
            .retain(|_, p| p.confidence > 0.1 || p.occurrences > 2);
    }
}

impl Default for StridePrefetch<i32> {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for StridePrefetch<i64> {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for StridePrefetch<usize> {
    fn default() -> Self {
        Self::new()
    }
}

/// Implement `PrefetchStrategy<i32>` for `StridePrefetch<i32>`
impl PrefetchStrategy<i32> for StridePrefetch<i32> {
    fn predict_next(&mut self, accessed_key: &i32) -> Vec<i32> {
        let mut predictions = Vec::with_capacity(self.max_predictions);

        if let Some(dominant) = self.dominant_stride {
            if let Some(pattern) = self.stride_patterns.get(&dominant) {
                if pattern.confidence >= self.min_confidence {
                    for i in 1..=self.prefetch_distance {
                        if predictions.len() >= self.max_predictions {
                            break;
                        }
                        predictions.push(accessed_key + (dominant as i32) * i as i32);
                    }
                }
            }
        }

        // Fill with other confident strides if needed
        if predictions.len() < self.max_predictions {
            let mut other_strides: Vec<_> = self
                .stride_patterns
                .iter()
                .filter(|(stride, pattern)| {
                    pattern.confidence >= self.min_confidence && Some(**stride) != self.dominant_stride
                })
                .collect();
            other_strides.sort_by(|a, b| b.1.confidence.partial_cmp(&a.1.confidence).unwrap());
            for (stride, _) in other_strides.iter().take(2) {
                if predictions.len() >= self.max_predictions {
                    break;
                }
                let candidate = accessed_key + **stride as i32;
                if !predictions.contains(&candidate) {
                    predictions.push(candidate);
                }
            }
        }

        predictions
    }

    fn update_access_pattern(&mut self, key: &i32) {
        self.access_history.push(*key);
        if self.access_history.len() > self.max_history {
            self.access_history.remove(0);
        }

        if self.access_history.len() >= 2 {
            let current = *key as i64;
            for i in 1..self.access_history.len() {
                let prev = self.access_history[self.access_history.len() - 1 - i] as i64;
                let stride = current - prev;

                let pattern = self.stride_patterns.entry(stride).or_insert(StridePattern {
                    confidence: 0.3,
                    occurrences: 0,
                });

                pattern.occurrences += 1;
                if pattern.occurrences > 2 {
                    pattern.confidence = (pattern.confidence + 0.05).min(1.0);
                }
            }
        }

        self.update_dominant_stride();

        if self.stride_patterns.len() > 10 {
            self.cleanup_patterns();
        }
    }

    fn reset(&mut self) {
        self.access_history.clear();
        self.stride_patterns.clear();
        self.dominant_stride = None;
    }
}

/// Implement `PrefetchStrategy<i64>` for `StridePrefetch<i64>`
impl PrefetchStrategy<i64> for StridePrefetch<i64> {
    fn predict_next(&mut self, accessed_key: &i64) -> Vec<i64> {
        let mut predictions = Vec::with_capacity(self.max_predictions);

        if let Some(dominant) = self.dominant_stride {
            if let Some(pattern) = self.stride_patterns.get(&dominant) {
                if pattern.confidence >= self.min_confidence {
                    for i in 1..=self.prefetch_distance {
                        if predictions.len() >= self.max_predictions {
                            break;
                        }
                        predictions.push(accessed_key + dominant * i as i64);
                    }
                }
            }
        }

        if predictions.len() < self.max_predictions {
            let mut other_strides: Vec<_> = self
                .stride_patterns
                .iter()
                .filter(|(stride, pattern)| {
                    pattern.confidence >= self.min_confidence && Some(**stride) != self.dominant_stride
                })
                .collect();
            other_strides.sort_by(|a, b| b.1.confidence.partial_cmp(&a.1.confidence).unwrap());
            for (stride, _) in other_strides.iter().take(2) {
                if predictions.len() >= self.max_predictions {
                    break;
                }
                let candidate = accessed_key + **stride;
                if !predictions.contains(&candidate) {
                    predictions.push(candidate);
                }
            }
        }

        predictions
    }

    fn update_access_pattern(&mut self, key: &i64) {
        self.access_history.push(*key);
        if self.access_history.len() > self.max_history {
            self.access_history.remove(0);
        }

        if self.access_history.len() >= 2 {
            let current = *key;
            for i in 1..self.access_history.len() {
                let prev = self.access_history[self.access_history.len() - 1 - i];
                let stride = current - prev;

                let pattern = self.stride_patterns.entry(stride).or_insert(StridePattern {
                    confidence: 0.3,
                    occurrences: 0,
                });

                pattern.occurrences += 1;
                if pattern.occurrences > 2 {
                    pattern.confidence = (pattern.confidence + 0.05).min(1.0);
                }
            }
        }

        self.update_dominant_stride();

        if self.stride_patterns.len() > 10 {
            self.cleanup_patterns();
        }
    }

    fn reset(&mut self) {
        self.access_history.clear();
        self.stride_patterns.clear();
        self.dominant_stride = None;
    }
}

/// Implement `PrefetchStrategy<usize>` for `StridePrefetch<usize>`
impl PrefetchStrategy<usize> for StridePrefetch<usize> {
    fn predict_next(&mut self, accessed_key: &usize) -> Vec<usize> {
        let mut predictions = Vec::with_capacity(self.max_predictions);

        if let Some(dominant) = self.dominant_stride {
            if dominant > 0 {
                if let Some(pattern) = self.stride_patterns.get(&dominant) {
                    if pattern.confidence >= self.min_confidence {
                        for i in 1..=self.prefetch_distance {
                            if predictions.len() >= self.max_predictions {
                                break;
                            }
                            if let Some(next_key) = accessed_key.checked_add((dominant as usize) * i) {
                                predictions.push(next_key);
                            }
                        }
                    }
                }
            }
        }

        if predictions.len() < self.max_predictions {
            let mut other_strides: Vec<_> = self
                .stride_patterns
                .iter()
                .filter(|(stride, pattern)| {
                    **stride > 0
                        && pattern.confidence >= self.min_confidence
                        && Some(**stride) != self.dominant_stride
                })
                .collect();
            other_strides.sort_by(|a, b| b.1.confidence.partial_cmp(&a.1.confidence).unwrap());
            for (stride, _) in other_strides.iter().take(2) {
                if predictions.len() >= self.max_predictions {
                    break;
                }
                if let Some(next_key) = accessed_key.checked_add(**stride as usize) {
                    if !predictions.contains(&next_key) {
                        predictions.push(next_key);
                    }
                }
            }
        }

        predictions
    }

    fn update_access_pattern(&mut self, key: &usize) {
        self.access_history.push(*key);
        if self.access_history.len() > self.max_history {
            self.access_history.remove(0);
        }

        if self.access_history.len() >= 2 {
            let current = *key as i64;
            for i in 1..self.access_history.len() {
                let prev = self.access_history[self.access_history.len() - 1 - i] as i64;
                let stride = current - prev;
                if stride > 0 {
                    let pattern = self.stride_patterns.entry(stride).or_insert(StridePattern {
                        confidence: 0.3,
                        occurrences: 0,
                    });
                    pattern.occurrences += 1;
                    if pattern.occurrences > 2 {
                        pattern.confidence = (pattern.confidence + 0.05).min(1.0);
                    }
                }
            }
        }

        self.update_dominant_stride();

        if self.stride_patterns.len() > 10 {
            self.cleanup_patterns();
        }
    }

    fn reset(&mut self) {
        self.access_history.clear();
        self.stride_patterns.clear();
        self.dominant_stride = None;
    }
}

/// For Criterion benchmarks integration
impl BenchmarkablePrefetch<i32> for StridePrefetch<i32> {
    fn prefetch_type(&self) -> PrefetchType {
        PrefetchType::Stride
    }
}

impl BenchmarkablePrefetch<i64> for StridePrefetch<i64> {
    fn prefetch_type(&self) -> PrefetchType {
        PrefetchType::Stride
    }
}

impl BenchmarkablePrefetch<usize> for StridePrefetch<usize> {
    fn prefetch_type(&self) -> PrefetchType {
        PrefetchType::Stride
    }
}

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

    #[test]
    fn test_stride_multiple_patterns() {
        let mut strategy = StridePrefetch::<i32>::new();
        // Create alternating stride patterns: +2, +3, +2, +3
        strategy.update_access_pattern(&0);
        strategy.update_access_pattern(&2);  // stride +2
        strategy.update_access_pattern(&5);  // stride +3
        strategy.update_access_pattern(&7);  // stride +2
        strategy.update_access_pattern(&10); // stride +3

        assert!(strategy.stride_patterns().contains_key(&2));
        assert!(strategy.stride_patterns().contains_key(&3));
    }

    #[test]
    fn test_stride_confidence_building() {
        let mut strategy = StridePrefetch::<i32>::new();
        // Build a consistent stride-5 pattern
        for i in 0..6 {
            strategy.update_access_pattern(&(i * 5));
        }

        if let Some(pattern) = strategy.stride_patterns().get(&5) {
            assert!(pattern.confidence > 0.5);
        }

        let predictions = strategy.predict_next(&25);
        assert!(predictions.contains(&30));
    }

    #[test]
    fn test_stride_pattern_cleanup() {
        let mut strategy = StridePrefetch::<i32>::with_config(4, 3, 4, 0.6);
        for i in 1..20 {
            strategy.update_access_pattern(&(i * i));
        }
        assert!(strategy.stride_patterns().len() <= 10);
    }
}