Medlar/crates/core/src/adapt.rs
2026-11-25 01:18:06 -06:00

341 lines
11 KiB
Rust

//! How many connections a download should use. Every connection has to prove that it helps.
use std::time::{Duration, Instant};
/// Connections of a download to a host nobody knows.
pub const START: u32 = 2;
/// What a connection must add, as a share of what the others bring on average.
const WORTH: f64 = 0.3;
/// A jump that brings less of that share went too far.
const FULL: f64 = 0.7;
#[derive(Debug, Clone, Copy)]
pub struct Timing {
/// Left out after a change: connections start slowly.
pub settle: Duration,
/// Measured before deciding.
pub window: Duration,
/// Until the next try after one that brought nothing. Doubles each time, up to eight times this.
pub hold: Duration,
/// Until more is tried again after the server refused a connection.
pub refused: Duration,
}
impl Default for Timing {
fn default() -> Self {
Timing {
settle: Duration::from_secs(1),
window: Duration::from_secs(3),
hold: Duration::from_secs(30),
refused: Duration::from_secs(600),
}
}
}
#[derive(Debug, Clone, Copy)]
struct Measure {
mean: f64,
/// Standard error of the mean.
error: f64,
}
#[derive(Debug, Clone, Copy)]
enum Phase {
Base,
/// Trying more or fewer than `n`, which measured `at_n`.
Try { n: u32, at_n: Measure },
Hold { until: Instant },
}
#[derive(Debug)]
pub struct Adapt {
n: u32,
cap: u32,
timing: Timing,
phase: Phase,
/// Doubling, until that fails.
fast: bool,
/// `n` was measured to be better than less.
proven: bool,
learned: bool,
hold: Duration,
window: Window,
}
#[derive(Debug, Default)]
struct Window {
/// All connections have delivered since the last change.
since: Option<Instant>,
last: Option<(Instant, u64)>,
rates: Vec<f64>,
}
impl Adapt {
pub fn new(start: u32, cap: u32, timing: Timing) -> Adapt {
let cap = cap.max(1);
Adapt {
n: start.clamp(1, cap),
cap,
timing,
phase: Phase::Base,
fast: true,
proven: false,
learned: false,
hold: timing.hold,
window: Window::default(),
}
}
pub fn target(&self) -> u32 {
self.n
}
/// The count to remember for this host, if something was found out.
pub fn learned(&self) -> Option<u32> {
match self.phase {
_ if !self.learned => None,
Phase::Try { n, .. } => Some(n),
_ => Some(self.n),
}
}
pub fn set_cap(&mut self, cap: u32) {
let cap = cap.max(1);
if cap == self.cap {
return;
}
if cap > self.cap || cap < self.n {
self.phase = Phase::Base;
self.window = Window::default();
self.fast = true;
}
self.cap = cap;
self.n = self.n.min(cap);
}
/// The server turned a connection away. With `others` there, and if they `work`, that says what it stands.
pub fn refused(&mut self, now: Instant, others: u32, work: bool) {
self.window = Window::default();
self.fast = !work;
self.proven = true;
self.n = self.n.min(others).max(1);
self.learned |= work;
let wait = if work { self.timing.refused } else { self.timing.window * 3 };
self.phase = Phase::Hold { until: now + wait };
}
/// To be called regularly. `running` connections exist, `delivering` of them have brought something, `received` bytes in all.
pub fn tick(&mut self, now: Instant, running: u32, delivering: u32, received: u64) {
if let Phase::Hold { until } = self.phase {
if now < until {
return;
}
self.phase = Phase::Base;
self.proven = false;
self.window = Window::default();
}
if running != self.n {
self.window = Window::default();
return;
}
let w = &mut self.window;
let Some(since) = w.since else {
if delivering == running {
w.since = Some(now);
}
return;
};
if now < since + self.timing.settle {
return;
}
if let Some((then, before)) = w.last {
let secs = (now - then).as_secs_f64();
if secs <= 0.0 {
return;
}
w.rates.push(received.saturating_sub(before) as f64 / secs);
}
w.last = Some((now, received));
if w.rates.len() >= 4 && now >= since + self.timing.settle + self.timing.window {
let found = measure(&w.rates);
self.window = Window::default();
self.decide(now, found);
}
}
fn decide(&mut self, now: Instant, found: Measure) {
match self.phase {
Phase::Hold { .. } => {}
Phase::Base => {
let more = if self.fast { self.n.saturating_mul(2) } else { self.n + 1 }.min(self.cap);
if more > self.n { self.try_count(more, found) } else { self.less(now, found) }
}
Phase::Try { n, at_n } if self.n > n => {
self.learned = true;
if helps((n, at_n), (self.n, found), WORTH) {
self.proven = helps((n, at_n), (self.n, found), FULL) || self.n == n + 1;
self.fast &= self.proven;
self.hold = self.timing.hold;
self.phase = Phase::Base;
// Already measured: go on at once.
self.decide(now, found);
} else if self.n > n + 1 {
self.fast = false;
self.try_count(n + 1, at_n);
} else {
self.fast = false;
self.n = n;
self.less(now, at_n);
}
}
Phase::Try { n, at_n } => {
self.learned = true;
if helps((self.n, found), (n, at_n), WORTH) {
self.n = n;
self.proven = true;
self.rest(now);
} else {
self.less(now, found);
}
}
}
}
/// Tries fewer connections, unless all are known to help.
fn less(&mut self, now: Instant, found: Measure) {
let fewer = (self.n - (self.n / 4).max(1)).max(START);
if self.proven || fewer >= self.n { self.rest(now) } else { self.try_count(fewer, found) }
}
fn try_count(&mut self, count: u32, at_n: Measure) {
// After a failed jump `self.n` is the failed count, not the base.
let n = match self.phase {
Phase::Try { n, .. } if self.n > n && count > n => n,
_ => self.n,
};
self.phase = Phase::Try { n, at_n };
self.n = count.min(self.cap);
}
fn rest(&mut self, now: Instant) {
self.phase = Phase::Hold { until: now + self.hold };
self.hold = (self.hold * 2).min(self.timing.hold * 8);
}
}
fn measure(rates: &[f64]) -> Measure {
let n = rates.len() as f64;
let mean = rates.iter().sum::<f64>() / n;
let variance = rates.iter().map(|r| (r - mean).powi(2)).sum::<f64>() / (n - 1.0).max(1.0);
Measure { mean, error: (variance / n).sqrt() }
}
/// Whether the additional connections add `share` of what one brings on average, beyond noise.
fn helps((few, a): (u32, Measure), (many, b): (u32, Measure), share: f64) -> bool {
let fair = a.mean * f64::from(many - few) / f64::from(few);
let noise = 2.0 * a.error.hypot(b.error);
b.mean - a.mean > (share * fair).max(noise)
}
#[cfg(test)]
mod tests {
use super::*;
struct Sim {
adapt: Adapt,
now: Instant,
received: u64,
seed: u64,
most: u32,
}
impl Sim {
fn new(start: u32, cap: u32) -> Sim {
Sim { adapt: Adapt::new(start, cap, Timing::default()), now: Instant::now(), received: 0, seed: 0x2545_f491_4f6c_dd1d, most: 0 }
}
/// `rate(n)` bytes per second, give or take `noise` of it.
fn run(&mut self, secs: u64, noise: f64, rate: impl Fn(u32) -> f64) -> u32 {
for _ in 0..secs * 4 {
self.seed ^= self.seed << 13;
self.seed ^= self.seed >> 7;
self.seed ^= self.seed << 17;
let swing = (self.seed % 2001) as f64 / 1000.0 - 1.0;
let n = self.adapt.target();
self.most = self.most.max(n);
self.received += (rate(n) * (1.0 + swing * noise) / 4.0) as u64;
self.now += Duration::from_millis(250);
self.adapt.tick(self.now, n, n, self.received);
}
self.adapt.learned().unwrap_or(self.adapt.target())
}
}
#[test]
fn grows_while_it_helps() {
let mut sim = Sim::new(START, 16);
assert_eq!(sim.run(20, 0.1, |n| f64::from(n) * 1e6), 16);
assert_eq!(Sim::new(START, 7).run(20, 0.1, |n| f64::from(n) * 1e6), 7);
// Until six, which doubling jumps over.
let six = Sim::new(START, 32).run(40, 0.02, |n| f64::from(n.min(6)) * 1e6);
assert!((5..=7).contains(&six), "{six}");
}
#[test]
fn stays_low_when_it_does_not() {
for noise in [0.0, 0.1, 0.4] {
let mut sim = Sim::new(START, 16);
assert_eq!(sim.run(300, noise, |_| 1e6), 2, "{noise}");
assert!(sim.most <= 4);
}
// A line that gets worse with more.
assert_eq!(Sim::new(START, 16).run(60, 0.1, |n| 1e6 / f64::from(n)), 2);
}
#[test]
fn a_remembered_count_is_checked() {
assert_eq!(Sim::new(12, 16).run(90, 0.05, |_| 1e6), 2);
let mut sim = Sim::new(8, 8);
sim.run(200, 0.05, |n| f64::from(n) * 1e6);
assert_eq!(sim.adapt.learned(), Some(8));
}
#[test]
fn conditions_change_during_a_download() {
let mut sim = Sim::new(START, 8);
assert_eq!(sim.run(60, 0.05, |_| 1e6), 2);
assert_eq!(sim.run(400, 0.05, |n| f64::from(n) * 1e6), 8);
}
#[test]
fn refusals_and_caps() {
let mut sim = Sim::new(START, 16);
sim.run(20, 0.05, |n| f64::from(n) * 1e6);
sim.adapt.refused(sim.now, 5, true);
assert_eq!(sim.run(300, 0.05, |n| f64::from(n) * 1e6), 5);
sim.adapt.set_cap(3);
assert_eq!(sim.adapt.target(), 3);
sim.run(60, 0.05, |n| f64::from(n) * 1e6);
sim.adapt.set_cap(0);
assert_eq!(sim.adapt.target(), 1);
sim.adapt.set_cap(9);
assert_eq!(sim.run(60, 0.05, |n| f64::from(n) * 1e6), 9);
// Nothing else was running: no lesson.
let mut sim = Sim::new(START, 16);
sim.adapt.refused(sim.now, 0, false);
assert_eq!((sim.adapt.target(), sim.adapt.learned()), (1, None));
assert_eq!(sim.run(60, 0.05, |n| f64::from(n) * 1e6), 16);
}
#[test]
fn nothing_is_measured_while_connections_come_and_go() {
let mut adapt = Adapt::new(START, 16, Timing::default());
let mut now = Instant::now();
for i in 0..400 {
now += Duration::from_millis(250);
adapt.tick(now, 1 + i % 2, 1, u64::from(i) * 1000);
}
assert_eq!((adapt.target(), adapt.learned()), (START, None));
}
}