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