Skip to main content

sql_splitter/writer/
controller.rs

1//! Feedback controller for the adaptive I/O profiles.
2//!
3//! The controller is a pure state machine: `(state, epoch measurement) →
4//! (state, actions)`. It never touches a clock or a device itself — epochs
5//! are *byte-based* (every N input bytes) and durations arrive as data, which
6//! is what makes every decision reproducible in tests with a mock clock.
7//! See `docs/features/ADAPTIVE_IO_PROFILES.md` for the full design.
8
9use super::profile::ProfileKind;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::Duration;
12
13/// Monotonic time source for epoch measurements.
14///
15/// Returns time elapsed since an arbitrary per-clock origin. The production
16/// implementation wraps [`std::time::Instant`]; tests use [`MockClock`] so
17/// controller behavior is a pure function of the scripted inputs.
18pub trait Clock: Send + Sync {
19    fn now(&self) -> Duration;
20}
21
22/// Wall-clock [`Clock`] backed by [`std::time::Instant`].
23#[derive(Debug)]
24pub struct RealClock {
25    origin: std::time::Instant,
26}
27
28impl RealClock {
29    pub fn new() -> Self {
30        Self {
31            origin: std::time::Instant::now(),
32        }
33    }
34}
35
36impl Default for RealClock {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42impl Clock for RealClock {
43    fn now(&self) -> Duration {
44        self.origin.elapsed()
45    }
46}
47
48/// Deterministic [`Clock`] for tests: every `now()` call advances time by a
49/// fixed step, so a pipeline that samples the clock once per epoch boundary
50/// sees identical epoch durations on every machine, every run.
51#[derive(Debug)]
52pub struct MockClock {
53    nanos: AtomicU64,
54    step_nanos: u64,
55}
56
57impl MockClock {
58    /// A clock that advances `step` per `now()` call.
59    pub fn stepping(step: Duration) -> Self {
60        Self {
61            nanos: AtomicU64::new(0),
62            step_nanos: step.as_nanos() as u64,
63        }
64    }
65}
66
67impl Clock for MockClock {
68    fn now(&self) -> Duration {
69        let t = self.nanos.fetch_add(self.step_nanos, Ordering::Relaxed);
70        Duration::from_nanos(t + self.step_nanos)
71    }
72}
73
74/// What the pipeline observed during one byte-based epoch.
75#[derive(Debug, Clone, Copy)]
76pub struct EpochMeasurement {
77    /// Bytes acked by the writer threads during the epoch.
78    pub bytes: u64,
79    /// Wall time the epoch spanned.
80    pub duration: Duration,
81    /// Time the producer spent blocked on full writer channels in the epoch.
82    pub send_stall: Duration,
83}
84
85impl EpochMeasurement {
86    /// Writer throughput in MB/s (MiB, matching the measurement notes).
87    ///
88    /// A zero-duration epoch is unmeasurable, not infinitely fast (two epoch
89    /// boundaries can land on the same clock tick); it reports `0.0` and
90    /// [`Controller::on_epoch`] discards the epoch entirely.
91    pub fn throughput_mbps(&self) -> f64 {
92        let secs = self.duration.as_secs_f64();
93        if secs <= 0.0 {
94            return 0.0;
95        }
96        self.bytes as f64 / (1024.0 * 1024.0) / secs
97    }
98
99    /// Fraction of the epoch the producer sat blocked on channel sends.
100    pub fn stall_fraction(&self) -> f64 {
101        let secs = self.duration.as_secs_f64();
102        if secs <= 0.0 {
103            return 0.0;
104        }
105        self.send_stall.as_secs_f64() / secs
106    }
107}
108
109/// What the splitter should do after an epoch boundary.
110#[derive(Debug, Clone, Copy, PartialEq)]
111pub struct EpochDecision {
112    /// `Some(kind)` when the controller changed state: swap the profile
113    /// values and emit the transition log line.
114    pub transition: Option<ProfileKind>,
115    /// Desired writer-thread count. The pool only ever grows toward this
116    /// (shrinking would reassign table ownership and break output ordering).
117    pub target_writers: usize,
118    /// Observed throughput for this epoch, for the transition log line.
119    pub throughput_mbps: f64,
120}
121
122/// `FAST → SLOW_SEEK` fires below this throughput (with high stall).
123const FAST_DOWN_MBPS: f64 = 150.0;
124/// `SLOW_SEEK → SLOW_OPS` fires below this throughput (with high stall).
125const SLOW_SEEK_DOWN_MBPS: f64 = 15.0;
126/// Downgrades additionally require the producer blocked on channel sends
127/// this fraction of the epoch — low throughput with near-zero stall means
128/// the *input* is the bottleneck and the write profile must not react.
129const STALL_DOWN_FRACTION: f64 = 0.30;
130/// Consecutive qualifying epochs required to downgrade.
131const DOWN_EPOCHS: u32 = 2;
132/// Consecutive qualifying epochs required to upgrade (asymmetric hysteresis:
133/// a wrong downgrade on NVMe costs ~15%; a wrong non-downgrade on an HDD
134/// costs 2.5×).
135const UP_EPOCHS: u32 = 3;
136/// Upgrades require throughput above `factor × downgrade threshold`.
137const UP_FACTOR: f64 = 2.0;
138
139/// The adaptive-profile state machine, evaluated at epoch boundaries.
140#[derive(Debug)]
141pub struct Controller {
142    state: ProfileKind,
143    /// Writer count to grow to once the device is proven fast.
144    fast_writers: usize,
145    /// The first epoch is discarded as page-cache warmup.
146    warmup_done: bool,
147    /// Consecutive epochs meeting the current state's downgrade condition.
148    down_streak: u32,
149    /// Consecutive epochs meeting the current state's upgrade condition.
150    up_streak: u32,
151    /// Set once a measured epoch shows FAST-class throughput; gates the
152    /// deferred writer spawn so slow media is never thrashed at all.
153    proven_fast: bool,
154    /// Output is compressed: throughput is measured in *compressed* bytes
155    /// beneath the encoders, so the raw-media thresholds are meaningless and
156    /// a CPU-bound encoder stalls the producer exactly like a slow device.
157    /// The state is frozen at the probe-chosen opening profile, and the SSD
158    /// opening requests its full writer count immediately (compression wants
159    /// cores; a lone encoder could never "prove" 150 MB/s compressed).
160    compressed_output: bool,
161}
162
163impl Controller {
164    /// `opening` is the probe-chosen starting state; `fast_writers` is the
165    /// FAST profile's writer count (the growth ceiling in auto mode).
166    pub fn new(opening: ProfileKind, fast_writers: usize) -> Self {
167        Self {
168            state: opening,
169            fast_writers: fast_writers.max(1),
170            warmup_done: false,
171            down_streak: 0,
172            up_streak: 0,
173            proven_fast: false,
174            compressed_output: false,
175        }
176    }
177
178    /// Freeze the controller for compressed-output runs: no transitions (the
179    /// epoch signals cannot distinguish a CPU-bound encoder from a slow
180    /// device) and immediate writer growth when the opening state is SSD.
181    pub fn for_compressed_output(mut self) -> Self {
182        self.compressed_output = true;
183        self
184    }
185
186    /// Current state.
187    pub fn state(&self) -> ProfileKind {
188        self.state
189    }
190
191    fn decision(&self, transition: Option<ProfileKind>, mbps: f64) -> EpochDecision {
192        EpochDecision {
193            transition,
194            target_writers: if self.state == ProfileKind::Ssd
195                && (self.proven_fast || self.compressed_output)
196            {
197                self.fast_writers
198            } else {
199                1
200            },
201            throughput_mbps: mbps,
202        }
203    }
204
205    /// Evaluate one epoch boundary. Pure: no clocks, no I/O.
206    pub fn on_epoch(&mut self, m: &EpochMeasurement) -> EpochDecision {
207        let mbps = m.throughput_mbps();
208
209        // A zero-duration epoch is unmeasurable, not infinitely fast: two
210        // boundary evaluations can land on the same clock tick (coarse or
211        // injected clocks). Discard it entirely — updating `proven_fast` or
212        // either streak from a non-measurement would fake throughput or
213        // reset legitimate hysteresis.
214        if m.duration.is_zero() {
215            return self.decision(None, mbps);
216        }
217
218        // First epoch is page-cache warmup: measure nothing from it.
219        if !self.warmup_done {
220            self.warmup_done = true;
221            return self.decision(None, mbps);
222        }
223
224        // Compressed output: the measurement is compressed MB/s from a
225        // CPU-bound encoder, meaningless against the raw-media thresholds
226        // (and its stall signature mimics a slow device). State stays frozen
227        // at the probe-chosen opening profile.
228        if self.compressed_output {
229            return self.decision(None, mbps);
230        }
231
232        let stalled = m.stall_fraction() > STALL_DOWN_FRACTION;
233        let mut transition = None;
234
235        match self.state {
236            ProfileKind::Ssd => {
237                if mbps < FAST_DOWN_MBPS && stalled {
238                    self.down_streak += 1;
239                    if self.down_streak >= DOWN_EPOCHS {
240                        transition = self.enter(ProfileKind::SlowSeek);
241                    }
242                } else {
243                    self.down_streak = 0;
244                    if mbps >= FAST_DOWN_MBPS {
245                        self.proven_fast = true;
246                    }
247                }
248            }
249            ProfileKind::SlowSeek => {
250                if mbps < SLOW_SEEK_DOWN_MBPS && stalled {
251                    self.down_streak += 1;
252                    self.up_streak = 0;
253                    if self.down_streak >= DOWN_EPOCHS {
254                        transition = self.enter(ProfileKind::SlowOps);
255                    }
256                } else if mbps > UP_FACTOR * FAST_DOWN_MBPS {
257                    self.down_streak = 0;
258                    self.up_streak += 1;
259                    if self.up_streak >= UP_EPOCHS {
260                        transition = self.enter(ProfileKind::Ssd);
261                        // The upgrade evidence (3 epochs > 300 MB/s) is
262                        // exactly what "proven fast" means.
263                        self.proven_fast = true;
264                    }
265                } else {
266                    self.down_streak = 0;
267                    self.up_streak = 0;
268                }
269            }
270            ProfileKind::SlowOps => {
271                if mbps > UP_FACTOR * SLOW_SEEK_DOWN_MBPS {
272                    self.up_streak += 1;
273                    if self.up_streak >= UP_EPOCHS {
274                        transition = self.enter(ProfileKind::SlowSeek);
275                    }
276                } else {
277                    self.up_streak = 0;
278                }
279            }
280        }
281
282        self.decision(transition, mbps)
283    }
284
285    /// Move to `next`, resetting both hysteresis streaks.
286    fn enter(&mut self, next: ProfileKind) -> Option<ProfileKind> {
287        self.state = next;
288        self.down_streak = 0;
289        self.up_streak = 0;
290        Some(next)
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    /// Build a measurement from MB/s and a stall fraction, using the mock
299    /// clock's fixed step as the epoch duration — the same shape the real
300    /// pipeline produces.
301    fn epoch(mbps: f64, stall_fraction: f64) -> EpochMeasurement {
302        let duration = Duration::from_millis(100);
303        EpochMeasurement {
304            bytes: (mbps * 1024.0 * 1024.0 * duration.as_secs_f64()) as u64,
305            duration,
306            send_stall: duration.mul_f64(stall_fraction),
307        }
308    }
309
310    /// Run a scripted sequence, returning the transition trace as
311    /// `(epoch_index_1_based, new_state)`.
312    fn trace(
313        controller: &mut Controller,
314        epochs: &[EpochMeasurement],
315    ) -> Vec<(usize, ProfileKind)> {
316        epochs
317            .iter()
318            .enumerate()
319            .filter_map(|(i, m)| controller.on_epoch(m).transition.map(|k| (i + 1, k)))
320            .collect()
321    }
322
323    #[test]
324    fn steady_fast_stays_fast() {
325        let mut c = Controller::new(ProfileKind::Ssd, 4);
326        let epochs: Vec<_> = std::iter::repeat_n(epoch(500.0, 0.05), 50).collect();
327        assert_eq!(trace(&mut c, &epochs), vec![]);
328        assert_eq!(c.state(), ProfileKind::Ssd);
329    }
330
331    #[test]
332    fn degradation_transitions_exactly_at_epoch_three() {
333        // 500, 30, 28 MB/s with high stall: epoch 1 is warmup, epochs 2 and 3
334        // qualify, so the FAST→SLOW_SEEK transition lands exactly at epoch 3.
335        let mut c = Controller::new(ProfileKind::Ssd, 4);
336        let epochs = [epoch(500.0, 0.8), epoch(30.0, 0.8), epoch(28.0, 0.8)];
337        assert_eq!(trace(&mut c, &epochs), vec![(3, ProfileKind::SlowSeek)]);
338    }
339
340    #[test]
341    fn oscillation_around_threshold_never_flaps() {
342        // 100/200 MB/s alternating straddles the 150 MB/s downgrade line but
343        // never sustains it for 2 consecutive epochs — hysteresis holds.
344        let mut c = Controller::new(ProfileKind::Ssd, 4);
345        let epochs: Vec<_> = (0..40)
346            .map(|i| epoch(if i % 2 == 0 { 100.0 } else { 200.0 }, 0.8))
347            .collect();
348        assert_eq!(trace(&mut c, &epochs), vec![]);
349        assert_eq!(c.state(), ProfileKind::Ssd);
350    }
351
352    /// Regression for the 2026-07-16 field bug: `bytes_acked` used to count
353    /// bytes landing in the writer's RAM coalescing buffer, so a slow device
354    /// reported ~600 MB/s "throughput" alongside heavy producer stall. Per
355    /// the design doc, a FAST downgrade requires *both* low throughput and
356    /// high stall — high measured throughput must veto the downgrade no
357    /// matter how stalled the producer is.
358    #[test]
359    fn high_throughput_high_stall_never_downgrades_from_fast() {
360        let mut c = Controller::new(ProfileKind::Ssd, 4);
361        let epochs: Vec<_> = std::iter::repeat_n(epoch(612.0, 0.9), 20).collect();
362        assert_eq!(trace(&mut c, &epochs), vec![]);
363        assert_eq!(c.state(), ProfileKind::Ssd);
364
365        // Same for SLOW_SEEK → SLOW_OPS: 40 MB/s + heavy stall is above the
366        // 15 MB/s line, so it must hold (and being above 2×15 for 3 epochs it
367        // legitimately upgrades instead — anything but a downgrade).
368        let mut c = Controller::new(ProfileKind::SlowSeek, 4);
369        let epochs: Vec<_> = std::iter::repeat_n(epoch(40.0, 0.9), 20).collect();
370        for (_, kind) in trace(&mut c, &epochs) {
371            assert_ne!(kind, ProfileKind::SlowOps, "downgrade despite 40 MB/s");
372        }
373    }
374
375    /// The value in the transition log line must be the exact value the
376    /// state machine compared against its thresholds: a downgrade decision
377    /// can therefore never carry a throughput above the downgrade line.
378    #[test]
379    fn logged_throughput_is_the_compared_throughput() {
380        let mut c = Controller::new(ProfileKind::Ssd, 4);
381        let script = [
382            epoch(500.0, 0.1), // warmup
383            epoch(30.0, 0.8),
384            epoch(28.0, 0.8), // → SLOW_SEEK
385        ];
386        for m in &script {
387            let d = c.on_epoch(m);
388            assert_eq!(
389                d.throughput_mbps,
390                m.throughput_mbps(),
391                "decision must carry the measured value it was computed from"
392            );
393            if d.transition == Some(ProfileKind::SlowSeek) {
394                assert!(
395                    d.throughput_mbps < FAST_DOWN_MBPS,
396                    "FAST downgrade fired at {} MB/s, above the {} MB/s line",
397                    d.throughput_mbps,
398                    FAST_DOWN_MBPS
399                );
400            }
401        }
402        assert_eq!(c.state(), ProfileKind::SlowSeek);
403    }
404
405    #[test]
406    fn input_bound_low_throughput_zero_stall_never_transitions() {
407        // 5 MB/s but the producer never blocks on sends: the input (slow
408        // decompression, other device) is the bottleneck, not the output.
409        let mut c = Controller::new(ProfileKind::Ssd, 4);
410        let epochs: Vec<_> = std::iter::repeat_n(epoch(5.0, 0.0), 20).collect();
411        assert_eq!(trace(&mut c, &epochs), vec![]);
412        assert_eq!(c.state(), ProfileKind::Ssd);
413
414        // Same holds for the SLOW_SEEK → SLOW_OPS downgrade.
415        let mut c = Controller::new(ProfileKind::SlowSeek, 4);
416        let epochs: Vec<_> = std::iter::repeat_n(epoch(5.0, 0.0), 20).collect();
417        assert_eq!(trace(&mut c, &epochs), vec![]);
418        assert_eq!(c.state(), ProfileKind::SlowSeek);
419    }
420
421    #[test]
422    fn double_downgrade_fast_to_slow_seek_to_slow_ops() {
423        let mut c = Controller::new(ProfileKind::Ssd, 4);
424        let epochs = [
425            epoch(400.0, 0.1), // warmup (discarded)
426            epoch(30.0, 0.8),
427            epoch(30.0, 0.8), // → SLOW_SEEK
428            epoch(8.0, 0.8),
429            epoch(8.0, 0.8), // → SLOW_OPS
430        ];
431        assert_eq!(
432            trace(&mut c, &epochs),
433            vec![(3, ProfileKind::SlowSeek), (5, ProfileKind::SlowOps)]
434        );
435    }
436
437    #[test]
438    fn recovery_upgrade_after_three_qualifying_epochs() {
439        // SLOW_SEEK → FAST needs 3 consecutive epochs above 2× the 150 MB/s
440        // downgrade threshold; two are not enough.
441        let mut c = Controller::new(ProfileKind::SlowSeek, 4);
442        let epochs = [
443            epoch(50.0, 0.1), // warmup
444            epoch(400.0, 0.0),
445            epoch(400.0, 0.0),
446            epoch(250.0, 0.0), // streak broken (below 300)
447            epoch(400.0, 0.0),
448            epoch(400.0, 0.0),
449            epoch(400.0, 0.0), // third consecutive → FAST
450        ];
451        assert_eq!(trace(&mut c, &epochs), vec![(7, ProfileKind::Ssd)]);
452
453        // SLOW_OPS recovers to SLOW_SEEK above 2× 15 MB/s.
454        let mut c = Controller::new(ProfileKind::SlowOps, 4);
455        let epochs = [
456            epoch(5.0, 0.8), // warmup
457            epoch(40.0, 0.0),
458            epoch(40.0, 0.0),
459            epoch(40.0, 0.0),
460        ];
461        assert_eq!(trace(&mut c, &epochs), vec![(4, ProfileKind::SlowSeek)]);
462    }
463
464    #[test]
465    fn writer_growth_waits_for_proven_fast() {
466        let mut c = Controller::new(ProfileKind::Ssd, 4);
467        // Warmup epoch: not proof, stay at 1 writer.
468        assert_eq!(c.on_epoch(&epoch(500.0, 0.0)).target_writers, 1);
469        // First measured fast epoch proves the device: grow to FAST's count.
470        assert_eq!(c.on_epoch(&epoch(500.0, 0.0)).target_writers, 4);
471        // Input-bound epochs are not proof either way; the flag is sticky.
472        assert_eq!(c.on_epoch(&epoch(5.0, 0.0)).target_writers, 4);
473    }
474
475    #[test]
476    fn slow_opening_never_requests_growth() {
477        let mut c = Controller::new(ProfileKind::SlowSeek, 8);
478        for _ in 0..10 {
479            assert_eq!(c.on_epoch(&epoch(30.0, 0.5)).target_writers, 1);
480        }
481    }
482
483    #[test]
484    fn upgrade_to_fast_requests_growth() {
485        let mut c = Controller::new(ProfileKind::SlowSeek, 4);
486        c.on_epoch(&epoch(50.0, 0.1)); // warmup
487        c.on_epoch(&epoch(400.0, 0.0));
488        c.on_epoch(&epoch(400.0, 0.0));
489        let d = c.on_epoch(&epoch(400.0, 0.0));
490        assert_eq!(d.transition, Some(ProfileKind::Ssd));
491        assert_eq!(d.target_writers, 4);
492    }
493
494    /// A zero-duration epoch used to report `f64::INFINITY` MB/s, instantly
495    /// setting `proven_fast` (spurious writer growth on a slow device) or
496    /// counting toward an upgrade streak. It must be discarded instead.
497    #[test]
498    fn zero_duration_epoch_is_discarded_not_infinite() {
499        let zero = EpochMeasurement {
500            bytes: 64 * 1024 * 1024,
501            duration: Duration::ZERO,
502            send_stall: Duration::ZERO,
503        };
504        assert_eq!(zero.throughput_mbps(), 0.0, "unmeasurable, not infinite");
505
506        // SSD opening: a zero-duration epoch must never prove the device
507        // fast — the deferred writer spawn stays deferred.
508        let mut c = Controller::new(ProfileKind::Ssd, 4);
509        c.on_epoch(&epoch(500.0, 0.0)); // warmup
510        assert_eq!(
511            c.on_epoch(&zero).target_writers,
512            1,
513            "zero-duration epoch proved the device fast"
514        );
515
516        // SLOW_SEEK: zero-duration epochs must not count toward an upgrade.
517        let mut c = Controller::new(ProfileKind::SlowSeek, 4);
518        c.on_epoch(&epoch(30.0, 0.1)); // warmup
519        for _ in 0..10 {
520            assert_eq!(c.on_epoch(&zero).transition, None);
521        }
522        assert_eq!(c.state(), ProfileKind::SlowSeek);
523    }
524
525    /// The companion hazard: a degenerate epoch must also not *reset* an
526    /// in-progress downgrade streak (that would block legitimate downgrades
527    /// on genuinely slow media).
528    #[test]
529    fn zero_duration_epoch_does_not_reset_downgrade_streak() {
530        let zero = EpochMeasurement {
531            bytes: 0,
532            duration: Duration::ZERO,
533            send_stall: Duration::ZERO,
534        };
535        let mut c = Controller::new(ProfileKind::Ssd, 4);
536        c.on_epoch(&epoch(500.0, 0.1)); // warmup
537        assert_eq!(c.on_epoch(&epoch(30.0, 0.8)).transition, None); // streak 1
538        assert_eq!(c.on_epoch(&zero).transition, None); // degenerate boundary
539        assert_eq!(
540            c.on_epoch(&epoch(28.0, 0.8)).transition,
541            Some(ProfileKind::SlowSeek),
542            "degenerate epoch reset the downgrade streak"
543        );
544    }
545
546    /// Compressed output: throughput is compressed MB/s from a CPU-bound
547    /// encoder. A lone gzip writer emits ~20-30 MB/s compressed while the
548    /// producer stalls on full channels — exactly the old downgrade
549    /// signature. The frozen controller must neither downgrade nor wait for
550    /// an unreachable 150 MB/s "proof" before growing writers.
551    #[test]
552    fn compressed_output_grows_immediately_and_never_downgrades() {
553        let mut c = Controller::new(ProfileKind::Ssd, 8).for_compressed_output();
554        // Even the warmup decision requests the full compression writer count.
555        assert_eq!(c.on_epoch(&epoch(25.0, 0.9)).target_writers, 8);
556        for _ in 0..20 {
557            let d = c.on_epoch(&epoch(25.0, 0.9));
558            assert_eq!(d.transition, None, "downgraded on CPU-bound compression");
559            assert_eq!(d.target_writers, 8);
560        }
561        assert_eq!(c.state(), ProfileKind::Ssd);
562    }
563
564    /// A slow probe verdict still holds under compressed output: one writer,
565    /// and no upgrade no matter what the (meaningless) numbers say.
566    #[test]
567    fn compressed_output_on_slow_opening_stays_single_writer() {
568        let mut c = Controller::new(ProfileKind::SlowSeek, 8).for_compressed_output();
569        for _ in 0..10 {
570            let d = c.on_epoch(&epoch(400.0, 0.0));
571            assert_eq!(d.transition, None);
572            assert_eq!(d.target_writers, 1);
573        }
574        assert_eq!(c.state(), ProfileKind::SlowSeek);
575    }
576
577    #[test]
578    fn mock_clock_steps_deterministically() {
579        let clock = MockClock::stepping(Duration::from_millis(5));
580        assert_eq!(clock.now(), Duration::from_millis(5));
581        assert_eq!(clock.now(), Duration::from_millis(10));
582        assert_eq!(clock.now(), Duration::from_millis(15));
583    }
584
585    #[test]
586    fn real_clock_is_monotonic() {
587        let clock = RealClock::new();
588        let a = clock.now();
589        let b = clock.now();
590        assert!(b >= a);
591    }
592}