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