Skip to main content

rtci_interceptor/gcc/
loss.rs

1//! The loss-based half: what to do when packets vanish without the queue growing.
2
3use std::time::{Duration, Instant};
4
5/// Below this loss fraction the path is considered healthy and the rate may climb.
6pub const DEFAULT_LOW_LOSS: f64 = 0.02;
7
8/// Above this the path is considered congested and the rate must fall.
9pub const DEFAULT_HIGH_LOSS: f64 = 0.10;
10
11/// How long between changes, so each is observed before the next.
12pub const DEFAULT_LOSS_INTERVAL: Duration = Duration::from_millis(200);
13
14/// Loss-based congestion control, per draft-ietf-rmcat-gcc-02 §5.5.
15///
16/// # Why delay is not enough
17///
18/// A path can drop packets without ever queueing them — a wireless link with interference, or a
19/// bottleneck whose buffer is so shallow that it overflows before the delay signal moves. The
20/// delay-based half sees nothing there, so without this a sender keeps pushing into a link that is
21/// discarding a tenth of what it sends.
22///
23/// Between the two thresholds nothing happens. That band is deliberate: a few per cent loss is
24/// normal on a wireless link and reacting to it would give up capacity permanently.
25///
26/// # Divergence from upstream (D4)
27///
28/// **This controller may move the target on its own.** Upstream's cannot: its `latestBitrate` is
29/// only written inside `onDelayUpdate` (`send_side_bwe.go:304`), so on a lossy link *without*
30/// queueing delay its loss estimate is computed and then never applied — exactly the case this
31/// exists for. That is a bug rather than a design choice, and it is not inherited.
32#[derive(Debug, Clone)]
33pub struct LossController {
34    /// Current loss-based target, in bits per second.
35    target: f64,
36    min: f64,
37    max: f64,
38    low: f64,
39    high: f64,
40    interval: Duration,
41    /// Exponentially-weighted average loss, so one bad report does not swing the target.
42    average_loss: Option<f64>,
43    last_change: Option<Instant>,
44}
45
46impl LossController {
47    /// A controller starting at `initial`, clamped to `min..=max`.
48    pub fn new(initial: f64, min: f64, max: f64) -> Self {
49        Self {
50            target: initial.clamp(min, max),
51            min,
52            max,
53            low: DEFAULT_LOW_LOSS,
54            high: DEFAULT_HIGH_LOSS,
55            interval: DEFAULT_LOSS_INTERVAL,
56            average_loss: None,
57            last_change: None,
58        }
59    }
60
61    /// Change the range the target is held in, and bring the target into it.
62    pub fn set_bounds(&mut self, min: f64, max: f64) {
63        self.min = min;
64        self.max = max.max(min);
65        self.target = self.target.clamp(self.min, self.max);
66    }
67
68    /// Bring the target up to `bound` if it is below it: a measurement showed the path
69    /// carries that much (a probe).
70    pub fn raise(&mut self, bound: f64) {
71        self.target = self.target.max(bound).clamp(self.min, self.max);
72    }
73
74    /// Bring the target down to `bound` if it is above it: a deliberate cut (missing feedback).
75    pub fn cap(&mut self, bound: f64) {
76        self.target = self.target.min(bound).clamp(self.min, self.max);
77    }
78
79    /// Update from a fraction lost a receiver report gave, when there is no per-packet
80    /// feedback to count from (section 7).
81    pub fn update_fraction(&mut self, now: Instant, fraction_lost: f64) -> f64 {
82        // 256 packets is the resolution of the field.
83        let lost = (fraction_lost.clamp(0.0, 1.0) * 256.0).round() as usize;
84        self.update(now, lost, 256)
85    }
86
87    /// The current loss-based target, in bits per second.
88    pub fn target(&self) -> f64 {
89        self.target
90    }
91
92    /// The smoothed loss fraction, if any feedback has arrived.
93    pub fn average_loss(&self) -> Option<f64> {
94        self.average_loss
95    }
96
97    /// Fold in one batch of feedback: `lost` of `total` packets did not arrive.
98    pub fn update(&mut self, now: Instant, lost: usize, total: usize) -> f64 {
99        if total == 0 {
100            return self.target;
101        }
102
103        let sample = lost as f64 / total as f64;
104        // Smoothed, but the raw sample still has a say below — a sudden collapse should not have to
105        // wait for the average to catch up.
106        let average = match self.average_loss {
107            Some(previous) => 0.8 * previous + 0.2 * sample,
108            None => sample,
109        };
110        self.average_loss = Some(average);
111
112        if let Some(last) = self.last_change
113            && now.saturating_duration_since(last) < self.interval
114        {
115            return self.target;
116        }
117
118        if average.max(sample) < self.low {
119            // Healthy: probe for more.
120            self.target = (self.target * 1.05).clamp(self.min, self.max);
121            self.last_change = Some(now);
122        } else if average.min(sample) > self.high {
123            // Losing badly: back off in proportion to how badly.
124            self.target = (self.target * (1.0 - 0.5 * average)).clamp(self.min, self.max);
125            self.last_change = Some(now);
126        }
127        // Between the thresholds: hold. A few per cent loss is normal, and reacting to it would
128        // give up capacity permanently.
129
130        self.target
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    const MIN: f64 = 100_000.0;
139    const MAX: f64 = 10_000_000.0;
140
141    fn controller() -> LossController {
142        LossController::new(1_000_000.0, MIN, MAX)
143    }
144
145    /// Heavy loss brings the target down — and does so on its own, with no delay signal anywhere.
146    /// This is D4: upstream computes this and then never applies it.
147    #[test]
148    fn heavy_loss_lowers_the_target_on_its_own() {
149        let epoch = Instant::now();
150        let mut controller = controller();
151        let before = controller.target();
152
153        let mut at = epoch;
154        for _ in 0..10 {
155            at += DEFAULT_LOSS_INTERVAL;
156            controller.update(at, 20, 100);
157        }
158
159        assert!(
160            controller.target() < before,
161            "20% loss must lower the target: {before} → {}",
162            controller.target()
163        );
164    }
165
166    /// A healthy path climbs.
167    #[test]
168    fn a_clean_path_raises_the_target() {
169        let epoch = Instant::now();
170        let mut controller = controller();
171        let before = controller.target();
172
173        let mut at = epoch;
174        for _ in 0..10 {
175            at += DEFAULT_LOSS_INTERVAL;
176            controller.update(at, 0, 100);
177        }
178
179        assert!(
180            controller.target() > before,
181            "a lossless path should be probed: {before} → {}",
182            controller.target()
183        );
184    }
185
186    /// The band between the thresholds is where nothing happens. A few per cent loss is normal on a
187    /// wireless link, and reacting to it would give up capacity for good.
188    #[test]
189    fn moderate_loss_changes_nothing() {
190        let epoch = Instant::now();
191        let mut controller = controller();
192        let before = controller.target();
193
194        let mut at = epoch;
195        for _ in 0..20 {
196            at += DEFAULT_LOSS_INTERVAL;
197            // 5%: above the 2% floor, below the 10% ceiling.
198            controller.update(at, 5, 100);
199        }
200
201        assert_eq!(
202            before,
203            controller.target(),
204            "loss inside the band must not move the target"
205        );
206    }
207
208    /// Worse loss backs off harder — the reaction is proportional, not a fixed step.
209    #[test]
210    fn the_backoff_is_proportional_to_the_loss() {
211        let epoch = Instant::now();
212        let mut mild = controller();
213        let mut severe = controller();
214
215        let mut at = epoch;
216        for _ in 0..5 {
217            at += DEFAULT_LOSS_INTERVAL;
218            mild.update(at, 12, 100);
219            severe.update(at, 50, 100);
220        }
221
222        assert!(
223            severe.target() < mild.target(),
224            "50% loss should back off further than 12%: {} vs {}",
225            severe.target(),
226            mild.target()
227        );
228    }
229
230    /// Empty feedback says nothing, and must not be read as a perfect path.
231    #[test]
232    fn empty_feedback_changes_nothing() {
233        let epoch = Instant::now();
234        let mut controller = controller();
235        let before = controller.target();
236
237        assert_eq!(before, controller.update(epoch, 0, 0));
238        assert_eq!(None, controller.average_loss());
239    }
240
241    /// One clamp, from configuration (D3). Upstream clamps this controller to a hard-coded
242    /// 100 kb/s–100 Mb/s that ignores the configured range entirely.
243    #[test]
244    fn the_target_stays_within_configured_bounds() {
245        let epoch = Instant::now();
246        let mut controller = LossController::new(MIN, MIN, 400_000.0);
247
248        let mut at = epoch;
249        for _ in 0..500 {
250            at += DEFAULT_LOSS_INTERVAL;
251            controller.update(at, 0, 100);
252        }
253        assert!(
254            controller.target() <= 400_000.0,
255            "ceiling breached: {}",
256            controller.target()
257        );
258
259        for _ in 0..500 {
260            at += DEFAULT_LOSS_INTERVAL;
261            controller.update(at, 90, 100);
262        }
263        assert!(
264            controller.target() >= MIN,
265            "floor breached: {}",
266            controller.target()
267        );
268    }
269}