Skip to main content

rtci_interceptor/gcc/
threshold.rs

1//! The adaptive threshold the delay trend is compared against.
2
3use std::time::{Duration, Instant};
4
5/// Starting threshold, in milliseconds — draft-ietf-rmcat-gcc-02 §5.4.
6pub const DEFAULT_INITIAL_MS: f64 = 12.5;
7
8/// Which time step the threshold adaptation of draft-ietf-rmcat-gcc-02 section 5.4 takes,
9/// `del_var_th(i) = del_var_th(i-1) + (t(i)-t(i-1)) * K(i) * (|m(i)| - del_var_th(i-1))`.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum ThresholdTimeBase {
12    /// The draft's, the default: t(i) is the arrival time of group i on the receiver's clock
13    /// (section 5.3), the step not capped.
14    #[default]
15    Arrival,
16    /// The engine's default until 0.1.0, a named setting since: the gap between the times the
17    /// groups' readings are taken on the sender's clock, capped at 100 ms. Measured against
18    /// the draft's on `rtci-interceptor/tests/rfc8836_multi_flow.rs`: two flows queue 18.5 ms
19    /// mean / 93.2 ms p95 against 2.9 / 11.0 ms; beside a TCP-like transfer with a 0.2 s buffer
20    /// it keeps a share of 0.22 against 0.14 (0.25 against 0.33 with a 0.05 s buffer).
21    Departure,
22    /// libwebrtc's: the gap between the groups' arrival times on the receiver's clock, as the
23    /// draft's, capped at 100 ms (`TrendlineEstimator::UpdateThreshold`,
24    /// `modules/congestion_controller/goog_cc/trendline_estimator.cc`: `now_ms` is the
25    /// packet's `receive_time`, `kMaxTimeDeltaMs` 100).
26    ArrivalCapped,
27}
28
29/// The longest time step a capped threshold adaptation takes.
30pub(crate) const MAX_STEP: Duration = Duration::from_millis(100);
31
32/// A threshold that follows the trend it is judging.
33///
34/// # Why it adapts
35///
36/// A fixed threshold cannot work on both a datacentre path and a mobile one: set low enough to
37/// detect congestion on a link with microseconds of jitter, it fires constantly on a link with
38/// tens of milliseconds of it. Worse, a fixed threshold is what lets a GCC flow be starved by a
39/// concurrent loss-based flow — the queue grows past the fixed point, GCC backs off, the other flow
40/// takes the space, and GCC never comes back.
41///
42/// So the threshold rises when the trend is outside it and falls when the trend is inside, slowly,
43/// and at different rates: `K_u` (moving away) is larger than `K_d` (moving back), so it yields
44/// quickly to a genuine overuse and returns to sensitivity only gradually.
45#[derive(Debug, Clone, Copy)]
46pub struct AdaptiveThreshold {
47    /// Current threshold, in milliseconds. Compared against `|estimate|`.
48    value_ms: f64,
49    /// Gain when the estimate is outside the threshold.
50    increase_gain: f64,
51    /// Gain when the estimate is inside it.
52    decrease_gain: f64,
53    /// When it was last updated, for the time-scaled adaptation.
54    last_update: Option<Instant>,
55}
56
57impl Default for AdaptiveThreshold {
58    fn default() -> Self {
59        Self {
60            value_ms: DEFAULT_INITIAL_MS,
61            increase_gain: 0.01,
62            decrease_gain: 0.00018,
63            last_update: None,
64        }
65    }
66}
67
68impl AdaptiveThreshold {
69    /// A threshold at the draft's starting value.
70    pub fn new() -> Self {
71        Self::default()
72    }
73
74    /// The current threshold, in milliseconds.
75    pub fn value_ms(&self) -> f64 {
76        self.value_ms
77    }
78
79    /// Move the threshold towards `estimate_ms`, given how long since the last update.
80    ///
81    /// Returns the updated threshold. `now` is a parameter rather than read from a clock: upstream
82    /// reads `time.Now()` here, which is why its own threshold tests cannot pin a trajectory.
83    pub fn update(&mut self, now: Instant, estimate_ms: f64) -> f64 {
84        let elapsed = match self.last_update {
85            Some(last) => now.saturating_duration_since(last),
86            None => {
87                self.last_update = Some(now);
88                return self.value_ms;
89            }
90        };
91        self.last_update = Some(now);
92        self.adapt(elapsed.min(MAX_STEP), estimate_ms)
93    }
94
95    /// Moves the threshold towards `estimate_ms` over a time step of `elapsed` (t(i) - t(i-1)
96    /// of the draft), uncapped. Returns the updated threshold.
97    pub fn update_over(&mut self, elapsed: Duration, estimate_ms: f64) -> f64 {
98        self.adapt(elapsed, estimate_ms)
99    }
100
101    fn adapt(&mut self, elapsed: Duration, estimate_ms: f64) -> f64 {
102        let magnitude = estimate_ms.abs();
103
104        // A wild sample is not evidence about where the threshold belongs; it is evidence that
105        // something transient happened. Letting it drag the threshold up would blind the detector
106        // to the sustained growth that follows.
107        if magnitude > self.value_ms + 15.0 {
108            return self.value_ms;
109        }
110
111        let gain = if magnitude > self.value_ms {
112            self.increase_gain
113        } else {
114            self.decrease_gain
115        };
116
117        // Time-scaled. The clamp below bounds what a long step can do.
118        let elapsed_ms = elapsed.as_secs_f64() * 1_000.0;
119        let step = gain * (magnitude - self.value_ms) * elapsed_ms;
120        self.value_ms = (self.value_ms + step).clamp(6.0, 600.0);
121
122        self.value_ms
123    }
124
125    /// How long since this threshold was last updated, if ever.
126    pub fn since_update(&self, now: Instant) -> Option<Duration> {
127        self.last_update
128            .map(|last| now.saturating_duration_since(last))
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn it_starts_at_the_drafts_value() {
138        assert_eq!(DEFAULT_INITIAL_MS, AdaptiveThreshold::new().value_ms());
139    }
140
141    /// A trend that stays outside pushes the threshold **up**, so a persistently jittery path stops
142    /// being read as persistently congested.
143    #[test]
144    fn a_trend_outside_the_threshold_raises_it() {
145        let epoch = Instant::now();
146        let mut threshold = AdaptiveThreshold::new();
147        threshold.update(epoch, 20.0);
148
149        for step in 1..=50u64 {
150            threshold.update(epoch + Duration::from_millis(step * 20), 20.0);
151        }
152
153        assert!(
154            threshold.value_ms() > DEFAULT_INITIAL_MS,
155            "threshold should have risen, got {}",
156            threshold.value_ms()
157        );
158    }
159
160    /// A trend inside brings it back **down**, so sensitivity returns once the path settles.
161    #[test]
162    fn a_trend_inside_the_threshold_lowers_it() {
163        let epoch = Instant::now();
164        let mut threshold = AdaptiveThreshold::new();
165        threshold.update(epoch, 0.0);
166
167        for step in 1..=500u64 {
168            threshold.update(epoch + Duration::from_millis(step * 20), 0.0);
169        }
170
171        assert!(
172            threshold.value_ms() < DEFAULT_INITIAL_MS,
173            "threshold should have fallen, got {}",
174            threshold.value_ms()
175        );
176    }
177
178    /// Up faster than down: the threshold yields quickly to overuse and returns to sensitivity
179    /// slowly. Symmetric gains would make it oscillate with the very signal it is judging.
180    #[test]
181    fn it_rises_faster_than_it_falls() {
182        let epoch = Instant::now();
183
184        let mut rising = AdaptiveThreshold::new();
185        rising.update(epoch, 25.0);
186        let mut falling = AdaptiveThreshold::new();
187        falling.update(epoch, 0.0);
188
189        for step in 1..=25u64 {
190            let at = epoch + Duration::from_millis(step * 20);
191            rising.update(at, 25.0);
192            falling.update(at, 0.0);
193        }
194
195        let rose = rising.value_ms() - DEFAULT_INITIAL_MS;
196        let fell = DEFAULT_INITIAL_MS - falling.value_ms();
197        assert!(
198            rose > fell,
199            "K_u must exceed K_d: rose by {rose}, fell by {fell}"
200        );
201    }
202
203    /// A single wild sample is transient, not evidence. Letting it drag the threshold up would
204    /// blind the detector to sustained growth immediately afterwards.
205    #[test]
206    fn an_outlier_does_not_move_it() {
207        let epoch = Instant::now();
208        let mut threshold = AdaptiveThreshold::new();
209        threshold.update(epoch, 0.0);
210
211        let before = threshold.value_ms();
212        threshold.update(epoch + Duration::from_millis(20), 5_000.0);
213
214        assert_eq!(
215            before,
216            threshold.value_ms(),
217            "an absurd sample must be ignored, not absorbed"
218        );
219    }
220
221    /// Bounded at both ends, so neither a long quiet spell nor a long storm drives it somewhere it
222    /// cannot come back from.
223    #[test]
224    fn it_stays_within_bounds() {
225        let epoch = Instant::now();
226
227        let mut low = AdaptiveThreshold::new();
228        low.update(epoch, 0.0);
229        for step in 1..=100_000u64 {
230            low.update(epoch + Duration::from_millis(step * 20), 0.0);
231        }
232        assert!(low.value_ms() >= 6.0, "floor breached: {}", low.value_ms());
233
234        let mut high = AdaptiveThreshold::new();
235        high.update(epoch, 0.0);
236        for step in 1..=100_000u64 {
237            // Just outside the current threshold each time, so it is never treated as an outlier.
238            let target = high.value_ms() + 1.0;
239            high.update(epoch + Duration::from_millis(step * 20), target);
240        }
241        assert!(
242            high.value_ms() <= 600.0,
243            "ceiling breached: {}",
244            high.value_ms()
245        );
246    }
247}