Skip to main content

fraiseql_wire/stream/
adaptive_chunking.rs

1//! Adaptive chunk sizing based on channel occupancy patterns
2//!
3//! This module implements self-tuning chunk sizes that automatically adjust batch sizes
4//! based on observed backpressure (channel occupancy).
5//!
6//! **Critical Semantics**:
7//! `chunk_size` controls **both**:
8//! 1. MPSC channel capacity (backpressure buffer)
9//! 2. Batch size for Postgres row parsing
10//!
11//! **Control Signal Interpretation**:
12//! - **High occupancy** (>80%): Producer waiting on channel capacity, consumer slow
13//!   → **Reduce chunk_size**: smaller batches reduce pressure, lower latency per item
14//!
15//! - **Low occupancy** (<20%): Consumer faster than producer, frequent context switches
16//!   → **Increase chunk_size**: larger batches amortize parsing cost, less frequent wakeups
17//!
18//! **Design Principles**:
19//! - Measurement-based adjustment (50-item window) for stability
20//! - Hysteresis band (20%-80%) prevents frequent oscillation
21//! - Minimum adjustment interval (1 second) prevents thrashing
22//! - Conservative bounds (16-1024) prevent pathological extremes
23//! - Clear window reset after adjustment (fresh observations)
24
25use std::collections::VecDeque;
26use std::time::{Duration, Instant};
27
28/// Single observation of channel occupancy
29#[derive(Copy, Clone, Debug)]
30struct Occupancy {
31    /// Percentage of channel capacity in use (0-100)
32    percentage: usize,
33}
34
35/// Tracks channel occupancy and automatically adjusts chunk size based on backpressure
36///
37/// # Examples
38///
39/// ```ignore
40/// let mut adaptive = AdaptiveChunking::new();
41///
42/// // Periodically observe channel occupancy
43/// for chunk_sent in 0..100 {
44///     let occupancy_pct = (buffered_items * 100) / channel_capacity;
45///     if let Some(new_size) = adaptive.observe(buffered_items, channel_capacity) {
46///         println!("Adjusted chunk size: {} -> {}", adaptive.current_size() - new_size, new_size);
47///     }
48/// }
49/// ```
50pub struct AdaptiveChunking {
51    /// Current chunk size (mutable, adjusted over time)
52    current_size: usize,
53
54    /// Absolute minimum chunk size (never decrease below this)
55    min_size: usize,
56
57    /// Absolute maximum chunk size (never increase beyond this)
58    max_size: usize,
59
60    /// Number of measurements to collect before making adjustment decision
61    adjustment_window: usize,
62
63    /// Rolling window of recent occupancy observations
64    measurements: VecDeque<Occupancy>,
65
66    /// Timestamp of last chunk size adjustment (for rate limiting)
67    last_adjustment_time: Option<Instant>,
68
69    /// Minimum time between adjustments (prevents thrashing/oscillation)
70    min_adjustment_interval: Duration,
71}
72
73impl AdaptiveChunking {
74    /// Create a new adaptive chunking controller with default bounds
75    ///
76    /// **Defaults**:
77    /// - Initial chunk size: 256 items
78    /// - Min size: 16 items
79    /// - Max size: 1024 items
80    /// - Adjustment window: 50 observations
81    /// - Min adjustment interval: 1 second
82    ///
83    /// # Examples
84    ///
85    /// ```ignore
86    /// let adaptive = AdaptiveChunking::new();
87    /// assert_eq!(adaptive.current_size(), 256);
88    /// ```
89    pub fn new() -> Self {
90        Self {
91            current_size: 256,
92            min_size: 16,
93            max_size: 1024,
94            adjustment_window: 50,
95            measurements: VecDeque::with_capacity(50),
96            last_adjustment_time: None,
97            min_adjustment_interval: Duration::from_secs(1),
98        }
99    }
100
101    /// Record an occupancy observation and check if chunk size adjustment is warranted
102    ///
103    /// Call this method after each chunk is sent to the channel.
104    /// Returns `Some(new_size)` if an adjustment should be applied, `None` otherwise.
105    ///
106    /// # Arguments
107    ///
108    /// * `items_buffered` - Number of items currently in the channel
109    /// * `capacity` - Total capacity of the channel (usually equal to chunk_size)
110    ///
111    /// # Examples
112    ///
113    /// ```ignore
114    /// let mut adaptive = AdaptiveChunking::new();
115    ///
116    /// // Simulate high occupancy (90%)
117    /// for _ in 0..50 {
118    ///     adaptive.observe(230, 256);  // ~90% occupancy
119    /// }
120    ///
121    /// // On the 51st observation, should trigger adjustment
122    /// if let Some(new_size) = adaptive.observe(230, 256) {
123    ///     println!("Adjusted to {}", new_size);  // Will be < 256
124    /// }
125    /// ```
126    pub fn observe(&mut self, items_buffered: usize, capacity: usize) -> Option<usize> {
127        // Calculate occupancy percentage (clamped at 100% if buffer exceeds capacity)
128        let pct = (items_buffered * 100)
129            .checked_div(capacity)
130            .map_or(0, |v| v.min(100));
131
132        // Record this observation
133        self.measurements.push_back(Occupancy { percentage: pct });
134
135        // Keep only the most recent measurements in the window
136        while self.measurements.len() > self.adjustment_window {
137            self.measurements.pop_front();
138        }
139
140        // Only consider adjustment if we have a FULL window of observations
141        // (i.e., exactly equal to the window size, not more)
142        // This ensures we only evaluate after collecting N measurements
143        if self.measurements.len() == self.adjustment_window && self.should_adjust() {
144            return self.calculate_adjustment();
145        }
146
147        None
148    }
149
150    /// Get the current chunk size
151    ///
152    /// # Examples
153    ///
154    /// ```ignore
155    /// let adaptive = AdaptiveChunking::new();
156    /// assert_eq!(adaptive.current_size(), 256);
157    /// ```
158    pub fn current_size(&self) -> usize {
159        self.current_size
160    }
161
162    /// Set custom min/max bounds for chunk size adjustments
163    ///
164    /// Allows overriding the default bounds (16-1024) with custom limits.
165    /// The current chunk size will be clamped to the new bounds.
166    ///
167    /// # Arguments
168    ///
169    /// * `min_size` - Minimum chunk size (must be > 0)
170    /// * `max_size` - Maximum chunk size (must be >= min_size)
171    ///
172    /// # Examples
173    ///
174    /// ```ignore
175    /// let mut adaptive = AdaptiveChunking::new();
176    /// adaptive = adaptive.with_bounds(32, 512);  // Custom range 32-512
177    /// assert!(adaptive.current_size() >= 32);
178    /// assert!(adaptive.current_size() <= 512);
179    /// ```
180    pub fn with_bounds(mut self, min_size: usize, max_size: usize) -> Self {
181        // Basic validation
182        if min_size == 0 || max_size < min_size {
183            tracing::warn!(
184                "invalid chunk bounds: min={}, max={}, keeping defaults",
185                min_size,
186                max_size
187            );
188            return self;
189        }
190
191        self.min_size = min_size;
192        self.max_size = max_size;
193
194        // Clamp current size to new bounds
195        if self.current_size < min_size {
196            self.current_size = min_size;
197        } else if self.current_size > max_size {
198            self.current_size = max_size;
199        }
200
201        tracing::debug!(
202            "adaptive chunking bounds set: min={}, max={}, current={}",
203            self.min_size,
204            self.max_size,
205            self.current_size
206        );
207
208        self
209    }
210
211    /// Calculate average occupancy percentage over the measurement window
212    fn average_occupancy(&self) -> usize {
213        if self.measurements.is_empty() {
214            return 0;
215        }
216
217        let sum: usize = self.measurements.iter().map(|m| m.percentage).sum();
218        sum / self.measurements.len()
219    }
220
221    /// Check if adjustment conditions are met
222    ///
223    /// Adjustment is only considered if:
224    /// 1. At least 1 second has elapsed since the last adjustment
225    /// 2. Average occupancy is outside the hysteresis band (< 20% or > 80%)
226    fn should_adjust(&self) -> bool {
227        // Rate limit: don't adjust too frequently
228        if let Some(last_adj) = self.last_adjustment_time {
229            if last_adj.elapsed() < self.min_adjustment_interval {
230                return false;
231            }
232        }
233
234        // Hysteresis: only adjust if we're clearly outside the comfort zone
235        let avg = self.average_occupancy();
236        !(20..=80).contains(&avg)
237    }
238
239    /// Calculate the new chunk size based on average occupancy
240    ///
241    /// **Logic**:
242    /// - If avg > 80%: **DECREASE** by factor of 1.5 (high occupancy = producer backed up)
243    /// - If avg < 20%: **INCREASE** by factor of 1.5 (low occupancy = consumer fast)
244    /// - Clamps to [min_size, max_size]
245    /// - Clears measurements after adjustment
246    ///
247    /// Returns `Some(new_size)` if size actually changed, `None` if no change needed.
248    fn calculate_adjustment(&mut self) -> Option<usize> {
249        let avg = self.average_occupancy();
250        let old_size = self.current_size;
251
252        let new_size = if avg > 80 {
253            // High occupancy: producer is waiting on channel, consumer is slow
254            // → DECREASE chunk_size to reduce backpressure and latency
255            ((self.current_size as f64 / 1.5).floor() as usize).max(self.min_size)
256        } else if avg < 20 {
257            // Low occupancy: consumer is draining fast, producer could batch more
258            // → INCREASE chunk_size to amortize parsing cost and reduce context switches
259            ((self.current_size as f64 * 1.5).ceil() as usize).min(self.max_size)
260        } else {
261            old_size
262        };
263
264        // Only return if there was an actual change
265        if new_size != old_size {
266            self.current_size = new_size;
267            self.last_adjustment_time = Some(Instant::now());
268            self.measurements.clear(); // Reset window for fresh observations
269            Some(new_size)
270        } else {
271            None
272        }
273    }
274}
275
276impl Default for AdaptiveChunking {
277    fn default() -> Self {
278        Self::new()
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn test_new_defaults() {
288        let adaptive = AdaptiveChunking::new();
289        assert_eq!(adaptive.current_size(), 256);
290        assert_eq!(adaptive.min_size, 16);
291        assert_eq!(adaptive.max_size, 1024);
292        assert_eq!(adaptive.adjustment_window, 50);
293        assert!(adaptive.last_adjustment_time.is_none());
294        assert!(adaptive.measurements.is_empty());
295    }
296
297    #[test]
298    fn test_no_adjustment_in_hysteresis_band() {
299        let mut adaptive = AdaptiveChunking::new();
300
301        // Simulate 50% occupancy (inside 20-80% hysteresis band)
302        // 50% of 256 = 128 items
303        for _ in 0..50 {
304            assert_eq!(adaptive.observe(128, 256), None);
305        }
306
307        // Should not adjust - still at 256
308        assert_eq!(adaptive.current_size(), 256);
309    }
310
311    #[test]
312    fn test_decrease_on_high_occupancy() {
313        let mut adaptive = AdaptiveChunking::new();
314        let original_size = 256;
315
316        // Simulate 90% occupancy (producer backed up, consumer slow)
317        // 90% of 256 = 230.4 ≈ 230 items
318        for _ in 0..49 {
319            assert_eq!(adaptive.observe(230, 256), None);
320        }
321
322        // On 50th observation, should trigger adjustment
323        let result = adaptive.observe(230, 256);
324        assert!(result.is_some());
325
326        let new_size = result.unwrap();
327        assert!(
328            new_size < original_size,
329            "Should decrease on high occupancy"
330        );
331        assert!(new_size >= 16, "Should respect min bound");
332    }
333
334    #[test]
335    fn test_increase_on_low_occupancy() {
336        let mut adaptive = AdaptiveChunking::new();
337        let original_size = 256;
338
339        // Simulate 10% occupancy (consumer fast, producer lagging)
340        // 10% of 256 = 25.6 ≈ 26 items
341        for _ in 0..49 {
342            assert_eq!(adaptive.observe(26, 256), None);
343        }
344
345        // On 50th observation, should trigger adjustment
346        let result = adaptive.observe(26, 256);
347        assert!(result.is_some());
348
349        let new_size = result.unwrap();
350        assert!(new_size > original_size, "Should increase on low occupancy");
351        assert!(new_size <= 1024, "Should respect max bound");
352    }
353
354    #[test]
355    fn test_respects_min_bound() {
356        let mut adaptive = AdaptiveChunking::new();
357
358        // Simulate very high occupancy repeatedly
359        for iteration in 0..20 {
360            // Reset measurements every iteration to allow adjustments
361            for _ in 0..50 {
362                adaptive.observe(250, 256);
363            }
364            adaptive.observe(250, 256);
365
366            // Verify we never go below minimum
367            assert!(
368                adaptive.current_size() >= 16,
369                "Iteration {}: size {} < min",
370                iteration,
371                adaptive.current_size()
372            );
373        }
374    }
375
376    #[test]
377    fn test_respects_max_bound() {
378        let mut adaptive = AdaptiveChunking::new();
379
380        // Simulate very low occupancy repeatedly
381        for iteration in 0..20 {
382            // Reset measurements every iteration to allow adjustments
383            for _ in 0..50 {
384                adaptive.observe(10, 256);
385            }
386            adaptive.observe(10, 256);
387
388            // Verify we never go above maximum
389            assert!(
390                adaptive.current_size() <= 1024,
391                "Iteration {}: size {} > max",
392                iteration,
393                adaptive.current_size()
394            );
395        }
396    }
397
398    #[test]
399    fn test_respects_min_adjustment_interval() {
400        let mut adaptive = AdaptiveChunking::new();
401
402        // Fill window with high occupancy (>80%) and trigger first adjustment
403        // 230/256 ≈ 89.8%
404        // Make 49 calls so window is not yet full
405        for _ in 0..49 {
406            let result = adaptive.observe(230, 256);
407            assert_eq!(result, None, "Should not adjust yet, window not full");
408        }
409
410        // 50th call: window becomes full, should trigger adjustment
411        let first_adjustment = adaptive.observe(230, 256);
412        assert!(
413            first_adjustment.is_some(),
414            "Should adjust on 50th observation when window is full"
415        );
416
417        let first_size = adaptive.current_size();
418        assert!(
419            first_size < 256,
420            "High occupancy should decrease chunk size"
421        );
422
423        // Immediately try to trigger another adjustment within 1 second
424        // This should NOT happen because of the 1-second minimum interval
425        // Build up a new window with different occupancy, still shouldn't trigger
426        for _ in 0..50 {
427            let result = adaptive.observe(230, 256);
428            assert_eq!(
429                result, None,
430                "Should not adjust again so soon (within min interval)"
431            );
432        }
433
434        // Should not adjust again immediately, even though window is full again
435        assert_eq!(
436            adaptive.current_size(),
437            first_size,
438            "Size should remain unchanged due to rate limiting"
439        );
440    }
441
442    #[test]
443    fn test_window_resets_after_adjustment() {
444        let mut adaptive = AdaptiveChunking::new();
445
446        // First window: high occupancy triggers decrease
447        // 230/256 ≈ 89.8%
448        // Make 49 calls to fill window to size 49
449        for _ in 0..49 {
450            let result = adaptive.observe(230, 256);
451            assert_eq!(result, None, "Should not adjust yet, window not full");
452        }
453
454        // 50th call: window becomes full, triggers adjustment
455        let first = adaptive.observe(230, 256);
456        assert!(
457            first.is_some(),
458            "Should adjust when window reaches 50 observations"
459        );
460
461        // Measurements should be cleared after adjustment
462        assert!(
463            adaptive.measurements.is_empty(),
464            "Measurements should be cleared after adjustment"
465        );
466    }
467
468    #[test]
469    fn test_zero_capacity_handling() {
470        let mut adaptive = AdaptiveChunking::new();
471
472        // Zero capacity edge case: percentage = 0
473        // 0% occupancy is OUTSIDE hysteresis band (< 20%), so it WILL increase chunk size
474        // This makes sense: consumer is draining instantly, we can send bigger batches
475        // Make 49 calls so window is not yet full (size 49 < 50)
476        for _ in 0..49 {
477            let result = adaptive.observe(0, 0);
478            // Should not adjust until window is full (50 observations)
479            assert_eq!(result, None, "Should not adjust until window is full");
480        }
481
482        // On the 50th observation, window becomes full
483        // We should trigger an increase because occupancy < 20%
484        let result = adaptive.observe(0, 0);
485        assert!(
486            result.is_some(),
487            "Should increase chunk size when occupancy < 20% and window is full"
488        );
489        assert!(
490            adaptive.current_size() > 256,
491            "Should increase from 256 due to low occupancy"
492        );
493    }
494
495    #[test]
496    fn test_average_occupancy_calculation() {
497        let mut adaptive = AdaptiveChunking::new();
498
499        // Add measurements: 10%, 20%, 30%, 40%, 50%
500        // Calculate actual item counts: 25.6, 51.2, 76.8, 102.4, 128
501        // Which truncate to: 25, 51, 76, 102, 128
502        // And percentages: (25*100)/256=9, (51*100)/256=19, (76*100)/256=29, (102*100)/256=39, (128*100)/256=50
503        for pct in [10, 20, 30, 40, 50].iter() {
504            let items = (pct * 256) / 100;
505            adaptive.observe(items, 256);
506        }
507
508        let avg = adaptive.average_occupancy();
509        // Average of [9, 19, 29, 39, 50] = 146 / 5 = 29 (integer division)
510        assert_eq!(
511            avg, 29,
512            "Average should account for integer division in percentages"
513        );
514    }
515}