Skip to main content

rtci_interceptor/rfc8888/
ecn.rs

1//! ECN initiation and failure detection for an RTP stream whose feedback is RFC 8888.
2//!
3//! RFC 8888 section 7: "When using ECN with RTP, the guidelines in Section 7.2 of [RFC6679]
4//! MUST be followed to initiate the use of ECN in an RTP session", section 7.3's ongoing use
5//! likewise, and "the guidance in Section 7.4 of [RFC6679] related to detecting failures MUST
6//! be followed, with the exception that the necessary information is retrieved from the RTCP
7//! Congestion Control Feedback Packets".
8//!
9//! [`EcnValidation`] is that sender-side procedure for one stream, sans-I/O: it is told of each
10//! packet sent ([`EcnValidation::on_send`], which answers whether the packet goes out ECT) and
11//! of each RFC 8888 report about one ([`EcnValidation::on_report`]).
12//!
13//! * **Initiation** (RFC 6679 section 7.2.1, the in-band method every implementation MUST
14//!   have): "an RTP sender SHALL mark a small fraction of its RTP traffic as ECT", "a minimum
15//!   of two packets with ECT markings per RTCP reporting interval" is RECOMMENDED, and it
16//!   "SHOULD NOT mark all RTP packets". Here one packet in [`PROBE_SPACING`], and one at least
17//!   every [`PROBE_INTERVAL`], never two in a row. On a unicast transport the initiation "MAY
18//!   [be treated] as provisionally successful if it receives [a report] indicating successful
19//!   receipt of the ECT-marked packets, with no negative indications": [`CONFIRMATIONS`]
20//!   probes reported received ECT (or CE) and none reported Not-ECT. It "is considered to have
21//!   failed" when the feedback shows the receiver "should have received multiple (>3)
22//!   ECT-marked RTP packets" and none arrived marked: here more than three probes reported
23//!   lost while none was reported received, or a probe reported received Not-ECT.
24//! * **Ongoing use** (section 7.3.1): after success the sender "SHOULD mark all the RTP data
25//!   packets it sends as ECT".
26//! * **Failures** (section 7.4): a path that clears the ECN field ("the ratio [...] has become
27//!   all not-ECT, or has substantially changed towards not-ECT", section 7.4.2) stops the
28//!   marking: more than a quarter of a window of [`WINDOW`] reported ECT packets arrived
29//!   Not-ECT. "A sender that detects high packet loss rates for ECT-marked packets SHOULD
30//!   immediately switch to sending packets as not-ECT to determine if the losses are
31//!   potentially due to the ECT markings. If the losses disappear when the ECT-marking is
32//!   discontinued, the RTP sender should go back to initiation procedures": half a window lost
33//!   switches to Not-ECT for a window; if the loss falls under a quarter the stream initiates
34//!   again, else (the loss is the path's, not ECN's) it resumes marking. After a failed
35//!   initiation the sender "periodically [retries] the ECN initiation" (the first option of
36//!   section 7.4.1) every [`DEFAULT_RETRY_AFTER`], and "if multiple initiations have been successful, but
37//!   the following full usage of ECN has resulted in the fallback procedures, then disabling
38//!   of the ECN support is RECOMMENDED": the second such fallback ends ECN for the stream.
39//!
40//! RTCP is never marked (section 7.2: "SHALL NOT ECT mark their RTCP traffic"); that is the
41//! caller's part, as is choosing the codepoint (ECT(1) for L4S, RFC 9331).
42
43use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
44use rtcp::transport_feedbacks::ecn_feedback::EcnCounters;
45use std::time::{Duration, Instant};
46
47/// During initiation one packet in this many is a probe sent ECT.
48pub const PROBE_SPACING: u32 = 10;
49/// During initiation a probe is sent at least this often (given an unmarked packet since the
50/// last one): two per RTCP reporting interval at the shortest regular interval RFC 3550
51/// section 6.2 allows a reduced-minimum sender (360 / session kbit/s seconds) is met for any
52/// session above 720 kbit/s by the spacing, and below by this.
53pub const PROBE_INTERVAL: Duration = Duration::from_millis(500);
54/// Probes reported received with an ECN-capable marking that make the initiation succeed.
55pub const CONFIRMATIONS: u32 = 2;
56/// Probes reported lost, none received, that make the initiation fail (RFC 6679 section 7.2.1:
57/// "multiple (>3)").
58pub const PROBES_LOST_TO_FAIL: u32 = 4;
59/// Reported packets the failure checks of ongoing use are made over.
60pub const WINDOW: u32 = 32;
61/// How long after a failed initiation the next one starts (RFC 6679 section 7.4.1 option 1).
62pub const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(60);
63/// Fallbacks from ongoing use, each confirmed as ECN's doing, after which ECN stays off.
64pub const FALLBACKS_TO_DISABLE: u32 = 2;
65/// How long after the start of an initiation a provisional success is watched for other
66/// receivers (RFC 6679 section 7.2.1: "three RTCP reporting intervals from the time the ECN
67/// initiation started"): three of RTP/AVP's 5 s minimum interval, the longest regular
68/// interval this engine computes without a configured `trr-int`.
69pub const PROVISIONAL_MONITOR: Duration = Duration::from_secs(15);
70
71/// Sent packets remembered, by sequence number, to match reports with how each was sent.
72const HISTORY: usize = 2048;
73
74/// Where a stream is in RFC 6679's procedure.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum EcnState {
77    /// Section 7.2.1: a fraction of the packets are probes sent ECT.
78    Initiating,
79    /// Section 7.3.1: every packet is sent ECT.
80    Active,
81    /// Section 7.4.1: ECT-marked packets were lost at a high rate; packets go out Not-ECT to
82    /// see whether the loss goes with the marking.
83    Fallback,
84    /// The path does not carry ECN; nothing is marked until `retry_at`.
85    Failed {
86        /// When the next initiation starts.
87        retry_at: Instant,
88    },
89    /// ECN is off for the stream for good (section 7.4.1).
90    Disabled,
91}
92
93/// Which ECT codepoint a receiver asks the sender to use: the `ect=` parameter of its
94/// `a=ecn-capable-rtp` (RFC 6679 section 6.1). Left out, the sender uses ECT(0).
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum EctPreference {
97    /// `ect=0`.
98    Ect0,
99    /// `ect=1`.
100    Ect1,
101    /// `ect=random`: the sender picks ECT(0) or ECT(1) at random for each packet.
102    Random,
103}
104
105impl EctPreference {
106    /// The value of an `ect=` parameter (`0`, `1` or `random`, any case); `None` for any
107    /// other, which RFC 6679 section 6.1 has the receiver of the description ignore.
108    pub fn from_sdp(value: &str) -> Option<Self> {
109        match value.trim().to_ascii_lowercase().as_str() {
110            "0" => Some(Self::Ect0),
111            "1" => Some(Self::Ect1),
112            "random" => Some(Self::Random),
113            _ => None,
114        }
115    }
116}
117
118/// Which ECT codepoint a stream that marks sends.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
120pub enum EcnMarking {
121    /// RFC 6679 section 7.3.1: ECT(0), unless the receiver asked for ECT(1) or a random
122    /// choice ([`EctPreference`]).
123    #[default]
124    Rfc6679,
125    /// ECT(1), the L4S identifier (RFC 9331), whatever the receiver asked: what browsers that
126    /// send L4S do.
127    L4s,
128}
129
130impl EcnMarking {
131    /// The codepoint the next packet goes out with, given the receiver's preference;
132    /// `coin` is a random bit, used for [`EctPreference::Random`].
133    pub fn codepoint(self, preference: Option<EctPreference>, coin: bool) -> shared::EcnCodepoint {
134        match (self, preference) {
135            (Self::L4s, _) | (Self::Rfc6679, Some(EctPreference::Ect1)) => {
136                shared::EcnCodepoint::Ect1
137            }
138            (Self::Rfc6679, Some(EctPreference::Random)) if coin => shared::EcnCodepoint::Ect1,
139            _ => shared::EcnCodepoint::Ect0,
140        }
141    }
142}
143
144/// How a stream starts using ECN.
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
146pub enum EcnInitiation {
147    /// RFC 6679 section 7.2.1: probes, then every packet once feedback confirmed them (the
148    /// method every implementation MUST have).
149    #[default]
150    RtpAndRtcp,
151    /// RFC 6679 section 7.2.3, leap of faith: every packet is sent ECT from the first, as
152    /// browsers that implement L4S do. Failure detection (section 7.4) still applies. The RFC
153    /// allows it only for sessions that accept its limitations (the first packets may be lost
154    /// on a path that drops ECT traffic).
155    LeapOfFaith,
156}
157
158impl EcnInitiation {
159    /// RFC 6679 section 7.2: "all participants in an RTP session MUST use the same ECN
160    /// initiation method". Given each section's transport and the method its negotiation
161    /// gave, the method each section's streams use: the first method negotiated on the
162    /// transport, for every section on it that uses ECN at all (bundled sections share one
163    /// RTP session, RFC 9143). A section without ECN stays without.
164    pub fn one_per_transport<K: PartialEq + Copy>(
165        sections: &[(K, Option<EcnInitiation>)],
166    ) -> Vec<Option<EcnInitiation>> {
167        sections
168            .iter()
169            .map(|(transport, method)| {
170                method.and_then(|_| {
171                    sections
172                        .iter()
173                        .find(|(other, m)| other == transport && m.is_some())
174                        .and_then(|(_, m)| *m)
175                })
176            })
177            .collect()
178    }
179}
180
181/// An ECN failure a stream's validation detected (RFC 6679 sections 7.2.1 and 7.4.2: detected
182/// failures and erroneous behaviour "should" be logged "to enable follow up"). Each is logged
183/// and kept for the application ([`EcnValidation::take_failures`]).
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185#[non_exhaustive]
186pub enum EcnFailure {
187    /// Initiation failed: an ECT probe was reported arriving Not-ECT.
188    ProbeArrivedNotEct,
189    /// Initiation failed: no ECT probe arrived.
190    NoProbeArrived,
191    /// Initiation failed: the path clears the ECN field.
192    FieldCleared,
193    /// Initiation failed: the receiver's counters counted the ECT probes as Not-ECT.
194    ProbesCountedNotEct,
195    /// Initiation failed: a receiver reported more than three probes in a reception report
196    /// without an ECN report (section 7.2.1).
197    NoEcnReport,
198    /// Leap of faith failed: two receiver reports in a row showed no reception of the stream
199    /// (section 7.2.3).
200    NoReception,
201    /// After initiation, ECT packets were lost where Not-ECT ones were not (section 7.4.2):
202    /// the stream falls back and initiates again, or, `disabled`, ECN stays off for it.
203    EctLost {
204        /// Whether ECN is now off for the stream.
205        disabled: bool,
206    },
207}
208
209impl EcnFailure {
210    /// Whether this ends an initiation (section 7.2.1), as against a failure after one.
211    pub fn is_initiation_failure(&self) -> bool {
212        !matches!(self, EcnFailure::EctLost { .. })
213    }
214}
215
216impl std::fmt::Display for EcnFailure {
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        f.write_str(match self {
219            EcnFailure::ProbeArrivedNotEct => "an ECT probe arrived Not-ECT",
220            EcnFailure::NoProbeArrived => "no ECT probe arrived",
221            EcnFailure::FieldCleared => "the path clears the ECN field",
222            EcnFailure::ProbesCountedNotEct => "ECT probes were counted Not-ECT",
223            EcnFailure::NoEcnReport => {
224                "a receiver reported more than three probes without an ECN report"
225            }
226            EcnFailure::NoReception => "two receiver reports in a row showed no reception",
227            EcnFailure::EctLost { disabled: true } => {
228                "ECT packets were lost again; ECN off for the stream"
229            }
230            EcnFailure::EctLost { disabled: false } => "ECT packets were lost; initiating again",
231        })
232    }
233}
234
235/// At most this many failures are kept for the application.
236const MAX_KEPT_FAILURES: usize = 16;
237
238#[derive(Debug, Clone, Copy, Default)]
239struct Sent {
240    sequence_number: u16,
241    /// Whether this slot describes a packet at all.
242    known: bool,
243    marked: bool,
244    /// Reported so far: received (true), lost (false), not yet (`None`).
245    reported: Option<bool>,
246}
247
248/// Counts over one window of reported packets.
249#[derive(Debug, Clone, Copy, Default)]
250struct Window {
251    reported: u32,
252    lost: u32,
253    bleached: u32,
254}
255
256/// RFC 6679 sections 7.2-7.4 for one RTP stream, fed from RFC 8888 reports. See the module
257/// documentation.
258#[derive(Debug, Clone)]
259pub struct EcnValidation {
260    state: EcnState,
261    retry_after: Duration,
262    since_probe: u32,
263    last_probe: Option<Instant>,
264    history: Box<[Sent]>,
265    probes_confirmed: u32,
266    probes_lost: u32,
267    window: Window,
268    /// The loss of the window that sent the stream into [`EcnState::Fallback`].
269    fallback_from: u32,
270    fallbacks: u32,
271    /// The last RFC 6679 counters reported, with the extended highest sequence number they
272    /// relate to ([`EcnValidation::on_counters`]).
273    last_counters: Option<(u32, EcnCounters)>,
274    /// When the current initiation sent its first probe.
275    initiated_at: Option<Instant>,
276    /// The success of the initiation is provisional until then (section 7.2.1).
277    provisional_until: Option<Instant>,
278    /// The RTCP CNAME of the receiver whose reports confirmed the probes.
279    receiver_cname: Option<String>,
280    /// Failures detected and not taken yet.
281    failures: Vec<EcnFailure>,
282    /// Marking from the first packet without probes (section 7.2.3), until reception is seen.
283    leap_of_faith: bool,
284    /// Receiver reports in a row that showed no reception of the stream.
285    reports_without_reception: u32,
286}
287
288impl Default for EcnValidation {
289    fn default() -> Self {
290        Self::new(EcnInitiation::default())
291    }
292}
293
294impl EcnValidation {
295    /// A stream about to send its first packet with ECN negotiated.
296    pub fn new(initiation: EcnInitiation) -> Self {
297        Self {
298            state: match initiation {
299                EcnInitiation::RtpAndRtcp => EcnState::Initiating,
300                EcnInitiation::LeapOfFaith => EcnState::Active,
301            },
302            retry_after: DEFAULT_RETRY_AFTER,
303            since_probe: PROBE_SPACING,
304            last_probe: None,
305            history: vec![Sent::default(); HISTORY].into_boxed_slice(),
306            probes_confirmed: 0,
307            probes_lost: 0,
308            window: Window::default(),
309            fallback_from: 0,
310            fallbacks: 0,
311            last_counters: None,
312            initiated_at: None,
313            provisional_until: None,
314            receiver_cname: None,
315            failures: Vec::new(),
316            leap_of_faith: initiation == EcnInitiation::LeapOfFaith,
317            reports_without_reception: 0,
318        }
319    }
320
321    /// How long after a failed initiation the next one starts ([`DEFAULT_RETRY_AFTER`]).
322    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
323        self.retry_after = retry_after;
324        self
325    }
326
327    /// Where the stream is in the procedure.
328    pub fn state(&self) -> EcnState {
329        self.state
330    }
331
332    /// Whether a packet of the stream that is not one of its own numbered packets (an RTX
333    /// retransmission, say) goes out ECT: only in ongoing use, so probes are the stream's own
334    /// packets, whose reports name them.
335    pub fn marks_all(&self) -> bool {
336        self.state == EcnState::Active
337    }
338
339    /// Whether the packet `sequence_number` was sent ECT, as far as the history still knows.
340    pub fn was_marked(&self, sequence_number: u16) -> bool {
341        let slot = &self.history[usize::from(sequence_number) % HISTORY];
342        slot.known && slot.sequence_number == sequence_number && slot.marked
343    }
344
345    /// A packet of the stream is sent at `now`: whether it goes out ECT.
346    pub fn on_send(&mut self, now: Instant, sequence_number: u16) -> bool {
347        if let EcnState::Failed { retry_at } = self.state
348            && now >= retry_at
349        {
350            self.initiate();
351        }
352        let marked = match self.state {
353            EcnState::Initiating => {
354                let due = self.since_probe + 1 >= PROBE_SPACING
355                    || (self.since_probe >= 1
356                        && self
357                            .last_probe
358                            .is_none_or(|at| now.saturating_duration_since(at) >= PROBE_INTERVAL));
359                if due {
360                    self.since_probe = 0;
361                    self.last_probe = Some(now);
362                    self.initiated_at.get_or_insert(now);
363                } else {
364                    self.since_probe += 1;
365                }
366                due
367            }
368            EcnState::Active => true,
369            EcnState::Fallback | EcnState::Failed { .. } | EcnState::Disabled => false,
370        };
371        self.history[usize::from(sequence_number) % HISTORY] = Sent {
372            sequence_number,
373            known: true,
374            marked,
375            reported: None,
376        };
377        marked
378    }
379
380    /// An RFC 8888 report about the packet `sequence_number` arrived at `now`: whether it was
381    /// received, and if so the ECN field it arrived with.
382    pub fn on_report(&mut self, now: Instant, sequence_number: u16, received: bool, ecn: Ecn) {
383        let slot = &mut self.history[usize::from(sequence_number) % HISTORY];
384        if !slot.known || slot.sequence_number != sequence_number {
385            return;
386        }
387        // Each packet counts once; a loss reported and then undone by a later report (the
388        // packet was late) is taken back.
389        let undo_loss = match slot.reported {
390            Some(true) => return,
391            Some(false) if !received => return,
392            Some(false) => true,
393            None => false,
394        };
395        slot.reported = Some(received);
396        let marked = slot.marked;
397        let ecn_capable = matches!(ecn, Ecn::Ect0 | Ecn::Ect1 | Ecn::Ce);
398
399        match self.state {
400            EcnState::Initiating if marked => {
401                if undo_loss {
402                    self.probes_lost = self.probes_lost.saturating_sub(1);
403                }
404                if !received {
405                    self.probes_lost += 1;
406                } else if ecn_capable {
407                    self.probes_confirmed += 1;
408                } else {
409                    // A negative indication: the path cleared the ECN field.
410                    self.fail(now, EcnFailure::ProbeArrivedNotEct);
411                    return;
412                }
413                if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
414                    self.fail(now, EcnFailure::NoProbeArrived);
415                } else if self.probes_confirmed >= CONFIRMATIONS {
416                    self.provisional_success(now);
417                }
418            }
419            EcnState::Active if marked => {
420                self.count(undo_loss, received, !ecn_capable);
421                if self.window.bleached * 4 > WINDOW {
422                    self.fail(now, EcnFailure::FieldCleared);
423                } else if self.window.lost * 2 >= WINDOW {
424                    log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
425                    self.state = EcnState::Fallback;
426                    self.fallback_from = self.window.lost;
427                    self.window = Window::default();
428                } else if self.window.reported >= WINDOW {
429                    self.window = Window::default();
430                }
431            }
432            EcnState::Fallback if !marked => {
433                self.count(undo_loss, received, false);
434                if self.window.reported >= WINDOW {
435                    if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
436                        // The loss went with the marking.
437                        self.fallbacks += 1;
438                        if self.fallbacks >= FALLBACKS_TO_DISABLE {
439                            self.record(EcnFailure::EctLost { disabled: true });
440                            self.state = EcnState::Disabled;
441                        } else {
442                            self.record(EcnFailure::EctLost { disabled: false });
443                            self.initiate();
444                        }
445                    } else {
446                        // Not-ECT packets were lost as much: the path's loss, not ECN's.
447                        self.state = EcnState::Active;
448                        self.window = Window::default();
449                    }
450                }
451            }
452            _ => {}
453        }
454    }
455
456    /// An RFC 6679 report about the stream arrived at `now`: the receiver's cumulative ECN
457    /// counters (an RTCP ECN Feedback packet, section 5.1, or an XR ECN Summary Report,
458    /// section 5.2) and the extended highest sequence number they relate to (the feedback
459    /// packet's, or the reception report's in the same compound packet). The procedure is the
460    /// one [`on_report`](Self::on_report) runs, on what changed since the last report: the
461    /// packets sent up to the new highest sequence number, how many went out ECT, and how many
462    /// the receiver counted ECT or CE, not-ECT, lost and duplicated (section 7.4.2).
463    ///
464    /// * Initiating: ECT or CE counts confirm probes; not-ECT counts beyond the unmarked
465    ///   packets sent (and the duplicates) are a negative indication; more than three probes
466    ///   sent with no ECT counted is a failure (section 7.2.1).
467    /// * Ongoing use: each packet sent ECT is reported; the not-ECT count beyond duplicates is
468    ///   bleaching, the lost count is loss; the thresholds are those of per-packet reports.
469    pub fn on_counters(&mut self, now: Instant, extended_highest: u32, counters: EcnCounters) {
470        let (previous_highest, previous) = match self.last_counters {
471            Some(last) => last,
472            None => (
473                extended_highest.wrapping_sub(self.known_since(extended_highest)),
474                EcnCounters::default(),
475            ),
476        };
477        // An older report than the last one says nothing new.
478        let span = extended_highest.wrapping_sub(previous_highest);
479        if span > 0x8000_0000 {
480            return;
481        }
482        self.last_counters = Some((extended_highest, counters));
483        if span == 0 && counters == previous {
484            return;
485        }
486        let ect = u64::from(counters.ect0.wrapping_sub(previous.ect0))
487            + u64::from(counters.ect1.wrapping_sub(previous.ect1))
488            + u64::from(counters.ce.wrapping_sub(previous.ce));
489        let not_ect = u64::from(counters.not_ect.wrapping_sub(previous.not_ect));
490        let duplicates = u64::from(counters.duplicates.wrapping_sub(previous.duplicates));
491        // The loss counter may fall (late packets) between reports.
492        let lost = i64::from(counters.lost.wrapping_sub(previous.lost) as i16).max(0) as u64;
493
494        // What went out in (previous_highest, extended_highest], as far as the history knows.
495        let (mut marked, mut unmarked) = (0u64, 0u64);
496        let first = previous_highest.wrapping_add(1);
497        for offset in 0..span.min(HISTORY as u32) {
498            let sequence_number = first.wrapping_add(offset) as u16;
499            let slot = &self.history[usize::from(sequence_number) % HISTORY];
500            if slot.known && slot.sequence_number == sequence_number {
501                if slot.marked {
502                    marked += 1;
503                } else {
504                    unmarked += 1;
505                }
506            }
507        }
508        let bleached = not_ect.saturating_sub(unmarked + duplicates);
509
510        match self.state {
511            EcnState::Initiating => {
512                if bleached > 0 && marked > 0 {
513                    self.fail(now, EcnFailure::ProbesCountedNotEct);
514                    return;
515                }
516                self.probes_confirmed += ect.min(u64::from(u32::MAX)) as u32;
517                if ect == 0 {
518                    self.probes_lost += marked as u32;
519                }
520                if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
521                    self.fail(now, EcnFailure::NoProbeArrived);
522                } else if self.probes_confirmed >= CONFIRMATIONS && bleached == 0 {
523                    self.provisional_success(now);
524                }
525            }
526            EcnState::Active => {
527                self.window.reported += marked as u32;
528                self.window.lost += lost.min(marked) as u32;
529                self.window.bleached += bleached.min(marked) as u32;
530                if self.window.bleached * 4 > WINDOW {
531                    self.fail(now, EcnFailure::FieldCleared);
532                } else if self.window.lost * 2 >= WINDOW {
533                    log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
534                    self.state = EcnState::Fallback;
535                    self.fallback_from = self.window.lost;
536                    self.window = Window::default();
537                } else if self.window.reported >= WINDOW {
538                    self.window = Window::default();
539                }
540            }
541            EcnState::Fallback => {
542                self.window.reported += unmarked as u32;
543                self.window.lost += lost.min(unmarked) as u32;
544                if self.window.reported >= WINDOW {
545                    if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
546                        self.fallbacks += 1;
547                        if self.fallbacks >= FALLBACKS_TO_DISABLE {
548                            self.record(EcnFailure::EctLost { disabled: true });
549                            self.state = EcnState::Disabled;
550                        } else {
551                            self.record(EcnFailure::EctLost { disabled: false });
552                            self.initiate();
553                        }
554                    } else {
555                        self.state = EcnState::Active;
556                        self.window = Window::default();
557                    }
558                }
559            }
560            EcnState::Failed { .. } | EcnState::Disabled => {}
561        }
562    }
563
564    /// How many sequence numbers before `extended_highest` the history holds sent packets
565    /// for: the span the first RFC 6679 report covers.
566    fn known_since(&self, extended_highest: u32) -> u32 {
567        let mut span = 0u32;
568        while span < HISTORY as u32 {
569            let sequence_number = extended_highest.wrapping_sub(span) as u16;
570            let slot = &self.history[usize::from(sequence_number) % HISTORY];
571            if !(slot.known && slot.sequence_number == sequence_number) {
572                break;
573            }
574            span += 1;
575        }
576        span
577    }
578
579    fn count(&mut self, undo_loss: bool, received: bool, bleached: bool) {
580        if undo_loss {
581            self.window.lost = self.window.lost.saturating_sub(1);
582        } else {
583            self.window.reported += 1;
584        }
585        if !received {
586            self.window.lost += 1;
587        } else if bleached {
588            self.window.bleached += 1;
589        }
590    }
591
592    /// The probes were confirmed by one receiver: every packet is marked from now on, while
593    /// the session is watched for other receivers (section 7.2.1's optimisation for a
594    /// unicast peer).
595    fn provisional_success(&mut self, now: Instant) {
596        self.state = EcnState::Active;
597        self.window = Window::default();
598        let started = self.initiated_at.unwrap_or(now);
599        self.provisional_until = Some(started + PROVISIONAL_MONITOR);
600    }
601
602    /// RFC 6679 section 7.2.1: a source of the session named its RTCP CNAME at `now`. The
603    /// first one is the receiver the probes are confirmed by. Another CNAME while the
604    /// success is provisional is another participant: "the sender MUST fallback to only
605    /// ECT-marking a small fraction of its RTP packets" and initiates again.
606    pub fn on_remote_cname(&mut self, now: Instant, cname: &str) {
607        match &self.receiver_cname {
608            None => self.receiver_cname = Some(cname.to_owned()),
609            Some(known) if known == cname => {}
610            Some(_) => {
611                let provisional = self.state == EcnState::Active
612                    && self.provisional_until.is_some_and(|until| now < until);
613                if provisional {
614                    log::info!(
615                        "ECN: another RTCP CNAME during a provisional success, probing again \
616                         (RFC 6679 section 7.2.1)"
617                    );
618                    self.initiate();
619                }
620                // Probing again, the confirmation has to come from the new set of receivers.
621                self.receiver_cname = Some(cname.to_owned());
622            }
623        }
624    }
625
626    /// RFC 6679 section 7.2.1: "ECN initiation is considered to have failed at the instant
627    /// the initiating RTP sender received an RTCP packet that doesn't contain an RTCP ECN
628    /// Feedback Report or ECN Summary Report from any RTP session participant that has an
629    /// RTCP RR with an extended RTP sequence number field that indicates that it should have
630    /// received multiple (>3) ECT-marked RTP packets." `extended_highest` is that field of a
631    /// reception report about the stream in a compound packet without an ECN report about it.
632    pub fn on_reception_report_without_ecn(&mut self, now: Instant, extended_highest: u32) {
633        if self.state != EcnState::Initiating {
634            return;
635        }
636        let highest = extended_highest as u16;
637        let due = self
638            .history
639            .iter()
640            .filter(|sent| {
641                sent.known && sent.marked && {
642                    // At or before `highest`, within the history's reach.
643                    let behind = highest.wrapping_sub(sent.sequence_number);
644                    usize::from(behind) < HISTORY
645                }
646            })
647            .count();
648        if due > 3 {
649            self.fail(now, EcnFailure::NoEcnReport);
650        }
651    }
652
653    /// RFC 6679 section 7.2.3, leap of faith: a receiver report (SR or RR) arrived that has no
654    /// report block about the stream, or one showing that nothing was received. A path with an
655    /// ECN-blocking middlebox shows that way; but "a receiver might generate its first RTCP
656    /// packet ... before it has had chance to receive any data packets", so "a sender that
657    /// receives an RTCP SR/RR packet indicating lack of reception by a receiver SHOULD ...
658    /// wait for a second RTCP report from that receiver": the second such report in a row
659    /// ends the marking. Nothing changes once reception was reported, outside the leap of
660    /// faith, or before a marked packet was sent.
661    pub fn on_report_without_reception(&mut self, now: Instant) {
662        if !self.leap_of_faith
663            || self.state != EcnState::Active
664            || !self.history.iter().any(|sent| sent.known && sent.marked)
665        {
666            return;
667        }
668        self.reports_without_reception += 1;
669        if self.reports_without_reception >= 2 {
670            self.leap_of_faith = false;
671            self.fail(now, EcnFailure::NoReception);
672        }
673    }
674
675    /// A receiver report showed reception of the stream: the path carries its ECT packets.
676    pub fn on_reception_reported(&mut self) {
677        self.reports_without_reception = 0;
678        self.leap_of_faith = false;
679    }
680
681    /// A validation that knows the receiver by its RTCP CNAME already (named before the
682    /// stream started marking).
683    pub fn with_receiver_cname(mut self, cname: &str) -> Self {
684        self.receiver_cname = Some(cname.to_owned());
685        self
686    }
687
688    /// Whether the success of the initiation is still provisional at `now`.
689    pub fn is_provisional(&self, now: Instant) -> bool {
690        self.state == EcnState::Active && self.provisional_until.is_some_and(|until| now < until)
691    }
692
693    fn initiate(&mut self) {
694        self.provisional_until = None;
695        self.initiated_at = None;
696        self.state = EcnState::Initiating;
697        self.since_probe = PROBE_SPACING;
698        self.last_probe = None;
699        self.probes_confirmed = 0;
700        self.probes_lost = 0;
701        self.window = Window::default();
702    }
703
704    /// RFC 6679 sections 7.2.1 and 7.4.2: a detected failure is logged ("they should log these
705    /// to enable follow up") and kept for the application.
706    fn record(&mut self, failure: EcnFailure) {
707        if failure.is_initiation_failure() {
708            log::warn!("ECN: {failure}; packets go out Not-ECT");
709        } else {
710            log::warn!("ECN: {failure}");
711        }
712        if self.failures.len() == MAX_KEPT_FAILURES {
713            self.failures.remove(0);
714        }
715        self.failures.push(failure);
716    }
717
718    /// The failures detected since the last call, oldest first (at most sixteen are kept).
719    pub fn take_failures(&mut self) -> Vec<EcnFailure> {
720        std::mem::take(&mut self.failures)
721    }
722
723    fn fail(&mut self, now: Instant, failure: EcnFailure) {
724        self.record(failure);
725        self.state = EcnState::Failed {
726            retry_at: now + self.retry_after,
727        };
728        self.window = Window::default();
729    }
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735
736    /// RFC 6679 counters for `marked` probes and the unmarked rest of `first..=last`, as a
737    /// receiver on a path that `ect_arrives` (or clears the field) counts them.
738    fn counters_for(
739        sent: &[u16],
740        marked: &[u16],
741        ect_arrives: bool,
742        lost: u16,
743        base: EcnCounters,
744    ) -> EcnCounters {
745        let marked_count = marked.len() as u32;
746        let unmarked = (sent.len() - marked.len()) as u16;
747        let mut c = base;
748        if ect_arrives {
749            c.ect1 += marked_count - u32::from(lost.min(marked_count as u16));
750            c.not_ect += unmarked;
751        } else {
752            c.not_ect += unmarked + marked_count as u16 - lost;
753        }
754        c.lost += lost;
755        c
756    }
757
758    /// RFC 6679 7.2.1 with the counters of section 5: probes counted ECT by the receiver's
759    /// ECN Feedback / XR ECN Summary Reports make the initiation succeed, and every packet is
760    /// then sent ECT (section 7.3.1).
761    /// RFC 6679 section 7.2: one initiation method per RTP session. Bundled sections that
762    /// negotiated different methods use the first one's; another transport keeps its own.
763    #[test]
764    fn bundled_sections_use_one_initiation_method() {
765        use EcnInitiation::{LeapOfFaith, RtpAndRtcp};
766        let methods = EcnInitiation::one_per_transport(&[
767            (0, Some(RtpAndRtcp)),
768            (0, Some(LeapOfFaith)),
769            (0, None),
770            (1, Some(LeapOfFaith)),
771        ]);
772        assert_eq!(
773            methods,
774            vec![Some(RtpAndRtcp), Some(RtpAndRtcp), None, Some(LeapOfFaith)]
775        );
776    }
777
778    #[test]
779    fn the_ect_parameter_names_ect0_ect1_or_random_and_nothing_else() {
780        assert_eq!(EctPreference::from_sdp("0"), Some(EctPreference::Ect0));
781        assert_eq!(EctPreference::from_sdp(" 1"), Some(EctPreference::Ect1));
782        assert_eq!(
783            EctPreference::from_sdp("Random"),
784            Some(EctPreference::Random)
785        );
786        assert_eq!(EctPreference::from_sdp("2"), None);
787        assert_eq!(
788            EcnMarking::Rfc6679.codepoint(None, true),
789            shared::EcnCodepoint::Ect0,
790            "RFC 6679 section 7.3.1: ECT(0) unless asked"
791        );
792        assert_eq!(
793            EcnMarking::L4s.codepoint(Some(EctPreference::Ect0), false),
794            shared::EcnCodepoint::Ect1
795        );
796    }
797
798    #[test]
799    fn counted_ect_probes_complete_the_initiation() {
800        let mut v = EcnValidation::default();
801        let mut at = Instant::now();
802        let sent: Vec<u16> = (0..40).collect();
803        let marked = send(&mut v, &mut at, 0, 40);
804        assert!(
805            marked.len() >= 2 && marked.len() < 40,
806            "probes only: {marked:?}"
807        );
808        let c = counters_for(&sent, &marked, true, 0, EcnCounters::default());
809        v.on_counters(at, 39, c);
810        assert_eq!(v.state(), EcnState::Active);
811        assert_eq!(
812            send(&mut v, &mut at, 40, 10).len(),
813            10,
814            "all marked once active"
815        );
816    }
817
818    /// Section 7.2.1: a path that clears the field (probes counted not-ECT) fails the
819    /// initiation; section 7.4.1: it is retried later.
820    #[test]
821    fn probes_counted_not_ect_fail_the_initiation() {
822        let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
823        let mut at = Instant::now();
824        let sent: Vec<u16> = (0..40).collect();
825        let marked = send(&mut v, &mut at, 0, 40);
826        let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
827        v.on_counters(at, 39, c);
828        assert!(
829            matches!(v.state(), EcnState::Failed { .. }),
830            "{:?}",
831            v.state()
832        );
833        assert!(
834            send(&mut v, &mut at, 40, 20).is_empty(),
835            "nothing marked after the failure"
836        );
837        at += Duration::from_secs(11);
838        assert!(
839            !send(&mut v, &mut at, 60, 20).is_empty(),
840            "probing again after the retry time"
841        );
842    }
843
844    /// Section 7.4.2, ongoing use: once every packet goes out ECT, a receiver counting them
845    /// not-ECT means the path clears the field, and marking stops.
846    #[test]
847    fn bleaching_counted_in_ongoing_use_stops_the_marking() {
848        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
849        let mut at = Instant::now();
850        let sent: Vec<u16> = (0..40).collect();
851        let marked = send(&mut v, &mut at, 0, 40);
852        assert_eq!(marked.len(), 40);
853        let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
854        v.on_counters(at, 39, c);
855        assert!(
856            matches!(v.state(), EcnState::Failed { .. }),
857            "{:?}",
858            v.state()
859        );
860    }
861
862    /// Section 7.4.1: high loss of ECT packets switches to not-ECT to compare.
863    #[test]
864    fn counted_loss_of_ect_packets_falls_back_to_not_ect() {
865        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
866        let mut at = Instant::now();
867        let sent: Vec<u16> = (0..40).collect();
868        let marked = send(&mut v, &mut at, 0, 40);
869        let c = counters_for(&sent, &marked, true, 20, EcnCounters::default());
870        v.on_counters(at, 39, c);
871        assert_eq!(v.state(), EcnState::Fallback);
872        assert!(send(&mut v, &mut at, 40, 10).is_empty());
873    }
874
875    /// Sends `count` packets 20 ms apart from `first`; returns which were marked.
876    fn send(v: &mut EcnValidation, at: &mut Instant, first: u16, count: u16) -> Vec<u16> {
877        let mut marked = vec![];
878        for n in 0..count {
879            let seq = first.wrapping_add(n);
880            if v.on_send(*at, seq) {
881                marked.push(seq);
882            }
883            *at += Duration::from_millis(20);
884        }
885        marked
886    }
887
888    /// Reports `first..first + count`: `path(seq, marked)` says how each arrived.
889    fn report(
890        v: &mut EcnValidation,
891        at: Instant,
892        first: u16,
893        count: u16,
894        path: impl Fn(u16, bool) -> Option<Ecn>,
895    ) {
896        for n in 0..count {
897            let seq = first.wrapping_add(n);
898            let marked = v.was_marked(seq);
899            match path(seq, marked) {
900                Some(ecn) => v.on_report(at, seq, true, ecn),
901                None => v.on_report(at, seq, false, Ecn::NotEct),
902            }
903        }
904    }
905
906    fn carries_ecn(_: u16, marked: bool) -> Option<Ecn> {
907        Some(if marked { Ecn::Ect1 } else { Ecn::NotEct })
908    }
909
910    /// RFC 6679 section 7.2.1: after a provisional success, another RTCP CNAME within three
911    /// reporting intervals of the initiation's start sends the sender back to probing; the
912    /// same CNAME again, or another after the watch, does not.
913    #[test]
914    fn a_second_cname_during_a_provisional_success_sends_the_stream_back_to_probing() {
915        let mut v = EcnValidation::default();
916        let mut at = Instant::now();
917        v.on_remote_cname(at, "peer");
918        send(&mut v, &mut at, 0, 40);
919        report(&mut v, at, 0, 40, carries_ecn);
920        assert!(v.is_provisional(at));
921        v.on_remote_cname(at, "peer");
922        assert_eq!(v.state(), EcnState::Active, "the same receiver");
923        v.on_remote_cname(at, "another participant");
924        assert_eq!(v.state(), EcnState::Initiating);
925        let probes = send(&mut v, &mut at, 40, 40).len();
926        assert!((1..40).contains(&probes), "a small fraction only: {probes}");
927
928        // Confirmed again and watched out: a later CNAME leaves ongoing use alone.
929        report(&mut v, at, 40, 40, carries_ecn);
930        assert_eq!(v.state(), EcnState::Active);
931        at += PROVISIONAL_MONITOR;
932        assert!(!v.is_provisional(at));
933        v.on_remote_cname(at, "a third");
934        assert_eq!(v.state(), EcnState::Active);
935    }
936
937    #[test]
938    fn initiation_marks_a_small_fraction_never_all() {
939        let mut v = EcnValidation::default();
940        let mut at = Instant::now();
941        let marked = send(&mut v, &mut at, 0, 100);
942        assert!(marked.len() >= 4, "probes: {marked:?}");
943        assert!(marked.len() <= 100 / 4, "a small fraction: {marked:?}");
944        assert!(
945            marked.windows(2).all(|w| w[1] - w[0] >= 2),
946            "never two in a row: {marked:?}"
947        );
948        assert_eq!(v.state(), EcnState::Initiating);
949    }
950
951    #[test]
952    fn a_slow_stream_still_probes_twice_a_second() {
953        let mut v = EcnValidation::default();
954        let mut at = Instant::now();
955        let mut marked = 0;
956        // Five packets a second for two seconds.
957        for seq in 0..10u16 {
958            marked += u32::from(v.on_send(at, seq));
959            at += Duration::from_millis(200);
960        }
961        assert!(marked >= 4, "{marked} probes in two seconds");
962        assert!(marked < 10);
963    }
964
965    #[test]
966    fn confirmed_probes_make_every_packet_ect() {
967        let mut v = EcnValidation::default();
968        let mut at = Instant::now();
969        send(&mut v, &mut at, 0, 40);
970        report(&mut v, at, 0, 40, carries_ecn);
971        assert_eq!(v.state(), EcnState::Active);
972        assert_eq!(send(&mut v, &mut at, 40, 20).len(), 20);
973        assert!(v.marks_all());
974    }
975
976    #[test]
977    fn a_ce_marked_probe_confirms_ecn_too() {
978        let mut v = EcnValidation::default();
979        let mut at = Instant::now();
980        send(&mut v, &mut at, 0, 40);
981        report(&mut v, at, 0, 40, |_, m| {
982            Some(if m { Ecn::Ce } else { Ecn::NotEct })
983        });
984        assert_eq!(v.state(), EcnState::Active);
985    }
986
987    #[test]
988    fn a_bleached_probe_fails_the_initiation_and_a_retry_follows() {
989        let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
990        let mut at = Instant::now();
991        send(&mut v, &mut at, 0, 40);
992        report(&mut v, at, 0, 40, |_, _| Some(Ecn::NotEct));
993        assert!(
994            matches!(v.state(), EcnState::Failed { .. }),
995            "{:?}",
996            v.state()
997        );
998        assert!(send(&mut v, &mut at, 40, 100).is_empty(), "nothing marked");
999        at += Duration::from_secs(10);
1000        assert!(
1001            !send(&mut v, &mut at, 140, 20).is_empty(),
1002            "initiating again"
1003        );
1004        assert_eq!(v.state(), EcnState::Initiating);
1005    }
1006
1007    #[test]
1008    fn a_path_that_drops_ect_packets_fails_the_initiation() {
1009        let mut v = EcnValidation::default();
1010        let mut at = Instant::now();
1011        let probes = send(&mut v, &mut at, 0, 60);
1012        assert!(probes.len() >= 4);
1013        report(&mut v, at, 0, 60, |_, m| (!m).then_some(Ecn::NotEct));
1014        assert!(
1015            matches!(v.state(), EcnState::Failed { .. }),
1016            "{:?}",
1017            v.state()
1018        );
1019    }
1020
1021    #[test]
1022    fn three_lost_probes_are_not_yet_a_failure() {
1023        let mut v = EcnValidation::default();
1024        let mut at = Instant::now();
1025        let probes = send(&mut v, &mut at, 0, 60);
1026        let lost: Vec<u16> = probes[..3].to_vec();
1027        report(&mut v, at, 0, 60, |s, m| {
1028            if lost.contains(&s) {
1029                None
1030            } else {
1031                carries_ecn(s, m)
1032            }
1033        });
1034        assert_eq!(v.state(), EcnState::Active, "the fourth probe arrived ECT");
1035    }
1036
1037    #[test]
1038    fn a_late_packet_reported_lost_then_received_is_not_a_loss() {
1039        let mut v = EcnValidation::default();
1040        let mut at = Instant::now();
1041        let probes = send(&mut v, &mut at, 0, 60);
1042        for &p in &probes {
1043            v.on_report(at, p, false, Ecn::NotEct);
1044            v.on_report(at, p, true, Ecn::Ect1);
1045            // A repeat of either report changes nothing.
1046            v.on_report(at, p, true, Ecn::Ect1);
1047            v.on_report(at, p, false, Ecn::NotEct);
1048        }
1049        assert_eq!(v.state(), EcnState::Active);
1050    }
1051
1052    #[test]
1053    fn bleaching_during_use_stops_the_marking() {
1054        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1055        let mut at = Instant::now();
1056        assert_eq!(
1057            send(&mut v, &mut at, 0, 32).len(),
1058            32,
1059            "leap of faith marks all"
1060        );
1061        // A few bleached packets are not a failure.
1062        report(&mut v, at, 0, 32, |s, _| {
1063            Some(if s % 16 == 0 { Ecn::NotEct } else { Ecn::Ect1 })
1064        });
1065        assert_eq!(v.state(), EcnState::Active);
1066        send(&mut v, &mut at, 32, 32);
1067        report(&mut v, at, 32, 32, |_, _| Some(Ecn::NotEct));
1068        assert!(
1069            matches!(v.state(), EcnState::Failed { .. }),
1070            "{:?}",
1071            v.state()
1072        );
1073        assert!(send(&mut v, &mut at, 64, 50).is_empty());
1074    }
1075
1076    /// RFC 6679 section 7.2.3: under the leap of faith, a receiver report showing no reception
1077    /// is not enough (the receiver may have reported before any packet reached it); the second
1078    /// in a row ends the marking. A report showing reception in between starts the count over,
1079    /// and once reception was shown the path is taken as carrying ECT.
1080    #[test]
1081    fn leap_of_faith_waits_for_a_second_report_without_reception() {
1082        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1083        let mut at = Instant::now();
1084        // Nothing sent yet: a report says nothing.
1085        v.on_report_without_reception(at);
1086        v.on_report_without_reception(at);
1087        assert_eq!(v.state(), EcnState::Active);
1088        assert_eq!(send(&mut v, &mut at, 0, 10).len(), 10);
1089        v.on_report_without_reception(at);
1090        assert_eq!(v.state(), EcnState::Active, "one report is not enough");
1091        v.on_report_without_reception(at);
1092        assert!(
1093            matches!(v.state(), EcnState::Failed { .. }),
1094            "{:?}",
1095            v.state()
1096        );
1097        assert_eq!(v.take_failures(), vec![EcnFailure::NoReception]);
1098        assert!(
1099            send(&mut v, &mut at, 10, 10).is_empty(),
1100            "Not-ECT after the failure"
1101        );
1102
1103        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1104        send(&mut v, &mut at, 0, 10);
1105        v.on_report_without_reception(at);
1106        v.on_reception_reported();
1107        v.on_report_without_reception(at);
1108        v.on_report_without_reception(at);
1109        assert_eq!(v.state(), EcnState::Active, "reception was reported");
1110
1111        // The probing initiation does not use the rule.
1112        let mut v = EcnValidation::new(EcnInitiation::RtpAndRtcp);
1113        send(&mut v, &mut at, 0, 40);
1114        v.on_report_without_reception(at);
1115        v.on_report_without_reception(at);
1116        assert!(v.take_failures().is_empty());
1117    }
1118
1119    #[test]
1120    fn loss_that_goes_with_the_marking_initiates_again_then_disables() {
1121        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1122        let mut at = Instant::now();
1123        let mut seq = 0u16;
1124        for round in 0..FALLBACKS_TO_DISABLE {
1125            // In use: ECT packets are dropped.
1126            if round > 0 {
1127                // Initiate again: probes go through, so the stream is back in use.
1128                let n = 40;
1129                send(&mut v, &mut at, seq, n);
1130                report(&mut v, at, seq, n, carries_ecn);
1131                seq += n;
1132            }
1133            assert_eq!(v.state(), EcnState::Active, "round {round}");
1134            send(&mut v, &mut at, seq, 32);
1135            report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
1136            seq += 32;
1137            assert_eq!(v.state(), EcnState::Fallback, "round {round}");
1138            assert!(
1139                send(&mut v, &mut at, seq, 32).is_empty(),
1140                "Not-ECT while comparing"
1141            );
1142            report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
1143            seq += 32;
1144        }
1145        assert_eq!(v.state(), EcnState::Disabled);
1146        at += DEFAULT_RETRY_AFTER * 2;
1147        assert!(
1148            send(&mut v, &mut at, seq, 40).is_empty(),
1149            "disabled for good"
1150        );
1151        // RFC 6679 section 7.4.2: the erroneous behaviour detected is kept for follow-up, each
1152        // fallback and the final one.
1153        let mut expected =
1154            vec![EcnFailure::EctLost { disabled: false }; FALLBACKS_TO_DISABLE as usize - 1];
1155        expected.push(EcnFailure::EctLost { disabled: true });
1156        assert_eq!(v.take_failures(), expected);
1157        assert!(v.take_failures().is_empty(), "taken once");
1158    }
1159
1160    #[test]
1161    fn loss_that_stays_without_the_marking_resumes_it() {
1162        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1163        let mut at = Instant::now();
1164        send(&mut v, &mut at, 0, 32);
1165        report(&mut v, at, 0, 32, |s, _| (s % 2 == 0).then_some(Ecn::Ect1));
1166        assert_eq!(v.state(), EcnState::Fallback);
1167        send(&mut v, &mut at, 32, 32);
1168        report(&mut v, at, 32, 32, |s, _| {
1169            (s % 2 == 0).then_some(Ecn::NotEct)
1170        });
1171        assert_eq!(v.state(), EcnState::Active, "congestion, not ECN");
1172    }
1173
1174    /// A fixed corpus of arbitrary send / report sequences (sequence numbers that jump, wrap,
1175    /// repeat; reports out of order, duplicated, for unknown packets): nothing panics, a stream
1176    /// that is initiating never marks two packets in a row nor more than a quarter of them,
1177    /// and one that is disabled never marks again.
1178    #[test]
1179    fn arbitrary_send_and_report_sequences_keep_the_invariants() {
1180        let mut state = 0x0EC0_0001u32;
1181        let mut next = move || {
1182            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1183            state >> 8
1184        };
1185        for _ in 0..400 {
1186            let mut v = if next() % 2 == 0 {
1187                EcnValidation::default()
1188            } else {
1189                EcnValidation::new(EcnInitiation::LeapOfFaith)
1190            }
1191            .with_retry_after(Duration::from_millis(u64::from(next() % 3000)));
1192            let mut at = Instant::now();
1193            let mut seq = next() as u16;
1194            let mut sent: Vec<u16> = vec![];
1195            let mut run_marked = 0u32;
1196            let mut initiating = (0u32, 0u32);
1197            for _ in 0..600 {
1198                at += Duration::from_millis(u64::from(next() % 60));
1199                match next() % 10 {
1200                    0..=5 => {
1201                        seq = match next() % 20 {
1202                            0 => seq.wrapping_add(next() as u16),
1203                            1 => seq,
1204                            _ => seq.wrapping_add(1),
1205                        };
1206                        let was = v.state();
1207                        let marked = v.on_send(at, seq);
1208                        sent.push(seq);
1209                        if was == EcnState::Disabled {
1210                            assert!(!marked, "a disabled stream marks nothing");
1211                        }
1212                        if v.state() == EcnState::Initiating && was == EcnState::Initiating {
1213                            initiating.0 += 1;
1214                            initiating.1 += u32::from(marked);
1215                            run_marked = if marked { run_marked + 1 } else { 0 };
1216                            assert!(run_marked <= 1, "two probes in a row");
1217                        } else {
1218                            run_marked = 0;
1219                        }
1220                    }
1221                    _ => {
1222                        let target = if sent.is_empty() || next() % 8 == 0 {
1223                            next() as u16
1224                        } else {
1225                            sent[(next() as usize) % sent.len()]
1226                        };
1227                        let ecn = match next() % 4 {
1228                            0 => Ecn::NotEct,
1229                            1 => Ecn::Ect1,
1230                            2 => Ecn::Ect0,
1231                            _ => Ecn::Ce,
1232                        };
1233                        v.on_report(at, target, next() % 5 != 0, ecn);
1234                    }
1235                }
1236            }
1237            if initiating.0 >= 40 {
1238                assert!(
1239                    initiating.1 * 4 <= initiating.0 + 4,
1240                    "a small fraction while initiating: {initiating:?}"
1241                );
1242            }
1243        }
1244    }
1245}