Skip to main content

rtci_interceptor/rtpfb/
history.rs

1//! What was sent, joined with what the receiver said about it.
2
3use super::acknowledgement::{Acknowledgement, PacketReport};
4use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
5use std::collections::HashMap;
6use std::time::{Duration, Instant};
7
8/// Records outgoing packets and matches incoming feedback against them.
9///
10/// The two feedback formats identify a packet differently — TWCC by its own transport-wide
11/// sequence number, RFC 8888 by the stream's SSRC and RTP sequence number — so both indexes are
12/// kept, pointing at one record.
13#[derive(Debug, Default)]
14pub struct History {
15    /// Monotonic id, so reports come out in send order however sequence numbers wrap.
16    next_id: u64,
17    packets: HashMap<u64, Sent>,
18    twcc_index: HashMap<u16, u64>,
19    ssrc_sequence_index: HashMap<(u32, u16), u64>,
20    /// Highest id acknowledged so far.
21    highest_acknowledged: Option<u64>,
22    /// Lowest id not yet reported to the consumer.
23    next_to_report: u64,
24    /// The `fb_pkt_count` of the last TWCC feedback read.
25    last_feedback_count: Option<u8>,
26    /// Feedback packets the count shows were sent and never read.
27    lost_feedback: u64,
28    /// Sent packets no feedback ever described, released without a verdict.
29    unreported: u64,
30    /// Packets a feedback reported as not received, held back for one more feedback: a
31    /// packet only overtaken on the path arrives after the report that named it missing.
32    pending_losses: Vec<u64>,
33    /// Packets reported as not received and then as received by a later feedback.
34    recovered: u64,
35}
36
37/// A sent packet and whether any feedback has described it yet.
38#[derive(Debug)]
39struct Sent {
40    report: PacketReport,
41    /// A feedback packet named this packet, as received or as not received. A packet no
42    /// feedback named has no verdict: the report that would have carried it was lost, or the
43    /// receiver does not report on its stream at all.
44    covered: bool,
45}
46
47impl History {
48    /// An empty history.
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// How many packets are being tracked.
54    pub fn len(&self) -> usize {
55        self.packets.len()
56    }
57
58    /// Whether nothing is being tracked.
59    pub fn is_empty(&self) -> bool {
60        self.packets.is_empty()
61    }
62
63    /// Record a packet as it leaves.
64    ///
65    /// `departure` must be the instant the packet was **released** to the network, not the
66    /// instant the application handed it over. A pacer can hold a packet for tens of
67    /// milliseconds, and counting that as network delay is exactly the error that makes a
68    /// bandwidth estimate collapse (chain contract rule 3).
69    #[allow(clippy::too_many_arguments)]
70    pub fn add_outgoing(
71        &mut self,
72        ssrc: u32,
73        rtp_sequence_number: u16,
74        is_twcc: bool,
75        twcc_sequence_number: u16,
76        size: usize,
77        departure: Instant,
78    ) -> u64 {
79        let id = self.next_id;
80        self.next_id += 1;
81
82        if is_twcc
83            && let Some(previous) = self.twcc_index.insert(twcc_sequence_number, id)
84            && let Some(earlier) = self.packets.get_mut(&previous)
85        {
86            // The same transport-wide number again: a retransmission sent as it was (no RTX),
87            // which keeps its number. The receiver reports a number once, so its verdict goes
88            // to this transmission; the earlier one was asked for again because it did not
89            // arrive, and is reported as the loss it was.
90            earlier.covered = true;
91        }
92        self.ssrc_sequence_index
93            .insert((ssrc, rtp_sequence_number), id);
94
95        self.packets.insert(
96            id,
97            Sent {
98                report: PacketReport {
99                    ssrc,
100                    id,
101                    rtp_sequence_number,
102                    is_twcc,
103                    twcc_sequence_number,
104                    size,
105                    arrived: false,
106                    departure,
107                    arrival: None,
108                    ecn: Ecn::NotEct,
109                },
110                covered: false,
111            },
112        );
113
114        id
115    }
116
117    /// Apply TWCC feedback, returning the round trip time it implies.
118    ///
119    /// `None` when the feedback names a packet this endpoint has no record of — which happens
120    /// routinely at startup and after the history has been pruned, and is not an error.
121    pub fn on_twcc_feedback(
122        &mut self,
123        received_at: Instant,
124        acknowledgement: Acknowledgement,
125    ) -> Option<Duration> {
126        let Some(&id) = self.twcc_index.get(&acknowledgement.sequence_number) else {
127            if acknowledgement.arrived {
128                log::debug!(
129                    "rtpfb: transport-wide {} reported received matches no packet held (released, or never sent)",
130                    acknowledgement.sequence_number
131                );
132            }
133            return None;
134        };
135        if acknowledgement.arrived
136            && self
137                .packets
138                .get(&id)
139                .is_some_and(|sent| sent.covered && !sent.report.arrived)
140        {
141            log::debug!(
142                "rtpfb: transport-wide {} reported received after a feedback reported it lost",
143                acknowledgement.sequence_number
144            );
145        }
146        self.apply(received_at, id, acknowledgement)
147    }
148
149    /// Apply RFC 8888 feedback for one stream, returning the round trip time it implies.
150    pub fn on_ccfb_feedback(
151        &mut self,
152        received_at: Instant,
153        ssrc: u32,
154        acknowledgement: Acknowledgement,
155    ) -> Option<Duration> {
156        let Some(&id) = self
157            .ssrc_sequence_index
158            .get(&(ssrc, acknowledgement.sequence_number))
159        else {
160            if acknowledgement.arrived {
161                log::debug!(
162                    "rtpfb: {ssrc:#x} {} reported received matches no packet held (released, or never sent)",
163                    acknowledgement.sequence_number
164                );
165            }
166            return None;
167        };
168        if acknowledgement.arrived
169            && self
170                .packets
171                .get(&id)
172                .is_some_and(|sent| sent.covered && !sent.report.arrived)
173        {
174            log::debug!(
175                "rtpfb: {ssrc:#x} {} reported received after a feedback reported it lost",
176                acknowledgement.sequence_number
177            );
178        }
179        self.apply(received_at, id, acknowledgement)
180    }
181
182    fn apply(
183        &mut self,
184        received_at: Instant,
185        id: u64,
186        acknowledgement: Acknowledgement,
187    ) -> Option<Duration> {
188        let sent = self.packets.get_mut(&id)?;
189        sent.covered = true;
190        let packet = &mut sent.report;
191
192        packet.arrived = acknowledgement.arrived;
193        packet.arrival = acknowledgement.arrival;
194        packet.ecn = acknowledgement.ecn;
195
196        if packet.arrived {
197            self.highest_acknowledged = Some(match self.highest_acknowledged {
198                Some(highest) => highest.max(id),
199                None => id,
200            });
201        }
202
203        // Round trip: this feedback arrived now, and the packet left then. Both instants are on
204        // this endpoint's clock, so unlike the arrival times this is a real duration.
205        Some(received_at.saturating_duration_since(packet.departure))
206    }
207
208    /// Note the feedback packet count of a TWCC feedback just read, and return how many feedback
209    /// packets the receiver sent between the previous one and this one that never arrived.
210    ///
211    /// The count is the only thing that tells a lost feedback packet from a quiet receiver
212    /// (draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3.1). The packets a lost
213    /// feedback would have described get no verdict at all, see
214    /// [`take_reports`](Self::take_reports); this is the measure of how often that happened.
215    pub fn on_twcc_feedback_count(&mut self, feedback_packet_count: u8) -> u8 {
216        let missed = match self.last_feedback_count {
217            // A count at or behind the last one is a reordered or repeated feedback: nothing
218            // is known to be missing.
219            Some(last) => {
220                let ahead = feedback_packet_count.wrapping_sub(last);
221                if ahead == 0 || ahead > 127 {
222                    return 0;
223                }
224                ahead - 1
225            }
226            None => 0,
227        };
228        self.last_feedback_count = Some(feedback_packet_count);
229        self.lost_feedback += u64::from(missed);
230        missed
231    }
232
233    /// How many TWCC feedback packets were sent by the receiver and never read here.
234    pub fn lost_feedback(&self) -> u64 {
235        self.lost_feedback
236    }
237
238    /// How many sent packets were released without any feedback describing them.
239    pub fn unreported(&self) -> u64 {
240        self.unreported
241    }
242
243    /// Take every packet a feedback described, up to the highest *arrived* one, since the last
244    /// call, in send order.
245    ///
246    /// A packet the receiver reported as not received is a loss. A packet below the highest
247    /// arrival that **no feedback described** is neither: the feedback that covered it was lost,
248    /// or the receiver does not report on its stream (no transport-wide sequence number, an SSRC
249    /// outside the RFC 8888 report). The draft is explicit that such packets are ignored, not
250    /// counted as lost or received (section 3), so they are released here without a report.
251    /// Loss feedback alone does not advance the reporting window; losses are emitted when a later
252    /// packet is reported as arrived.
253    pub fn take_reports(&mut self) -> Vec<PacketReport> {
254        let mut reports = Vec::new();
255        // The losses the previous call held back: lost after all, or received meanwhile. A
256        // packet received late is reported as received but without its arrival time: it
257        // counts for the loss fraction, while the delay model, which reads reports in send
258        // order, does not see an old packet among new ones.
259        for id in std::mem::take(&mut self.pending_losses) {
260            if let Some(sent) = self.release(id) {
261                let mut packet = sent.report;
262                if packet.arrived {
263                    self.recovered += 1;
264                    packet.arrival = None;
265                }
266                reports.push(packet);
267            }
268        }
269        let Some(highest) = self.highest_acknowledged else {
270            return reports;
271        };
272        if self.next_to_report > highest {
273            return reports;
274        }
275        for id in self.next_to_report..=highest {
276            // Held only while a later feedback can still name it: a transmission superseded
277            // under the same number never will.
278            let held = self.packets.get(&id).is_some_and(|sent| {
279                let packet = &sent.report;
280                let reachable = if packet.is_twcc {
281                    self.twcc_index.get(&packet.twcc_sequence_number) == Some(&id)
282                } else {
283                    self.ssrc_sequence_index
284                        .get(&(packet.ssrc, packet.rtp_sequence_number))
285                        == Some(&id)
286                };
287                sent.covered && !packet.arrived && reachable
288            });
289            if held {
290                // A loss is final only when the next feedback has not reported it received
291                // either (libwebrtc's TransportFeedbackAdapter keeps a lost packet "because
292                // it might be reported as received by a later feedback").
293                self.pending_losses.push(id);
294                continue;
295            }
296            if let Some(sent) = self.release(id) {
297                if sent.covered {
298                    reports.push(sent.report);
299                } else {
300                    self.unreported += 1;
301                }
302            }
303        }
304        self.next_to_report = highest + 1;
305
306        reports
307    }
308
309    /// Take a packet out of the history and its indexes.
310    fn release(&mut self, id: u64) -> Option<Sent> {
311        let sent = self.packets.remove(&id)?;
312        let packet = &sent.report;
313        if packet.is_twcc && self.twcc_index.get(&packet.twcc_sequence_number) == Some(&id) {
314            self.twcc_index.remove(&packet.twcc_sequence_number);
315        }
316        if self
317            .ssrc_sequence_index
318            .get(&(packet.ssrc, packet.rtp_sequence_number))
319            == Some(&id)
320        {
321            self.ssrc_sequence_index
322                .remove(&(packet.ssrc, packet.rtp_sequence_number));
323        }
324        Some(sent)
325    }
326
327    /// Forget every packet sent so far, as on a new path: those went into the path that was
328    /// left, and what a later feedback says of them is neither a loss nor a delivery of the new
329    /// one's. libwebrtc's `TransportFeedbackAdapter::SetNetworkRoute` does the same, so that
330    /// "the feedback adapter only reports packets sent on the new route"
331    /// (`RtpTransportControllerSend::OnNetworkRouteChanged`). A feedback that names one of
332    /// them later matches nothing, as for a packet pruned.
333    pub fn forget_sent(&mut self) {
334        self.packets.clear();
335        self.twcc_index.clear();
336        self.ssrc_sequence_index.clear();
337        self.pending_losses.clear();
338        self.highest_acknowledged = None;
339        self.next_to_report = self.next_id;
340    }
341
342    /// Packets reported as not received that a later feedback reported as received.
343    pub fn recovered(&self) -> u64 {
344        self.recovered
345    }
346
347    /// Drop records of packets sent before `cutoff` that were never acknowledged.
348    ///
349    /// Without this the history grows without bound on a lossy path: an unacknowledged packet is
350    /// never reported and never removed, so nothing else would ever release it.
351    pub fn prune_before(&mut self, cutoff: Instant) {
352        let stale: Vec<u64> = self
353            .packets
354            .iter()
355            .filter(|(_, sent)| sent.report.departure < cutoff && !sent.report.arrived)
356            .map(|(&id, _)| id)
357            .collect();
358
359        for id in stale {
360            if let Some(sent) = self.packets.remove(&id) {
361                let packet = sent.report;
362                // Only a TWCC packet has an entry under its transport-wide sequence number. A
363                // non-TWCC packet carries whatever the caller passed — typically 0 — and removing
364                // that key would evict whichever real TWCC packet holds it.
365                if packet.is_twcc {
366                    self.twcc_index.remove(&packet.twcc_sequence_number);
367                }
368                self.ssrc_sequence_index
369                    .remove(&(packet.ssrc, packet.rtp_sequence_number));
370            }
371        }
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    fn history_with_three_packets(now: Instant) -> History {
380        let mut history = History::new();
381        for sequence_number in 0..3u16 {
382            history.add_outgoing(1, 100 + sequence_number, true, sequence_number, 1200, now);
383        }
384        history
385    }
386
387    #[test]
388    fn feedback_for_an_unknown_packet_is_ignored() {
389        let now = Instant::now();
390        let mut history = History::new();
391
392        assert_eq!(
393            None,
394            history.on_twcc_feedback(now, Acknowledgement::received(5, None, Ecn::NotEct)),
395            "nothing was sent with that sequence number"
396        );
397        assert!(history.take_reports().is_empty());
398    }
399
400    #[test]
401    fn twcc_feedback_matches_by_transport_wide_sequence_number() {
402        let now = Instant::now();
403        let mut history = history_with_three_packets(now);
404
405        let rtt = history.on_twcc_feedback(
406            now + Duration::from_millis(80),
407            Acknowledgement::received(1, Some(Duration::from_millis(5)), Ecn::NotEct),
408        );
409        assert_eq!(Some(Duration::from_millis(80)), rtt);
410
411        let reports = history.take_reports();
412        assert_eq!(1, reports.len(), "only what the feedback described");
413        assert_eq!(101, reports[0].rtp_sequence_number);
414        assert!(reports[0].arrived);
415    }
416
417    /// draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3: when a feedback packet is
418    /// lost, the packets it would have reported are ignored, "not counted as lost or received".
419    #[test]
420    fn packets_whose_feedback_was_lost_are_not_reported_as_lost() {
421        let now = Instant::now();
422        let mut history = History::new();
423        for sequence_number in 0..20u16 {
424            history.add_outgoing(1, 100 + sequence_number, true, sequence_number, 1200, now);
425        }
426
427        // The feedback for 0..=9 never arrives; the one for 10..=19 does.
428        for sequence_number in 10..20u16 {
429            history.on_twcc_feedback(
430                now + Duration::from_millis(50),
431                Acknowledgement::received(sequence_number, None, Ecn::NotEct),
432            );
433        }
434
435        let reports = history.take_reports();
436        assert_eq!(10, reports.len(), "the ten packets the feedback described");
437        assert!(
438            reports.iter().all(|report| report.arrived),
439            "no loss was reported by the receiver, so none is reported here"
440        );
441        assert_eq!(110, reports[0].rtp_sequence_number);
442        assert_eq!(
443            10,
444            history.unreported(),
445            "the uncovered ten have no verdict"
446        );
447        assert!(history.is_empty(), "and are not kept");
448    }
449
450    /// A retransmission that keeps its transport-wide number takes the receiver's verdict; the
451    /// transmission it replaces is the loss that caused it, and stays one.
452    #[test]
453    fn a_transmission_superseded_under_the_same_number_is_reported_lost() {
454        let now = Instant::now();
455        let mut history = History::new();
456        history.add_outgoing(1, 100, true, 7, 1200, now);
457        history.add_outgoing(1, 100, true, 7, 1200, now + Duration::from_millis(40));
458
459        history.on_twcc_feedback(
460            now + Duration::from_millis(80),
461            Acknowledgement::received(7, None, Ecn::NotEct),
462        );
463
464        let reports = history.take_reports();
465        assert_eq!(
466            vec![false, true],
467            reports
468                .iter()
469                .map(|report| report.arrived)
470                .collect::<Vec<_>>()
471        );
472        assert_eq!(0, history.unreported());
473    }
474
475    /// A packet the receiver itself reports as not received is still a loss, once the next
476    /// feedback has not reported it received either.
477    #[test]
478    fn a_packet_reported_not_received_is_a_loss() {
479        let now = Instant::now();
480        let mut history = history_with_three_packets(now);
481
482        history.on_twcc_feedback(now, Acknowledgement::lost(0));
483        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
484        history.on_twcc_feedback(now, Acknowledgement::received(2, None, Ecn::NotEct));
485
486        let arrived = |reports: Vec<PacketReport>| -> Vec<bool> {
487            reports.iter().map(|report| report.arrived).collect()
488        };
489        assert_eq!(vec![true, true], arrived(history.take_reports()));
490        assert_eq!(
491            vec![false],
492            arrived(history.take_reports()),
493            "the next feedback's turn"
494        );
495        assert_eq!(0, history.unreported());
496        assert_eq!(0, history.recovered());
497    }
498
499    /// A packet only overtaken on the path is reported as not received by the feedback that
500    /// covered the packets after it, and as received by the next. It is not a loss
501    /// (libwebrtc's `TransportFeedbackAdapter` keeps a lost packet "because it might be
502    /// reported as received by a later feedback"): the history holds a reported loss for one
503    /// more feedback, and reports the packet as received, without an arrival time for the
504    /// delay model, which reads reports in send order.
505    #[test]
506    fn a_packet_reported_lost_and_then_received_is_not_a_loss() {
507        let now = Instant::now();
508        let mut history = history_with_three_packets(now);
509
510        history.on_twcc_feedback(now, Acknowledgement::lost(0));
511        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
512        assert_eq!(1, history.take_reports().len(), "1, and 0 held back");
513        history.on_twcc_feedback(
514            now,
515            Acknowledgement::received(0, Some(Duration::from_millis(50)), Ecn::NotEct),
516        );
517        history.on_twcc_feedback(now, Acknowledgement::received(2, None, Ecn::NotEct));
518        let reports = history.take_reports();
519        assert_eq!(2, reports.len());
520        assert!(reports.iter().all(|report| report.arrived), "{reports:?}");
521        assert_eq!(None, reports[0].arrival, "0 is out of send order now");
522        assert_eq!(1, history.recovered());
523    }
524
525    /// The feedback packet count is how a lost feedback packet is told from a quiet receiver
526    /// (section 3.1).
527    #[test]
528    fn a_gap_in_the_feedback_packet_count_is_a_lost_feedback_packet() {
529        let mut history = History::new();
530
531        assert_eq!(0, history.on_twcc_feedback_count(254), "the first one");
532        assert_eq!(0, history.on_twcc_feedback_count(255), "consecutive");
533        assert_eq!(
534            2,
535            history.on_twcc_feedback_count(2),
536            "0 and 1 are missing, across the wrap"
537        );
538        assert_eq!(
539            0,
540            history.on_twcc_feedback_count(1),
541            "a late one is not a gap"
542        );
543        assert_eq!(0, history.on_twcc_feedback_count(3));
544        assert_eq!(2, history.lost_feedback());
545    }
546
547    /// RFC 8888 names packets by the stream's own sequence number, so two streams can use the
548    /// same one and must not be confused.
549    #[test]
550    fn ccfb_feedback_matches_by_ssrc_and_sequence_number() {
551        let now = Instant::now();
552        let mut history = History::new();
553        history.add_outgoing(1, 500, false, 0, 1000, now);
554        history.add_outgoing(2, 500, false, 0, 1000, now);
555
556        history.on_ccfb_feedback(
557            now + Duration::from_millis(50),
558            2,
559            Acknowledgement::received(500, Some(Duration::from_millis(1)), Ecn::Ce),
560        );
561
562        // Stream 1's packet was sent first and no report block described it: it has no verdict,
563        // and is not a loss (draft-ietf-rmcat-gcc bug G2).
564        let reports = history.take_reports();
565        assert_eq!(1, reports.len());
566        assert_eq!(2, reports[0].ssrc);
567        assert!(reports[0].arrived, "stream 2's was acknowledged");
568        assert_eq!(Ecn::Ce, reports[0].ecn);
569    }
570
571    /// Feedback naming a stream that never sent that sequence number must not match another
572    /// stream that did. RFC 8888 numbers packets per stream, so the same sequence number is in
573    /// use on every stream at once — matching on it alone would attribute one stream's arrival to
574    /// another and corrupt both their delay estimates.
575    ///
576    /// Deterministic by construction: only stream 1 ever sent 500, so a lookup that ignores the
577    /// SSRC can only match stream 1's packet, and a correct one can only fail.
578    #[test]
579    fn ccfb_feedback_for_a_sequence_number_another_stream_sent_does_not_match() {
580        let now = Instant::now();
581        let mut history = History::new();
582        history.add_outgoing(1, 500, false, 0, 1000, now);
583
584        assert_eq!(
585            None,
586            history.on_ccfb_feedback(
587                now + Duration::from_millis(50),
588                2,
589                Acknowledgement::received(500, Some(Duration::from_millis(1)), Ecn::NotEct),
590            ),
591            "stream 2 never sent sequence 500"
592        );
593        assert!(
594            history.take_reports().is_empty(),
595            "and nothing was acknowledged, so stream 1's packet is still outstanding"
596        );
597    }
598
599    #[test]
600    fn nothing_is_reported_until_something_is_acknowledged() {
601        let now = Instant::now();
602        let mut history = history_with_three_packets(now);
603
604        assert!(
605            history.take_reports().is_empty(),
606            "sent but not yet acknowledged"
607        );
608        assert_eq!(3, history.len(), "and still tracked");
609    }
610
611    /// A packet reported once must not be reported again: congestion control would count it
612    /// twice, and a loss re-reported later looks like a reordered arrival.
613    #[test]
614    fn packets_are_reported_once() {
615        let now = Instant::now();
616        let mut history = history_with_three_packets(now);
617
618        history.on_twcc_feedback(now, Acknowledgement::lost(0));
619        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
620        history.on_twcc_feedback(now, Acknowledgement::received(2, None, Ecn::NotEct));
621        // 1 and 2, then the loss of 0 a feedback later.
622        assert_eq!(2, history.take_reports().len());
623        assert_eq!(1, history.take_reports().len());
624        assert!(history.take_reports().is_empty());
625        assert!(history.is_empty(), "and released");
626    }
627
628    #[test]
629    fn later_feedback_reports_only_what_follows() {
630        let now = Instant::now();
631        let mut history = History::new();
632        history.add_outgoing(1, 100, true, 0, 1200, now);
633        history.add_outgoing(1, 101, true, 1, 1200, now);
634
635        history.on_twcc_feedback(now, Acknowledgement::received(0, None, Ecn::NotEct));
636        assert_eq!(1, history.take_reports().len());
637
638        history.on_twcc_feedback(now, Acknowledgement::received(1, None, Ecn::NotEct));
639        let reports = history.take_reports();
640        assert_eq!(1, reports.len());
641        assert_eq!(101, reports[0].rtp_sequence_number);
642    }
643
644    /// A packet reported as lost does not advance the reporting window on its own — otherwise a
645    /// long run of losses would flush packets that have not been heard about yet.
646    #[test]
647    fn a_loss_alone_does_not_advance_the_window() {
648        let now = Instant::now();
649        let mut history = history_with_three_packets(now);
650
651        history.on_twcc_feedback(now, Acknowledgement::lost(1));
652        assert!(
653            history.take_reports().is_empty(),
654            "nothing has been acknowledged as arrived"
655        );
656        assert_eq!(3, history.len());
657    }
658
659    /// The round trip is measured between two instants on *this* endpoint's clock, unlike the
660    /// arrival times, which are on the receiver's.
661    #[test]
662    fn the_round_trip_is_measured_locally() {
663        let now = Instant::now();
664        let mut history = History::new();
665        history.add_outgoing(1, 100, true, 0, 1200, now);
666
667        assert_eq!(
668            Some(Duration::from_millis(120)),
669            history.on_twcc_feedback(
670                now + Duration::from_millis(120),
671                Acknowledgement::received(0, Some(Duration::from_secs(9999)), Ecn::NotEct),
672            ),
673            "the receiver's arrival clock does not affect it"
674        );
675    }
676
677    /// Without pruning, an unacknowledged packet is never reported and never removed, so a lossy
678    /// path grows the history without bound.
679    /// A non-TWCC packet carries a meaningless `twcc_sequence_number` (whatever the caller
680    /// passed, typically 0) and was never entered into the TWCC index. Removing that key when it
681    /// is released evicts whichever *real* TWCC packet happens to hold it, and that packet's
682    /// feedback can then never match.
683    #[test]
684    fn releasing_a_non_twcc_packet_does_not_evict_a_twcc_packets_index_entry() {
685        let now = Instant::now();
686        let mut history = History::new();
687
688        // The non-TWCC packet is sent *first*, so reporting it does not sweep up the TWCC one:
689        // the reporting window runs to the highest arrived id, and anything below it is released
690        // regardless. Ordering this way isolates the index eviction from that.
691        history.add_outgoing(2, 200, false, 0, 1200, now);
692        // A real TWCC packet holding transport-wide sequence 0, sent after.
693        history.add_outgoing(1, 100, true, 0, 1200, now);
694
695        // Release the non-TWCC packet by reporting it.
696        history.on_ccfb_feedback(now, 2, Acknowledgement::received(200, None, Ecn::NotEct));
697        history.take_reports();
698
699        assert!(
700            history
701                .on_twcc_feedback(now, Acknowledgement::received(0, None, Ecn::NotEct))
702                .is_some(),
703            "the TWCC packet is still matchable by its transport-wide sequence number"
704        );
705    }
706
707    /// The same hazard on the pruning path.
708    #[test]
709    fn pruning_a_non_twcc_packet_does_not_evict_a_twcc_packets_index_entry() {
710        let now = Instant::now();
711        let mut history = History::new();
712
713        // Old, non-TWCC, carrying the default 0 it never registered.
714        history.add_outgoing(2, 200, false, 0, 1200, now);
715        // Recent, a real TWCC packet holding transport-wide sequence 0.
716        history.add_outgoing(1, 100, true, 0, 1200, now + Duration::from_secs(5));
717
718        history.prune_before(now + Duration::from_secs(1));
719
720        assert!(
721            history
722                .on_twcc_feedback(
723                    now + Duration::from_secs(5),
724                    Acknowledgement::received(0, None, Ecn::NotEct)
725                )
726                .is_some(),
727            "pruning the unrelated packet must not take the TWCC index entry with it"
728        );
729    }
730
731    /// An acknowledged packet that has not been reported yet must survive pruning, or the arrival
732    /// is lost and congestion control never hears about it.
733    #[test]
734    fn an_acknowledged_packet_is_not_pruned_before_it_is_reported() {
735        let now = Instant::now();
736        let mut history = History::new();
737        history.add_outgoing(1, 100, true, 0, 1200, now);
738
739        history.on_twcc_feedback(
740            now + Duration::from_millis(50),
741            Acknowledgement::received(0, None, Ecn::NotEct),
742        );
743
744        // Well past the cutoff, but it has been acknowledged and not yet collected.
745        history.prune_before(now + Duration::from_secs(30));
746
747        let reports = history.take_reports();
748        assert_eq!(1, reports.len(), "the arrival survived to be reported");
749        assert!(reports[0].arrived);
750    }
751
752    #[test]
753    fn old_unacknowledged_packets_are_pruned() {
754        let now = Instant::now();
755        let mut history = History::new();
756        history.add_outgoing(1, 100, true, 0, 1200, now);
757        history.add_outgoing(1, 101, true, 1, 1200, now + Duration::from_secs(5));
758
759        history.prune_before(now + Duration::from_secs(1));
760
761        assert_eq!(1, history.len(), "only the recent one survives");
762        assert_eq!(
763            None,
764            history.on_twcc_feedback(now, Acknowledgement::received(0, None, Ecn::NotEct)),
765            "and the pruned one is no longer matchable"
766        );
767    }
768}