Skip to main content

rtci_interceptor/cc/
probe.rs

1//! Bandwidth probing: short bursts above the target rate, and the capacity their arrival shows.
2//!
3//! A delay-based controller finds out that a path has room only by using it, and climbs a few
4//! percent a second (8% in `Gcc`): from 300 kbit/s to 2.5 Mbit/s takes most of half a minute.
5//! A probe asks the question directly. A cluster of packets leaves at a multiple of the target
6//! for some milliseconds; if the receiver reports them arriving as closely spaced as they left,
7//! the path carries that rate and the estimate moves there at once.
8//!
9//! RFC 8836 section 2 asks that a congestion controller "adapt as quickly as possible to
10//! initial network conditions" and "allow for different modes of adaptation", naming "probing
11//! during setup" as one (requirement 4, both SHOULD); draft-ietf-rmcat-gcc-02 has no probing at
12//! all. It is what libwebrtc does, in outline. The peer connection's default interceptor set
13//! probes (a SHOULD is met by default); `DefaultInterceptorOptions::bandwidth_probing` turns it
14//! off, and a chain built by hand probes only with
15//! [`CongestionControlBuilder::with_bandwidth_probing`](crate::CongestionControlBuilder::with_bandwidth_probing).
16//!
17//! The parts:
18//!
19//! - [`ProbeController`] decides when a cluster is sent and at what rate: two at the start
20//!   (three and six times the starting rate), a further one at twice the result while results
21//!   keep confirming the rate probed, and one every few seconds while the application sends
22//!   less than the target allows, when nothing else would show that the path has grown; and,
23//!   for a few seconds after the target dropped by a third or more, the rate before the drop.
24//! - [`ProbeRequest`] is what travels through the chain: the congestion controller announces
25//!   it on the read leg, the pacer releases the next packets at its rate and marks them
26//!   ([`ProbePacket`]), and the NACK responder fills the cluster with padding-only packets on
27//!   the RTX stream when the application's own media is not enough: they carry no media, so a
28//!   receiver never has a packet twice.
29//! - [`probe_estimate`] turns the receiver's reports on a cluster into a bit rate.
30
31use crate::rtpfb::acknowledgement::PacketReport;
32use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
33use shared::TransportContext;
34use std::sync::Arc;
35use std::time::{Duration, Instant};
36
37/// How long a cluster lasts at its rate, at least.
38pub const PROBE_MIN_DURATION: Duration = Duration::from_millis(15);
39/// How many packets a cluster has, at least.
40pub const PROBE_MIN_PACKETS: usize = 5;
41/// The size a probe packet is taken to have when a cluster is sized.
42const PROBE_PACKET_OCTETS: usize = 1200;
43/// The most a cluster asks for, whatever its rate.
44pub const PROBE_MAX_OCTETS: usize = 64_000;
45/// The clusters at the start, as multiples of the starting rate.
46const INITIAL_PROBES: [f64; 2] = [3.0, 6.0];
47/// The next cluster after a result, as a multiple of it.
48const FURTHER_PROBE: f64 = 2.0;
49/// A result confirms the rate probed when it reaches this share of it: the path was not the
50/// limit, and probing goes on.
51const FURTHER_PROBE_THRESHOLD: f64 = 0.7;
52/// How often a cluster is sent while the application sends less than the target.
53pub const PROBE_APPLICATION_LIMITED_INTERVAL: Duration = Duration::from_secs(5);
54/// The share of the target below which the sender counts as application limited.
55const APPLICATION_LIMITED_SHARE: f64 = 0.65;
56/// How long a cluster's reports are waited for before it is given up.
57pub const PROBE_RESULT_TIMEOUT: Duration = Duration::from_secs(1);
58/// The least time between two clusters.
59const PROBE_SPACING: Duration = Duration::from_millis(100);
60/// The target falling below this share of its recent high is a large drop.
61const LARGE_DROP_SHARE: f64 = 0.66;
62/// How long the recent high of the target is remembered for drop detection.
63const LARGE_DROP_WINDOW: Duration = Duration::from_secs(2);
64/// How long after a large drop the old rate is probed for.
65pub const PROBE_AFTER_DROP_TIMEOUT: Duration = Duration::from_secs(5);
66/// The first probe after a large drop waits this long: the back-off has to take effect.
67const PROBE_AFTER_DROP_DELAY: Duration = Duration::from_secs(1);
68/// And they are this far apart.
69const PROBE_AFTER_DROP_INTERVAL: Duration = Duration::from_secs(1);
70/// A probe after a drop asks for this share of the rate before it.
71const PROBE_AFTER_DROP_SHARE: f64 = 0.85;
72
73/// A probe cluster the congestion controller asks for.
74///
75/// Carried as an [`Attribute::Custom`] on an empty RTCP packet on the read leg
76/// ([`ProbeRequest::into_packet`]), from the congestion controller towards the application:
77/// the pacer and the NACK responder read it on its way past.
78#[derive(Debug, Clone, Copy, PartialEq)]
79pub struct ProbeRequest {
80    /// Which cluster this is; the packets sent for it carry the same number.
81    pub cluster: u32,
82    /// The rate the cluster leaves at, bits per second.
83    pub bits_per_second: f64,
84    /// How much the cluster holds, octets on the wire.
85    pub octets: usize,
86}
87
88impl ProbeRequest {
89    /// The packet that carries this application-ward from where it is read at `now`.
90    pub fn into_packet(self, now: Instant) -> TaggedPacket {
91        TaggedPacket {
92            now,
93            transport: TransportContext::default(),
94            message: AttributedPacket::new(Packet::Rtcp(vec![]))
95                .with(Attribute::Custom(Arc::new(self))),
96        }
97    }
98}
99
100/// The mark of an RTP packet the pacer released as part of a probe cluster, as an
101/// [`Attribute::Custom`] on its way to the wire.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct ProbePacket {
104    /// The cluster it belongs to.
105    pub cluster: u32,
106}
107
108/// How much a cluster at `bits_per_second` holds.
109pub(crate) fn cluster_octets(bits_per_second: f64) -> usize {
110    let by_duration = (bits_per_second * PROBE_MIN_DURATION.as_secs_f64() / 8.0) as usize;
111    by_duration.clamp(PROBE_MIN_PACKETS * PROBE_PACKET_OCTETS, PROBE_MAX_OCTETS)
112}
113
114/// The bit rate a path showed it carries, from the reports on the packets of one cluster.
115///
116/// The cluster left at the send rate and arrived at the receive rate; the path carries the
117/// lower of the two. The send rate is taken over all but the last packet and the span from
118/// the first departure to the last, the receive rate over all but the first packet and the
119/// span of the arrivals, so that each is octets over the time they took. When the packets
120/// arrived more than a tenth slower than they left, the bottleneck was reached and held them
121/// apart: the estimate is 95% of the receive rate, to stay below it.
122///
123/// `None` when fewer than four packets of the cluster arrived with a time, or their times do
124/// not span anything: too little to measure.
125pub fn probe_estimate(reports: &[PacketReport]) -> Option<f64> {
126    let arrived: Vec<(Instant, Duration, usize)> = reports
127        .iter()
128        .filter(|report| report.arrived)
129        .filter_map(|report| Some((report.departure, report.arrival?, report.size)))
130        .collect();
131    if arrived.len() < 4 {
132        return None;
133    }
134    let total: usize = arrived.iter().map(|(_, _, size)| size).sum();
135
136    let (first_sent, last_sent) =
137        arrived
138            .iter()
139            .fold(None, |span: Option<(Instant, Instant)>, (sent, _, _)| {
140                Some(span.map_or((*sent, *sent), |(first, last)| {
141                    (first.min(*sent), last.max(*sent))
142                }))
143            })?;
144    let last_sent_size = arrived
145        .iter()
146        .filter(|(sent, _, _)| *sent == last_sent)
147        .map(|(_, _, size)| *size)
148        .next_back()?;
149    let (first_arrival, last_arrival) =
150        arrived
151            .iter()
152            .fold(None, |span: Option<(Duration, Duration)>, (_, at, _)| {
153                Some(span.map_or((*at, *at), |(first, last)| (first.min(*at), last.max(*at))))
154            })?;
155    let first_arrival_size = arrived
156        .iter()
157        .find(|(_, at, _)| *at == first_arrival)
158        .map(|(_, _, size)| *size)?;
159
160    let send_span = last_sent
161        .saturating_duration_since(first_sent)
162        .as_secs_f64();
163    let receive_span = last_arrival.saturating_sub(first_arrival).as_secs_f64();
164    if receive_span <= 0.0 {
165        return None;
166    }
167    let receive_rate = (total - first_arrival_size) as f64 * 8.0 / receive_span;
168    // Packets that left in the same instant have no send rate to compare with: the arrivals
169    // alone say what the path did with them.
170    if send_span <= 0.0 {
171        return Some(receive_rate * 0.95);
172    }
173    let send_rate = (total - last_sent_size) as f64 * 8.0 / send_span;
174    if receive_rate < 0.9 * send_rate {
175        Some(receive_rate * 0.95)
176    } else {
177        Some(send_rate.min(receive_rate))
178    }
179}
180
181/// Decides when a probe cluster is sent and at what rate.
182#[derive(Debug)]
183pub struct ProbeController {
184    next_cluster: u32,
185    /// Rates still to probe from the start-up sequence.
186    initial: Vec<f64>,
187    started: bool,
188    /// The cluster awaiting its result: its number, its rate and when it was asked for.
189    outstanding: Option<(u32, f64, Instant)>,
190    last_probe: Option<Instant>,
191    /// A further cluster owed after a result that confirmed its rate.
192    further: Option<f64>,
193    max_bitrate: f64,
194    /// Whether the rate before a large drop is probed for (see
195    /// [`with_probe_after_drop`](Self::with_probe_after_drop)).
196    after_drop: bool,
197    /// The highest target of the last [`LARGE_DROP_WINDOW`], and when it was.
198    peak: Option<(f64, Instant)>,
199    /// The last large drop: the target before it, and when it happened.
200    drop: Option<(f64, Instant)>,
201    /// Whether the outstanding cluster probes for the rate before a drop.
202    drop_probe: bool,
203    /// When [`poll`](Self::poll) was last called.
204    polled_at: Option<Instant>,
205}
206
207impl ProbeController {
208    /// A controller for an estimator that starts at `initial_bitrate` and never goes above
209    /// `max_bitrate`.
210    pub fn new(initial_bitrate: f64, max_bitrate: f64) -> Self {
211        Self {
212            next_cluster: 1,
213            initial: INITIAL_PROBES
214                .iter()
215                .rev()
216                .map(|multiple| initial_bitrate * multiple)
217                .collect(),
218            started: false,
219            outstanding: None,
220            last_probe: None,
221            further: None,
222            max_bitrate,
223            after_drop: true,
224            peak: None,
225            drop: None,
226            drop_probe: false,
227            polled_at: None,
228        }
229    }
230
231    /// Whether the rate the target had before a large drop is probed for, for a few seconds
232    /// after it (the default), as libwebrtc's `ProbeController::RequestProbe` does.
233    ///
234    /// A short burst of competing traffic, or a moment of loss, makes the delay-based
235    /// controller back off by a third or more; once it has passed, the climb back is the
236    /// controller's additive increase near the old operating point, half a packet per
237    /// response time, and takes tens of seconds (23 s after a 2 s burst at half the capacity,
238    /// in `rtci-interceptor/tests/rfc8836_multi_flow.rs`), against RFC 8836 section 2
239    /// (requirement 1f: the flow "regains its share quickly"). With this, a drop of the
240    /// target below two thirds of its high of the last two seconds is followed, from a second
241    /// on and once a second for five seconds, by a cluster at 85% of the rate before the drop
242    /// while the target is still below that. A result above the target raises it (as every
243    /// probe does); one below it changes nothing: the competing traffic is still there.
244    pub fn with_probe_after_drop(mut self, enabled: bool) -> Self {
245        self.after_drop = enabled;
246        self
247    }
248
249    /// The ceiling of what is probed for: the estimator's own maximum, or a limit from
250    /// outside it (REMB, TMMBR, the session bit rate).
251    pub fn set_max_bitrate(&mut self, max_bitrate: f64) {
252        self.max_bitrate = max_bitrate;
253    }
254
255    /// The cluster to send now, if one is due.
256    ///
257    /// `target` is the current target bit rate and `sending` the rate the application is
258    /// sending at; `media_flowing` is whether a packet has left yet (a probe before the
259    /// first one would measure nothing the receiver reports).
260    pub fn poll(
261        &mut self,
262        now: Instant,
263        target: f64,
264        sending: f64,
265        media_flowing: bool,
266    ) -> Option<ProbeRequest> {
267        self.polled_at = Some(now);
268        if !media_flowing {
269            return None;
270        }
271        if self.after_drop {
272            self.track_drops(now, target);
273        }
274        if let Some((_, _, asked)) = self.outstanding {
275            if now.saturating_duration_since(asked) < PROBE_RESULT_TIMEOUT {
276                return None;
277            }
278            // Its reports never came: the cluster is given up, and with it the sequence it
279            // was part of.
280            self.outstanding = None;
281            self.further = None;
282            self.drop_probe = false;
283        }
284        if self
285            .last_probe
286            .is_some_and(|last| now.saturating_duration_since(last) < PROBE_SPACING)
287        {
288            return None;
289        }
290
291        self.started = true;
292        let rate = if let Some(rate) = self.initial.pop() {
293            Some(rate)
294        } else if let Some(rate) = self.further.take() {
295            Some(rate)
296        } else if let Some((before, at)) = self.drop
297            && now.saturating_duration_since(at) >= PROBE_AFTER_DROP_DELAY
298            && target < PROBE_AFTER_DROP_SHARE * before
299            && self
300                .last_probe
301                .is_none_or(|last| now.saturating_duration_since(last) >= PROBE_AFTER_DROP_INTERVAL)
302        {
303            // The rate before a large drop, while the drop is recent: if what caused it has
304            // gone, the path carries it again.
305            self.drop_probe = true;
306            Some(PROBE_AFTER_DROP_SHARE * before)
307        } else if sending < APPLICATION_LIMITED_SHARE * target
308            && self.last_probe.is_none_or(|last| {
309                now.saturating_duration_since(last) >= PROBE_APPLICATION_LIMITED_INTERVAL
310            })
311        {
312            // Sending less than the target allows, the delay-based controller learns nothing
313            // about the room above what is sent.
314            Some(target * FURTHER_PROBE)
315        } else {
316            None
317        }?;
318
319        let rate = rate.min(self.max_bitrate);
320        if rate <= target {
321            // Nothing above the target is allowed, so there is nothing to ask.
322            self.drop_probe = false;
323            return None;
324        }
325        let cluster = self.next_cluster;
326        self.next_cluster = self.next_cluster.wrapping_add(1).max(1);
327        self.outstanding = Some((cluster, rate, now));
328        self.last_probe = Some(now);
329        Some(ProbeRequest {
330            cluster,
331            bits_per_second: rate,
332            octets: cluster_octets(rate),
333        })
334    }
335
336    /// Follows the target's recent high, and notes a large drop below it.
337    fn track_drops(&mut self, now: Instant, target: f64) {
338        match self.peak {
339            Some((peak, at))
340                if target < peak && now.saturating_duration_since(at) <= LARGE_DROP_WINDOW =>
341            {
342                if target < LARGE_DROP_SHARE * peak {
343                    self.drop = Some((peak, now));
344                    self.peak = Some((target, now));
345                }
346            }
347            _ => self.peak = Some((target, now)),
348        }
349        if self
350            .drop
351            .is_some_and(|(_, at)| now.saturating_duration_since(at) > PROBE_AFTER_DROP_TIMEOUT)
352        {
353            self.drop = None;
354        }
355    }
356
357    /// The number of the cluster whose result is awaited.
358    pub fn outstanding(&self) -> Option<u32> {
359        self.outstanding.map(|(cluster, _, _)| cluster)
360    }
361
362    /// The result of `cluster`: `estimate` bits per second. Returns the estimate when it is
363    /// the outstanding cluster's, for the estimator to take.
364    pub fn on_result(&mut self, cluster: u32, estimate: f64) -> Option<f64> {
365        let (outstanding, rate, _) = self.outstanding?;
366        if outstanding != cluster {
367            return None;
368        }
369        self.outstanding = None;
370        // The path carried what was asked of it: it may carry more. Not after a probe for the
371        // rate before a drop: that asks only whether the path is back where it was.
372        let drop_probe = std::mem::take(&mut self.drop_probe);
373        if !drop_probe && estimate >= FURTHER_PROBE_THRESHOLD * rate && self.initial.is_empty() {
374            let next = estimate * FURTHER_PROBE;
375            if next <= self.max_bitrate * FURTHER_PROBE {
376                self.further = Some(next);
377            }
378        }
379        Some(estimate)
380    }
381
382    /// When [`poll`](Self::poll) next has something to say without anything else happening.
383    ///
384    /// Never an instant `poll` has already been called at or after: a deadline that passed
385    /// with nothing to send (no media flowing, a sender that is no longer application
386    /// limited, a target that recovered by itself) waits for the next write instead of
387    /// asking to be woken again at once.
388    pub fn poll_timeout(&self) -> Option<Instant> {
389        self.deadlines()
390            .into_iter()
391            .flatten()
392            .filter(|deadline| self.polled_at.is_none_or(|polled| *deadline > polled))
393            .min()
394    }
395
396    /// The instants something may be due: a result to give up, the next cluster of a
397    /// sequence or of an application-limited sender, the next probe after a drop.
398    fn deadlines(&self) -> [Option<Instant>; 2] {
399        if !self.started {
400            return [None, None];
401        }
402        if let Some((_, _, asked)) = self.outstanding {
403            return [Some(asked + PROBE_RESULT_TIMEOUT), None];
404        }
405        let Some(last) = self.last_probe else {
406            return [None, None];
407        };
408        let next = if !self.initial.is_empty() || self.further.is_some() {
409            last + PROBE_SPACING
410        } else {
411            last + PROBE_APPLICATION_LIMITED_INTERVAL
412        };
413        let after_drop = self
414            .drop
415            .map(|(_, at)| (at + PROBE_AFTER_DROP_DELAY).max(last + PROBE_AFTER_DROP_INTERVAL));
416        [Some(next), after_drop]
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423    use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
424
425    fn report(id: u64, departure: Instant, arrival_us: u64, size: usize) -> PacketReport {
426        PacketReport {
427            ssrc: 1,
428            id,
429            rtp_sequence_number: id as u16,
430            is_twcc: true,
431            twcc_sequence_number: id as u16,
432            size,
433            arrived: true,
434            departure,
435            arrival: Some(Duration::from_micros(arrival_us)),
436            ecn: Ecn::NotEct,
437        }
438    }
439
440    /// Six 1200-octet packets sent 2 ms apart (4.8 Mbit/s) that arrive 2 ms apart: the path
441    /// carried the cluster, and the estimate is the rate it was sent at.
442    #[test]
443    fn a_cluster_that_arrives_as_it_left_shows_its_own_rate() {
444        let epoch = Instant::now();
445        let reports: Vec<PacketReport> = (0..6u64)
446            .map(|i| {
447                report(
448                    i,
449                    epoch + Duration::from_millis(2 * i),
450                    50_000 + 2_000 * i,
451                    1200,
452                )
453            })
454            .collect();
455        let estimate = probe_estimate(&reports).expect("measurable");
456        assert!((estimate - 4_800_000.0).abs() < 1_000.0, "{estimate}");
457    }
458
459    /// The same cluster through a 2.4 Mbit/s bottleneck arrives 4 ms apart: the estimate is
460    /// 95% of the rate it arrived at, not the rate it was sent at.
461    #[test]
462    fn a_cluster_spread_out_by_the_bottleneck_shows_the_bottleneck() {
463        let epoch = Instant::now();
464        let reports: Vec<PacketReport> = (0..6u64)
465            .map(|i| {
466                report(
467                    i,
468                    epoch + Duration::from_millis(2 * i),
469                    50_000 + 4_000 * i,
470                    1200,
471                )
472            })
473            .collect();
474        let estimate = probe_estimate(&reports).expect("measurable");
475        assert!(
476            (estimate - 0.95 * 2_400_000.0).abs() < 1_000.0,
477            "{estimate}"
478        );
479    }
480
481    /// Three arrivals are not a measurement, and neither are packets without arrival times.
482    #[test]
483    fn too_few_arrivals_give_no_estimate() {
484        let epoch = Instant::now();
485        let mut reports: Vec<PacketReport> = (0..3u64)
486            .map(|i| {
487                report(
488                    i,
489                    epoch + Duration::from_millis(2 * i),
490                    50_000 + 2_000 * i,
491                    1200,
492                )
493            })
494            .collect();
495        assert_eq!(None, probe_estimate(&reports));
496        let mut lost = report(3, epoch + Duration::from_millis(6), 0, 1200);
497        lost.arrived = false;
498        lost.arrival = None;
499        reports.push(lost);
500        assert_eq!(None, probe_estimate(&reports));
501    }
502
503    /// At the start: three times the starting rate, then six times, each once its predecessor
504    /// has a result, and nothing before media flows.
505    #[test]
506    fn the_start_probes_at_three_and_six_times_the_starting_rate() {
507        let epoch = Instant::now();
508        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
509        assert_eq!(None, controller.poll(epoch, 300_000.0, 0.0, false));
510
511        let first = controller
512            .poll(epoch, 300_000.0, 300_000.0, true)
513            .expect("first cluster");
514        assert_eq!(900_000.0, first.bits_per_second);
515        assert_eq!(
516            PROBE_MIN_PACKETS * PROBE_PACKET_OCTETS,
517            first.octets,
518            "five packets at least"
519        );
520        assert_eq!(
521            None,
522            controller.poll(
523                epoch + Duration::from_millis(200),
524                300_000.0,
525                300_000.0,
526                true
527            ),
528            "one cluster at a time"
529        );
530
531        assert_eq!(
532            Some(900_000.0),
533            controller.on_result(first.cluster, 900_000.0)
534        );
535        let second = controller
536            .poll(
537                epoch + Duration::from_millis(200),
538                900_000.0,
539                300_000.0,
540                true,
541            )
542            .expect("second cluster");
543        assert_eq!(1_800_000.0, second.bits_per_second);
544    }
545
546    /// A result that confirms the rate probed is followed by a cluster at twice the result; one
547    /// that shows the bottleneck is not.
548    #[test]
549    fn probing_goes_on_while_the_path_carries_what_is_asked() {
550        let epoch = Instant::now();
551        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
552        let mut now = epoch;
553        let mut target = 300_000.0;
554        let mut asked = Vec::new();
555        // The path carries 2.5 Mbit/s.
556        for _ in 0..8 {
557            if let Some(request) = controller.poll(now, target, target, true) {
558                asked.push(request.bits_per_second);
559                let estimate = request.bits_per_second.min(2_500_000.0 * 0.95);
560                target = controller
561                    .on_result(request.cluster, estimate)
562                    .expect("the outstanding cluster");
563            }
564            now += Duration::from_millis(150);
565        }
566        assert_eq!(
567            vec![900_000.0, 1_800_000.0, 3_600_000.0],
568            asked,
569            "the third cluster found the bottleneck (2.375 of 3.6 Mbit/s) and ended the sequence"
570        );
571        assert_eq!(2_375_000.0, target);
572    }
573
574    /// While the application sends less than the target allows, a cluster goes out every five
575    /// seconds; at the target, none.
576    #[test]
577    fn an_application_limited_sender_probes_every_few_seconds() {
578        let epoch = Instant::now();
579        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
580        // The start-up sequence, answered with the bottleneck at once.
581        for at in [epoch, epoch + Duration::from_millis(150)] {
582            let request = controller
583                .poll(at, 300_000.0, 300_000.0, true)
584                .expect("start-up cluster");
585            controller.on_result(request.cluster, 500_000.0);
586        }
587
588        let later = epoch + Duration::from_secs(6);
589        assert_eq!(
590            None,
591            controller.poll(later, 1_000_000.0, 1_000_000.0, true),
592            "sending at the target: the delay-based controller is asking already"
593        );
594        let request = controller
595            .poll(later, 1_000_000.0, 200_000.0, true)
596            .expect("application limited");
597        assert_eq!(2_000_000.0, request.bits_per_second);
598        controller.on_result(request.cluster, 1_200_000.0);
599        assert_eq!(
600            None,
601            controller.poll(later + Duration::from_secs(1), 1_000_000.0, 200_000.0, true),
602            "not again within five seconds"
603        );
604    }
605
606    /// Nothing is probed above the ceiling, and a cluster whose reports never come is given up.
607    #[test]
608    fn the_ceiling_and_the_timeout_end_a_probe() {
609        let epoch = Instant::now();
610        let mut controller = ProbeController::new(300_000.0, 600_000.0);
611        let request = controller
612            .poll(epoch, 300_000.0, 300_000.0, true)
613            .expect("capped cluster");
614        assert_eq!(600_000.0, request.bits_per_second);
615        assert_eq!(Some(request.cluster), controller.outstanding());
616        assert_eq!(
617            Some(epoch + PROBE_RESULT_TIMEOUT),
618            controller.poll_timeout()
619        );
620
621        let after = epoch + PROBE_RESULT_TIMEOUT;
622        // Given up; the next of the start-up sequence is capped at the ceiling too, which the
623        // target has reached by then.
624        assert_eq!(None, controller.poll(after, 600_000.0, 600_000.0, true));
625        assert_eq!(None, controller.outstanding());
626    }
627
628    /// Settles a controller after its start-up sequence: two clusters answered at the
629    /// bottleneck, so no further cluster is owed.
630    fn settled(epoch: Instant) -> ProbeController {
631        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
632        for at in [epoch, epoch + Duration::from_millis(150)] {
633            let request = controller
634                .poll(at, 300_000.0, 300_000.0, true)
635                .expect("start-up cluster");
636            controller.on_result(request.cluster, 500_000.0);
637        }
638        controller
639    }
640
641    /// RFC 8836 section 2 (1f): after a large drop of the target (a burst of competing
642    /// traffic), the rate before it is probed for, from a second after the drop and once a
643    /// second, and a result never asks for a further cluster above it.
644    #[test]
645    fn a_large_drop_is_followed_by_a_probe_at_the_rate_before_it() {
646        let epoch = Instant::now();
647        let mut controller = settled(epoch);
648        let at = |ms: u64| epoch + Duration::from_millis(ms);
649        // At 2 Mbit/s, sending at the target, for a while.
650        for ms in (1_000..2_000).step_by(100) {
651            assert_eq!(
652                None,
653                controller.poll(at(ms), 2_000_000.0, 2_000_000.0, true)
654            );
655        }
656        // Down to 900 kbit/s: a drop of more than a third.
657        assert_eq!(None, controller.poll(at(2_000), 900_000.0, 900_000.0, true));
658        assert_eq!(
659            None,
660            controller.poll(at(2_500), 900_000.0, 900_000.0, true),
661            "the back-off is given a second first"
662        );
663        assert_eq!(Some(at(3_000)), controller.poll_timeout());
664        let request = controller
665            .poll(at(3_000), 900_000.0, 900_000.0, true)
666            .expect("the rate before the drop");
667        assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
668        // The path carries it again: the estimator takes it, and nothing above it is asked.
669        assert_eq!(
670            Some(1_700_000.0),
671            controller.on_result(request.cluster, 1_700_000.0)
672        );
673        assert_eq!(
674            None,
675            controller.poll(at(3_200), 1_700_000.0, 1_700_000.0, true)
676        );
677        assert_eq!(
678            None,
679            controller.poll(at(4_500), 1_700_000.0, 1_700_000.0, true)
680        );
681    }
682
683    /// While the competing traffic is still there the probe shows less than the rate before
684    /// the drop: it is asked again a second later, and not after the drop is five seconds old.
685    #[test]
686    fn probes_after_a_drop_stop_after_a_few_seconds() {
687        let epoch = Instant::now();
688        let mut controller = settled(epoch);
689        let at = |ms: u64| epoch + Duration::from_millis(ms);
690        assert_eq!(
691            None,
692            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
693        );
694        assert_eq!(None, controller.poll(at(1_100), 900_000.0, 900_000.0, true));
695        let mut probes = 0;
696        for ms in (1_200..9_000).step_by(100) {
697            if let Some(request) = controller.poll(at(ms), 900_000.0, 900_000.0, true) {
698                probes += 1;
699                assert!(ms <= 1_100 + 5_000, "at {ms} ms");
700                controller.on_result(request.cluster, 950_000.0);
701            }
702        }
703        assert!((3..=5).contains(&probes), "{probes} probes");
704    }
705
706    /// `with_probe_after_drop(false)`: a drop is left to the delay-based controller's climb.
707    #[test]
708    fn without_the_option_a_drop_is_not_probed() {
709        let epoch = Instant::now();
710        let mut controller = settled(epoch).with_probe_after_drop(false);
711        let at = |ms: u64| epoch + Duration::from_millis(ms);
712        assert_eq!(
713            None,
714            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
715        );
716        for ms in (1_100..8_000).step_by(100) {
717            assert_eq!(None, controller.poll(at(ms), 900_000.0, 900_000.0, true));
718        }
719    }
720
721    /// A deadline that came with nothing to send (here: an application-limited probe falls due
722    /// while the sender has caught up with its target) is not asked for again: a driver that
723    /// sleeps until `poll_timeout` would otherwise be woken at once, over and over.
724    #[test]
725    fn a_deadline_that_passed_with_nothing_due_is_not_asked_again() {
726        let epoch = Instant::now();
727        let mut controller = settled(epoch);
728        let due = controller
729            .poll_timeout()
730            .expect("the next application-limited probe");
731        assert_eq!(None, controller.poll(due, 1_000_000.0, 1_000_000.0, true));
732        assert!(
733            controller.poll_timeout().is_none_or(|next| next > due),
734            "{:?}",
735            controller.poll_timeout()
736        );
737        // Not flowing at all: nothing to wake for either.
738        let later = due + Duration::from_secs(10);
739        assert_eq!(None, controller.poll(later, 1_000_000.0, 0.0, false));
740        assert!(controller.poll_timeout().is_none_or(|next| next > later));
741    }
742}