1use super::profile::ProfileKind;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::Duration;
12
13pub trait Clock: Send + Sync {
19 fn now(&self) -> Duration;
20}
21
22#[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#[derive(Debug)]
52pub struct MockClock {
53 nanos: AtomicU64,
54 step_nanos: u64,
55}
56
57impl MockClock {
58 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#[derive(Debug, Clone, Copy)]
76pub struct EpochMeasurement {
77 pub bytes: u64,
79 pub duration: Duration,
81 pub send_stall: Duration,
83}
84
85impl EpochMeasurement {
86 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 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#[derive(Debug, Clone, Copy, PartialEq)]
111pub struct EpochDecision {
112 pub transition: Option<ProfileKind>,
115 pub target_writers: usize,
118 pub throughput_mbps: f64,
120}
121
122const FAST_DOWN_MBPS: f64 = 150.0;
124const SLOW_SEEK_DOWN_MBPS: f64 = 15.0;
126const STALL_DOWN_FRACTION: f64 = 0.30;
130const DOWN_EPOCHS: u32 = 2;
132const UP_EPOCHS: u32 = 3;
136const UP_FACTOR: f64 = 2.0;
138
139#[derive(Debug)]
141pub struct Controller {
142 state: ProfileKind,
143 fast_writers: usize,
145 warmup_done: bool,
147 down_streak: u32,
149 up_streak: u32,
151 proven_fast: bool,
154 compressed_output: bool,
161}
162
163impl Controller {
164 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 pub fn for_compressed_output(mut self) -> Self {
182 self.compressed_output = true;
183 self
184 }
185
186 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 pub fn on_epoch(&mut self, m: &EpochMeasurement) -> EpochDecision {
207 let mbps = m.throughput_mbps();
208
209 if m.duration.is_zero() {
215 return self.decision(None, mbps);
216 }
217
218 if !self.warmup_done {
220 self.warmup_done = true;
221 return self.decision(None, mbps);
222 }
223
224 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 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 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 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 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 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 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 #[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 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 #[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), epoch(30.0, 0.8),
384 epoch(28.0, 0.8), ];
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 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 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), epoch(30.0, 0.8),
427 epoch(30.0, 0.8), epoch(8.0, 0.8),
429 epoch(8.0, 0.8), ];
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 let mut c = Controller::new(ProfileKind::SlowSeek, 4);
442 let epochs = [
443 epoch(50.0, 0.1), epoch(400.0, 0.0),
445 epoch(400.0, 0.0),
446 epoch(250.0, 0.0), epoch(400.0, 0.0),
448 epoch(400.0, 0.0),
449 epoch(400.0, 0.0), ];
451 assert_eq!(trace(&mut c, &epochs), vec![(7, ProfileKind::Ssd)]);
452
453 let mut c = Controller::new(ProfileKind::SlowOps, 4);
455 let epochs = [
456 epoch(5.0, 0.8), 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 assert_eq!(c.on_epoch(&epoch(500.0, 0.0)).target_writers, 1);
469 assert_eq!(c.on_epoch(&epoch(500.0, 0.0)).target_writers, 4);
471 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)); 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 #[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 let mut c = Controller::new(ProfileKind::Ssd, 4);
509 c.on_epoch(&epoch(500.0, 0.0)); assert_eq!(
511 c.on_epoch(&zero).target_writers,
512 1,
513 "zero-duration epoch proved the device fast"
514 );
515
516 let mut c = Controller::new(ProfileKind::SlowSeek, 4);
518 c.on_epoch(&epoch(30.0, 0.1)); for _ in 0..10 {
520 assert_eq!(c.on_epoch(&zero).transition, None);
521 }
522 assert_eq!(c.state(), ProfileKind::SlowSeek);
523 }
524
525 #[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)); assert_eq!(c.on_epoch(&epoch(30.0, 0.8)).transition, None); assert_eq!(c.on_epoch(&zero).transition, None); 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 #[test]
552 fn compressed_output_grows_immediately_and_never_downgrades() {
553 let mut c = Controller::new(ProfileKind::Ssd, 8).for_compressed_output();
554 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 #[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}