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//!
31//! In a chain without a pacer nothing releases a cluster at its rate. The NACK responder's
32//! padding is then the cluster: it leaves as one burst with the cluster's mark, and
33//! [`burst_estimate`] reads the rate of the narrowest link from how far apart the burst
34//! arrived, never more than the rate asked for. Where nothing sends a cluster at all (no
35//! pacer and no RTX stream to pad on), the congestion controller stops asking after the first
36//! cluster that no packet left for, until another stream starts to send: a request that can
37//! have no result is not made again.
38
39use crate::rtpfb::acknowledgement::PacketReport;
40use crate::{Attribute, AttributedPacket, Packet, TaggedPacket, Usage};
41use shared::TransportContext;
42use std::sync::Arc;
43use std::time::{Duration, Instant};
44
45/// How long a cluster lasts at its rate, at least.
46pub const PROBE_MIN_DURATION: Duration = Duration::from_millis(15);
47/// How many packets a cluster has, at least.
48pub const PROBE_MIN_PACKETS: usize = 5;
49/// The size a probe packet is taken to have when a cluster is sized.
50const PROBE_PACKET_OCTETS: usize = 1200;
51/// The most a cluster asks for, whatever its rate.
52pub const PROBE_MAX_OCTETS: usize = 64_000;
53/// The clusters at the start, as multiples of the starting rate.
54const INITIAL_PROBES: [f64; 2] = [3.0, 6.0];
55/// The next cluster after a result, as a multiple of it.
56const FURTHER_PROBE: f64 = 2.0;
57/// A result confirms the rate probed when it reaches this share of it: the path was not the
58/// limit, and probing goes on.
59const FURTHER_PROBE_THRESHOLD: f64 = 0.7;
60/// How often a cluster is sent while the application sends less than the target.
61pub const PROBE_APPLICATION_LIMITED_INTERVAL: Duration = Duration::from_secs(5);
62/// The share of the target below which the sender counts as application limited.
63const APPLICATION_LIMITED_SHARE: f64 = 0.65;
64/// How long a cluster's reports are waited for before it is given up.
65pub const PROBE_RESULT_TIMEOUT: Duration = Duration::from_secs(1);
66/// The least time between two clusters.
67const PROBE_SPACING: Duration = Duration::from_millis(100);
68/// The target falling below this share of its recent high is a large drop.
69const LARGE_DROP_SHARE: f64 = 0.66;
70/// How long the recent high of the target is remembered for drop detection.
71const LARGE_DROP_WINDOW: Duration = Duration::from_secs(2);
72/// How long after a large drop the old rate is probed for.
73pub const PROBE_AFTER_DROP_TIMEOUT: Duration = Duration::from_secs(5);
74/// The first probe after a large drop waits this long: the back-off has to take effect.
75const PROBE_AFTER_DROP_DELAY: Duration = Duration::from_secs(1);
76/// And they are this far apart.
77const PROBE_AFTER_DROP_INTERVAL: Duration = Duration::from_secs(1);
78/// A probe after a drop asks for this share of the rate before it.
79const PROBE_AFTER_DROP_SHARE: f64 = 0.85;
80/// How long the rate before a large drop is remembered as the rate the path had, for
81/// recovery probing ([`ProbeController::with_recovery_probing`]): the highest such rate of
82/// this long.
83pub const PROBE_DROP_MEMORY: Duration = Duration::from_secs(60);
84/// How often a recovery cluster is sent while the target is below the remembered rate
85/// ([`ProbeController::with_recovery_probing`]).
86pub const PROBE_RECOVERY_INTERVAL: Duration = Duration::from_secs(5);
87/// [`AfterDropProbe::Libwebrtc`]: how long after the sender stopped being application limited
88/// a drop is still probed (libwebrtc `kAlrEndedTimeout`).
89const ALR_ENDED_TIMEOUT: Duration = Duration::from_secs(3);
90/// [`AfterDropProbe::Libwebrtc`]: the least time between two probes after a drop (libwebrtc
91/// `kMinTimeBetweenAlrProbes`).
92const LIBWEBRTC_DROP_PROBE_INTERVAL: Duration = Duration::from_secs(5);
93/// [`AfterDropProbe::Libwebrtc`]: the probe is asked only when 95% of it is above the
94/// estimate (libwebrtc `kProbeUncertainty`).
95const LIBWEBRTC_PROBE_UNCERTAINTY: f64 = 0.05;
96
97/// What is probed for after a large drop of the target
98/// ([`ProbeController::with_after_drop_probe`]).
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
100pub enum AfterDropProbe {
101    /// The engine's form, and the default. A drop of the target below two thirds of its high
102    /// of the last two seconds is followed, from a second on and once a second for five
103    /// seconds, by a cluster at 85% of that high while the target is still below it, whether
104    /// or not the sender is application limited.
105    ///
106    /// No specification says how to probe after a drop (RFC 8836 section 2, 1f, asks only
107    /// that a flow regain its share quickly), so the default is the form the capacity
108    /// instrument measured best (`tests/capacity_instrument.rs`; the default chain, a
109    /// 2.5 Mbit/s path that drops to 300 kbit/s for 20 s; 1000 calls in each of the two
110    /// reference cells and 200 in six others, each form against this one by the merge-point
111    /// rule of `docs/capacity-instrument.md`). Without a probe ([`Off`](Self::Off)) and with
112    /// libwebrtc's ([`Libwebrtc`](Self::Libwebrtc), which never fires for a sender that
113    /// keeps up with its target, so the two measure alike) seven figures are worse: with
114    /// both directions limited the oldest picture is 3.07 s against 2.64 s, with 5% of the
115    /// feedback lost the rate is not back within 20 s in 30 (24) of 200 calls against 2, and
116    /// the target 15 to 25 s after the limit is 1205 against 1278 kbit/s. Asking for the
117    /// highest rate of the last minute instead of the last drop's own high (the rate before
118    /// the limit, not the peak of the controller's sawtooth under it) makes fifteen figures
119    /// worse (audio packets lost 27 -> 35 a call, behind a 1000 ms queue over 2 s without a
120    /// new picture in 33 of 200 calls against 6) and was not taken. What this form costs
121    /// against no probe: behind a 1000 ms queue 96 audio packets lost a call against 66, and
122    /// under a limit that lasts a minute 74 against 45.
123    #[default]
124    Repeated,
125    /// libwebrtc's form (`ProbeController::RequestProbe`, goog_cc `probe_controller.cc`): a
126    /// drop is one update of the estimate below two thirds of the one before it; one cluster
127    /// at 85% of the estimate before the drop, asked when the delay-based detector has
128    /// returned to normal after the drop ([`ProbeController::set_usage`]: under-use, then
129    /// normal), only while the sender is application limited or was within the last three
130    /// seconds, within five seconds of the drop, at most once in five seconds, and only when
131    /// 95% of that rate is above the estimate.
132    Libwebrtc,
133    /// No probe after a drop: the climb back is the delay-based controller's.
134    Off,
135}
136
137/// A probe cluster the congestion controller asks for.
138///
139/// Carried as an [`Attribute::Custom`] on an empty RTCP packet on the read leg
140/// ([`ProbeRequest::into_packet`]), from the congestion controller towards the application:
141/// the pacer and the NACK responder read it on its way past.
142#[derive(Debug, Clone, Copy, PartialEq)]
143pub struct ProbeRequest {
144    /// Which cluster this is; the packets sent for it carry the same number.
145    pub cluster: u32,
146    /// The rate the cluster leaves at, bits per second.
147    pub bits_per_second: f64,
148    /// How much the cluster holds, octets on the wire.
149    pub octets: usize,
150}
151
152impl ProbeRequest {
153    /// The packet that carries this application-ward from where it is read at `now`.
154    pub fn into_packet(self, now: Instant) -> TaggedPacket {
155        TaggedPacket {
156            now,
157            transport: TransportContext::default(),
158            message: AttributedPacket::new(Packet::Rtcp(vec![]))
159                .with(Attribute::Custom(Arc::new(self))),
160        }
161    }
162}
163
164/// How much padding a probe cluster needs, from the pacer that sends it.
165///
166/// The pacer reads a [`ProbeRequest`] first on its way application-ward and adds this to the
167/// same carrier: the cluster's size less the media and retransmissions already waiting in its
168/// queue, which leave first, at the cluster's rate and with its mark, and so fill the cluster
169/// in place of padding. The NACK responder makes that much padding and no more (none at all
170/// while a backlog waits, as during the pacer's pause): padding made for a cluster that media
171/// fills never leaves in it, and each such packet uses up a sequence number of the RTX stream.
172/// Without a pacer in the chain there is no such attribute and the responder fills the whole
173/// cluster.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct ProbeFill {
176    /// The cluster this is about ([`ProbeRequest::cluster`]).
177    pub cluster: u32,
178    /// The padding wanted, octets on the wire.
179    pub octets: usize,
180}
181
182/// The mark of an RTP packet the pacer released as part of a probe cluster, as an
183/// [`Attribute::Custom`] on its way to the wire.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub struct ProbePacket {
186    /// The cluster it belongs to.
187    pub cluster: u32,
188}
189
190/// A cluster nothing in the chain could carry: the NACK responder had no stream to pad on and
191/// no pacer took the request on its way ([`ProbeFill`] absent), so no packet leaves for it.
192///
193/// The responder writes it wire-ward as an empty RTCP packet ([`ProbeUnsent::into_packet`]),
194/// tagged with the request's RTP session when it had one; the congestion controller takes it
195/// out of the chain and counts the cluster as never asked for
196/// ([`ProbeController::on_unsent`]), instead of waiting [`PROBE_RESULT_TIMEOUT`] for a result
197/// that cannot come and spending the cluster's place in the start-up sequence on it.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub(crate) struct ProbeUnsent {
200    /// The cluster ([`ProbeRequest::cluster`]).
201    pub(crate) cluster: u32,
202}
203
204impl ProbeUnsent {
205    /// The packet that carries this wire-ward from where it is written at `now`.
206    pub(crate) fn into_packet(self, now: Instant, session: Option<usize>) -> TaggedPacket {
207        let mut message =
208            AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(Arc::new(self)));
209        if let Some(session) = session {
210            message.add(crate::RtpSession(session).attribute());
211        }
212        TaggedPacket {
213            now,
214            transport: TransportContext::default(),
215            message,
216        }
217    }
218}
219
220/// What [`ProbeController::poll`] changed in asking for a cluster, to be put back when the
221/// cluster turns out to have left no packet ([`ProbeController::on_unsent`]).
222#[derive(Debug)]
223struct Asked {
224    cluster: u32,
225    initial: Vec<f64>,
226    started: bool,
227    last_probe: Option<Instant>,
228    further: Option<f64>,
229    drop_probe: bool,
230    last_drop_probe: Option<Instant>,
231    last_recovery: Option<Instant>,
232}
233
234/// How much a cluster at `bits_per_second` holds.
235pub(crate) fn cluster_octets(bits_per_second: f64) -> usize {
236    let by_duration = (bits_per_second * PROBE_MIN_DURATION.as_secs_f64() / 8.0) as usize;
237    by_duration.clamp(PROBE_MIN_PACKETS * PROBE_PACKET_OCTETS, PROBE_MAX_OCTETS)
238}
239
240/// The bit rate a path showed it carries, from the reports on the packets of one cluster.
241///
242/// The cluster left at the send rate and arrived at the receive rate; the path carries the
243/// lower of the two. The send rate is taken over all but the last packet and the span from
244/// the first departure to the last, the receive rate over all but the first packet and the
245/// span of the arrivals, so that each is octets over the time they took. When the packets
246/// arrived more than a tenth slower than they left, the bottleneck was reached and held them
247/// apart: the estimate is 95% of the receive rate, to stay below it.
248///
249/// `None` when fewer than four packets of the cluster arrived with a time, or their times do
250/// not span anything: too little to measure.
251pub fn probe_estimate(reports: &[PacketReport]) -> Option<f64> {
252    let arrived: Vec<(Instant, Duration, usize)> = reports
253        .iter()
254        .filter(|report| report.arrived)
255        .filter_map(|report| Some((report.departure, report.arrival?, report.size)))
256        .collect();
257    if arrived.len() < 4 {
258        return None;
259    }
260    let total: usize = arrived.iter().map(|(_, _, size)| size).sum();
261
262    let (first_sent, last_sent) =
263        arrived
264            .iter()
265            .fold(None, |span: Option<(Instant, Instant)>, (sent, _, _)| {
266                Some(span.map_or((*sent, *sent), |(first, last)| {
267                    (first.min(*sent), last.max(*sent))
268                }))
269            })?;
270    let last_sent_size = arrived
271        .iter()
272        .filter(|(sent, _, _)| *sent == last_sent)
273        .map(|(_, _, size)| *size)
274        .next_back()?;
275    let (first_arrival, last_arrival) =
276        arrived
277            .iter()
278            .fold(None, |span: Option<(Duration, Duration)>, (_, at, _)| {
279                Some(span.map_or((*at, *at), |(first, last)| (first.min(*at), last.max(*at))))
280            })?;
281    let first_arrival_size = arrived
282        .iter()
283        .find(|(_, at, _)| *at == first_arrival)
284        .map(|(_, _, size)| *size)?;
285
286    let send_span = last_sent
287        .saturating_duration_since(first_sent)
288        .as_secs_f64();
289    let receive_span = last_arrival.saturating_sub(first_arrival).as_secs_f64();
290    if receive_span <= 0.0 {
291        return None;
292    }
293    let receive_rate = (total - first_arrival_size) as f64 * 8.0 / receive_span;
294    // Packets that left in the same instant have no send rate to compare with: the arrivals
295    // alone say what the path did with them.
296    if send_span <= 0.0 {
297        return Some(receive_rate * 0.95);
298    }
299    let send_rate = (total - last_sent_size) as f64 * 8.0 / send_span;
300    if receive_rate < 0.9 * send_rate {
301        Some(receive_rate * 0.95)
302    } else {
303        Some(send_rate.min(receive_rate))
304    }
305}
306
307/// The bit rate a path showed it carries, from the reports on a cluster that left as one burst
308/// (a chain without a pacer: the NACK responder's padding, written in the same instant).
309///
310/// Such a cluster has no send rate. What the path did with it is the measurement: packets
311/// that left together arrive as far apart as the narrowest link takes to send each, so the
312/// octets after the first over the span of the arrivals is that link's rate (95% of it is
313/// taken, as [`probe_estimate`] takes of a cluster the bottleneck held apart). The cluster was
314/// asked for at `asked` bits per second and nothing was sent to show more than that: the
315/// result is never above it, and it is `asked` itself when the arrivals span no time the
316/// receiver's clock resolves.
317///
318/// A known limit of this measurement: a path that delivers the burst as one aggregate (a
319/// Wi-Fi or cellular link that hands several packets over at once behind the narrow link)
320/// shows no spread, or less than the narrow link made, and is credited with up to the rate
321/// asked for although it carries less. Nothing was sent at that rate, so the cluster cannot
322/// contradict it; the estimate is then above the path until the delay-based controller's
323/// over-use detection brings it down, a few feedback reports after the media follows it. A
324/// paced cluster does not have the limit (its packets leave at the rate asked for, and the
325/// path either carries them so or delays them). The credit is not held to a multiple of
326/// what the path carried in the last second: at the start, which is where the clusters
327/// matter, the path has carried next to nothing yet.
328///
329/// `None` when fewer than four packets of the cluster arrived with a time.
330pub fn burst_estimate(reports: &[PacketReport], asked: f64) -> Option<f64> {
331    let arrived: Vec<(Duration, usize)> = reports
332        .iter()
333        .filter(|report| report.arrived)
334        .filter_map(|report| Some((report.arrival?, report.size)))
335        .collect();
336    if arrived.len() < 4 {
337        return None;
338    }
339    let total: usize = arrived.iter().map(|(_, size)| size).sum();
340    let first = arrived.iter().min_by_key(|(at, _)| *at)?;
341    let last = arrived.iter().max_by_key(|(at, _)| *at)?;
342    let span = last.0.saturating_sub(first.0).as_secs_f64();
343    if span <= 0.0 {
344        return Some(asked);
345    }
346    Some(((total - first.1) as f64 * 8.0 / span * 0.95).min(asked))
347}
348
349/// Decides when a probe cluster is sent and at what rate.
350#[derive(Debug)]
351pub struct ProbeController {
352    next_cluster: u32,
353    /// Rates still to probe from the start-up sequence.
354    initial: Vec<f64>,
355    started: bool,
356    /// The cluster awaiting its result: its number, its rate and when it was asked for.
357    outstanding: Option<(u32, f64, Instant)>,
358    last_probe: Option<Instant>,
359    /// A further cluster owed after a result that confirmed its rate.
360    further: Option<f64>,
361    max_bitrate: f64,
362    /// What is probed for after a large drop (see
363    /// [`with_after_drop_probe`](Self::with_after_drop_probe)).
364    after_drop: AfterDropProbe,
365    /// The highest target of the last [`LARGE_DROP_WINDOW`], and when it was.
366    peak: Option<(f64, Instant)>,
367    /// The last large drop: the target before it, and when it happened.
368    drop: Option<(f64, Instant)>,
369    /// Whether the outstanding cluster probes for the rate before a drop.
370    drop_probe: bool,
371    /// When [`poll`](Self::poll) was last called.
372    polled_at: Option<Instant>,
373    /// Whether clusters leave as bursts of padding ([`set_unpaced`](Self::set_unpaced)).
374    unpaced: bool,
375    /// The target at the last [`poll`](Self::poll).
376    last_target: Option<f64>,
377    /// [`AfterDropProbe::Libwebrtc`]: the last update of the target below two thirds of the
378    /// one before it: the target before it, and when.
379    step_drop: Option<(f64, Instant)>,
380    /// [`AfterDropProbe::Libwebrtc`]: when a probe after a drop was last asked for.
381    last_drop_probe: Option<Instant>,
382    /// Whether the sender is application limited, and when it last stopped being so.
383    application_limited: bool,
384    application_limited_ended: Option<Instant>,
385    /// The estimator's reading of the path ([`set_usage`](Self::set_usage)), and whether it
386    /// has returned from under-use to normal since the last poll.
387    usage: Usage,
388    recovered_from_overuse: bool,
389    /// Whether the rate before a large drop is probed back towards for as long as it is
390    /// remembered ([`with_recovery_probing`](Self::with_recovery_probing)).
391    recovery: bool,
392    /// The highest rate the target had before a large drop of the last
393    /// [`PROBE_DROP_MEMORY`], and when that drop was.
394    remembered: Option<(f64, Instant)>,
395    /// When the last recovery cluster was asked for.
396    last_recovery: Option<Instant>,
397    /// The state before the outstanding cluster was asked for.
398    asked: Option<Asked>,
399}
400
401impl ProbeController {
402    /// A controller for an estimator that starts at `initial_bitrate` and never goes above
403    /// `max_bitrate`.
404    pub fn new(initial_bitrate: f64, max_bitrate: f64) -> Self {
405        Self {
406            next_cluster: 1,
407            initial: INITIAL_PROBES
408                .iter()
409                .rev()
410                .map(|multiple| initial_bitrate * multiple)
411                .collect(),
412            started: false,
413            outstanding: None,
414            last_probe: None,
415            further: None,
416            max_bitrate,
417            after_drop: AfterDropProbe::default(),
418            peak: None,
419            drop: None,
420            drop_probe: false,
421            polled_at: None,
422            unpaced: false,
423            last_target: None,
424            step_drop: None,
425            last_drop_probe: None,
426            application_limited: false,
427            application_limited_ended: None,
428            usage: Usage::Normal,
429            recovered_from_overuse: false,
430            recovery: false,
431            remembered: None,
432            last_recovery: None,
433            asked: None,
434        }
435    }
436
437    /// Whether the path is probed back towards the rate it carried before a large drop for as
438    /// long as that rate is remembered: recovery probing. Off by default.
439    ///
440    /// A capacity that fell and comes back (a cellular link out of a tunnel, a competing
441    /// transfer that ends after half a minute) leaves a sender that keeps up with its target
442    /// at the bottom of the delay-based controller's climb: 8% a second, about 18 s from
443    /// 250 kbit/s to 1 Mbit/s. Nothing else asks: the probes after a drop
444    /// ([`with_after_drop_probe`](Self::with_after_drop_probe)) end five seconds after it, and
445    /// the periodic ones are for a sender that sends less than its target. With this, the
446    /// target before a large drop (below two thirds of its high of the last two seconds) is
447    /// remembered for [`PROBE_DROP_MEMORY`] (the highest such rate, through the smaller
448    /// drops of the time under the limit), and while the target is below 85% of it and the
449    /// estimator does not read the path as over-used ([`set_usage`](Self::set_usage)),
450    /// a cluster at twice the target is asked for every [`PROBE_RECOVERY_INTERVAL`], with
451    /// further ones at twice the result while results confirm the rate probed. A cluster the
452    /// path does not carry changes nothing (a probe only ever raises the estimate).
453    ///
454    /// No specification asks for it (RFC 8836 section 2 names probing at the start only;
455    /// draft-ietf-rmcat-gcc-02 has no probing), and libwebrtc does not do it: its periodic
456    /// probes are for an application-limited sender, its probe after a drop is one cluster
457    /// within five seconds. It is a performance choice: it puts a cluster above the target
458    /// into a path that may still be limited, every five seconds for up to a minute. Not for
459    /// a chain whose clusters leave as bursts ([`set_unpaced`](Self::set_unpaced)).
460    ///
461    /// Measured on the capacity instrument (`tests/capacity_instrument.rs`; the default
462    /// chain, a 2.5 Mbit/s path that drops to 300 kbit/s for 20 s, 200 calls a cell, without
463    /// the setting against with it). WHAT IT GAINS: the target is back at 1 Mbit/s 4.9 s
464    /// after the limit went (5.4 s at most) instead of 17.3 s, and at the 2.5 Mbit/s maximum
465    /// through the window 15 to 25 s after it instead of 1283 kbit/s on average; the same
466    /// behind a 100 ms queue (17.6 -> 5.0 s) and with both directions limited (16.2 -> 4.8 s);
467    /// behind a 1000 ms queue in nine calls of ten (median 17.6 -> 5.0 s, the slowest tenth
468    /// 17.5 s: the deep queue is still draining when the first clusters come). The five
469    /// seconds are the interval: the wait is anywhere up to it. WHAT IT COSTS: under the
470    /// limit the target is 238 kbit/s against 246 (3%), behind a 100 ms queue 52 audio
471    /// packets are lost a call against 41 and 201 packets dropped at the queue against 159;
472    /// the counts of calls with an old picture, a freeze or an audio gap do not move in any
473    /// cell. WHERE IT GAINS NOTHING: a limit that outlasts the minute the rate is remembered
474    /// (held 60 s: 17.6 s against 16.9 s, and the rate not back within 20 s in 33 of 200
475    /// calls against 14). As bursts in a chain without a pacer the gain was the same and
476    /// the calls with an old picture rose in every cell that had any (both directions
477    /// limited 25 -> 31 of 200), which is why it is the paced chain's only.
478    pub fn with_recovery_probing(mut self, enabled: bool) -> Self {
479        self.recovery = enabled;
480        self
481    }
482
483    /// What is probed for after a large drop of the target: [`AfterDropProbe`].
484    pub fn with_after_drop_probe(mut self, after_drop: AfterDropProbe) -> Self {
485        self.after_drop = after_drop;
486        self
487    }
488
489    /// The estimator's reading of the path now
490    /// ([`BandwidthEstimator::usage`](crate::BandwidthEstimator::usage)).
491    /// [`AfterDropProbe::Libwebrtc`] asks for its cluster when the reading returns from
492    /// under-use to normal: the queue an over-use left has drained (libwebrtc
493    /// `DelayBasedBwe`: `recovered_from_overuse`).
494    pub fn set_usage(&mut self, usage: Usage) {
495        if self.usage == Usage::Under && usage == Usage::Normal {
496            self.recovered_from_overuse = true;
497        }
498        self.usage = usage;
499    }
500
501    /// Whether the rate the target had before a large drop is probed for, for a few seconds
502    /// after it: `true` is [`AfterDropProbe::Repeated`] (the default), `false`
503    /// [`AfterDropProbe::Off`]; [`with_after_drop_probe`](Self::with_after_drop_probe) names
504    /// libwebrtc's form too.
505    ///
506    /// A short burst of competing traffic, or a moment of loss, makes the delay-based
507    /// controller back off by a third or more; once it has passed, the climb back is the
508    /// controller's additive increase near the old operating point, half a packet per
509    /// response time, and takes tens of seconds (23 s after a 2 s burst at half the capacity,
510    /// in `rtci-interceptor/tests/rfc8836_multi_flow.rs`), against RFC 8836 section 2
511    /// (requirement 1f: the flow "regains its share quickly"). With this, a drop of the
512    /// target below two thirds of its high of the last two seconds is followed, from a second
513    /// on and once a second for five seconds, by a cluster at 85% of the rate before the drop
514    /// while the target is still below that. A result above the target raises it (as every
515    /// probe does); one below it changes nothing: the competing traffic is still there.
516    pub fn with_probe_after_drop(mut self, enabled: bool) -> Self {
517        self.after_drop = if enabled {
518            AfterDropProbe::Repeated
519        } else {
520            AfterDropProbe::Off
521        };
522        self
523    }
524
525    /// Whether this chain's clusters leave as one burst of padding (no pacer: the congestion
526    /// controller says so when it measures a cluster whose packets left in one instant).
527    ///
528    /// Then the rate before a large drop is not probed for. A paced cluster is the media
529    /// already waiting, released faster for a few milliseconds, with padding only for what
530    /// is missing; a burst is five packets of padding on top of the media, at once. After a
531    /// drop that is 160 ms of a 300 kbit/s link put into the queue that caused the drop, once
532    /// a second. Measured on the capacity instrument (200 calls a cell, a 2.5 Mbit/s path
533    /// that drops to 300 kbit/s): with such bursts 7 of 200 calls of ParolNet's chain were
534    /// over 2 s without a new picture against 3 without them, 172 retransmissions a call
535    /// against 142, and behind a 1000 ms queue the audio paused for over a second in 72 of
536    /// 200 calls against 21. The start-up clusters and those of an application-limited
537    /// sender are still asked for.
538    pub fn set_unpaced(&mut self, unpaced: bool) {
539        self.unpaced = unpaced;
540    }
541
542    /// The path changed and the estimator started over at `start_bitrate`: probing starts over
543    /// too, as at the beginning of the call, and what was noted of the old path is dropped.
544    ///
545    /// The start-up clusters are owed again, at three and six times `start_bitrate` and on
546    /// while the new path carries what is asked (RFC 8836 section 2, requirement 4: the
547    /// conditions of a new path are initial conditions). The target's recent high, the drop
548    /// below it and the cluster awaiting its result belong to the path that was left: the
549    /// estimator's fall back to its starting rate is not a drop of the path's capacity, and
550    /// the rate "before" it is the old path's.
551    ///
552    /// Without this an outage ended by an ICE restart left the call at the estimator's 8% a
553    /// second on the new path (traced on the capacity instrument's outage cell, the default
554    /// chain: 1 Mbit/s 15.1 s after the new pair). While nothing is acknowledged the
555    /// estimator halves at every feedback timeout, each halving a large drop, and the probe
556    /// for the rate before the last of them (133 kbit/s, asked into the dead path half a
557    /// second before the new pair) was still awaiting its result when the path changed. It
558    /// held the controller's one slot for the half second in which the sender, still sending
559    /// at the old path's floor, counted as application limited against the new starting
560    /// rate; after it nothing was due. Without the probe after a drop that
561    /// application-limited cluster did find the path (1.0 s), but only in the calls where
562    /// one happened to be due (134 of 200; 12 to 13 s in the others).
563    ///
564    /// libwebrtc does the same on a network route change: `ProbeController::Reset`
565    /// (goog_cc `probe_controller.cc`) returns to its initial state and forgets the rate
566    /// before the last large drop, and the constraints set next start the exponential probes
567    /// again (`GoogCcNetworkController::OnNetworkRouteChange`).
568    pub fn on_path_change(&mut self, now: Instant, start_bitrate: f64) {
569        self.initial = INITIAL_PROBES
570            .iter()
571            .rev()
572            .map(|multiple| start_bitrate * multiple)
573            .collect();
574        self.started = false;
575        self.outstanding = None;
576        self.last_probe = None;
577        self.further = None;
578        self.peak = None;
579        self.drop = None;
580        self.drop_probe = false;
581        self.last_target = None;
582        self.step_drop = None;
583        // libwebrtc's `Reset` counts the change as the time of its last probe after a drop.
584        self.last_drop_probe = Some(now);
585        self.application_limited_ended = None;
586        self.usage = Usage::Normal;
587        self.recovered_from_overuse = false;
588        // The rate remembered for recovery probing was the old path's.
589        self.remembered = None;
590        self.last_recovery = None;
591        self.asked = None;
592    }
593
594    /// The ceiling of what is probed for: the estimator's own maximum, or a limit from
595    /// outside it (REMB, TMMBR, the session bit rate).
596    pub fn set_max_bitrate(&mut self, max_bitrate: f64) {
597        self.max_bitrate = max_bitrate;
598    }
599
600    /// The cluster to send now, if one is due.
601    ///
602    /// `target` is the current target bit rate and `sending` the rate the application is
603    /// sending at; `media_flowing` is whether a packet has left yet (a probe before the
604    /// first one would measure nothing the receiver reports).
605    pub fn poll(
606        &mut self,
607        now: Instant,
608        target: f64,
609        sending: f64,
610        media_flowing: bool,
611    ) -> Option<ProbeRequest> {
612        self.polled_at = Some(now);
613        if !media_flowing {
614            return None;
615        }
616        self.track_drops(now, target);
617        self.track_application_limited(now, target, sending);
618        let recovered_from_overuse = std::mem::take(&mut self.recovered_from_overuse);
619        if let Some((_, _, asked)) = self.outstanding {
620            if now.saturating_duration_since(asked) < PROBE_RESULT_TIMEOUT {
621                return None;
622            }
623            // Its reports never came: the cluster is given up, and with it the sequence it
624            // was part of.
625            self.outstanding = None;
626            self.further = None;
627            self.drop_probe = false;
628        }
629        if self
630            .last_probe
631            .is_some_and(|last| now.saturating_duration_since(last) < PROBE_SPACING)
632        {
633            return None;
634        }
635
636        let before = Asked {
637            cluster: 0,
638            initial: self.initial.clone(),
639            started: self.started,
640            last_probe: self.last_probe,
641            further: self.further,
642            drop_probe: self.drop_probe,
643            last_drop_probe: self.last_drop_probe,
644            last_recovery: self.last_recovery,
645        };
646        self.started = true;
647        let rate = if let Some(rate) = self.initial.pop() {
648            Some(rate)
649        } else if let Some(rate) = self.further.take() {
650            Some(rate)
651        } else if let Some((before, at)) = self.drop
652            && self.after_drop == AfterDropProbe::Repeated
653            && !self.unpaced
654            && now.saturating_duration_since(at) >= PROBE_AFTER_DROP_DELAY
655            && target < PROBE_AFTER_DROP_SHARE * before
656            && self
657                .last_probe
658                .is_none_or(|last| now.saturating_duration_since(last) >= PROBE_AFTER_DROP_INTERVAL)
659        {
660            // The rate before a large drop, while the drop is recent: if what caused it has
661            // gone, the path carries it again.
662            self.drop_probe = true;
663            Some(PROBE_AFTER_DROP_SHARE * before)
664        } else if let Some(rate) = self.libwebrtc_drop_probe(now, target, recovered_from_overuse) {
665            self.drop_probe = true;
666            self.last_drop_probe = Some(now);
667            Some(rate)
668        } else if self.recovery_due(now, target) {
669            // Below the rate the path carried before a large drop that is still remembered:
670            // what limited it may have gone, and a sender at its target is not asked by
671            // anything else.
672            self.last_recovery = Some(now);
673            Some(target * FURTHER_PROBE)
674        } else if sending < APPLICATION_LIMITED_SHARE * target
675            && self.last_probe.is_none_or(|last| {
676                now.saturating_duration_since(last) >= PROBE_APPLICATION_LIMITED_INTERVAL
677            })
678        {
679            // Sending less than the target allows, the delay-based controller learns nothing
680            // about the room above what is sent.
681            Some(target * FURTHER_PROBE)
682        } else {
683            None
684        }?;
685
686        let rate = rate.min(self.max_bitrate);
687        if rate <= target {
688            // Nothing above the target is allowed, so there is nothing to ask.
689            self.drop_probe = false;
690            return None;
691        }
692        let cluster = self.next_cluster;
693        self.next_cluster = self.next_cluster.wrapping_add(1).max(1);
694        self.outstanding = Some((cluster, rate, now));
695        self.last_probe = Some(now);
696        self.asked = Some(Asked { cluster, ..before });
697        Some(ProbeRequest {
698            cluster,
699            bits_per_second: rate,
700            octets: cluster_octets(rate),
701        })
702    }
703
704    /// Whether a recovery cluster is due: the setting, paced clusters, a remembered rate the
705    /// target is well below, no over-use, and the interval since the drop or the last one.
706    fn recovery_due(&self, now: Instant, target: f64) -> bool {
707        let Some(at) = self.recovery_deadline() else {
708            return false;
709        };
710        let Some((before, _)) = self.remembered else {
711            return false;
712        };
713        now >= at && self.usage != Usage::Over && target < PROBE_AFTER_DROP_SHARE * before
714    }
715
716    /// When the next recovery cluster may be asked for, while a rate is remembered.
717    fn recovery_deadline(&self) -> Option<Instant> {
718        if !self.recovery || self.unpaced {
719            return None;
720        }
721        let (_, dropped) = self.remembered?;
722        let since = self.last_recovery.map_or(dropped, |last| last.max(dropped));
723        Some(since + PROBE_RECOVERY_INTERVAL)
724    }
725
726    /// libwebrtc's probe after a drop (`ProbeController::RequestProbe`), when it is due: the
727    /// detector has just returned to normal, the sender is or was lately application limited,
728    /// the drop is under five seconds old, the last such probe over five seconds, and 95% of
729    /// the rate to ask for is above the target.
730    fn libwebrtc_drop_probe(
731        &self,
732        now: Instant,
733        target: f64,
734        recovered_from_overuse: bool,
735    ) -> Option<f64> {
736        if self.after_drop != AfterDropProbe::Libwebrtc || self.unpaced || !recovered_from_overuse {
737            return None;
738        }
739        let limited = self.application_limited
740            || self
741                .application_limited_ended
742                .is_some_and(|ended| now.saturating_duration_since(ended) < ALR_ENDED_TIMEOUT);
743        let (before, at) = self.step_drop?;
744        let rate = PROBE_AFTER_DROP_SHARE * before;
745        (limited
746            && (1.0 - LIBWEBRTC_PROBE_UNCERTAINTY) * rate > target
747            && now.saturating_duration_since(at) < PROBE_AFTER_DROP_TIMEOUT
748            && self.last_drop_probe.is_none_or(|last| {
749                now.saturating_duration_since(last) > LIBWEBRTC_DROP_PROBE_INTERVAL
750            }))
751        .then_some(rate)
752    }
753
754    /// Whether the sender is application limited, and when it stopped being so.
755    fn track_application_limited(&mut self, now: Instant, target: f64, sending: f64) {
756        let limited = sending < APPLICATION_LIMITED_SHARE * target;
757        if self.application_limited && !limited {
758            self.application_limited_ended = Some(now);
759        }
760        self.application_limited = limited;
761    }
762
763    /// Follows the target's recent high, and notes a large drop below it.
764    fn track_drops(&mut self, now: Instant, target: f64) {
765        // libwebrtc's drop: one update below two thirds of the one before it.
766        if let Some(last) = self.last_target
767            && target < LARGE_DROP_SHARE * last
768        {
769            self.step_drop = Some((last, now));
770        }
771        self.last_target = Some(target);
772        if self
773            .remembered
774            .is_some_and(|(_, at)| now.saturating_duration_since(at) > PROBE_DROP_MEMORY)
775        {
776            self.remembered = None;
777        }
778        match self.peak {
779            Some((peak, at))
780                if target < peak && now.saturating_duration_since(at) <= LARGE_DROP_WINDOW =>
781            {
782                if target < LARGE_DROP_SHARE * peak {
783                    self.drop = Some((peak, now));
784                    self.peak = Some((target, now));
785                    // The highest rate before a drop of the last minute stays the one
786                    // remembered: the smaller drops under a limit (the controller's own
787                    // sawtooth) do not replace the rate the path had before it.
788                    if self.remembered.is_none_or(|(before, _)| peak >= before) {
789                        self.remembered = Some((peak, now));
790                    }
791                }
792            }
793            _ => self.peak = Some((target, now)),
794        }
795        if self
796            .drop
797            .is_some_and(|(_, at)| now.saturating_duration_since(at) > PROBE_AFTER_DROP_TIMEOUT)
798        {
799            self.drop = None;
800        }
801    }
802
803    /// `cluster` left no packet: nothing in the chain could carry it ([`ProbeUnsent`]). It is
804    /// counted as never asked for: what asking for it used up (its place in the start-up
805    /// sequence, the further cluster it was, the time since the last cluster that spaces the
806    /// next one) is owed again, and the next poll at which something can carry it asks for it
807    /// at once. RFC 8836 section 2, requirement 4 asks for probing at the start of a flow; a
808    /// start-up cluster asked for while only audio has sent (no RTX stream to pad on, no
809    /// pacer) is not that probe, and the one the video can carry still is. Returns whether it
810    /// was the outstanding cluster.
811    pub fn on_unsent(&mut self, cluster: u32) -> bool {
812        if self.outstanding() != Some(cluster) {
813            return false;
814        }
815        self.outstanding = None;
816        if let Some(asked) = self.asked.take().filter(|asked| asked.cluster == cluster) {
817            self.initial = asked.initial;
818            self.started = asked.started;
819            self.last_probe = asked.last_probe;
820            self.further = asked.further;
821            self.drop_probe = asked.drop_probe;
822            self.last_drop_probe = asked.last_drop_probe;
823            self.last_recovery = asked.last_recovery;
824        }
825        true
826    }
827
828    /// A media stream sent its first packet after the call's start, at a target of `target`:
829    /// the start of a flow. When the start-up sequence is over, it is owed again, at three
830    /// and six times `target`, and goes on while the path carries what is asked, as at the
831    /// call's start.
832    ///
833    /// RFC 8836 section 2, requirement 4: the algorithm "SHOULD adapt as quickly as possible to
834    /// initial network conditions at the start of a flow" (draft-ietf-rmcat-gcc-02 has no
835    /// probing). The start-up clusters of a call that began with audio alone were spent on the
836    /// audio, which carries no cluster at its rate (the pacer releases what it holds, and
837    /// audio is a packet every 20 ms); when video is added nothing else asks for one, since a
838    /// sender that follows its target is not application limited: the video climbed at 8 % a
839    /// second (461 kbit/s six seconds after it started, paced or not). While the start-up
840    /// sequence is still owed or under way (the sources of a call starting within a few
841    /// milliseconds of each other) nothing changes. libwebrtc probes on a growth of the
842    /// allocated maximum instead (`ProbeController::OnMaxTotalAllocatedBitrate`); this rule
843    /// needs no allocation, only the flow's first packet.
844    pub fn on_new_flow(&mut self, target: f64) {
845        if !self.started || !self.initial.is_empty() {
846            return;
847        }
848        self.initial = INITIAL_PROBES
849            .iter()
850            .rev()
851            .map(|multiple| target * multiple)
852            .collect();
853        self.further = None;
854    }
855
856    /// The number of the cluster whose result is awaited.
857    pub fn outstanding(&self) -> Option<u32> {
858        self.outstanding.map(|(cluster, _, _)| cluster)
859    }
860
861    /// The rate `cluster` was asked for at, while its result is awaited.
862    pub fn asked_rate(&self, cluster: u32) -> Option<f64> {
863        self.outstanding
864            .filter(|(outstanding, _, _)| *outstanding == cluster)
865            .map(|(_, rate, _)| rate)
866    }
867
868    /// The result of `cluster`: `estimate` bits per second. Returns the estimate when it is
869    /// the outstanding cluster's, for the estimator to take.
870    pub fn on_result(&mut self, cluster: u32, estimate: f64) -> Option<f64> {
871        let (outstanding, rate, _) = self.outstanding?;
872        if outstanding != cluster {
873            return None;
874        }
875        self.outstanding = None;
876        self.asked = None;
877        // The path carried what was asked of it: it may carry more. Not after a probe for the
878        // rate before a drop: that asks only whether the path is back where it was.
879        let drop_probe = std::mem::take(&mut self.drop_probe);
880        if !drop_probe && estimate >= FURTHER_PROBE_THRESHOLD * rate && self.initial.is_empty() {
881            let next = estimate * FURTHER_PROBE;
882            if next <= self.max_bitrate * FURTHER_PROBE {
883                self.further = Some(next);
884            }
885        }
886        Some(estimate)
887    }
888
889    /// When [`poll`](Self::poll) next has something to say without anything else happening.
890    ///
891    /// Never an instant `poll` has already been called at or after: a deadline that passed
892    /// with nothing to send (no media flowing, a sender that is no longer application
893    /// limited, a target that recovered by itself) waits for the next write instead of
894    /// asking to be woken again at once.
895    pub fn poll_timeout(&self) -> Option<Instant> {
896        self.deadlines()
897            .into_iter()
898            .flatten()
899            .filter(|deadline| self.polled_at.is_none_or(|polled| *deadline > polled))
900            .min()
901    }
902
903    /// The instants something may be due: a result to give up, the next cluster of a
904    /// sequence or of an application-limited sender, the next probe after a drop, the next
905    /// recovery cluster.
906    fn deadlines(&self) -> [Option<Instant>; 3] {
907        if !self.started {
908            return [None, None, None];
909        }
910        if let Some((_, _, asked)) = self.outstanding {
911            return [Some(asked + PROBE_RESULT_TIMEOUT), None, None];
912        }
913        let Some(last) = self.last_probe else {
914            return [None, None, None];
915        };
916        let next = if !self.initial.is_empty() || self.further.is_some() {
917            last + PROBE_SPACING
918        } else {
919            last + PROBE_APPLICATION_LIMITED_INTERVAL
920        };
921        let after_drop = self
922            .drop
923            .filter(|_| self.after_drop == AfterDropProbe::Repeated && !self.unpaced)
924            .map(|(_, at)| (at + PROBE_AFTER_DROP_DELAY).max(last + PROBE_AFTER_DROP_INTERVAL));
925        let recovery = self
926            .recovery_deadline()
927            .map(|at| at.max(last + PROBE_SPACING));
928        [Some(next), after_drop, recovery]
929    }
930}
931
932#[cfg(test)]
933mod tests {
934    use super::*;
935    use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
936
937    fn report(id: u64, departure: Instant, arrival_us: u64, size: usize) -> PacketReport {
938        PacketReport {
939            ssrc: 1,
940            id,
941            rtp_sequence_number: id as u16,
942            is_twcc: true,
943            twcc_sequence_number: id as u16,
944            size,
945            arrived: true,
946            departure,
947            arrival: Some(Duration::from_micros(arrival_us)),
948            ecn: Ecn::NotEct,
949        }
950    }
951
952    /// Six 1200-octet packets sent 2 ms apart (4.8 Mbit/s) that arrive 2 ms apart: the path
953    /// carried the cluster, and the estimate is the rate it was sent at.
954    #[test]
955    fn a_cluster_that_arrives_as_it_left_shows_its_own_rate() {
956        let epoch = Instant::now();
957        let reports: Vec<PacketReport> = (0..6u64)
958            .map(|i| {
959                report(
960                    i,
961                    epoch + Duration::from_millis(2 * i),
962                    50_000 + 2_000 * i,
963                    1200,
964                )
965            })
966            .collect();
967        let estimate = probe_estimate(&reports).expect("measurable");
968        assert!((estimate - 4_800_000.0).abs() < 1_000.0, "{estimate}");
969    }
970
971    /// The same cluster through a 2.4 Mbit/s bottleneck arrives 4 ms apart: the estimate is
972    /// 95% of the rate it arrived at, not the rate it was sent at.
973    #[test]
974    fn a_cluster_spread_out_by_the_bottleneck_shows_the_bottleneck() {
975        let epoch = Instant::now();
976        let reports: Vec<PacketReport> = (0..6u64)
977            .map(|i| {
978                report(
979                    i,
980                    epoch + Duration::from_millis(2 * i),
981                    50_000 + 4_000 * i,
982                    1200,
983                )
984            })
985            .collect();
986        let estimate = probe_estimate(&reports).expect("measurable");
987        assert!(
988            (estimate - 0.95 * 2_400_000.0).abs() < 1_000.0,
989            "{estimate}"
990        );
991    }
992
993    /// Three arrivals are not a measurement, and neither are packets without arrival times.
994    #[test]
995    fn too_few_arrivals_give_no_estimate() {
996        let epoch = Instant::now();
997        let mut reports: Vec<PacketReport> = (0..3u64)
998            .map(|i| {
999                report(
1000                    i,
1001                    epoch + Duration::from_millis(2 * i),
1002                    50_000 + 2_000 * i,
1003                    1200,
1004                )
1005            })
1006            .collect();
1007        assert_eq!(None, probe_estimate(&reports));
1008        let mut lost = report(3, epoch + Duration::from_millis(6), 0, 1200);
1009        lost.arrived = false;
1010        lost.arrival = None;
1011        reports.push(lost);
1012        assert_eq!(None, probe_estimate(&reports));
1013    }
1014
1015    /// At the start: three times the starting rate, then six times, each once its predecessor
1016    /// has a result, and nothing before media flows.
1017    #[test]
1018    fn the_start_probes_at_three_and_six_times_the_starting_rate() {
1019        let epoch = Instant::now();
1020        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
1021        assert_eq!(None, controller.poll(epoch, 300_000.0, 0.0, false));
1022
1023        let first = controller
1024            .poll(epoch, 300_000.0, 300_000.0, true)
1025            .expect("first cluster");
1026        assert_eq!(900_000.0, first.bits_per_second);
1027        assert_eq!(
1028            PROBE_MIN_PACKETS * PROBE_PACKET_OCTETS,
1029            first.octets,
1030            "five packets at least"
1031        );
1032        assert_eq!(
1033            None,
1034            controller.poll(
1035                epoch + Duration::from_millis(200),
1036                300_000.0,
1037                300_000.0,
1038                true
1039            ),
1040            "one cluster at a time"
1041        );
1042
1043        assert_eq!(
1044            Some(900_000.0),
1045            controller.on_result(first.cluster, 900_000.0)
1046        );
1047        let second = controller
1048            .poll(
1049                epoch + Duration::from_millis(200),
1050                900_000.0,
1051                300_000.0,
1052                true,
1053            )
1054            .expect("second cluster");
1055        assert_eq!(1_800_000.0, second.bits_per_second);
1056    }
1057
1058    /// A start-up cluster that left no packet ([`ProbeController::on_unsent`]) is owed again,
1059    /// at once: the next poll asks for the same rate, without the spacing between clusters
1060    /// and without waiting for the result's time-out. A cluster with a result is not undone.
1061    #[test]
1062    fn a_cluster_that_left_no_packet_is_asked_for_again_at_once() {
1063        let epoch = Instant::now();
1064        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
1065        let first = controller
1066            .poll(epoch, 300_000.0, 300_000.0, true)
1067            .expect("first cluster");
1068        assert!(controller.on_unsent(first.cluster));
1069        assert_eq!(None, controller.outstanding());
1070        assert!(!controller.on_unsent(first.cluster), "only once");
1071
1072        let at = epoch + Duration::from_millis(10);
1073        let again = controller
1074            .poll(at, 300_000.0, 300_000.0, true)
1075            .expect("the first start-up cluster again");
1076        assert_eq!(900_000.0, again.bits_per_second);
1077        assert_ne!(first.cluster, again.cluster, "a new number");
1078
1079        assert_eq!(
1080            Some(900_000.0),
1081            controller.on_result(again.cluster, 900_000.0)
1082        );
1083        assert!(!controller.on_unsent(again.cluster), "it had a result");
1084        let second = controller
1085            .poll(at + Duration::from_millis(200), 900_000.0, 300_000.0, true)
1086            .expect("second cluster");
1087        assert_eq!(1_800_000.0, second.bits_per_second);
1088    }
1089
1090    /// A flow that starts after the start-up sequence is over owes it again, at three and six
1091    /// times the target then; one that starts while it is still owed changes nothing.
1092    #[test]
1093    fn a_flow_that_starts_later_starts_the_probing_again() {
1094        let epoch = Instant::now();
1095        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
1096        controller.on_new_flow(300_000.0);
1097        let first = controller
1098            .poll(epoch, 300_000.0, 300_000.0, true)
1099            .expect("first cluster");
1100        controller.on_new_flow(300_000.0);
1101        controller.on_result(first.cluster, 100_000.0);
1102        let second = controller
1103            .poll(
1104                epoch + Duration::from_millis(200),
1105                300_000.0,
1106                300_000.0,
1107                true,
1108            )
1109            .expect("second cluster");
1110        assert_eq!(
1111            1_800_000.0, second.bits_per_second,
1112            "the sequence as it was"
1113        );
1114        controller.on_result(second.cluster, 100_000.0);
1115        let later = epoch + Duration::from_millis(400);
1116        assert_eq!(
1117            None,
1118            controller.poll(later, 300_000.0, 300_000.0, true),
1119            "the start-up is over"
1120        );
1121
1122        controller.on_new_flow(500_000.0);
1123        let again = controller
1124            .poll(later, 500_000.0, 500_000.0, true)
1125            .expect("the start-up again");
1126        assert_eq!(1_500_000.0, again.bits_per_second);
1127        controller.on_result(again.cluster, 1_500_000.0);
1128        let next = controller
1129            .poll(
1130                later + Duration::from_millis(200),
1131                1_500_000.0,
1132                500_000.0,
1133                true,
1134            )
1135            .expect("its second cluster");
1136        assert_eq!(3_000_000.0, next.bits_per_second);
1137    }
1138
1139    /// A result that confirms the rate probed is followed by a cluster at twice the result; one
1140    /// that shows the bottleneck is not.
1141    #[test]
1142    fn probing_goes_on_while_the_path_carries_what_is_asked() {
1143        let epoch = Instant::now();
1144        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
1145        let mut now = epoch;
1146        let mut target = 300_000.0;
1147        let mut asked = Vec::new();
1148        // The path carries 2.5 Mbit/s.
1149        for _ in 0..8 {
1150            if let Some(request) = controller.poll(now, target, target, true) {
1151                asked.push(request.bits_per_second);
1152                let estimate = request.bits_per_second.min(2_500_000.0 * 0.95);
1153                target = controller
1154                    .on_result(request.cluster, estimate)
1155                    .expect("the outstanding cluster");
1156            }
1157            now += Duration::from_millis(150);
1158        }
1159        assert_eq!(
1160            vec![900_000.0, 1_800_000.0, 3_600_000.0],
1161            asked,
1162            "the third cluster found the bottleneck (2.375 of 3.6 Mbit/s) and ended the sequence"
1163        );
1164        assert_eq!(2_375_000.0, target);
1165    }
1166
1167    /// While the application sends less than the target allows, a cluster goes out every five
1168    /// seconds; at the target, none.
1169    #[test]
1170    fn an_application_limited_sender_probes_every_few_seconds() {
1171        let epoch = Instant::now();
1172        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
1173        // The start-up sequence, answered with the bottleneck at once.
1174        for at in [epoch, epoch + Duration::from_millis(150)] {
1175            let request = controller
1176                .poll(at, 300_000.0, 300_000.0, true)
1177                .expect("start-up cluster");
1178            controller.on_result(request.cluster, 500_000.0);
1179        }
1180
1181        let later = epoch + Duration::from_secs(6);
1182        assert_eq!(
1183            None,
1184            controller.poll(later, 1_000_000.0, 1_000_000.0, true),
1185            "sending at the target: the delay-based controller is asking already"
1186        );
1187        let request = controller
1188            .poll(later, 1_000_000.0, 200_000.0, true)
1189            .expect("application limited");
1190        assert_eq!(2_000_000.0, request.bits_per_second);
1191        controller.on_result(request.cluster, 1_200_000.0);
1192        assert_eq!(
1193            None,
1194            controller.poll(later + Duration::from_secs(1), 1_000_000.0, 200_000.0, true),
1195            "not again within five seconds"
1196        );
1197    }
1198
1199    /// Nothing is probed above the ceiling, and a cluster whose reports never come is given up.
1200    #[test]
1201    fn the_ceiling_and_the_timeout_end_a_probe() {
1202        let epoch = Instant::now();
1203        let mut controller = ProbeController::new(300_000.0, 600_000.0);
1204        let request = controller
1205            .poll(epoch, 300_000.0, 300_000.0, true)
1206            .expect("capped cluster");
1207        assert_eq!(600_000.0, request.bits_per_second);
1208        assert_eq!(Some(request.cluster), controller.outstanding());
1209        assert_eq!(
1210            Some(epoch + PROBE_RESULT_TIMEOUT),
1211            controller.poll_timeout()
1212        );
1213
1214        let after = epoch + PROBE_RESULT_TIMEOUT;
1215        // Given up; the next of the start-up sequence is capped at the ceiling too, which the
1216        // target has reached by then.
1217        assert_eq!(None, controller.poll(after, 600_000.0, 600_000.0, true));
1218        assert_eq!(None, controller.outstanding());
1219    }
1220
1221    /// Settles a controller after its start-up sequence: two clusters answered at the
1222    /// bottleneck, so no further cluster is owed.
1223    fn settled(epoch: Instant) -> ProbeController {
1224        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
1225        for at in [epoch, epoch + Duration::from_millis(150)] {
1226            let request = controller
1227                .poll(at, 300_000.0, 300_000.0, true)
1228                .expect("start-up cluster");
1229            controller.on_result(request.cluster, 500_000.0);
1230        }
1231        controller
1232    }
1233
1234    /// RFC 8836 section 2 (1f): after a large drop of the target (a burst of competing
1235    /// traffic), the rate before it is probed for, from a second after the drop and once a
1236    /// second, and a result never asks for a further cluster above it.
1237    #[test]
1238    fn a_large_drop_is_followed_by_a_probe_at_the_rate_before_it() {
1239        let epoch = Instant::now();
1240        let mut controller = settled(epoch);
1241        let at = |ms: u64| epoch + Duration::from_millis(ms);
1242        // At 2 Mbit/s, sending at the target, for a while.
1243        for ms in (1_000..2_000).step_by(100) {
1244            assert_eq!(
1245                None,
1246                controller.poll(at(ms), 2_000_000.0, 2_000_000.0, true)
1247            );
1248        }
1249        // Down to 900 kbit/s: a drop of more than a third.
1250        assert_eq!(None, controller.poll(at(2_000), 900_000.0, 900_000.0, true));
1251        assert_eq!(
1252            None,
1253            controller.poll(at(2_500), 900_000.0, 900_000.0, true),
1254            "the back-off is given a second first"
1255        );
1256        assert_eq!(Some(at(3_000)), controller.poll_timeout());
1257        let request = controller
1258            .poll(at(3_000), 900_000.0, 900_000.0, true)
1259            .expect("the rate before the drop");
1260        assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
1261        // The path carries it again: the estimator takes it, and nothing above it is asked.
1262        assert_eq!(
1263            Some(1_700_000.0),
1264            controller.on_result(request.cluster, 1_700_000.0)
1265        );
1266        assert_eq!(
1267            None,
1268            controller.poll(at(3_200), 1_700_000.0, 1_700_000.0, true)
1269        );
1270        assert_eq!(
1271            None,
1272            controller.poll(at(4_500), 1_700_000.0, 1_700_000.0, true)
1273        );
1274    }
1275
1276    /// While the competing traffic is still there the probe shows less than the rate before
1277    /// the drop: it is asked again a second later, and not after the drop is five seconds old.
1278    #[test]
1279    fn probes_after_a_drop_stop_after_a_few_seconds() {
1280        let epoch = Instant::now();
1281        let mut controller = settled(epoch);
1282        let at = |ms: u64| epoch + Duration::from_millis(ms);
1283        assert_eq!(
1284            None,
1285            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1286        );
1287        assert_eq!(None, controller.poll(at(1_100), 900_000.0, 900_000.0, true));
1288        let mut probes = 0;
1289        for ms in (1_200..9_000).step_by(100) {
1290            if let Some(request) = controller.poll(at(ms), 900_000.0, 900_000.0, true) {
1291                probes += 1;
1292                assert!(ms <= 1_100 + 5_000, "at {ms} ms");
1293                controller.on_result(request.cluster, 950_000.0);
1294            }
1295        }
1296        assert!((3..=5).contains(&probes), "{probes} probes");
1297    }
1298
1299    /// A chain whose clusters leave as bursts ([`ProbeController::set_unpaced`]) is not probed
1300    /// after a large drop, and names no deadline for it; the same drop is probed once the
1301    /// clusters are paced.
1302    #[test]
1303    fn a_drop_is_not_probed_while_clusters_leave_as_bursts() {
1304        let epoch = Instant::now();
1305        let mut controller = settled(epoch);
1306        controller.set_unpaced(true);
1307        let at = |ms: u64| epoch + Duration::from_millis(ms);
1308        assert_eq!(
1309            None,
1310            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1311        );
1312        for ms in (1_100..4_000).step_by(100) {
1313            assert_eq!(None, controller.poll(at(ms), 900_000.0, 900_000.0, true));
1314            assert!(
1315                controller
1316                    .poll_timeout()
1317                    .is_none_or(|next| next > at(ms) + Duration::from_secs(1)),
1318                "a deadline for a probe that will not be asked for, at {ms} ms"
1319            );
1320        }
1321        controller.set_unpaced(false);
1322        let request = controller
1323            .poll(at(4_000), 900_000.0, 900_000.0, true)
1324            .expect("paced clusters: the rate before the drop");
1325        assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
1326    }
1327
1328    /// A path change starts probing over: the start-up clusters again, from the rate the
1329    /// estimator starts over at, and nothing of the old path's drop. The script is an outage
1330    /// ended by an ICE restart, as the default chain's estimator goes through it: at
1331    /// 2.5 Mbit/s, then halved every half second while nothing is acknowledged (each halving
1332    /// a large drop), a probe for the rate before the last one asked into the dead path, and
1333    /// the new path while that probe still awaits its result.
1334    #[test]
1335    fn a_path_change_starts_probing_over_and_forgets_the_drop() {
1336        let epoch = Instant::now();
1337        let mut controller = settled(epoch);
1338        let at = |ms: u64| epoch + Duration::from_millis(ms);
1339        for ms in (1_000..2_000).step_by(100) {
1340            assert_eq!(
1341                None,
1342                controller.poll(at(ms), 2_500_000.0, 2_500_000.0, true)
1343            );
1344        }
1345        // The outage: 1250, 625, 312, 156 kbit/s, then the floor.
1346        let mut target = 2_500_000.0;
1347        for ms in (2_000..4_500).step_by(500) {
1348            target = f64::max(target / 2.0, 100_000.0);
1349            assert_eq!(None, controller.poll(at(ms), target, target, true));
1350        }
1351        assert_eq!(100_000.0, target);
1352        let stale = controller
1353            .poll(at(5_000), target, target, true)
1354            .expect("the rate before the last halving");
1355        assert_eq!(0.85 * 156_250.0, stale.bits_per_second);
1356
1357        // The new path, 300 ms later: the estimator starts over at 300 kbit/s.
1358        controller.on_path_change(at(5_300), 300_000.0);
1359        assert_eq!(None, controller.outstanding(), "the old path's cluster");
1360        assert_eq!(None, controller.poll_timeout(), "nothing of the old path");
1361        let first = controller
1362            .poll(at(5_300), 300_000.0, 100_000.0, true)
1363            .expect("the first start-up cluster, at once");
1364        assert_eq!(900_000.0, first.bits_per_second);
1365        assert_eq!(
1366            None,
1367            controller.on_result(stale.cluster, 120_000.0),
1368            "a late result of the old path's cluster is nobody's"
1369        );
1370        assert_eq!(
1371            Some(900_000.0),
1372            controller.on_result(first.cluster, 900_000.0)
1373        );
1374        let second = controller
1375            .poll(at(5_450), 900_000.0, 300_000.0, true)
1376            .expect("the second start-up cluster");
1377        assert_eq!(1_800_000.0, second.bits_per_second);
1378        // The new path carries it: a further cluster, as at the start of the call.
1379        assert_eq!(
1380            Some(1_800_000.0),
1381            controller.on_result(second.cluster, 1_800_000.0)
1382        );
1383        let third = controller
1384            .poll(at(5_600), 1_800_000.0, 900_000.0, true)
1385            .expect("a further cluster");
1386        assert_eq!(3_600_000.0, third.bits_per_second);
1387        // It found the bottleneck. From here on the sender is at its target, and nothing of
1388        // the old path's drops is probed for in the seconds that follow.
1389        assert_eq!(
1390            Some(2_375_000.0),
1391            controller.on_result(third.cluster, 2_375_000.0)
1392        );
1393        for ms in (5_700..12_000).step_by(100) {
1394            assert_eq!(
1395                None,
1396                controller.poll(at(ms), 2_375_000.0, 2_375_000.0, true),
1397                "at {ms} ms"
1398            );
1399        }
1400    }
1401
1402    /// The estimator's fall to its starting rate at a path change is not a drop to probe
1403    /// after: from 2.5 Mbit/s to 300 kbit/s on a new path that carries no more than the
1404    /// start-up clusters show, no cluster asks for the old path's rate.
1405    #[test]
1406    fn the_fall_to_the_starting_rate_at_a_path_change_is_not_a_drop() {
1407        let epoch = Instant::now();
1408        let mut controller = settled(epoch);
1409        let at = |ms: u64| epoch + Duration::from_millis(ms);
1410        for ms in (1_000..2_000).step_by(100) {
1411            assert_eq!(
1412                None,
1413                controller.poll(at(ms), 2_500_000.0, 2_500_000.0, true)
1414            );
1415        }
1416        controller.on_path_change(at(2_000), 300_000.0);
1417        let mut asked = Vec::new();
1418        for ms in (2_000..10_000).step_by(100) {
1419            if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
1420                asked.push(request.bits_per_second);
1421                // The new path is narrow: every cluster shows 350 kbit/s.
1422                controller.on_result(request.cluster, 350_000.0);
1423            }
1424        }
1425        assert_eq!(
1426            vec![900_000.0, 1_800_000.0],
1427            asked,
1428            "the start-up clusters, and no probe for 85% of 2.5 Mbit/s"
1429        );
1430    }
1431
1432    /// [`AfterDropProbe::Libwebrtc`] across a path change: neither the old path's drop nor the
1433    /// estimator's fall to its starting rate is probed after, however often the new path's
1434    /// detector returns from under-use to normal (libwebrtc's `Reset` forgets the rate before
1435    /// the drop and counts the change as the time of its last such probe). The start-up
1436    /// clusters are all that is asked in the five seconds a drop stays eligible.
1437    #[test]
1438    fn libwebrtcs_probe_after_a_drop_is_not_asked_across_a_path_change() {
1439        let epoch = Instant::now();
1440        let mut controller = dropped_libwebrtc(epoch);
1441        let at = |ms: u64| epoch + Duration::from_millis(ms);
1442        controller.set_usage(Usage::Over);
1443        assert_eq!(None, controller.poll(at(1_200), 900_000.0, 450_000.0, true));
1444        controller.on_path_change(at(1_300), 300_000.0);
1445        let mut asked = Vec::new();
1446        for ms in (1_300..6_300).step_by(100) {
1447            recover_from_overuse(&mut controller);
1448            if let Some(request) = controller.poll(at(ms), 300_000.0, 150_000.0, true) {
1449                asked.push(request.bits_per_second);
1450                controller.on_result(request.cluster, 350_000.0);
1451            }
1452        }
1453        assert_eq!(vec![900_000.0, 1_800_000.0], asked);
1454    }
1455
1456    /// A controller with libwebrtc's probe after a drop, settled, application limited (it
1457    /// sends half its target) at 2 Mbit/s until 1 s and dropped to 900 kbit/s at 1.1 s.
1458    fn dropped_libwebrtc(epoch: Instant) -> ProbeController {
1459        let mut controller = settled(epoch).with_after_drop_probe(AfterDropProbe::Libwebrtc);
1460        let at = |ms: u64| epoch + Duration::from_millis(ms);
1461        assert_eq!(
1462            None,
1463            controller.poll(at(1_000), 2_000_000.0, 1_000_000.0, true)
1464        );
1465        assert_eq!(None, controller.poll(at(1_100), 900_000.0, 450_000.0, true));
1466        controller
1467    }
1468
1469    /// The detector's way back to normal after an over-use: over, under, normal.
1470    fn recover_from_overuse(controller: &mut ProbeController) {
1471        controller.set_usage(Usage::Over);
1472        controller.set_usage(Usage::Under);
1473        controller.set_usage(Usage::Normal);
1474    }
1475
1476    /// [`AfterDropProbe::Libwebrtc`]: nothing is asked until the detector has returned from
1477    /// under-use to normal; then one cluster at 85% of the target before the drop, which is
1478    /// not followed up, and no second one within five seconds.
1479    #[test]
1480    fn libwebrtcs_probe_after_a_drop_is_one_cluster_once_overuse_has_ended() {
1481        let epoch = Instant::now();
1482        let mut controller = dropped_libwebrtc(epoch);
1483        let at = |ms: u64| epoch + Duration::from_millis(ms);
1484        controller.set_usage(Usage::Over);
1485        for ms in (1_200..3_000).step_by(100) {
1486            assert_eq!(
1487                None,
1488                controller.poll(at(ms), 900_000.0, 450_000.0, true),
1489                "still over-used at {ms} ms"
1490            );
1491        }
1492        controller.set_usage(Usage::Under);
1493        assert_eq!(None, controller.poll(at(3_000), 900_000.0, 450_000.0, true));
1494        controller.set_usage(Usage::Normal);
1495        let request = controller
1496            .poll(at(3_100), 900_000.0, 450_000.0, true)
1497            .expect("back to normal: the rate before the drop");
1498        assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
1499        assert_eq!(
1500            Some(1_700_000.0),
1501            controller.on_result(request.cluster, 1_700_000.0)
1502        );
1503        assert_eq!(
1504            None,
1505            controller.poll(at(3_300), 1_700_000.0, 850_000.0, true),
1506            "no further cluster above it"
1507        );
1508        // A second drop and recovery a moment later: not within five seconds of the probe.
1509        assert_eq!(None, controller.poll(at(3_400), 900_000.0, 450_000.0, true));
1510        recover_from_overuse(&mut controller);
1511        assert_eq!(None, controller.poll(at(3_600), 900_000.0, 450_000.0, true));
1512    }
1513
1514    /// [`AfterDropProbe::Libwebrtc`] does not probe a sender that keeps up with its target
1515    /// (not application limited, nor lately), nor one whose target is within 5% of the rate
1516    /// it would ask for, nor a drop that is five seconds old.
1517    #[test]
1518    fn libwebrtcs_probe_after_a_drop_has_its_conditions() {
1519        let epoch = Instant::now();
1520        let at = |ms: u64| epoch + Duration::from_millis(ms);
1521
1522        // A sender at its target.
1523        let mut controller = settled(epoch).with_after_drop_probe(AfterDropProbe::Libwebrtc);
1524        assert_eq!(
1525            None,
1526            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1527        );
1528        assert_eq!(None, controller.poll(at(1_100), 900_000.0, 900_000.0, true));
1529        recover_from_overuse(&mut controller);
1530        assert_eq!(None, controller.poll(at(1_300), 900_000.0, 900_000.0, true));
1531
1532        // The target is back at 1.65 Mbit/s: 95% of 1.7 Mbit/s is not above it.
1533        let mut controller = dropped_libwebrtc(epoch);
1534        recover_from_overuse(&mut controller);
1535        assert_eq!(
1536            None,
1537            controller.poll(at(1_300), 1_650_000.0, 825_000.0, true)
1538        );
1539
1540        // The detector is back to normal only once the drop is over five seconds old: no
1541        // cluster at the rate before the drop (the one asked meanwhile is the
1542        // application-limited sender's, at twice the target).
1543        let mut controller = dropped_libwebrtc(epoch);
1544        let mut asked = Vec::new();
1545        for ms in (1_200..7_000).step_by(100) {
1546            if ms == 6_200 {
1547                recover_from_overuse(&mut controller);
1548            }
1549            if let Some(request) = controller.poll(at(ms), 900_000.0, 450_000.0, true) {
1550                asked.push(request.bits_per_second);
1551                controller.on_result(request.cluster, 950_000.0);
1552            }
1553        }
1554        assert_eq!(vec![1_800_000.0], asked);
1555    }
1556
1557    /// `with_probe_after_drop(false)`: a drop is left to the delay-based controller's climb.
1558    #[test]
1559    fn without_the_option_a_drop_is_not_probed() {
1560        let epoch = Instant::now();
1561        let mut controller = settled(epoch).with_probe_after_drop(false);
1562        let at = |ms: u64| epoch + Duration::from_millis(ms);
1563        assert_eq!(
1564            None,
1565            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1566        );
1567        for ms in (1_100..8_000).step_by(100) {
1568            assert_eq!(None, controller.poll(at(ms), 900_000.0, 900_000.0, true));
1569        }
1570    }
1571
1572    /// A controller with recovery probing and without the probes after a drop (so that every
1573    /// cluster seen is a recovery cluster), settled, at 2 Mbit/s until 1 s and dropped to
1574    /// 300 kbit/s at 1.1 s.
1575    fn dropped_with_recovery(epoch: Instant) -> ProbeController {
1576        let mut controller = settled(epoch)
1577            .with_probe_after_drop(false)
1578            .with_recovery_probing(true);
1579        let at = |ms: u64| epoch + Duration::from_millis(ms);
1580        assert_eq!(
1581            None,
1582            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1583        );
1584        assert_eq!(None, controller.poll(at(1_100), 300_000.0, 300_000.0, true));
1585        controller
1586    }
1587
1588    /// Recovery probing: after a large drop a sender at its target is asked for a cluster at
1589    /// twice the target every five seconds, from five seconds after the drop, for as long as
1590    /// the rate before the drop is remembered (a minute), and not after.
1591    #[test]
1592    fn recovery_probing_asks_twice_the_target_every_five_seconds_for_a_minute() {
1593        let epoch = Instant::now();
1594        let mut controller = dropped_with_recovery(epoch);
1595        let at = |ms: u64| epoch + Duration::from_millis(ms);
1596        let mut asked = Vec::new();
1597        for ms in (1_200..90_000).step_by(100) {
1598            if ms == 5_300 {
1599                assert_eq!(
1600                    Some(at(6_100)),
1601                    controller.poll_timeout(),
1602                    "the first recovery cluster's instant is a deadline"
1603                );
1604            }
1605            if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
1606                assert_eq!(600_000.0, request.bits_per_second, "at {ms} ms");
1607                asked.push(ms);
1608                // The path is still limited: the cluster shows less than the target.
1609                controller.on_result(request.cluster, 285_000.0);
1610            }
1611        }
1612        let expected: Vec<u64> = (0..12).map(|n| 6_100 + 5_000 * n).collect();
1613        assert_eq!(
1614            expected, asked,
1615            "every 5 s from 5 s after the drop, for 60 s"
1616        );
1617    }
1618
1619    /// The rate remembered for recovery probing is the path's: after a path change the
1620    /// start-up clusters look for the new path's rate, and when they show it to be narrow
1621    /// nothing goes on asking for the rate the old path had.
1622    #[test]
1623    fn recovery_probing_forgets_the_old_paths_rate_at_a_path_change() {
1624        let epoch = Instant::now();
1625        let mut controller = dropped_with_recovery(epoch);
1626        let at = |ms: u64| epoch + Duration::from_millis(ms);
1627        controller.on_path_change(at(2_000), 300_000.0);
1628        let mut asked = Vec::new();
1629        for ms in (2_000..30_000).step_by(100) {
1630            if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
1631                asked.push(request.bits_per_second);
1632                controller.on_result(request.cluster, 285_000.0);
1633            }
1634        }
1635        assert_eq!(
1636            vec![900_000.0, 1_800_000.0],
1637            asked,
1638            "the start-up clusters, and no recovery cluster for the old path's 2 Mbit/s"
1639        );
1640    }
1641
1642    /// Without the setting (the default) nothing is asked of a sender at its target once the
1643    /// probes after the drop have ended.
1644    #[test]
1645    fn without_recovery_probing_a_sender_at_its_target_is_not_probed_after_the_drop() {
1646        let epoch = Instant::now();
1647        let mut controller = settled(epoch).with_probe_after_drop(false);
1648        let at = |ms: u64| epoch + Duration::from_millis(ms);
1649        assert_eq!(
1650            None,
1651            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1652        );
1653        for ms in (1_100..30_000).step_by(100) {
1654            assert_eq!(
1655                None,
1656                controller.poll(at(ms), 300_000.0, 300_000.0, true),
1657                "at {ms} ms"
1658            );
1659        }
1660    }
1661
1662    /// A recovery cluster the path carries is followed by clusters at twice the result until
1663    /// one shows the bottleneck: the rate before the drop is back within a second.
1664    #[test]
1665    fn a_recovery_cluster_the_path_carries_is_followed_up() {
1666        let epoch = Instant::now();
1667        let mut controller = dropped_with_recovery(epoch);
1668        let at = |ms: u64| epoch + Duration::from_millis(ms);
1669        let mut target = 300_000.0;
1670        let mut asked = Vec::new();
1671        // The path carries 2.5 Mbit/s again.
1672        for ms in (1_200..8_000).step_by(100) {
1673            if let Some(request) = controller.poll(at(ms), target, target, true) {
1674                asked.push((ms, request.bits_per_second));
1675                let estimate = request.bits_per_second.min(2_500_000.0 * 0.95);
1676                target = controller
1677                    .on_result(request.cluster, estimate)
1678                    .expect("the outstanding cluster");
1679            }
1680        }
1681        assert_eq!(
1682            vec![
1683                (6_100, 600_000.0),
1684                (6_200, 1_200_000.0),
1685                (6_300, 2_400_000.0),
1686                (6_400, 4_750_000.0)
1687            ],
1688            asked
1689        );
1690        assert_eq!(2_375_000.0, target);
1691    }
1692
1693    /// No recovery cluster while the estimator reads over-use; the one that was due goes out
1694    /// when it no longer does.
1695    #[test]
1696    fn recovery_probing_waits_while_the_path_is_overused() {
1697        let epoch = Instant::now();
1698        let mut controller = dropped_with_recovery(epoch);
1699        let at = |ms: u64| epoch + Duration::from_millis(ms);
1700        controller.set_usage(Usage::Over);
1701        for ms in (1_200..9_000).step_by(100) {
1702            assert_eq!(
1703                None,
1704                controller.poll(at(ms), 300_000.0, 300_000.0, true),
1705                "at {ms} ms"
1706            );
1707        }
1708        controller.set_usage(Usage::Normal);
1709        let request = controller
1710            .poll(at(9_000), 300_000.0, 300_000.0, true)
1711            .expect("no over-use: the cluster that was due");
1712        assert_eq!(600_000.0, request.bits_per_second);
1713    }
1714
1715    /// The smaller drops under a limit (the controller's own sawtooth) do not replace the
1716    /// rate remembered from before it: a target above 85% of the sawtooth's peak is still
1717    /// probed, and one above 85% of the rate before the limit is not.
1718    #[test]
1719    fn recovery_probing_remembers_the_rate_before_the_limit_through_smaller_drops() {
1720        let epoch = Instant::now();
1721        let mut controller = dropped_with_recovery(epoch);
1722        let at = |ms: u64| epoch + Duration::from_millis(ms);
1723        // A sawtooth under the limit: up to 350 kbit/s, cut to 220 kbit/s (a large drop).
1724        assert_eq!(None, controller.poll(at(2_000), 350_000.0, 350_000.0, true));
1725        assert_eq!(None, controller.poll(at(2_100), 220_000.0, 220_000.0, true));
1726        // 400 kbit/s is above the sawtooth's peak and far below the 2 Mbit/s before the limit.
1727        let request = (2_200..8_000)
1728            .step_by(100)
1729            .find_map(|ms| controller.poll(at(ms), 400_000.0, 400_000.0, true))
1730            .expect("still below the remembered rate");
1731        assert_eq!(800_000.0, request.bits_per_second);
1732        controller.on_result(request.cluster, 380_000.0);
1733        // At 1.8 Mbit/s (over 85% of 2 Mbit/s) there is nothing left to recover.
1734        for ms in (8_000..20_000).step_by(100) {
1735            assert_eq!(
1736                None,
1737                controller.poll(at(ms), 1_800_000.0, 1_800_000.0, true),
1738                "at {ms} ms"
1739            );
1740        }
1741    }
1742
1743    /// A chain whose clusters leave as bursts is not probed for recovery, and names no
1744    /// deadline for it.
1745    #[test]
1746    fn recovery_probing_is_not_for_clusters_that_leave_as_bursts() {
1747        let epoch = Instant::now();
1748        let mut controller = dropped_with_recovery(epoch);
1749        controller.set_unpaced(true);
1750        let at = |ms: u64| epoch + Duration::from_millis(ms);
1751        for ms in (1_200..20_000).step_by(100) {
1752            assert_eq!(
1753                None,
1754                controller.poll(at(ms), 300_000.0, 300_000.0, true),
1755                "at {ms} ms"
1756            );
1757            // The one deadline left is the application-limited cluster's, five seconds after
1758            // the start-up sequence.
1759            assert!(
1760                controller
1761                    .poll_timeout()
1762                    .is_none_or(|next| next == at(5_150)),
1763                "a deadline for a cluster that will not be asked for, at {ms} ms"
1764            );
1765        }
1766    }
1767
1768    /// A deadline that came with nothing to send (here: an application-limited probe falls due
1769    /// while the sender has caught up with its target) is not asked for again: a driver that
1770    /// sleeps until `poll_timeout` would otherwise be woken at once, over and over.
1771    #[test]
1772    fn a_deadline_that_passed_with_nothing_due_is_not_asked_again() {
1773        let epoch = Instant::now();
1774        let mut controller = settled(epoch);
1775        let due = controller
1776            .poll_timeout()
1777            .expect("the next application-limited probe");
1778        assert_eq!(None, controller.poll(due, 1_000_000.0, 1_000_000.0, true));
1779        assert!(
1780            controller.poll_timeout().is_none_or(|next| next > due),
1781            "{:?}",
1782            controller.poll_timeout()
1783        );
1784        // Not flowing at all: nothing to wake for either.
1785        let later = due + Duration::from_secs(10);
1786        assert_eq!(None, controller.poll(later, 1_000_000.0, 0.0, false));
1787        assert!(controller.poll_timeout().is_none_or(|next| next > later));
1788    }
1789}