Skip to main content

srt_runtime/arq/
receiver.rs

1//! ARQ receiver-side reliability state — `draft-sharabayko-srt-01` §4.8.1
2//! (Full/Light ACK generation), §4.8.2 (loss detection + NAK), §4.10 (RTT
3//! measurement via the ACK/ACKACK round trip). Curated rules:
4//! `private/specs-verified/rules/srt-arq.md`.
5//!
6//! Sans-IO: [`Receiver`] never reads a wall clock — [`Receiver::feed_data`]
7//! and [`Receiver::tick`] take a caller-supplied
8//! `now: broadcast_core::stage::Instant` (monotonic time since a fixed
9//! epoch the caller owns).
10//!
11//! # Delivery model
12//! [`FeedOutcome::delivered`] lists the sequence numbers that became
13//! cumulatively in-order-deliverable as a result of one `feed_data` call —
14//! i.e. the ARQ engine's view of "no longer missing" (rule 8's ack point),
15//! not a TSBPD-timed playout (that delay is `srt-tsbpd.md` scope, a
16//! separate follow-up).
17//!
18//! # TLPKTDROP fake ACK
19//! The receiver advances its ack point past packets the delivery side gave up
20//! on only when told to (the crate-internal skip the tokio adapter calls when
21//! the TSBPD scheduler reports a drop, rule 13); it never skips a gap on its
22//! own, so without that call it keeps NAKing and never acknowledges what it
23//! has not received.
24
25use alloc::collections::{BTreeMap, BTreeSet};
26use alloc::vec::Vec;
27use broadcast_core::stage::Instant;
28use core::time::Duration;
29
30use crate::packet::number::{AckNumber, SeqNo, SocketId, SrtTimestamp};
31use crate::packet::{AckAckPacket, AckCif, AckPacket, ControlPacket, LossListEntry, NakPacket};
32
33use super::rtt::RttEstimator;
34use super::{FULL_ACK_PERIOD, LIGHT_ACK_THRESHOLD, nak_interval, seq, timestamp_to_wire_us};
35
36/// The bounds an ARQ [`Receiver`] holds a peer to, all chosen by the caller: the crate supplies
37/// none of them.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct ReceiverBounds {
40    /// The most sequence numbers ahead of the cumulative ack point this receiver will ever track
41    /// (a bound on `loss_list` + `out_of_order`, which together can never name more sequence
42    /// numbers than the window spans). The effective bound is the negotiated Maximum Flow Window
43    /// Size (`draft-sharabayko-srt-01` §3.2.1: a packet further ahead than the window cannot be
44    /// buffered by the peer's own flow control either), clamped to this value so a hostile or
45    /// misconfigured window cannot turn one packet into unbounded work.
46    pub max_tracked_window: u32,
47    /// Most DROPREQ ranges held ahead of the ack point at once.
48    pub max_pending_skips: usize,
49    /// Hard cap on outstanding Full ACKs awaiting an ACKACK, however long the retention.
50    pub max_outstanding_acks: usize,
51}
52
53/// IPv4 (20 B) + UDP (8 B) header bytes inside one MTU-sized datagram — what
54/// the handshake's `MTU` field (§3.2.1, "Maximum Transmission Unit Size")
55/// counts but a NAK's Control Information Field cannot use.
56const IP_UDP_HEADER_LEN: usize = 28;
57
58/// Encoded size of one loss-list entry: a single sequence number is one
59/// 32-bit word, a range is two (Appendix A, Figures 21/22).
60const LOSS_ENTRY_SINGLE_LEN: usize = 4;
61const LOSS_ENTRY_RANGE_LEN: usize = 8;
62
63/// How many multiples of the round-trip time a Full ACK waits for its ACKACK
64/// before the entry is forgotten (the ACKACK was lost, or the peer never
65/// sends one). Implementation-defined — `srt-arq.md` rules 26-28 do not say
66/// when to give up.
67const ACK_RETENTION_RTTS: u32 = 4;
68
69/// Floor on the time an outstanding Full ACK is retained, so a very low RTT
70/// estimate cannot expire an ACKACK that is merely queued.
71const ACK_RETENTION_FLOOR: Duration = Duration::from_secs(1);
72
73/// Outcome of one [`Receiver::feed_data`] call.
74#[derive(Debug, Clone, PartialEq, Eq, Default)]
75#[non_exhaustive]
76pub struct FeedOutcome {
77    /// Sequence numbers that became cumulatively in-order-deliverable as a
78    /// result of this packet's arrival — includes `seq` itself when it was
79    /// the next-expected packet, plus any previously-buffered out-of-order
80    /// packets it consequently unblocked.
81    pub delivered: Vec<u32>,
82    /// An immediate NAK to send, if this packet's arrival revealed a new
83    /// gap (`private/specs-verified/rules/srt-arq.md` rules 4, 14).
84    pub nak: Option<Vec<u8>>,
85    /// The packet was not a 31-bit sequence number (§3.1), or was further
86    /// ahead of the cumulative ack point than the flow window allows, and was
87    /// ignored entirely (not recorded, not
88    /// NAKed): accepting it would let one crafted datagram inflate the loss
89    /// list. The caller must not stage or deliver it.
90    pub out_of_window: bool,
91}
92
93/// ARQ receiver-side state (`draft-sharabayko-srt-01` §4.8.1/§4.8.2/§4.10).
94#[derive(Debug)]
95pub struct Receiver {
96    dest_socket_id: u32,
97    /// Cumulative ack point: every seq strictly before this has been
98    /// delivered in order (rule 8).
99    next_expected: u32,
100    /// Received but not yet in-order-deliverable (a gap remains below it).
101    out_of_order: BTreeSet<u32>,
102    /// Sequence numbers currently believed lost (rules 4, 14, 21).
103    loss_list: BTreeSet<u32>,
104    /// DROPREQ ranges (§3.2.9) still ahead of the ack point, keyed by their
105    /// inclusive `first` sequence number with the inclusive `last` as the
106    /// value. Coalesced on insert and queried by range, so a repeated or
107    /// overlapping DROPREQ costs at most [`ReceiverBounds::max_pending_skips`] comparisons
108    /// rather than a rescan of the tracking sets.
109    pending_skips: BTreeMap<u32, u32>,
110    /// The highest sequence number ever received, to detect newly-opened
111    /// gaps (bookkeeping, not itself a spec-named field).
112    highest_received: Option<u32>,
113    /// Packets received since the last ACK of either kind (rule 12).
114    packets_since_ack: u32,
115    /// Absolute time the last Full ACK was sent (rule 11).
116    last_full_ack_at: Instant,
117    /// Absolute time the last periodic NAK was sent (rule 22).
118    last_nak_at: Instant,
119    /// Next Full ACK's Acknowledgement Number ("starting from 1", §3.2.4).
120    next_ack_number: u32,
121    /// Outstanding Full ACKs awaiting their ACKACK, send-time keyed by
122    /// Acknowledgement Number (rules 24, 26-28).
123    outstanding_acks: BTreeMap<u32, Instant>,
124    rtt: RttEstimator,
125    /// The Full ACK's "Available Buffer Size" (packets) — the negotiated
126    /// Maximum Flow Window Size (§3.2.1), the most this receiver will ever
127    /// have staged ahead of its delivery cursor (`Driver::ingress`'s flow-
128    /// window overflow guard enforces that cap independently, so this is
129    /// never an overstatement). A real libsrt sender's own flow control
130    /// treats this field as "room for N more packets": reporting `0` here
131    /// (this crate's old default, chosen to avoid fabricating a real
132    /// buffer-occupancy estimate) reads as "no room at all" and a real
133    /// libsrt Caller then withholds every DATA packet forever, connected but
134    /// silent — a real, previously undetected interop stall found live
135    /// against `srt-live-transmit`, independent of the caller-side
136    /// CONCLUSION `dest_socket_id` bug `libsrt_interop.rs` was originally
137    /// written to catch (libsrt interop; no tracked issue number for this
138    /// one).
139    avail_buf_size: u32,
140    /// The MTU the periodic NAK is sized against (`IP_UDP_HEADER_LEN` and the
141    /// SRT header come off it, see [`Self::with_mtu`]).
142    mtu: u32,
143    /// Pending-skip comparison work, counted so a test can prove a new-highest
144    /// packet does not rescan the loss list against every skip (#2821).
145    #[cfg(test)]
146    skip_scan_steps: u64,
147    bounds: ReceiverBounds,
148}
149
150impl Receiver {
151    /// A fresh receiver expecting `initial_seq` first (the peer's ISN),
152    /// addressing `dest_socket_id` (the peer's SRT Socket ID, §3), advertising
153    /// `max_flow_window` (§3.2.1) as its Full ACK's Available Buffer Size, sizing periodic NAKs
154    /// against `mtu` (the handshake's Maximum Transmission Unit Size, §3.2.1) and held to the
155    /// caller's `bounds`.
156    pub fn new(
157        dest_socket_id: u32,
158        initial_seq: u32,
159        max_flow_window: u32,
160        mtu: u32,
161        bounds: ReceiverBounds,
162    ) -> Self {
163        Receiver {
164            dest_socket_id,
165            next_expected: initial_seq,
166            out_of_order: BTreeSet::new(),
167            loss_list: BTreeSet::new(),
168            pending_skips: BTreeMap::new(),
169            highest_received: None,
170            packets_since_ack: 0,
171            last_full_ack_at: Instant::ZERO,
172            last_nak_at: Instant::ZERO,
173            next_ack_number: 1,
174            outstanding_acks: BTreeMap::new(),
175            rtt: RttEstimator::new(),
176            avail_buf_size: max_flow_window,
177            mtu,
178            #[cfg(test)]
179            skip_scan_steps: 0,
180            bounds,
181        }
182    }
183
184    /// Size periodic NAK datagrams against `mtu` (the handshake's negotiated
185    /// Maximum Transmission Unit Size, §3.2.1) instead of the 1500-byte
186    /// default: a loss list too long for one datagram is split across several
187    /// NAK packets rather than emitted as one the socket cannot send.
188    pub fn with_mtu(mut self, mtu: u32) -> Self {
189        self.mtu = mtu;
190        self
191    }
192
193    /// How far ahead of the ack point a packet may be and still be tracked.
194    fn window(&self) -> u32 {
195        self.avail_buf_size.min(self.bounds.max_tracked_window)
196    }
197
198    /// Most NAK Control Information Field bytes one datagram may carry:
199    /// the MTU less the IP/UDP and SRT headers, never less than one range
200    /// entry (so a pathological MTU still makes progress).
201    fn max_nak_cif_len(&self) -> usize {
202        usize::try_from(self.mtu)
203            .unwrap_or(usize::MAX)
204            .saturating_sub(IP_UDP_HEADER_LEN + crate::packet::SRT_HEADER_LEN)
205            .max(LOSS_ENTRY_RANGE_LEN)
206    }
207
208    /// The cumulative ack point — every seq strictly before this has been
209    /// delivered in order (rule 8's ACK `n + 1` semantics).
210    pub fn ack_point(&self) -> u32 {
211        self.next_expected
212    }
213
214    /// The current RTT estimate (rules 26-31).
215    pub fn rtt(&self) -> Duration {
216        self.rtt.rtt()
217    }
218
219    /// The current RTTVar estimate.
220    pub fn rtt_var(&self) -> Duration {
221        self.rtt.rtt_var()
222    }
223
224    /// Number of sequence numbers currently believed lost.
225    pub fn loss_list_len(&self) -> usize {
226        self.loss_list.len()
227    }
228
229    /// Process one arriving data packet's sequence number.
230    ///
231    /// A packet more than the flow window ahead of the ack point is ignored
232    /// ([`FeedOutcome::out_of_window`]): a crafted sequence jump therefore
233    /// never grows the loss list or the out-of-order set past the window.
234    pub fn feed_data(&mut self, seq_number: u32, now: Instant) -> FeedOutcome {
235        // Not a 31-bit sequence number at all (§3.1): never a real packet.
236        if seq_number > crate::packet::SEQ_NUMBER_MASK {
237            return FeedOutcome {
238                out_of_window: true,
239                ..FeedOutcome::default()
240            };
241        }
242        if seq::seq_gt(seq_number, self.next_expected)
243            && !u32::try_from(seq::seq_diff(seq_number, self.next_expected))
244                .is_ok_and(|ahead| ahead <= self.window())
245        {
246            return FeedOutcome {
247                out_of_window: true,
248                ..FeedOutcome::default()
249            };
250        }
251
252        self.packets_since_ack = self.packets_since_ack.saturating_add(1);
253
254        let mut nak_entries = Vec::new();
255        // Before any packet has arrived the "highest received" is the one
256        // just below the peer's ISN (the ack point), so a first packet
257        // ahead of the ISN reveals a gap like any other.
258        let highest = self
259            .highest_received
260            .unwrap_or_else(|| seq::seq_add(self.next_expected, crate::packet::SEQ_NUMBER_MASK));
261        if seq::seq_gt(seq_number, highest) {
262            // The newly opened gap, `highest + 1 ..= seq_number - 1` —
263            // clipped to the ack point (a DROPREQ may have moved it past
264            // a `highest` that never saw those packets).
265            let mut first_lost = seq::seq_next(highest);
266            if seq::seq_lt(first_lost, self.next_expected) {
267                first_lost = self.next_expected;
268            }
269            if first_lost != seq_number && seq::seq_lt(first_lost, seq_number) {
270                // `+ (2^31 - 1)` is `- 1` in the 31-bit sequence space.
271                let last_lost = seq::seq_add(seq_number, crate::packet::SEQ_NUMBER_MASK);
272                // Only this newly opened gap is filtered against the pending
273                // DROPREQ skips: every sequence number already in the loss
274                // list was filtered when *it* was inserted (and `skip_range`
275                // clears what a later DROPREQ names), so an in-order packet
276                // that merely advances `highest_received` does no skip work
277                // at all (#2821).
278                for (run_first, run_last) in self.uncovered_runs(first_lost, last_lost) {
279                    let mut s = run_first;
280                    loop {
281                        self.loss_list.insert(s);
282                        if s == run_last {
283                            break;
284                        }
285                        s = seq::seq_next(s);
286                    }
287                    let (run_first, run_last) = (
288                        SeqNo::from_wire_masked(run_first),
289                        SeqNo::from_wire_masked(run_last),
290                    );
291                    nak_entries.push(if run_first == run_last {
292                        LossListEntry::Single(run_first)
293                    } else {
294                        LossListEntry::Range(run_first, run_last)
295                    });
296                }
297            }
298            self.highest_received = Some(seq_number);
299        }
300
301        self.loss_list.remove(&seq_number);
302
303        let mut delivered = Vec::new();
304        if seq_number == self.next_expected {
305            delivered.push(seq_number);
306            self.next_expected = seq::seq_next(seq_number);
307            while self.out_of_order.remove(&self.next_expected) {
308                delivered.push(self.next_expected);
309                self.next_expected = seq::seq_next(self.next_expected);
310            }
311            self.cross_pending_skips(&mut delivered);
312        } else if seq::seq_gt(seq_number, self.next_expected) {
313            self.out_of_order.insert(seq_number);
314        }
315        // seq_number before next_expected: a duplicate of an
316        // already-delivered packet (e.g. a redundant retransmission) —
317        // nothing to do.
318
319        let nak = if nak_entries.is_empty() {
320            None
321        } else {
322            self.build_naks(&nak_entries, now).into_iter().next()
323        };
324
325        FeedOutcome {
326            delivered,
327            nak,
328            out_of_window: false,
329        }
330    }
331
332    /// Serialize `entries` into one or more NAK datagrams, none larger than
333    /// the MTU allows (a periodic NAK of a bursty-loss list otherwise grows
334    /// past one datagram, which the socket refuses with `EMSGSIZE`).
335    fn build_naks(&self, entries: &[LossListEntry], now: Instant) -> Vec<Vec<u8>> {
336        let budget = self.max_nak_cif_len();
337        let mut out = Vec::new();
338        let mut chunk: Vec<LossListEntry> = Vec::new();
339        let mut used = 0usize;
340        for &entry in entries {
341            let len = match entry {
342                LossListEntry::Range(..) => LOSS_ENTRY_RANGE_LEN,
343                _ => LOSS_ENTRY_SINGLE_LEN,
344            };
345            if used + len > budget && !chunk.is_empty() {
346                out.extend(self.nak_datagram(&chunk, now));
347                chunk.clear();
348                used = 0;
349            }
350            chunk.push(entry);
351            used += len;
352        }
353        if !chunk.is_empty() {
354            out.extend(self.nak_datagram(&chunk, now));
355        }
356        out
357    }
358
359    /// One NAK datagram for `entries`, or `None` if it cannot be serialized.
360    fn nak_datagram(&self, entries: &[LossListEntry], now: Instant) -> Option<Vec<u8>> {
361        let pkt = ControlPacket::Nak(NakPacket {
362            timestamp: timestamp_to_wire_us(now),
363            dest_socket_id: SocketId::from_wire(self.dest_socket_id),
364            entries: entries.to_vec(),
365        });
366        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
367        pkt.serialize_into(&mut buf).ok()?;
368        Some(buf)
369    }
370
371    /// Advance to absolute time `now` and emit any periodic control packets
372    /// now due: a Full ACK every [`super::FULL_ACK_PERIOD`] (rule 11), a
373    /// Light ACK once [`super::LIGHT_ACK_THRESHOLD`] packets have arrived
374    /// since the last ACK (rule 12), and a periodic NAK once `NAKInterval`
375    /// has elapsed *and* the loss list is non-empty (rules 21, 22) — never a
376    /// NAK when nothing is believed lost.
377    pub fn tick(&mut self, now: Instant) -> Vec<Vec<u8>> {
378        let mut out = Vec::new();
379
380        if elapsed(now, self.last_full_ack_at) >= FULL_ACK_PERIOD {
381            out.extend(self.build_full_ack(now));
382            self.last_full_ack_at = now;
383            self.packets_since_ack = 0;
384        } else if self.packets_since_ack >= LIGHT_ACK_THRESHOLD {
385            out.extend(self.build_light_ack());
386            self.packets_since_ack = 0;
387        }
388
389        let interval = nak_interval(self.rtt.rtt(), self.rtt.rtt_var());
390        if !self.loss_list.is_empty() && elapsed(now, self.last_nak_at) >= interval {
391            // Circular order from the ack point, so a run that straddles the
392            // 31-bit wrap coalesces into one range.
393            let base = self.next_expected;
394            let mut seqs: Vec<u32> = self.loss_list.iter().copied().collect();
395            seqs.sort_unstable_by_key(|&s| seq::seq_diff(s, base));
396            out.extend(self.build_naks(&coalesce(&seqs), now));
397            self.last_nak_at = now;
398        }
399
400        self.expire_outstanding_acks(now);
401
402        out
403    }
404
405    /// Absolute (since the connection epoch) time of the next periodic Full
406    /// ACK or, while the loss list is non-empty, the next periodic NAK —
407    /// whichever is earlier and still representable. The 10 ms Full ACK is
408    /// unconditional (rule 11), so an idle connection still has a deadline;
409    /// `None` means a deadline past the end of the clock, which never fires
410    /// (a deadline is [`Instant::checked_add`], never a saturated instant
411    /// that reads as "due now" forever).
412    pub fn next_deadline(&self) -> Option<Instant> {
413        let ack = self.last_full_ack_at.checked_add(FULL_ACK_PERIOD);
414        if self.loss_list.is_empty() {
415            return ack;
416        }
417        let nak = self
418            .last_nak_at
419            .checked_add(nak_interval(self.rtt.rtt(), self.rtt.rtt_var()));
420        match (ack, nak) {
421            (Some(a), Some(n)) => Some(a.min(n)),
422            (a, n) => a.or(n),
423        }
424    }
425
426    /// Forget Full ACKs whose ACKACK never came (W3): a lost ACKACK, or a
427    /// peer that never sends one, would otherwise leave one entry per Full
428    /// ACK (100/s) forever.
429    fn expire_outstanding_acks(&mut self, now: Instant) {
430        let retention = (self.rtt.rtt() * ACK_RETENTION_RTTS).max(ACK_RETENTION_FLOOR);
431        self.outstanding_acks
432            .retain(|_, sent_at| elapsed(now, *sent_at) <= retention);
433    }
434
435    fn build_full_ack(&mut self, now: Instant) -> Option<Vec<u8>> {
436        let ack_number = self.next_ack_number;
437        self.next_ack_number = self.next_ack_number.wrapping_add(1);
438        if self.outstanding_acks.len() >= self.bounds.max_outstanding_acks {
439            // Oldest first: Acknowledgement Numbers only ever increase (the
440            // 32-bit `AckNumber` counter wraps only after ~2^32 Full ACKs at
441            // 100/s).
442            self.outstanding_acks.pop_first();
443        }
444        self.outstanding_acks.insert(ack_number, now);
445        let pkt = ControlPacket::Ack(AckPacket {
446            ack_number: AckNumber::from_wire(ack_number),
447            timestamp: timestamp_to_wire_us(now),
448            dest_socket_id: SocketId::from_wire(self.dest_socket_id),
449            cif: AckCif::Full {
450                last_ack_seq: SeqNo::from_wire_masked(self.next_expected),
451                rtt_us: self.rtt.rtt_us(),
452                rtt_var_us: self.rtt.rtt_var_us(),
453                avail_buf_size: self.avail_buf_size,
454                // Bandwidth/rate estimation (§4.7) is out of ARQ scope — not
455                // curated in srt-arq.md, so left at 0 rather than fabricated.
456                pkt_recv_rate: 0,
457                est_link_capacity: 0,
458                recv_rate_bps: 0,
459            },
460        });
461        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
462        pkt.serialize_into(&mut buf).ok()?;
463        Some(buf)
464    }
465
466    fn build_light_ack(&self) -> Option<Vec<u8>> {
467        // §3.2.4: a Light ACK's Acknowledgement Number "should be set to
468        // 0"; it carries no RTT/CIF payload beyond the sequence number
469        // (rule 24).
470        let pkt = ControlPacket::Ack(AckPacket {
471            ack_number: AckNumber::ZERO,
472            timestamp: SrtTimestamp::ZERO,
473            dest_socket_id: SocketId::from_wire(self.dest_socket_id),
474            cif: AckCif::Light {
475                last_ack_seq: SeqNo::from_wire_masked(self.next_expected),
476            },
477        });
478        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
479        pkt.serialize_into(&mut buf).ok()?;
480        Some(buf)
481    }
482
483    /// Process an incoming ACKACK: match it against the outstanding Full ACK
484    /// it acknowledges and update RTT/RTTVar from the round-trip sample
485    /// (rules 26-30). An ACKACK for an unknown/already-matched
486    /// Acknowledgement Number is ignored.
487    pub fn on_ackack(&mut self, ackack: &AckAckPacket, now: Instant) {
488        if let Some(sent_at) = self.outstanding_acks.remove(&ackack.ack_number.value()) {
489            self.rtt.update(elapsed(now, sent_at));
490        }
491    }
492
493    /// Handle a peer's DROPREQ (`draft-sharabayko-srt-01` §3.2.9): the sender
494    /// has given up on delivering the inclusive sequence range
495    /// `first..=last`, so they will never arrive.
496    ///
497    /// Without this, loss detection would NAK those numbers forever and the
498    /// cumulative ack point (`next_expected`) would stall below the gap for
499    /// the life of the connection. The range is removed from the loss list
500    /// (stop asking) and the out-of-order set (the sender has given up on
501    /// them, so anything they unblocked can no longer be delivered in order),
502    /// and when the range covers `next_expected` the ack point jumps to the
503    /// sequence after `last`. A `last` preceding `first` is a malformed
504    /// (empty) range and ignored.
505    //
506    // Public so a sans-IO driver other than the tokio adapter (`crate::io`) can apply a DROPREQ
507    // and the Too-Late Packet Drop fake ACK.
508    pub fn skip_range(&mut self, first: u32, last: u32) {
509        if seq::seq_diff(last, first) < 0 {
510            return;
511        }
512        let reach = seq::seq_diff(last, self.next_expected);
513        if reach < 0 || !u32::try_from(reach).is_ok_and(|ahead| ahead <= self.window()) {
514            return;
515        }
516        // A repeat of a range already recorded is a no-op beyond crossing the
517        // cursor: it has already been removed from the tracking sets, so the
518        // two O(n) retains below are skipped (a peer flooding the same
519        // DROPREQ repeatedly costs O(MAX_PENDING_SKIPS) per datagram, #2821).
520        let covered = self
521            .pending_skips
522            .iter()
523            .any(|(&f, &l)| seq::seq_leq(f, first) && seq::seq_leq(last, l));
524        if covered {
525            self.cross_pending_skips(&mut Vec::new());
526            return;
527        }
528        // Both sets only ever hold sequence numbers at or below the highest
529        // received, so a range that starts beyond it cannot overlap either
530        // one — the DROPREQ-ahead-of-data shape does no scanning at all.
531        if self
532            .highest_received
533            .is_none_or(|highest| seq::seq_leq(first, highest))
534        {
535            self.loss_list
536                .retain(|s| !seq::seq_in_closed_range(*s, first, last));
537            self.out_of_order
538                .retain(|s| !seq::seq_in_closed_range(*s, first, last));
539        }
540        if seq::seq_lt(self.next_expected, first) {
541            self.remember_skip(first, last);
542        } else {
543            self.next_expected = seq::seq_next(last);
544        }
545        self.cross_pending_skips(&mut Vec::new());
546    }
547
548    /// Record one not-yet-reached DROPREQ range, coalescing it with every
549    /// overlapping or adjacent range already held so the map stays a set of
550    /// disjoint runs (`MAX_PENDING_SKIPS` bounds the scan).
551    fn remember_skip(&mut self, mut first: u32, mut last: u32) {
552        let overlapping: Vec<u32> = self
553            .pending_skips
554            .iter()
555            .filter(|&(&f, &l)| {
556                seq::seq_in_closed_range(f, first, last)
557                    || seq::seq_in_closed_range(l, first, last)
558                    || seq::seq_in_closed_range(first, f, l)
559                    || seq::seq_next(l) == first
560                    || seq::seq_next(last) == f
561            })
562            .map(|(&f, _)| f)
563            .collect();
564        for key in overlapping {
565            let Some(entry_last) = self.pending_skips.remove(&key) else {
566                continue;
567            };
568            if seq::seq_lt(key, first) {
569                first = key;
570            }
571            if seq::seq_gt(entry_last, last) {
572                last = entry_last;
573            }
574        }
575        if self.pending_skips.len() < self.bounds.max_pending_skips {
576            self.pending_skips.insert(first, last);
577        }
578    }
579
580    /// The parts of the inclusive circular range `first..=last` not covered
581    /// by a pending DROPREQ skip, in circular order. `first..=last` spans at
582    /// most the flow window, so treating each endpoint's forward distance
583    /// from `first` as a plain offset is exact.
584    fn uncovered_runs(&mut self, first: u32, last: u32) -> Vec<(u32, u32)> {
585        if self.pending_skips.is_empty() {
586            return alloc::vec![(first, last)];
587        }
588        let span = seq::seq_diff(last, first);
589        let mut _steps = 0u64;
590        let mut cuts: Vec<(u32, u32)> = self
591            .pending_skips
592            .iter()
593            .filter_map(|(&f, &l)| {
594                _steps = _steps.saturating_add(1);
595                let start = seq::seq_diff(f, first);
596                let end = seq::seq_diff(l, first);
597                if end < 0 || start > span {
598                    return None;
599                }
600                let start = u32::try_from(start.max(0)).ok()?;
601                let end = u32::try_from(end.min(span)).ok()?;
602                (start <= end).then_some((start, end))
603            })
604            .collect();
605        #[cfg(test)]
606        {
607            self.skip_scan_steps = self.skip_scan_steps.saturating_add(_steps);
608        }
609        if cuts.is_empty() {
610            return alloc::vec![(first, last)];
611        }
612        cuts.sort_unstable_by_key(|&(start, _)| start);
613        let mut out = Vec::new();
614        let mut next = 0u32;
615        for (start, end) in cuts {
616            if start > next {
617                out.push((seq::seq_add(first, next), seq::seq_add(first, start - 1)));
618            }
619            next = next.max(end.saturating_add(1));
620        }
621        if next <= u32::try_from(span).unwrap_or(0) {
622            out.push((seq::seq_add(first, next), last));
623        }
624        out
625    }
626
627    /// Advance the ack point over every packet already received and every
628    /// DROPREQ range it has reached, pushing the received ones onto
629    /// `delivered`.
630    fn cross_pending_skips(&mut self, delivered: &mut Vec<u32>) {
631        loop {
632            while self.out_of_order.remove(&self.next_expected) {
633                delivered.push(self.next_expected);
634                self.next_expected = seq::seq_next(self.next_expected);
635            }
636            let next = self.next_expected;
637            self.pending_skips.retain(|_, l| !seq::seq_lt(*l, next));
638            let covering = self
639                .pending_skips
640                .iter()
641                .find(|(f, l)| seq::seq_in_closed_range(next, **f, **l))
642                .map(|(&f, &l)| (f, l));
643            let Some((first, last)) = covering else {
644                return;
645            };
646            self.pending_skips.remove(&first);
647            self.next_expected = seq::seq_next(last);
648        }
649    }
650}
651
652/// `now - since`, clamped to zero rather than panicking on a non-monotonic
653/// `now` (a caller bug, not a protocol condition this module needs to
654/// reject).
655fn elapsed(now: Instant, since: Instant) -> Duration {
656    now.saturating_duration_since(since)
657}
658
659/// Coalesce a run of sequence numbers (already circularly increasing) into
660/// [`LossListEntry`] Single/Range entries (Appendix A) — a compact NAK
661/// encoding; the coalescing itself is not a spec rule.
662fn coalesce(seqs: &[u32]) -> Vec<LossListEntry> {
663    let mut out = Vec::new();
664    let mut i = 0;
665    while i < seqs.len() {
666        let start = seqs[i];
667        let mut end = start;
668        let mut j = i + 1;
669        while j < seqs.len() && seqs[j] == seq::seq_next(end) {
670            end = seqs[j];
671            j += 1;
672        }
673        let (start, end) = (SeqNo::from_wire_masked(start), SeqNo::from_wire_masked(end));
674        if start == end {
675            out.push(LossListEntry::Single(start));
676        } else {
677            out.push(LossListEntry::Range(start, end));
678        }
679        i = j;
680    }
681    out
682}
683
684#[cfg(test)]
685mod tests {
686    use super::*;
687
688    const MAX_TRACKED_WINDOW: u32 = 1 << 18;
689    const MAX_PENDING_SKIPS: usize = 1024;
690    const MAX_OUTSTANDING_ACKS: usize = 1024;
691    const TEST_MTU: u32 = 1500;
692    const TEST_BOUNDS: ReceiverBounds = ReceiverBounds {
693        max_tracked_window: MAX_TRACKED_WINDOW,
694        max_pending_skips: MAX_PENDING_SKIPS,
695        max_outstanding_acks: MAX_OUTSTANDING_ACKS,
696    };
697
698    const PEER: u32 = 0xBBBB;
699    const MAX_FLOW_WINDOW: u32 = 8192;
700
701    /// A `Instant` at `d` microseconds since the test epoch.
702    fn ts(d: Duration) -> Instant {
703        Instant::from_micros(u64::try_from(d.as_micros()).expect("in range"))
704    }
705
706    #[test]
707    fn next_timeout_is_the_full_ack_period_then_tracks_the_nak_interval() {
708        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
709        assert_eq!(
710            r.next_deadline(),
711            Some(ts(FULL_ACK_PERIOD)),
712            "fresh receiver: first Full ACK at 10 ms"
713        );
714        let _ = r.tick(ts(FULL_ACK_PERIOD));
715        assert_eq!(r.next_deadline(), Some(ts(FULL_ACK_PERIOD * 2)));
716        // a gap puts a NAK deadline on the table; it can only make the deadline earlier or equal
717        let _ = r.feed_data(5, Instant::from_millis(11)); // 1..=4 now lost
718        assert!(
719            r.next_deadline()
720                .is_some_and(|t| t <= ts(FULL_ACK_PERIOD * 2))
721        );
722    }
723
724    /// A deadline past the end of the clock never fires: at the last
725    /// representable `Instant` the next Full ACK (and, with a loss, the next
726    /// NAK) cannot be scheduled, so `next_deadline` reports `None` — not a
727    /// saturated instant equal to "now" that would re-fire forever.
728    #[test]
729    fn next_timeout_at_the_end_of_the_clock_is_none() {
730        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
731        r.last_full_ack_at = Instant::from_micros(u64::MAX);
732        assert_eq!(r.next_deadline(), None, "Full ACK deadline past the clock");
733
734        // A loss adds a NAK deadline too; it is equally unrepresentable.
735        r.last_nak_at = Instant::from_micros(u64::MAX);
736        r.loss_list.insert(0);
737        assert_eq!(r.next_deadline(), None, "NAK deadline past the clock");
738    }
739
740    #[test]
741    fn in_order_arrivals_deliver_immediately_without_nak() {
742        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
743        for seq_number in 0..5u32 {
744            let outcome = r.feed_data(seq_number, Instant::ZERO);
745            assert_eq!(outcome.delivered, alloc::vec![seq_number]);
746            assert!(outcome.nak.is_none());
747        }
748        assert_eq!(r.ack_point(), 5);
749        assert_eq!(r.loss_list_len(), 0);
750    }
751
752    #[test]
753    fn a_gap_triggers_an_immediate_nak_and_stalls_delivery() {
754        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
755        r.feed_data(0, Instant::ZERO);
756        r.feed_data(1, Instant::ZERO);
757        let outcome = r.feed_data(3, Instant::ZERO); // seq 2 missing
758        assert!(outcome.delivered.is_empty());
759        let nak = outcome.nak.expect("gap must trigger an immediate NAK");
760        let ControlPacket::Nak(n) = ControlPacket::parse(&nak).unwrap() else {
761            panic!("expected NAK");
762        };
763        assert_eq!(n.entries, alloc::vec![LossListEntry::Single(sn(2))]);
764        assert_eq!(r.ack_point(), 2); // stalled at the gap
765        assert_eq!(r.loss_list_len(), 1);
766
767        // Filling the gap unblocks the buffered seq 3 too.
768        let fill = r.feed_data(2, Instant::ZERO);
769        assert_eq!(fill.delivered, alloc::vec![2, 3]);
770        assert!(fill.nak.is_none());
771        assert_eq!(r.ack_point(), 4);
772        assert_eq!(r.loss_list_len(), 0);
773    }
774
775    #[test]
776    fn zero_loss_tick_never_emits_a_nak() {
777        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
778        for seq_number in 0..5u32 {
779            r.feed_data(seq_number, Instant::ZERO);
780        }
781        for ms in 1..200u64 {
782            let out = r.tick(Instant::from_millis(ms));
783            for bytes in &out {
784                assert!(!matches!(
785                    ControlPacket::parse(bytes).unwrap(),
786                    ControlPacket::Nak(_)
787                ));
788            }
789        }
790    }
791
792    #[test]
793    fn full_ack_fires_on_the_10ms_timer_and_light_ack_on_the_64_packet_threshold() {
794        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
795        let out = r.tick(ts(FULL_ACK_PERIOD));
796        assert_eq!(out.len(), 1);
797        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
798            panic!("expected ACK");
799        };
800        assert!(matches!(ack.cif, AckCif::Full { .. }));
801        assert_eq!(ack.ack_number.value(), 1);
802
803        // Under the Full ACK period, but past the light-ack packet count.
804        for seq_number in 0..LIGHT_ACK_THRESHOLD {
805            r.feed_data(seq_number, Instant::ZERO);
806        }
807        let out = r.tick(ts(FULL_ACK_PERIOD + Duration::from_millis(1)));
808        // Immediately after a Full ACK, the next tick 1ms later is still
809        // under the 10ms period, so a Light ACK fires instead.
810        let out2 = r.tick(ts(FULL_ACK_PERIOD + Duration::from_millis(2)));
811        let light =
812            out.into_iter()
813                .chain(out2)
814                .find_map(|b| match ControlPacket::parse(&b).unwrap() {
815                    ControlPacket::Ack(a) if matches!(a.cif, AckCif::Light { .. }) => Some(a),
816                    _ => None,
817                });
818        assert!(
819            light.is_some(),
820            "expected a Light ACK from the 64-packet threshold"
821        );
822    }
823
824    #[test]
825    fn ackack_updates_rtt_from_the_measured_round_trip() {
826        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
827        let out = r.tick(ts(FULL_ACK_PERIOD));
828        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
829            panic!("expected ACK");
830        };
831        let ackack = AckAckPacket {
832            ack_number: ack.ack_number,
833            timestamp: SrtTimestamp::ZERO,
834            dest_socket_id: SocketId::from_wire(PEER),
835            libsrt_pad: false,
836        };
837        let sample = Duration::from_millis(20);
838        r.on_ackack(&ackack, ts(FULL_ACK_PERIOD + sample));
839        // moved from the 100ms initial value toward the 20ms sample.
840        assert!(r.rtt() < Duration::from_millis(100));
841        assert!(r.rtt() > sample);
842    }
843
844    fn nak_entries(bytes: &[u8]) -> Vec<LossListEntry> {
845        let ControlPacket::Nak(n) = ControlPacket::parse(bytes).unwrap() else {
846            panic!("expected NAK");
847        };
848        n.entries
849    }
850
851    fn sn(v: u32) -> SeqNo {
852        SeqNo::try_new(v).expect("fits 31 bits")
853    }
854
855    /// r08-SRT-W2: a sequence number past the flow window is ignored, so one
856    /// crafted datagram cannot inflate the loss list. 2^30 - 1 is the farthest
857    /// "ahead" the 31-bit circular order allows (the old code enumerated
858    /// 65 536 losses for it and then jumped `highest_received`, so the next
859    /// spoofed packet added another 65 536).
860    #[test]
861    fn a_sequence_number_wider_than_31_bits_is_refused() {
862        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
863        for seq in [0x8000_0000u32, 0x8000_0001, u32::MAX] {
864            let out = r.feed_data(seq, Instant::ZERO);
865            assert!(out.out_of_window, "{seq:#x}");
866            assert!(out.delivered.is_empty() && out.nak.is_none());
867        }
868        assert_eq!(r.loss_list_len(), 0);
869        assert_eq!(r.highest_received, None);
870        assert_eq!(r.ack_point(), 0);
871    }
872
873    #[test]
874    fn a_hostile_sequence_jump_is_ignored_not_enumerated() {
875        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
876        r.feed_data(0, Instant::ZERO);
877        for jump in [(1u32 << 30) - 1, 1 << 20, 1 << 18, 5 << 16] {
878            let out = r.feed_data(jump, Instant::ZERO);
879            assert!(out.out_of_window, "jump to {jump} must be refused");
880            assert!(out.nak.is_none());
881            assert!(out.delivered.is_empty());
882        }
883        assert_eq!(r.loss_list_len(), 0);
884        assert_eq!(r.out_of_order.len(), 0);
885        assert_eq!(r.ack_point(), 1);
886        // The ack point is where the window is measured from: repeating the
887        // attack does not move `highest_received` either.
888        assert_eq!(r.highest_received, Some(0));
889    }
890
891    /// The window boundary is exact: `next_expected + window` is accepted
892    /// (and its whole gap NAKed as one range), one more is refused.
893    #[test]
894    fn the_flow_window_boundary_is_exact() {
895        const WINDOW: u32 = 1000;
896        let mut r = Receiver::new(PEER, 0, WINDOW, TEST_MTU, TEST_BOUNDS);
897        let beyond = r.feed_data(WINDOW + 1, Instant::ZERO);
898        assert!(beyond.out_of_window);
899        assert_eq!(r.loss_list_len(), 0);
900
901        let edge = r.feed_data(WINDOW, Instant::ZERO);
902        assert!(!edge.out_of_window);
903        assert_eq!(r.loss_list_len(), (WINDOW - 1) as usize + 1); // 0..WINDOW-1
904        let nak = edge.nak.expect("the gap is NAKed immediately");
905        // One Range entry, not 1000 singles.
906        assert_eq!(
907            nak_entries(&nak),
908            alloc::vec![LossListEntry::Range(sn(0), sn(WINDOW - 1))]
909        );
910        assert!(r.out_of_order.len() <= WINDOW as usize);
911    }
912
913    /// A window larger than the receiver is willing to track is clamped, so
914    /// a hostile `max_flow_window_size` cannot re-open the flood.
915    #[test]
916    fn an_oversized_negotiated_window_is_clamped() {
917        let mut r = Receiver::new(PEER, 0, u32::MAX, TEST_MTU, TEST_BOUNDS);
918        let out = r.feed_data((1 << 30) - 1, Instant::ZERO);
919        assert!(out.out_of_window);
920        assert_eq!(r.loss_list_len(), 0);
921    }
922
923    /// r08-SRT-W3: Full ACKs whose ACKACK never arrives are forgotten. 5 000
924    /// ticks (50 s) with no ACKACK at all used to leave 5 000 entries.
925    #[test]
926    fn unanswered_full_acks_age_out() {
927        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
928        for tick in 1..=5_000u64 {
929            r.tick(Instant::from_millis(10 * tick));
930        }
931        // Retention is max(4 x RTT, 1 s) = 1 s of 10 ms ACKs.
932        let retention_acks =
933            (ACK_RETENTION_FLOOR.as_millis() / FULL_ACK_PERIOD.as_millis()) as usize;
934        assert!(
935            r.outstanding_acks.len() <= retention_acks + 1,
936            "{} outstanding ACKs retained",
937            r.outstanding_acks.len()
938        );
939        assert!(!r.outstanding_acks.is_empty(), "recent ACKs are kept");
940    }
941
942    /// An ACKACK arriving inside the retention window still measures RTT; one
943    /// that arrives after its entry aged out is ignored.
944    #[test]
945    fn ackack_after_expiry_is_ignored() {
946        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
947        let out = r.tick(ts(FULL_ACK_PERIOD));
948        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
949            panic!("expected ACK");
950        };
951        let ackack = AckAckPacket {
952            ack_number: ack.ack_number,
953            timestamp: SrtTimestamp::ZERO,
954            dest_socket_id: SocketId::from_wire(PEER),
955            libsrt_pad: false,
956        };
957        let rtt_before = r.rtt();
958        // Age the entry out (no ACKACK for 10 s), then deliver the ACKACK.
959        for tick in 2..=1_000u64 {
960            r.tick(Instant::from_millis(10 * tick));
961        }
962        r.on_ackack(&ackack, ts(Duration::from_secs(10)));
963        assert_eq!(r.rtt(), rtt_before, "an expired ACK must not move the RTT");
964    }
965
966    /// The hard cap: more Full ACKs than `MAX_OUTSTANDING_ACKS` inside one
967    /// retention window evict the oldest rather than growing.
968    #[test]
969    fn outstanding_acks_are_capped() {
970        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
971        for _ in 0..(MAX_OUTSTANDING_ACKS * 5) {
972            r.build_full_ack(Instant::ZERO);
973        }
974        assert_eq!(r.outstanding_acks.len(), MAX_OUTSTANDING_ACKS);
975        // The survivors are the newest.
976        let oldest = *r.outstanding_acks.keys().next().unwrap();
977        assert_eq!(oldest as usize, MAX_OUTSTANDING_ACKS * 4 + 1);
978    }
979
980    /// r08-SRT-W4: a bursty (non-contiguous) loss list no longer becomes one
981    /// datagram larger than the MTU — it is split, every datagram fits, and
982    /// together they name every lost packet exactly once.
983    #[test]
984    fn periodic_nak_is_split_to_fit_the_mtu() {
985        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
986        r.feed_data(0, Instant::ZERO);
987        // Receive every other packet: 2, 4, ..., 2000 → 1000 isolated losses.
988        let mut lost = Vec::new();
989        for q in (2..=2000u32).step_by(2) {
990            r.feed_data(q, Instant::ZERO);
991            lost.push(q - 1);
992        }
993        assert_eq!(r.loss_list_len(), 1000);
994
995        let naks: Vec<Vec<u8>> = r
996            .tick(ts(Duration::from_secs(1)))
997            .into_iter()
998            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
999            .collect();
1000        assert!(naks.len() > 1, "1000 singles cannot fit one datagram");
1001        let mut named = Vec::new();
1002        for nak in &naks {
1003            assert!(
1004                nak.len() + IP_UDP_HEADER_LEN <= TEST_MTU as usize,
1005                "NAK of {} B exceeds the {} B MTU",
1006                nak.len() + IP_UDP_HEADER_LEN,
1007                TEST_MTU
1008            );
1009            for e in nak_entries(nak) {
1010                match e {
1011                    LossListEntry::Single(s) => named.push(s.value()),
1012                    other => panic!("unexpected entry {other:?}"),
1013                }
1014            }
1015        }
1016        named.sort_unstable();
1017        assert_eq!(named, lost);
1018    }
1019
1020    /// The MTU is configurable: 576 gives smaller datagrams.
1021    #[test]
1022    fn nak_chunking_follows_the_configured_mtu() {
1023        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS).with_mtu(576);
1024        r.feed_data(0, Instant::ZERO);
1025        for q in (2..=400u32).step_by(2) {
1026            r.feed_data(q, Instant::ZERO);
1027        }
1028        let naks: Vec<Vec<u8>> = r
1029            .tick(ts(Duration::from_secs(1)))
1030            .into_iter()
1031            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
1032            .collect();
1033        assert!(naks.len() >= 2);
1034        for nak in &naks {
1035            assert!(nak.len() + IP_UDP_HEADER_LEN <= 576);
1036        }
1037    }
1038
1039    /// A loss run that straddles the 31-bit wrap is one range in the periodic
1040    /// NAK (the loss list is ordered by raw value, which would split it at
1041    /// the wrap).
1042    #[test]
1043    fn periodic_nak_coalesces_a_loss_run_across_the_wrap() {
1044        const MAX: u32 = crate::packet::SEQ_NUMBER_MASK;
1045        let mut r = Receiver::new(PEER, MAX - 2, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1046        r.feed_data(MAX - 2, Instant::ZERO);
1047        let imm = r.feed_data(2, Instant::ZERO); // MAX-1, MAX, 0, 1 lost
1048        assert_eq!(
1049            nak_entries(&imm.nak.expect("gap NAK")),
1050            alloc::vec![LossListEntry::Range(sn(MAX - 1), sn(1))]
1051        );
1052        let naks: Vec<Vec<u8>> = r
1053            .tick(ts(Duration::from_secs(1)))
1054            .into_iter()
1055            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
1056            .collect();
1057        assert_eq!(naks.len(), 1);
1058        assert_eq!(
1059            nak_entries(&naks[0]),
1060            alloc::vec![LossListEntry::Range(sn(MAX - 1), sn(1))]
1061        );
1062    }
1063
1064    /// After a DROPREQ moves the ack point past packets this receiver never
1065    /// saw, the next gap is measured from the ack point, not from a stale
1066    /// `highest_received` (which would NAK sequence numbers the sender gave
1067    /// up on).
1068    #[cfg(feature = "tokio")]
1069    #[test]
1070    fn gap_after_a_dropreq_starts_at_the_ack_point() {
1071        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1072        r.feed_data(0, Instant::ZERO);
1073        r.skip_range(1, 99); // sender gave up on 1..=99
1074        assert_eq!(r.ack_point(), 100);
1075        let out = r.feed_data(105, Instant::ZERO);
1076        assert_eq!(
1077            nak_entries(&out.nak.expect("gap NAK")),
1078            alloc::vec![LossListEntry::Range(sn(100), sn(104))]
1079        );
1080        assert_eq!(r.loss_list_len(), 5);
1081    }
1082
1083    /// #2860: the tracked window is clamped to `MAX_TRACKED_WINDOW` no matter
1084    /// how large a flow window was negotiated, and a packet beyond the clamp
1085    /// is rejected even though the advertised window would allow it.
1086    #[test]
1087    fn tracked_window_is_clamped_and_a_packet_beyond_it_is_out_of_window() {
1088        let mut r = Receiver::new(PEER, 0, u32::MAX, TEST_MTU, TEST_BOUNDS);
1089        assert_eq!(r.window(), MAX_TRACKED_WINDOW);
1090        r.feed_data(0, Instant::ZERO);
1091        let beyond = r.feed_data(MAX_TRACKED_WINDOW + 2, Instant::ZERO);
1092        assert!(beyond.out_of_window);
1093        assert_eq!(r.loss_list_len(), 0);
1094        let at_limit = r.feed_data(MAX_TRACKED_WINDOW + 1, Instant::ZERO);
1095        assert!(!at_limit.out_of_window);
1096        assert_eq!(
1097            r.loss_list_len(),
1098            usize::try_from(MAX_TRACKED_WINDOW).unwrap()
1099        );
1100    }
1101
1102    /// #2860: a DROPREQ flood cannot grow the pending-skip set past
1103    /// `MAX_PENDING_SKIPS`.
1104    #[test]
1105    fn a_dropreq_flood_stops_at_the_pending_skip_cap() {
1106        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1107        let flood = u32::try_from(MAX_PENDING_SKIPS).unwrap() + 48;
1108        for i in 0..flood {
1109            let s = 1000 + 2 * i;
1110            r.skip_range(s, s);
1111        }
1112        assert_eq!(r.pending_skips.len(), MAX_PENDING_SKIPS);
1113    }
1114
1115    /// #2821: an in-order arrival that only advances `highest_received` must
1116    /// not rescan the loss list against every pending DROPREQ skip. The old
1117    /// `retain(.. any ..)` ran on every new-highest packet — including a
1118    /// fully in-order one — at `loss_list × skips` comparisons per packet.
1119    #[test]
1120    fn in_order_arrivals_do_no_skip_scan_work() {
1121        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1122        r.feed_data(0, Instant::ZERO);
1123        r.feed_data(4000, Instant::ZERO); // 1..=3999 lost
1124        for s in 1..3000 {
1125            r.feed_data(s, Instant::ZERO); // ack point advances to 3000
1126        }
1127        assert_eq!(r.ack_point(), 3000);
1128        assert_eq!(r.loss_list_len(), 1000); // 3000..=3999 still lost
1129        for i in 0..64u32 {
1130            r.skip_range(5000 + 2 * i, 5000 + 2 * i);
1131        }
1132        assert_eq!(r.pending_skips.len(), 64);
1133        assert_eq!(r.loss_list_len(), 1000);
1134
1135        let before = r.skip_scan_steps;
1136        for i in 1..=100u32 {
1137            let out = r.feed_data(4000 + i, Instant::ZERO);
1138            assert!(!out.out_of_window);
1139        }
1140        assert_eq!(r.loss_list_len(), 1000);
1141        assert_eq!(
1142            r.skip_scan_steps, before,
1143            "100 in-order arrivals must do no skip-map work"
1144        );
1145    }
1146
1147    /// The Full ACK's ACKACK round trip pins both EWMAs to their hand-computed
1148    /// rule 29/30 values (10 ms then 50 ms samples).
1149    #[test]
1150    fn ackack_round_trips_pin_rtt_and_rtt_var() {
1151        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1152        let out = r.tick(ts(FULL_ACK_PERIOD));
1153        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
1154            panic!("expected ACK");
1155        };
1156        let ackack = AckAckPacket {
1157            ack_number: ack.ack_number,
1158            timestamp: SrtTimestamp::ZERO,
1159            dest_socket_id: SocketId::from_wire(PEER),
1160            libsrt_pad: false,
1161        };
1162        r.on_ackack(&ackack, ts(FULL_ACK_PERIOD + Duration::from_millis(10)));
1163        // RTT = (7*100 000 + 10 000) / 8 = 88 750 us.
1164        assert_eq!(r.rtt(), Duration::from_micros(88_750));
1165        // RTTVar = (3*50 000 + |100 000 - 10 000|) / 4 = 60 000 us.
1166        assert_eq!(r.rtt_var(), Duration::from_micros(60_000));
1167
1168        let out = r.tick(ts(FULL_ACK_PERIOD * 2));
1169        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
1170            panic!("expected ACK");
1171        };
1172        let ackack = AckAckPacket {
1173            ack_number: ack.ack_number,
1174            timestamp: SrtTimestamp::ZERO,
1175            dest_socket_id: SocketId::from_wire(PEER),
1176            libsrt_pad: false,
1177        };
1178        r.on_ackack(&ackack, ts(Duration::from_millis(70))); // 50 ms after the second ACK
1179        // RTT = (7*88 750 + 50 000) / 8 = 83 906 us.
1180        assert_eq!(r.rtt(), Duration::from_micros(83_906));
1181        // RTTVar = (3*60 000 + |88 750 - 50 000|) / 4 = 54 687 us.
1182        assert_eq!(r.rtt_var(), Duration::from_micros(54_687));
1183    }
1184
1185    /// A Full ACK awaiting its ACKACK is retained for
1186    /// `ACK_RETENTION_RTTS * RTT` (5.35 s at a 1.3375 s estimate, well above
1187    /// the 1 s floor) and forgotten one tick past it.
1188    #[test]
1189    fn ack_retention_scales_with_the_rtt_estimate() {
1190        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1191        r.rtt.update(Duration::from_secs(10));
1192        assert_eq!(r.rtt(), Duration::from_micros(1_337_500));
1193        let retention = Duration::from_micros(5_350_000);
1194        assert_eq!(retention, Duration::from_micros(1_337_500 * 4));
1195
1196        let _ = r.build_full_ack(ts(Duration::from_secs(1)));
1197        assert_eq!(r.outstanding_acks.len(), 1);
1198        r.expire_outstanding_acks(ts(
1199            Duration::from_secs(1) + retention - Duration::from_millis(1)
1200        ));
1201        assert_eq!(r.outstanding_acks.len(), 1, "still inside the window");
1202        r.expire_outstanding_acks(ts(Duration::from_secs(1)
1203            + retention
1204            + Duration::from_millis(1)));
1205        assert_eq!(r.outstanding_acks.len(), 0, "one tick past the window");
1206    }
1207
1208    fn periodic_nak_bytes(r: &mut Receiver, now: Instant) -> Vec<Vec<u8>> {
1209        r.tick(now)
1210            .into_iter()
1211            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
1212            .collect()
1213    }
1214
1215    /// 400 isolated losses (4-byte Single entries) fill a 1500-byte MTU
1216    /// exactly 364 entries per NAK datagram, so exactly two datagrams carry
1217    /// them, neither past the MTU.
1218    #[test]
1219    fn periodic_nak_splits_singles_at_the_exact_mtu_fill() {
1220        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1221        for q in (0..800u32).step_by(2) {
1222            r.loss_list.insert(q);
1223        }
1224        let naks = periodic_nak_bytes(&mut r, ts(Duration::from_secs(1)));
1225        assert_eq!(naks.len(), 2);
1226        assert_eq!(naks[0].len() + IP_UDP_HEADER_LEN, TEST_MTU as usize);
1227        assert_eq!(naks[1].len(), crate::packet::SRT_HEADER_LEN + 36 * 4);
1228        assert_eq!(nak_entries(&naks[0]).len(), 364);
1229        assert_eq!(nak_entries(&naks[1]).len(), 36);
1230    }
1231
1232    /// A Range entry is 8 wire bytes: 300 two-packet ranges split 182/118
1233    /// across two MTU-sized NAK datagrams.
1234    #[test]
1235    fn periodic_nak_splits_ranges_at_the_exact_mtu_fill() {
1236        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1237        for i in 0..300u32 {
1238            r.loss_list.insert(4 * i);
1239            r.loss_list.insert(4 * i + 1);
1240        }
1241        let naks = periodic_nak_bytes(&mut r, ts(Duration::from_secs(1)));
1242        assert_eq!(naks.len(), 2);
1243        for nak in &naks {
1244            assert!(nak.len() + IP_UDP_HEADER_LEN <= TEST_MTU as usize);
1245        }
1246        let first = nak_entries(&naks[0]);
1247        assert_eq!(first.len(), 182);
1248        assert!(first.iter().all(|e| matches!(e, LossListEntry::Range(..))));
1249        assert_eq!(nak_entries(&naks[1]).len(), 118);
1250    }
1251
1252    /// The largest valid 31-bit sequence number is a real packet; one past it
1253    /// is not.
1254    #[test]
1255    fn the_largest_31_bit_sequence_number_is_in_window() {
1256        const MAX: u32 = crate::packet::SEQ_NUMBER_MASK;
1257        let mut r = Receiver::new(PEER, MAX - 2, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1258        assert_eq!(
1259            r.feed_data(MAX - 2, Instant::ZERO).delivered,
1260            alloc::vec![MAX - 2]
1261        );
1262        assert_eq!(
1263            r.feed_data(MAX - 1, Instant::ZERO).delivered,
1264            alloc::vec![MAX - 1]
1265        );
1266        let out = r.feed_data(MAX, Instant::ZERO);
1267        assert!(!out.out_of_window);
1268        assert_eq!(out.delivered, alloc::vec![MAX]);
1269        assert_eq!(r.ack_point(), 0);
1270        assert!(r.feed_data(MAX + 1, Instant::ZERO).out_of_window);
1271    }
1272
1273    /// A DROPREQ removes its inclusive range from the loss list, and
1274    /// overlapping plus adjacent DROPREQs coalesce into one skip run: the next
1275    /// periodic NAK never re-asks for data the sender already dropped.
1276    #[test]
1277    fn dropreq_ranges_merge_and_are_subtracted_from_the_loss_list() {
1278        let mut r = Receiver::new(PEER, 10, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1279        r.feed_data(10, Instant::ZERO);
1280        let gap = r.feed_data(20, Instant::ZERO); // 11..=19 lost
1281        assert_eq!(
1282            nak_entries(&gap.nak.expect("gap NAK")),
1283            alloc::vec![LossListEntry::Range(sn(11), sn(19))]
1284        );
1285        assert_eq!(r.loss_list_len(), 9);
1286
1287        r.skip_range(12, 14);
1288        let naks = periodic_nak_bytes(&mut r, ts(Duration::from_secs(1)));
1289        assert_eq!(naks.len(), 1);
1290        assert_eq!(
1291            nak_entries(&naks[0]),
1292            alloc::vec![
1293                LossListEntry::Single(sn(11)),
1294                LossListEntry::Range(sn(15), sn(19))
1295            ]
1296        );
1297        assert_eq!(r.loss_list_len(), 6);
1298        assert_eq!(r.pending_skips.get(&12), Some(&14));
1299
1300        // Overlapping (13..=16) then adjacent-after (17..=17) merge into one
1301        // 12..=17 skip.
1302        r.skip_range(13, 16);
1303        r.skip_range(17, 17);
1304        assert_eq!(r.pending_skips.len(), 1);
1305        assert_eq!(r.pending_skips.get(&12), Some(&17));
1306        let naks = periodic_nak_bytes(&mut r, ts(Duration::from_secs(2)));
1307        assert_eq!(naks.len(), 1);
1308        assert_eq!(
1309            nak_entries(&naks[0]),
1310            alloc::vec![
1311                LossListEntry::Single(sn(11)),
1312                LossListEntry::Range(sn(18), sn(19))
1313            ]
1314        );
1315        assert_eq!(r.loss_list_len(), 3);
1316    }
1317
1318    /// Overlapping skips inserted in either order coalesce into one disjoint
1319    /// run (the four overlap/adjacency predicates each contribute).
1320    #[test]
1321    fn remember_skip_coalesces_every_overlap_and_adjacency_shape() {
1322        let mut r = Receiver::new(PEER, 100, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1323        r.skip_range(112, 120);
1324        // Overlaps the existing run at its front and contains its start.
1325        r.skip_range(111, 114);
1326        assert_eq!(r.pending_skips.len(), 1);
1327        assert_eq!(r.pending_skips.get(&111), Some(&120));
1328
1329        // Adjacent-before: 108..=111 abuts 112 from below.
1330        let mut r = Receiver::new(PEER, 100, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1331        r.skip_range(112, 120);
1332        r.skip_range(108, 111);
1333        assert_eq!(r.pending_skips.len(), 1);
1334        assert_eq!(r.pending_skips.get(&108), Some(&120));
1335
1336        // Adjacent-after: 121..=125 abuts 120 from above.
1337        let mut r = Receiver::new(PEER, 100, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1338        r.skip_range(112, 120);
1339        r.skip_range(121, 125);
1340        assert_eq!(r.pending_skips.len(), 1);
1341        assert_eq!(r.pending_skips.get(&112), Some(&125));
1342    }
1343
1344    /// A DROPREQ outside the loss list records only a skip: the loss list and
1345    /// ack point are untouched, and a DROPREQ wholly behind the ack point is
1346    /// ignored.
1347    #[test]
1348    fn a_dropreq_outside_the_loss_list_changes_nothing() {
1349        let mut r = Receiver::new(PEER, 10, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1350        r.feed_data(10, Instant::ZERO);
1351        r.feed_data(20, Instant::ZERO); // 11..=19 lost
1352        r.skip_range(30, 35); // ahead of the highest received
1353        assert_eq!(r.loss_list_len(), 9);
1354        assert_eq!(r.ack_point(), 11);
1355        assert_eq!(r.pending_skips.get(&30), Some(&35));
1356
1357        r.skip_range(5, 8); // wholly behind the ack point
1358        assert_eq!(r.loss_list_len(), 9);
1359        assert_eq!(r.ack_point(), 11);
1360
1361        let naks = periodic_nak_bytes(&mut r, ts(Duration::from_secs(1)));
1362        assert_eq!(naks.len(), 1);
1363        assert_eq!(
1364            nak_entries(&naks[0]),
1365            alloc::vec![LossListEntry::Range(sn(11), sn(19))]
1366        );
1367    }
1368
1369    /// A skip covering the whole loss list suppresses every NAK for it.
1370    #[test]
1371    fn a_skip_over_the_whole_loss_list_suppresses_the_nak() {
1372        let mut r = Receiver::new(PEER, 10, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1373        r.feed_data(10, Instant::ZERO);
1374        r.feed_data(20, Instant::ZERO); // 11..=19 lost
1375        r.skip_range(11, 19);
1376        assert_eq!(r.loss_list_len(), 0);
1377        assert_eq!(r.ack_point(), 21);
1378        assert!(periodic_nak_bytes(&mut r, ts(Duration::from_secs(1))).is_empty());
1379    }
1380
1381    /// A gap opened while a DROPREQ skip is pending omits the skipped run
1382    /// (the skip's interior is cut out, the tail after it kept).
1383    #[test]
1384    fn a_gap_opened_after_a_pending_skip_omits_the_skipped_run() {
1385        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1386        for q in 0..6u32 {
1387            r.feed_data(q, Instant::ZERO);
1388        }
1389        r.skip_range(10, 12);
1390        let out = r.feed_data(16, Instant::ZERO); // gap 6..=15
1391        assert_eq!(
1392            nak_entries(&out.nak.expect("gap NAK")),
1393            alloc::vec![
1394                LossListEntry::Range(sn(6), sn(9)),
1395                LossListEntry::Range(sn(13), sn(15))
1396            ]
1397        );
1398    }
1399
1400    /// A skip ending one before the gap's last packet keeps that last packet
1401    /// (the uncovered tail is still a loss).
1402    #[test]
1403    fn a_skip_ending_before_the_last_lost_packet_keeps_the_tail() {
1404        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1405        for q in 0..6u32 {
1406            r.feed_data(q, Instant::ZERO);
1407        }
1408        r.skip_range(10, 14);
1409        let out = r.feed_data(16, Instant::ZERO); // gap 6..=15
1410        assert_eq!(
1411            nak_entries(&out.nak.expect("gap NAK")),
1412            alloc::vec![
1413                LossListEntry::Range(sn(6), sn(9)),
1414                LossListEntry::Single(sn(15))
1415            ]
1416        );
1417    }
1418
1419    /// A skip whose last packet is exactly the gap's first packet hides it
1420    /// (a cut at offset 0 is still a cut).
1421    #[test]
1422    fn a_skip_ending_at_the_gap_start_hides_it() {
1423        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1424        for q in 0..5u32 {
1425            r.feed_data(q, Instant::ZERO);
1426        }
1427        r.skip_range(12, 15);
1428        r.feed_data(14, Instant::ZERO); // gap 5..=13, 12..=13 skipped
1429        assert_eq!(r.loss_list_len(), 7); // 5..=11
1430        let out = r.feed_data(16, Instant::ZERO); // gap is exactly 15, skipped
1431        assert!(out.nak.is_none());
1432        assert_eq!(r.loss_list_len(), 7);
1433    }
1434
1435    /// A skip starting exactly at the gap's last packet leaves the rest of the
1436    /// gap uncovered.
1437    #[test]
1438    fn a_skip_starting_at_the_last_lost_packet_is_still_a_cut() {
1439        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1440        for q in 0..6u32 {
1441            r.feed_data(q, Instant::ZERO);
1442        }
1443        r.skip_range(15, 20);
1444        let out = r.feed_data(16, Instant::ZERO); // gap 6..=15
1445        assert_eq!(
1446            nak_entries(&out.nak.expect("gap NAK")),
1447            alloc::vec![LossListEntry::Range(sn(6), sn(14))]
1448        );
1449    }
1450
1451    /// A packet the ack point has already passed (a DROPREQ jumped
1452    /// `next_expected` past `highest_received`) is a duplicate: it opens no
1453    /// gap, NAKs nothing and grows no loss list.
1454    #[test]
1455    fn a_packet_behind_the_ack_point_after_a_skip_opens_no_gap() {
1456        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1457        for q in 0..6u32 {
1458            r.feed_data(q, Instant::ZERO);
1459        }
1460        r.skip_range(6, 20);
1461        assert_eq!(r.ack_point(), 21);
1462        let out = r.feed_data(10, Instant::ZERO);
1463        assert!(!out.out_of_window);
1464        assert!(out.delivered.is_empty());
1465        assert!(out.nak.is_none());
1466        assert_eq!(r.loss_list_len(), 0);
1467    }
1468
1469    /// A DROPREQ whose `last` is exactly the ack point still advances it, and
1470    /// one reaching past the flow window is ignored entirely.
1471    #[test]
1472    fn dropreq_reach_boundaries_are_exact() {
1473        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW, TEST_MTU, TEST_BOUNDS);
1474        for q in 0..6u32 {
1475            r.feed_data(q, Instant::ZERO);
1476        }
1477        assert_eq!(r.ack_point(), 6);
1478        r.skip_range(4, 6);
1479        assert_eq!(r.ack_point(), 7);
1480
1481        let mut r = Receiver::new(PEER, 0, 1000, TEST_MTU, TEST_BOUNDS);
1482        r.skip_range(5000, 7000);
1483        assert_eq!(r.ack_point(), 0);
1484        assert!(r.pending_skips.is_empty());
1485        assert_eq!(r.loss_list_len(), 0);
1486    }
1487}