use super::profile::ProfileKind;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
pub trait Clock: Send + Sync {
fn now(&self) -> Duration;
}
#[derive(Debug)]
pub struct RealClock {
origin: std::time::Instant,
}
impl RealClock {
pub fn new() -> Self {
Self {
origin: std::time::Instant::now(),
}
}
}
impl Default for RealClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for RealClock {
fn now(&self) -> Duration {
self.origin.elapsed()
}
}
#[derive(Debug)]
pub struct MockClock {
nanos: AtomicU64,
step_nanos: u64,
}
impl MockClock {
pub fn stepping(step: Duration) -> Self {
Self {
nanos: AtomicU64::new(0),
step_nanos: step.as_nanos() as u64,
}
}
}
impl Clock for MockClock {
fn now(&self) -> Duration {
let t = self.nanos.fetch_add(self.step_nanos, Ordering::Relaxed);
Duration::from_nanos(t + self.step_nanos)
}
}
#[derive(Debug, Clone, Copy)]
pub struct EpochMeasurement {
pub bytes: u64,
pub duration: Duration,
pub send_stall: Duration,
}
impl EpochMeasurement {
pub fn throughput_mbps(&self) -> f64 {
let secs = self.duration.as_secs_f64();
if secs <= 0.0 {
return 0.0;
}
self.bytes as f64 / (1024.0 * 1024.0) / secs
}
pub fn stall_fraction(&self) -> f64 {
let secs = self.duration.as_secs_f64();
if secs <= 0.0 {
return 0.0;
}
self.send_stall.as_secs_f64() / secs
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EpochDecision {
pub transition: Option<ProfileKind>,
pub target_writers: usize,
pub throughput_mbps: f64,
}
const FAST_DOWN_MBPS: f64 = 150.0;
const SLOW_SEEK_DOWN_MBPS: f64 = 15.0;
const STALL_DOWN_FRACTION: f64 = 0.30;
const DOWN_EPOCHS: u32 = 2;
const UP_EPOCHS: u32 = 3;
const UP_FACTOR: f64 = 2.0;
#[derive(Debug)]
pub struct Controller {
state: ProfileKind,
fast_writers: usize,
warmup_done: bool,
down_streak: u32,
up_streak: u32,
proven_fast: bool,
compressed_output: bool,
}
impl Controller {
pub fn new(opening: ProfileKind, fast_writers: usize) -> Self {
Self {
state: opening,
fast_writers: fast_writers.max(1),
warmup_done: false,
down_streak: 0,
up_streak: 0,
proven_fast: false,
compressed_output: false,
}
}
pub fn for_compressed_output(mut self) -> Self {
self.compressed_output = true;
self
}
pub fn state(&self) -> ProfileKind {
self.state
}
fn decision(&self, transition: Option<ProfileKind>, mbps: f64) -> EpochDecision {
EpochDecision {
transition,
target_writers: if self.state == ProfileKind::Ssd
&& (self.proven_fast || self.compressed_output)
{
self.fast_writers
} else {
1
},
throughput_mbps: mbps,
}
}
pub fn on_epoch(&mut self, m: &EpochMeasurement) -> EpochDecision {
let mbps = m.throughput_mbps();
if m.duration.is_zero() {
return self.decision(None, mbps);
}
if !self.warmup_done {
self.warmup_done = true;
return self.decision(None, mbps);
}
if self.compressed_output {
return self.decision(None, mbps);
}
let stalled = m.stall_fraction() > STALL_DOWN_FRACTION;
let mut transition = None;
match self.state {
ProfileKind::Ssd => {
if mbps < FAST_DOWN_MBPS && stalled {
self.down_streak += 1;
if self.down_streak >= DOWN_EPOCHS {
transition = self.enter(ProfileKind::SlowSeek);
}
} else {
self.down_streak = 0;
if mbps >= FAST_DOWN_MBPS {
self.proven_fast = true;
}
}
}
ProfileKind::SlowSeek => {
if mbps < SLOW_SEEK_DOWN_MBPS && stalled {
self.down_streak += 1;
self.up_streak = 0;
if self.down_streak >= DOWN_EPOCHS {
transition = self.enter(ProfileKind::SlowOps);
}
} else if mbps > UP_FACTOR * FAST_DOWN_MBPS {
self.down_streak = 0;
self.up_streak += 1;
if self.up_streak >= UP_EPOCHS {
transition = self.enter(ProfileKind::Ssd);
self.proven_fast = true;
}
} else {
self.down_streak = 0;
self.up_streak = 0;
}
}
ProfileKind::SlowOps => {
if mbps > UP_FACTOR * SLOW_SEEK_DOWN_MBPS {
self.up_streak += 1;
if self.up_streak >= UP_EPOCHS {
transition = self.enter(ProfileKind::SlowSeek);
}
} else {
self.up_streak = 0;
}
}
}
self.decision(transition, mbps)
}
fn enter(&mut self, next: ProfileKind) -> Option<ProfileKind> {
self.state = next;
self.down_streak = 0;
self.up_streak = 0;
Some(next)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn epoch(mbps: f64, stall_fraction: f64) -> EpochMeasurement {
let duration = Duration::from_millis(100);
EpochMeasurement {
bytes: (mbps * 1024.0 * 1024.0 * duration.as_secs_f64()) as u64,
duration,
send_stall: duration.mul_f64(stall_fraction),
}
}
fn trace(
controller: &mut Controller,
epochs: &[EpochMeasurement],
) -> Vec<(usize, ProfileKind)> {
epochs
.iter()
.enumerate()
.filter_map(|(i, m)| controller.on_epoch(m).transition.map(|k| (i + 1, k)))
.collect()
}
#[test]
fn steady_fast_stays_fast() {
let mut c = Controller::new(ProfileKind::Ssd, 4);
let epochs: Vec<_> = std::iter::repeat_n(epoch(500.0, 0.05), 50).collect();
assert_eq!(trace(&mut c, &epochs), vec![]);
assert_eq!(c.state(), ProfileKind::Ssd);
}
#[test]
fn degradation_transitions_exactly_at_epoch_three() {
let mut c = Controller::new(ProfileKind::Ssd, 4);
let epochs = [epoch(500.0, 0.8), epoch(30.0, 0.8), epoch(28.0, 0.8)];
assert_eq!(trace(&mut c, &epochs), vec![(3, ProfileKind::SlowSeek)]);
}
#[test]
fn oscillation_around_threshold_never_flaps() {
let mut c = Controller::new(ProfileKind::Ssd, 4);
let epochs: Vec<_> = (0..40)
.map(|i| epoch(if i % 2 == 0 { 100.0 } else { 200.0 }, 0.8))
.collect();
assert_eq!(trace(&mut c, &epochs), vec![]);
assert_eq!(c.state(), ProfileKind::Ssd);
}
#[test]
fn high_throughput_high_stall_never_downgrades_from_fast() {
let mut c = Controller::new(ProfileKind::Ssd, 4);
let epochs: Vec<_> = std::iter::repeat_n(epoch(612.0, 0.9), 20).collect();
assert_eq!(trace(&mut c, &epochs), vec![]);
assert_eq!(c.state(), ProfileKind::Ssd);
let mut c = Controller::new(ProfileKind::SlowSeek, 4);
let epochs: Vec<_> = std::iter::repeat_n(epoch(40.0, 0.9), 20).collect();
for (_, kind) in trace(&mut c, &epochs) {
assert_ne!(kind, ProfileKind::SlowOps, "downgrade despite 40 MB/s");
}
}
#[test]
fn logged_throughput_is_the_compared_throughput() {
let mut c = Controller::new(ProfileKind::Ssd, 4);
let script = [
epoch(500.0, 0.1), epoch(30.0, 0.8),
epoch(28.0, 0.8), ];
for m in &script {
let d = c.on_epoch(m);
assert_eq!(
d.throughput_mbps,
m.throughput_mbps(),
"decision must carry the measured value it was computed from"
);
if d.transition == Some(ProfileKind::SlowSeek) {
assert!(
d.throughput_mbps < FAST_DOWN_MBPS,
"FAST downgrade fired at {} MB/s, above the {} MB/s line",
d.throughput_mbps,
FAST_DOWN_MBPS
);
}
}
assert_eq!(c.state(), ProfileKind::SlowSeek);
}
#[test]
fn input_bound_low_throughput_zero_stall_never_transitions() {
let mut c = Controller::new(ProfileKind::Ssd, 4);
let epochs: Vec<_> = std::iter::repeat_n(epoch(5.0, 0.0), 20).collect();
assert_eq!(trace(&mut c, &epochs), vec![]);
assert_eq!(c.state(), ProfileKind::Ssd);
let mut c = Controller::new(ProfileKind::SlowSeek, 4);
let epochs: Vec<_> = std::iter::repeat_n(epoch(5.0, 0.0), 20).collect();
assert_eq!(trace(&mut c, &epochs), vec![]);
assert_eq!(c.state(), ProfileKind::SlowSeek);
}
#[test]
fn double_downgrade_fast_to_slow_seek_to_slow_ops() {
let mut c = Controller::new(ProfileKind::Ssd, 4);
let epochs = [
epoch(400.0, 0.1), epoch(30.0, 0.8),
epoch(30.0, 0.8), epoch(8.0, 0.8),
epoch(8.0, 0.8), ];
assert_eq!(
trace(&mut c, &epochs),
vec![(3, ProfileKind::SlowSeek), (5, ProfileKind::SlowOps)]
);
}
#[test]
fn recovery_upgrade_after_three_qualifying_epochs() {
let mut c = Controller::new(ProfileKind::SlowSeek, 4);
let epochs = [
epoch(50.0, 0.1), epoch(400.0, 0.0),
epoch(400.0, 0.0),
epoch(250.0, 0.0), epoch(400.0, 0.0),
epoch(400.0, 0.0),
epoch(400.0, 0.0), ];
assert_eq!(trace(&mut c, &epochs), vec![(7, ProfileKind::Ssd)]);
let mut c = Controller::new(ProfileKind::SlowOps, 4);
let epochs = [
epoch(5.0, 0.8), epoch(40.0, 0.0),
epoch(40.0, 0.0),
epoch(40.0, 0.0),
];
assert_eq!(trace(&mut c, &epochs), vec![(4, ProfileKind::SlowSeek)]);
}
#[test]
fn writer_growth_waits_for_proven_fast() {
let mut c = Controller::new(ProfileKind::Ssd, 4);
assert_eq!(c.on_epoch(&epoch(500.0, 0.0)).target_writers, 1);
assert_eq!(c.on_epoch(&epoch(500.0, 0.0)).target_writers, 4);
assert_eq!(c.on_epoch(&epoch(5.0, 0.0)).target_writers, 4);
}
#[test]
fn slow_opening_never_requests_growth() {
let mut c = Controller::new(ProfileKind::SlowSeek, 8);
for _ in 0..10 {
assert_eq!(c.on_epoch(&epoch(30.0, 0.5)).target_writers, 1);
}
}
#[test]
fn upgrade_to_fast_requests_growth() {
let mut c = Controller::new(ProfileKind::SlowSeek, 4);
c.on_epoch(&epoch(50.0, 0.1)); c.on_epoch(&epoch(400.0, 0.0));
c.on_epoch(&epoch(400.0, 0.0));
let d = c.on_epoch(&epoch(400.0, 0.0));
assert_eq!(d.transition, Some(ProfileKind::Ssd));
assert_eq!(d.target_writers, 4);
}
#[test]
fn zero_duration_epoch_is_discarded_not_infinite() {
let zero = EpochMeasurement {
bytes: 64 * 1024 * 1024,
duration: Duration::ZERO,
send_stall: Duration::ZERO,
};
assert_eq!(zero.throughput_mbps(), 0.0, "unmeasurable, not infinite");
let mut c = Controller::new(ProfileKind::Ssd, 4);
c.on_epoch(&epoch(500.0, 0.0)); assert_eq!(
c.on_epoch(&zero).target_writers,
1,
"zero-duration epoch proved the device fast"
);
let mut c = Controller::new(ProfileKind::SlowSeek, 4);
c.on_epoch(&epoch(30.0, 0.1)); for _ in 0..10 {
assert_eq!(c.on_epoch(&zero).transition, None);
}
assert_eq!(c.state(), ProfileKind::SlowSeek);
}
#[test]
fn zero_duration_epoch_does_not_reset_downgrade_streak() {
let zero = EpochMeasurement {
bytes: 0,
duration: Duration::ZERO,
send_stall: Duration::ZERO,
};
let mut c = Controller::new(ProfileKind::Ssd, 4);
c.on_epoch(&epoch(500.0, 0.1)); assert_eq!(c.on_epoch(&epoch(30.0, 0.8)).transition, None); assert_eq!(c.on_epoch(&zero).transition, None); assert_eq!(
c.on_epoch(&epoch(28.0, 0.8)).transition,
Some(ProfileKind::SlowSeek),
"degenerate epoch reset the downgrade streak"
);
}
#[test]
fn compressed_output_grows_immediately_and_never_downgrades() {
let mut c = Controller::new(ProfileKind::Ssd, 8).for_compressed_output();
assert_eq!(c.on_epoch(&epoch(25.0, 0.9)).target_writers, 8);
for _ in 0..20 {
let d = c.on_epoch(&epoch(25.0, 0.9));
assert_eq!(d.transition, None, "downgraded on CPU-bound compression");
assert_eq!(d.target_writers, 8);
}
assert_eq!(c.state(), ProfileKind::Ssd);
}
#[test]
fn compressed_output_on_slow_opening_stays_single_writer() {
let mut c = Controller::new(ProfileKind::SlowSeek, 8).for_compressed_output();
for _ in 0..10 {
let d = c.on_epoch(&epoch(400.0, 0.0));
assert_eq!(d.transition, None);
assert_eq!(d.target_writers, 1);
}
assert_eq!(c.state(), ProfileKind::SlowSeek);
}
#[test]
fn mock_clock_steps_deterministically() {
let clock = MockClock::stepping(Duration::from_millis(5));
assert_eq!(clock.now(), Duration::from_millis(5));
assert_eq!(clock.now(), Duration::from_millis(10));
assert_eq!(clock.now(), Duration::from_millis(15));
}
#[test]
fn real_clock_is_monotonic() {
let clock = RealClock::new();
let a = clock.now();
let b = clock.now();
assert!(b >= a);
}
}