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 `now: core::time::Duration`
8//! (elapsed time since a fixed epoch the caller owns).
9//!
10//! # Delivery model
11//! [`FeedOutcome::delivered`] lists the sequence numbers that became
12//! cumulatively in-order-deliverable as a result of one `feed_data` call —
13//! i.e. the ARQ engine's view of "no longer missing" (rule 8's ack point),
14//! not a TSBPD-timed playout (that delay is `srt-tsbpd.md` scope, a
15//! separate follow-up).
16//!
17//! # TLPKTDROP fake ACK
18//! The receiver advances its ack point past packets the delivery side gave up
19//! on only when told to (the crate-internal skip the tokio adapter calls when
20//! the TSBPD scheduler reports a drop, rule 13); it never skips a gap on its
21//! own, so without that call it keeps NAKing and never acknowledges what it
22//! has not received.
23
24use alloc::collections::{BTreeMap, BTreeSet};
25use alloc::vec::Vec;
26use core::time::Duration;
27
28use crate::packet::nak::build_loss_list;
29use crate::packet::{AckAckPacket, AckCif, AckPacket, ControlPacket, LossListEntry, NakPacket};
30
31use super::rtt::RttEstimator;
32use super::{FULL_ACK_PERIOD, LIGHT_ACK_THRESHOLD, duration_to_wire_us, nak_interval, seq};
33
34/// The most sequence numbers ahead of the cumulative ack point this receiver
35/// will ever track (a bound on `loss_list` + `out_of_order`, which together
36/// can never name more sequence numbers than the window spans). The
37/// effective bound is the negotiated Maximum Flow Window Size
38/// (`draft-sharabayko-srt-01` §3.2.1 — a packet further ahead than the window
39/// cannot be buffered by the peer's own flow control either), clamped to this
40/// value so a hostile or misconfigured window cannot turn one packet into
41/// unbounded work. Not a `private/specs-verified/rules/srt-arq.md` rule — an implementation
42/// bound (about ten times libsrt's default 25 600-packet flow window).
43const MAX_TRACKED_WINDOW: u32 = 1 << 18;
44
45/// IPv4 (20 B) + UDP (8 B) header bytes inside one MTU-sized datagram — what
46/// the handshake's `MTU` field (§3.2.1, "Maximum Transmission Unit Size")
47/// counts but a NAK's Control Information Field cannot use.
48const IP_UDP_HEADER_LEN: usize = 28;
49
50/// Encoded size of one loss-list entry: a single sequence number is one
51/// 32-bit word, a range is two (Appendix A, Figures 21/22).
52const LOSS_ENTRY_SINGLE_LEN: usize = 4;
53const LOSS_ENTRY_RANGE_LEN: usize = 8;
54
55/// Default MTU assumed for NAK sizing until [`Receiver::with_mtu`] sets the
56/// negotiated value (the handshake's default `MTU`, 1500 B).
57const DEFAULT_MTU: u32 = 1500;
58
59/// How many multiples of the round-trip time a Full ACK waits for its ACKACK
60/// before the entry is forgotten (the ACKACK was lost, or the peer never
61/// sends one). Implementation-defined — `srt-arq.md` rules 26-28 do not say
62/// when to give up.
63const ACK_RETENTION_RTTS: u32 = 4;
64
65/// Floor on the time an outstanding Full ACK is retained, so a very low RTT
66/// estimate cannot expire an ACKACK that is merely queued.
67const ACK_RETENTION_FLOOR: Duration = Duration::from_secs(1);
68
69/// Hard cap on outstanding Full ACKs awaiting an ACKACK, however long the
70/// retention (at one Full ACK per 10 ms this is ten seconds' worth).
71const MAX_OUTSTANDING_ACKS: usize = 1024;
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    /// The highest sequence number ever received, to detect newly-opened
105    /// gaps (bookkeeping, not itself a spec-named field).
106    highest_received: Option<u32>,
107    /// Packets received since the last ACK of either kind (rule 12).
108    packets_since_ack: u32,
109    /// Absolute time the last Full ACK was sent (rule 11).
110    last_full_ack_at: Duration,
111    /// Absolute time the last periodic NAK was sent (rule 22).
112    last_nak_at: Duration,
113    /// Next Full ACK's Acknowledgement Number ("starting from 1", §3.2.4).
114    next_ack_number: u32,
115    /// Outstanding Full ACKs awaiting their ACKACK, send-time keyed by
116    /// Acknowledgement Number (rules 24, 26-28).
117    outstanding_acks: BTreeMap<u32, Duration>,
118    rtt: RttEstimator,
119    /// The Full ACK's "Available Buffer Size" (packets) — the negotiated
120    /// Maximum Flow Window Size (§3.2.1), the most this receiver will ever
121    /// have staged ahead of its delivery cursor (`Driver::ingress`'s flow-
122    /// window overflow guard enforces that cap independently, so this is
123    /// never an overstatement). A real libsrt sender's own flow control
124    /// treats this field as "room for N more packets": reporting `0` here
125    /// (this crate's old default, chosen to avoid fabricating a real
126    /// buffer-occupancy estimate) reads as "no room at all" and a real
127    /// libsrt Caller then withholds every DATA packet forever, connected but
128    /// silent — a real, previously undetected interop stall found live
129    /// against `srt-live-transmit`, independent of the caller-side
130    /// CONCLUSION `dest_socket_id` bug `libsrt_interop.rs` was originally
131    /// written to catch (libsrt interop; no tracked issue number for this
132    /// one).
133    avail_buf_size: u32,
134    /// The MTU the periodic NAK is sized against (`IP_UDP_HEADER_LEN` and the
135    /// SRT header come off it, see [`Self::with_mtu`]).
136    mtu: u32,
137}
138
139impl Receiver {
140    /// A fresh receiver expecting `initial_seq` first (the peer's ISN),
141    /// addressing `dest_socket_id` (the peer's SRT Socket ID, §3), advertising
142    /// `max_flow_window` (§3.2.1) as its Full ACK's Available Buffer Size.
143    pub fn new(dest_socket_id: u32, initial_seq: u32, max_flow_window: u32) -> Self {
144        Receiver {
145            dest_socket_id,
146            next_expected: initial_seq,
147            out_of_order: BTreeSet::new(),
148            loss_list: BTreeSet::new(),
149            highest_received: None,
150            packets_since_ack: 0,
151            last_full_ack_at: Duration::ZERO,
152            last_nak_at: Duration::ZERO,
153            next_ack_number: 1,
154            outstanding_acks: BTreeMap::new(),
155            rtt: RttEstimator::new(),
156            avail_buf_size: max_flow_window,
157            mtu: DEFAULT_MTU,
158        }
159    }
160
161    /// Size periodic NAK datagrams against `mtu` (the handshake's negotiated
162    /// Maximum Transmission Unit Size, §3.2.1) instead of the 1500-byte
163    /// default: a loss list too long for one datagram is split across several
164    /// NAK packets rather than emitted as one the socket cannot send.
165    pub fn with_mtu(mut self, mtu: u32) -> Self {
166        self.mtu = mtu;
167        self
168    }
169
170    /// How far ahead of the ack point a packet may be and still be tracked.
171    fn window(&self) -> u32 {
172        self.avail_buf_size.min(MAX_TRACKED_WINDOW)
173    }
174
175    /// Most NAK Control Information Field bytes one datagram may carry:
176    /// the MTU less the IP/UDP and SRT headers, never less than one range
177    /// entry (so a pathological MTU still makes progress).
178    fn max_nak_cif_len(&self) -> usize {
179        usize::try_from(self.mtu)
180            .unwrap_or(usize::MAX)
181            .saturating_sub(IP_UDP_HEADER_LEN + crate::packet::SRT_HEADER_LEN)
182            .max(LOSS_ENTRY_RANGE_LEN)
183    }
184
185    /// The cumulative ack point — every seq strictly before this has been
186    /// delivered in order (rule 8's ACK `n + 1` semantics).
187    pub fn ack_point(&self) -> u32 {
188        self.next_expected
189    }
190
191    /// The current RTT estimate (rules 26-31).
192    pub fn rtt(&self) -> Duration {
193        self.rtt.rtt()
194    }
195
196    /// The current RTTVar estimate.
197    pub fn rtt_var(&self) -> Duration {
198        self.rtt.rtt_var()
199    }
200
201    /// Number of sequence numbers currently believed lost.
202    pub fn loss_list_len(&self) -> usize {
203        self.loss_list.len()
204    }
205
206    /// Process one arriving data packet's sequence number.
207    ///
208    /// A packet more than the flow window ahead of the ack point is ignored
209    /// ([`FeedOutcome::out_of_window`]): a crafted sequence jump therefore
210    /// never grows the loss list or the out-of-order set past the window.
211    pub fn feed_data(&mut self, seq_number: u32, now: Duration) -> FeedOutcome {
212        // Not a 31-bit sequence number at all (§3.1): never a real packet.
213        if seq_number > crate::packet::SEQ_NUMBER_MASK {
214            return FeedOutcome {
215                out_of_window: true,
216                ..FeedOutcome::default()
217            };
218        }
219        if seq::seq_gt(seq_number, self.next_expected)
220            && !u32::try_from(seq::seq_diff(seq_number, self.next_expected))
221                .is_ok_and(|ahead| ahead <= self.window())
222        {
223            return FeedOutcome {
224                out_of_window: true,
225                ..FeedOutcome::default()
226            };
227        }
228
229        self.packets_since_ack = self.packets_since_ack.saturating_add(1);
230
231        let mut nak_entries = Vec::new();
232        // Before any packet has arrived the "highest received" is the one
233        // just below the peer's ISN (the ack point), so a first packet
234        // ahead of the ISN reveals a gap like any other.
235        let highest = self
236            .highest_received
237            .unwrap_or_else(|| seq::seq_add(self.next_expected, crate::packet::SEQ_NUMBER_MASK));
238        if seq::seq_gt(seq_number, highest) {
239            // The newly opened gap, `highest + 1 ..= seq_number - 1` —
240            // clipped to the ack point (a DROPREQ may have moved it past
241            // a `highest` that never saw those packets).
242            let mut first_lost = seq::seq_next(highest);
243            if seq::seq_lt(first_lost, self.next_expected) {
244                first_lost = self.next_expected;
245            }
246            if first_lost != seq_number && seq::seq_lt(first_lost, seq_number) {
247                // `+ (2^31 - 1)` is `- 1` in the 31-bit sequence space.
248                let last_lost = seq::seq_add(seq_number, crate::packet::SEQ_NUMBER_MASK);
249                let mut s = first_lost;
250                loop {
251                    self.loss_list.insert(s);
252                    if s == last_lost {
253                        break;
254                    }
255                    s = seq::seq_next(s);
256                }
257                nak_entries.push(if first_lost == last_lost {
258                    LossListEntry::Single(first_lost)
259                } else {
260                    LossListEntry::Range(first_lost, last_lost)
261                });
262            }
263            self.highest_received = Some(seq_number);
264        }
265
266        self.loss_list.remove(&seq_number);
267
268        let mut delivered = Vec::new();
269        if seq_number == self.next_expected {
270            delivered.push(seq_number);
271            self.next_expected = seq::seq_next(seq_number);
272            while self.out_of_order.remove(&self.next_expected) {
273                delivered.push(self.next_expected);
274                self.next_expected = seq::seq_next(self.next_expected);
275            }
276        } else if seq::seq_gt(seq_number, self.next_expected) {
277            self.out_of_order.insert(seq_number);
278        }
279        // seq_number before next_expected: a duplicate of an
280        // already-delivered packet (e.g. a redundant retransmission) —
281        // nothing to do.
282
283        let nak = if nak_entries.is_empty() {
284            None
285        } else {
286            self.build_naks(&nak_entries, now).into_iter().next()
287        };
288
289        FeedOutcome {
290            delivered,
291            nak,
292            out_of_window: false,
293        }
294    }
295
296    /// Serialize `entries` into one or more NAK datagrams, none larger than
297    /// the MTU allows (a periodic NAK of a bursty-loss list otherwise grows
298    /// past one datagram, which the socket refuses with `EMSGSIZE`).
299    fn build_naks(&self, entries: &[LossListEntry], now: Duration) -> Vec<Vec<u8>> {
300        let budget = self.max_nak_cif_len();
301        let mut out = Vec::new();
302        let mut chunk: Vec<LossListEntry> = Vec::new();
303        let mut used = 0usize;
304        for &entry in entries {
305            let len = match entry {
306                LossListEntry::Range(..) => LOSS_ENTRY_RANGE_LEN,
307                _ => LOSS_ENTRY_SINGLE_LEN,
308            };
309            if used + len > budget && !chunk.is_empty() {
310                out.extend(self.nak_datagram(&chunk, now));
311                chunk.clear();
312                used = 0;
313            }
314            chunk.push(entry);
315            used += len;
316        }
317        if !chunk.is_empty() {
318            out.extend(self.nak_datagram(&chunk, now));
319        }
320        out
321    }
322
323    /// One NAK datagram for `entries`, or `None` if the entries cannot be
324    /// encoded (a sequence number wider than 31 bits — unreachable, every
325    /// entry derives from a masked sequence number — is dropped rather than
326    /// panicking the connection).
327    fn nak_datagram(&self, entries: &[LossListEntry], now: Duration) -> Option<Vec<u8>> {
328        let raw = build_loss_list(entries).ok()?;
329        let pkt = ControlPacket::Nak(NakPacket {
330            timestamp: duration_to_wire_us(now),
331            dest_socket_id: self.dest_socket_id,
332            raw_loss_list: &raw,
333        });
334        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
335        pkt.serialize_into(&mut buf).ok()?;
336        Some(buf)
337    }
338
339    /// Advance to absolute time `now` and emit any periodic control packets
340    /// now due: a Full ACK every [`super::FULL_ACK_PERIOD`] (rule 11), a
341    /// Light ACK once [`super::LIGHT_ACK_THRESHOLD`] packets have arrived
342    /// since the last ACK (rule 12), and a periodic NAK once `NAKInterval`
343    /// has elapsed *and* the loss list is non-empty (rules 21, 22) — never a
344    /// NAK when nothing is believed lost.
345    pub fn tick(&mut self, now: Duration) -> Vec<Vec<u8>> {
346        let mut out = Vec::new();
347
348        if elapsed(now, self.last_full_ack_at) >= FULL_ACK_PERIOD {
349            out.extend(self.build_full_ack(now));
350            self.last_full_ack_at = now;
351            self.packets_since_ack = 0;
352        } else if self.packets_since_ack >= LIGHT_ACK_THRESHOLD {
353            out.extend(self.build_light_ack());
354            self.packets_since_ack = 0;
355        }
356
357        let interval = nak_interval(self.rtt.rtt(), self.rtt.rtt_var());
358        if !self.loss_list.is_empty() && elapsed(now, self.last_nak_at) >= interval {
359            // Circular order from the ack point, so a run that straddles the
360            // 31-bit wrap coalesces into one range.
361            let base = self.next_expected;
362            let mut seqs: Vec<u32> = self.loss_list.iter().copied().collect();
363            seqs.sort_unstable_by_key(|&s| seq::seq_diff(s, base));
364            out.extend(self.build_naks(&coalesce(&seqs), now));
365            self.last_nak_at = now;
366        }
367
368        self.expire_outstanding_acks(now);
369
370        out
371    }
372
373    /// Absolute (since the connection epoch) time of the next periodic Full
374    /// ACK or, while the loss list is non-empty, the next periodic NAK —
375    /// whichever is earlier. Always defined: the 10 ms Full ACK is
376    /// unconditional (rule 11), so an idle connection still has a deadline.
377    pub fn next_timeout(&self) -> Duration {
378        let ack = self.last_full_ack_at + FULL_ACK_PERIOD;
379        if self.loss_list.is_empty() {
380            return ack;
381        }
382        let nak = self.last_nak_at + nak_interval(self.rtt.rtt(), self.rtt.rtt_var());
383        ack.min(nak)
384    }
385
386    /// Forget Full ACKs whose ACKACK never came (W3): a lost ACKACK, or a
387    /// peer that never sends one, would otherwise leave one entry per Full
388    /// ACK (100/s) forever.
389    fn expire_outstanding_acks(&mut self, now: Duration) {
390        let retention = (self.rtt.rtt() * ACK_RETENTION_RTTS).max(ACK_RETENTION_FLOOR);
391        self.outstanding_acks
392            .retain(|_, sent_at| elapsed(now, *sent_at) <= retention);
393    }
394
395    fn build_full_ack(&mut self, now: Duration) -> Option<Vec<u8>> {
396        let ack_number = self.next_ack_number;
397        self.next_ack_number = self.next_ack_number.wrapping_add(1);
398        if self.outstanding_acks.len() >= MAX_OUTSTANDING_ACKS {
399            // Oldest first: Acknowledgement Numbers only ever increase.
400            self.outstanding_acks.pop_first();
401        }
402        self.outstanding_acks.insert(ack_number, now);
403        let pkt = ControlPacket::Ack(AckPacket {
404            ack_number,
405            timestamp: duration_to_wire_us(now),
406            dest_socket_id: self.dest_socket_id,
407            cif: AckCif::Full {
408                last_ack_seq: self.next_expected,
409                rtt_us: self.rtt.rtt_us(),
410                rtt_var_us: self.rtt.rtt_var_us(),
411                avail_buf_size: self.avail_buf_size,
412                // Bandwidth/rate estimation (§4.7) is out of ARQ scope — not
413                // curated in srt-arq.md, so left at 0 rather than fabricated.
414                pkt_recv_rate: 0,
415                est_link_capacity: 0,
416                recv_rate_bps: 0,
417            },
418        });
419        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
420        pkt.serialize_into(&mut buf).ok()?;
421        Some(buf)
422    }
423
424    fn build_light_ack(&self) -> Option<Vec<u8>> {
425        // §3.2.4: a Light ACK's Acknowledgement Number "should be set to
426        // 0"; it carries no RTT/CIF payload beyond the sequence number
427        // (rule 24).
428        let pkt = ControlPacket::Ack(AckPacket {
429            ack_number: 0,
430            timestamp: 0,
431            dest_socket_id: self.dest_socket_id,
432            cif: AckCif::Light {
433                last_ack_seq: self.next_expected,
434            },
435        });
436        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
437        pkt.serialize_into(&mut buf).ok()?;
438        Some(buf)
439    }
440
441    /// Process an incoming ACKACK: match it against the outstanding Full ACK
442    /// it acknowledges and update RTT/RTTVar from the round-trip sample
443    /// (rules 26-30). An ACKACK for an unknown/already-matched
444    /// Acknowledgement Number is ignored.
445    pub fn on_ackack(&mut self, ackack: &AckAckPacket, now: Duration) {
446        if let Some(sent_at) = self.outstanding_acks.remove(&ackack.ack_number) {
447            self.rtt.update(elapsed(now, sent_at));
448        }
449    }
450
451    /// Handle a peer's DROPREQ (`draft-sharabayko-srt-01` §3.2.9): the sender
452    /// has given up on delivering the inclusive sequence range
453    /// `first..=last`, so they will never arrive.
454    ///
455    /// Without this, loss detection would NAK those numbers forever and the
456    /// cumulative ack point (`next_expected`) would stall below the gap for
457    /// the life of the connection. The range is removed from the loss list
458    /// (stop asking) and the out-of-order set (the sender has given up on
459    /// them, so anything they unblocked can no longer be delivered in order),
460    /// and when the range covers `next_expected` the ack point jumps to the
461    /// sequence after `last`. A `last` preceding `first` is a malformed
462    /// (empty) range and ignored.
463    //
464    // Public so a sans-IO driver other than the tokio adapter (`crate::io`) can apply a DROPREQ
465    // and the Too-Late Packet Drop fake ACK.
466    pub fn skip_range(&mut self, first: u32, last: u32) {
467        if seq::seq_diff(last, first) < 0 {
468            return;
469        }
470        self.loss_list
471            .retain(|s| !seq::seq_in_closed_range(*s, first, last));
472        self.out_of_order
473            .retain(|s| !seq::seq_in_closed_range(*s, first, last));
474        if seq::seq_in_closed_range(self.next_expected, first, last) {
475            self.next_expected = seq::seq_next(last);
476        }
477        // Anything at or beyond the new ack point that was already received
478        // is now cumulatively deliverable — drain it exactly like `feed_data`
479        // does when a gap is filled.
480        while self.out_of_order.remove(&self.next_expected) {
481            self.next_expected = seq::seq_next(self.next_expected);
482        }
483    }
484}
485
486/// `now - since`, clamped to zero rather than panicking on a non-monotonic
487/// `now` (a caller bug, not a protocol condition this module needs to
488/// reject).
489fn elapsed(now: Duration, since: Duration) -> Duration {
490    now.checked_sub(since).unwrap_or(Duration::ZERO)
491}
492
493/// Coalesce a run of sequence numbers (already circularly increasing) into
494/// [`LossListEntry`] Single/Range entries (Appendix A) — a compact NAK
495/// encoding; the coalescing itself is not a spec rule.
496fn coalesce(seqs: &[u32]) -> Vec<LossListEntry> {
497    let mut out = Vec::new();
498    let mut i = 0;
499    while i < seqs.len() {
500        let start = seqs[i];
501        let mut end = start;
502        let mut j = i + 1;
503        while j < seqs.len() && seqs[j] == seq::seq_next(end) {
504            end = seqs[j];
505            j += 1;
506        }
507        if start == end {
508            out.push(LossListEntry::Single(start));
509        } else {
510            out.push(LossListEntry::Range(start, end));
511        }
512        i = j;
513    }
514    out
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520
521    const PEER: u32 = 0xBBBB;
522    const MAX_FLOW_WINDOW: u32 = 8192;
523
524    #[test]
525    fn next_timeout_is_the_full_ack_period_then_tracks_the_nak_interval() {
526        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
527        assert_eq!(
528            r.next_timeout(),
529            FULL_ACK_PERIOD,
530            "fresh receiver: first Full ACK at 10 ms"
531        );
532        let _ = r.tick(FULL_ACK_PERIOD);
533        assert_eq!(r.next_timeout(), FULL_ACK_PERIOD * 2);
534        // a gap puts a NAK deadline on the table; it can only make the deadline earlier or equal
535        let _ = r.feed_data(5, Duration::from_millis(11)); // 1..=4 now lost
536        assert!(r.next_timeout() <= FULL_ACK_PERIOD * 2);
537    }
538
539    #[test]
540    fn in_order_arrivals_deliver_immediately_without_nak() {
541        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
542        for seq_number in 0..5u32 {
543            let outcome = r.feed_data(seq_number, Duration::ZERO);
544            assert_eq!(outcome.delivered, alloc::vec![seq_number]);
545            assert!(outcome.nak.is_none());
546        }
547        assert_eq!(r.ack_point(), 5);
548        assert_eq!(r.loss_list_len(), 0);
549    }
550
551    #[test]
552    fn a_gap_triggers_an_immediate_nak_and_stalls_delivery() {
553        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
554        r.feed_data(0, Duration::ZERO);
555        r.feed_data(1, Duration::ZERO);
556        let outcome = r.feed_data(3, Duration::ZERO); // seq 2 missing
557        assert!(outcome.delivered.is_empty());
558        let nak = outcome.nak.expect("gap must trigger an immediate NAK");
559        let ControlPacket::Nak(n) = ControlPacket::parse(&nak).unwrap() else {
560            panic!("expected NAK");
561        };
562        let entries: Vec<LossListEntry> = n.entries().map(|e| e.unwrap()).collect();
563        assert_eq!(entries, alloc::vec![LossListEntry::Single(2)]);
564        assert_eq!(r.ack_point(), 2); // stalled at the gap
565        assert_eq!(r.loss_list_len(), 1);
566
567        // Filling the gap unblocks the buffered seq 3 too.
568        let fill = r.feed_data(2, Duration::ZERO);
569        assert_eq!(fill.delivered, alloc::vec![2, 3]);
570        assert!(fill.nak.is_none());
571        assert_eq!(r.ack_point(), 4);
572        assert_eq!(r.loss_list_len(), 0);
573    }
574
575    #[test]
576    fn zero_loss_tick_never_emits_a_nak() {
577        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
578        for seq_number in 0..5u32 {
579            r.feed_data(seq_number, Duration::ZERO);
580        }
581        for ms in 1..200u64 {
582            let out = r.tick(Duration::from_millis(ms));
583            for bytes in &out {
584                assert!(!matches!(
585                    ControlPacket::parse(bytes).unwrap(),
586                    ControlPacket::Nak(_)
587                ));
588            }
589        }
590    }
591
592    #[test]
593    fn full_ack_fires_on_the_10ms_timer_and_light_ack_on_the_64_packet_threshold() {
594        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
595        let out = r.tick(FULL_ACK_PERIOD);
596        assert_eq!(out.len(), 1);
597        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
598            panic!("expected ACK");
599        };
600        assert!(matches!(ack.cif, AckCif::Full { .. }));
601        assert_eq!(ack.ack_number, 1);
602
603        // Under the Full ACK period, but past the light-ack packet count.
604        for seq_number in 0..LIGHT_ACK_THRESHOLD {
605            r.feed_data(seq_number, Duration::ZERO);
606        }
607        let out = r.tick(FULL_ACK_PERIOD + Duration::from_millis(1));
608        // Immediately after a Full ACK, the next tick 1ms later is still
609        // under the 10ms period, so a Light ACK fires instead.
610        let out2 = r.tick(FULL_ACK_PERIOD + Duration::from_millis(2));
611        let light =
612            out.into_iter()
613                .chain(out2)
614                .find_map(|b| match ControlPacket::parse(&b).unwrap() {
615                    ControlPacket::Ack(a) if matches!(a.cif, AckCif::Light { .. }) => Some(a),
616                    _ => None,
617                });
618        assert!(
619            light.is_some(),
620            "expected a Light ACK from the 64-packet threshold"
621        );
622    }
623
624    #[test]
625    fn ackack_updates_rtt_from_the_measured_round_trip() {
626        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
627        let out = r.tick(FULL_ACK_PERIOD);
628        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
629            panic!("expected ACK");
630        };
631        let ackack = AckAckPacket {
632            ack_number: ack.ack_number,
633            timestamp: 0,
634            dest_socket_id: PEER,
635            libsrt_pad: false,
636        };
637        let sample = Duration::from_millis(20);
638        r.on_ackack(&ackack, FULL_ACK_PERIOD + sample);
639        // moved from the 100ms initial value toward the 20ms sample.
640        assert!(r.rtt() < Duration::from_millis(100));
641        assert!(r.rtt() > sample);
642    }
643
644    fn nak_entries(bytes: &[u8]) -> Vec<LossListEntry> {
645        let ControlPacket::Nak(n) = ControlPacket::parse(bytes).unwrap() else {
646            panic!("expected NAK");
647        };
648        n.entries().map(|e| e.unwrap()).collect()
649    }
650
651    /// r08-SRT-W2: a sequence number past the flow window is ignored, so one
652    /// crafted datagram cannot inflate the loss list. 2^30 - 1 is the farthest
653    /// "ahead" the 31-bit circular order allows (the old code enumerated
654    /// 65 536 losses for it and then jumped `highest_received`, so the next
655    /// spoofed packet added another 65 536).
656    #[test]
657    fn a_sequence_number_wider_than_31_bits_is_refused() {
658        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
659        for seq in [0x8000_0000u32, 0x8000_0001, u32::MAX] {
660            let out = r.feed_data(seq, Duration::ZERO);
661            assert!(out.out_of_window, "{seq:#x}");
662            assert!(out.delivered.is_empty() && out.nak.is_none());
663        }
664        assert_eq!(r.loss_list_len(), 0);
665        assert_eq!(r.highest_received, None);
666        assert_eq!(r.ack_point(), 0);
667    }
668
669    #[test]
670    fn a_hostile_sequence_jump_is_ignored_not_enumerated() {
671        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
672        r.feed_data(0, Duration::ZERO);
673        for jump in [(1u32 << 30) - 1, 1 << 20, 1 << 18, 5 << 16] {
674            let out = r.feed_data(jump, Duration::ZERO);
675            assert!(out.out_of_window, "jump to {jump} must be refused");
676            assert!(out.nak.is_none());
677            assert!(out.delivered.is_empty());
678        }
679        assert_eq!(r.loss_list_len(), 0);
680        assert_eq!(r.out_of_order.len(), 0);
681        assert_eq!(r.ack_point(), 1);
682        // The ack point is where the window is measured from: repeating the
683        // attack does not move `highest_received` either.
684        assert_eq!(r.highest_received, Some(0));
685    }
686
687    /// The window boundary is exact: `next_expected + window` is accepted
688    /// (and its whole gap NAKed as one range), one more is refused.
689    #[test]
690    fn the_flow_window_boundary_is_exact() {
691        const WINDOW: u32 = 1000;
692        let mut r = Receiver::new(PEER, 0, WINDOW);
693        let beyond = r.feed_data(WINDOW + 1, Duration::ZERO);
694        assert!(beyond.out_of_window);
695        assert_eq!(r.loss_list_len(), 0);
696
697        let edge = r.feed_data(WINDOW, Duration::ZERO);
698        assert!(!edge.out_of_window);
699        assert_eq!(r.loss_list_len(), (WINDOW - 1) as usize + 1); // 0..WINDOW-1
700        let nak = edge.nak.expect("the gap is NAKed immediately");
701        // One Range entry, not 1000 singles.
702        assert_eq!(
703            nak_entries(&nak),
704            alloc::vec![LossListEntry::Range(0, WINDOW - 1)]
705        );
706        assert!(r.out_of_order.len() <= WINDOW as usize);
707    }
708
709    /// A window larger than the receiver is willing to track is clamped, so
710    /// a hostile `max_flow_window_size` cannot re-open the flood.
711    #[test]
712    fn an_oversized_negotiated_window_is_clamped() {
713        let mut r = Receiver::new(PEER, 0, u32::MAX);
714        let out = r.feed_data((1 << 30) - 1, Duration::ZERO);
715        assert!(out.out_of_window);
716        assert_eq!(r.loss_list_len(), 0);
717    }
718
719    /// r08-SRT-W3: Full ACKs whose ACKACK never arrives are forgotten. 5 000
720    /// ticks (50 s) with no ACKACK at all used to leave 5 000 entries.
721    #[test]
722    fn unanswered_full_acks_age_out() {
723        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
724        for tick in 1..=5_000u64 {
725            r.tick(Duration::from_millis(10 * tick));
726        }
727        // Retention is max(4 x RTT, 1 s) = 1 s of 10 ms ACKs.
728        let retention_acks =
729            (ACK_RETENTION_FLOOR.as_millis() / FULL_ACK_PERIOD.as_millis()) as usize;
730        assert!(
731            r.outstanding_acks.len() <= retention_acks + 1,
732            "{} outstanding ACKs retained",
733            r.outstanding_acks.len()
734        );
735        assert!(!r.outstanding_acks.is_empty(), "recent ACKs are kept");
736    }
737
738    /// An ACKACK arriving inside the retention window still measures RTT; one
739    /// that arrives after its entry aged out is ignored.
740    #[test]
741    fn ackack_after_expiry_is_ignored() {
742        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
743        let out = r.tick(FULL_ACK_PERIOD);
744        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
745            panic!("expected ACK");
746        };
747        let ackack = AckAckPacket {
748            ack_number: ack.ack_number,
749            timestamp: 0,
750            dest_socket_id: PEER,
751            libsrt_pad: false,
752        };
753        let rtt_before = r.rtt();
754        // Age the entry out (no ACKACK for 10 s), then deliver the ACKACK.
755        for tick in 2..=1_000u64 {
756            r.tick(Duration::from_millis(10 * tick));
757        }
758        r.on_ackack(&ackack, Duration::from_secs(10));
759        assert_eq!(r.rtt(), rtt_before, "an expired ACK must not move the RTT");
760    }
761
762    /// The hard cap: more Full ACKs than `MAX_OUTSTANDING_ACKS` inside one
763    /// retention window evict the oldest rather than growing.
764    #[test]
765    fn outstanding_acks_are_capped() {
766        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
767        for _ in 0..(MAX_OUTSTANDING_ACKS * 5) {
768            r.build_full_ack(Duration::ZERO);
769        }
770        assert_eq!(r.outstanding_acks.len(), MAX_OUTSTANDING_ACKS);
771        // The survivors are the newest.
772        let oldest = *r.outstanding_acks.keys().next().unwrap();
773        assert_eq!(oldest as usize, MAX_OUTSTANDING_ACKS * 4 + 1);
774    }
775
776    /// r08-SRT-W4: a bursty (non-contiguous) loss list no longer becomes one
777    /// datagram larger than the MTU — it is split, every datagram fits, and
778    /// together they name every lost packet exactly once.
779    #[test]
780    fn periodic_nak_is_split_to_fit_the_mtu() {
781        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
782        r.feed_data(0, Duration::ZERO);
783        // Receive every other packet: 2, 4, ..., 2000 → 1000 isolated losses.
784        let mut lost = Vec::new();
785        for q in (2..=2000u32).step_by(2) {
786            r.feed_data(q, Duration::ZERO);
787            lost.push(q - 1);
788        }
789        assert_eq!(r.loss_list_len(), 1000);
790
791        let naks: Vec<Vec<u8>> = r
792            .tick(Duration::from_secs(1))
793            .into_iter()
794            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
795            .collect();
796        assert!(naks.len() > 1, "1000 singles cannot fit one datagram");
797        let mut named = Vec::new();
798        for nak in &naks {
799            assert!(
800                nak.len() + IP_UDP_HEADER_LEN <= DEFAULT_MTU as usize,
801                "NAK of {} B exceeds the {} B MTU",
802                nak.len() + IP_UDP_HEADER_LEN,
803                DEFAULT_MTU
804            );
805            for e in nak_entries(nak) {
806                match e {
807                    LossListEntry::Single(s) => named.push(s),
808                    other => panic!("unexpected entry {other:?}"),
809                }
810            }
811        }
812        named.sort_unstable();
813        assert_eq!(named, lost);
814    }
815
816    /// The MTU is configurable: 576 gives smaller datagrams.
817    #[test]
818    fn nak_chunking_follows_the_configured_mtu() {
819        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW).with_mtu(576);
820        r.feed_data(0, Duration::ZERO);
821        for q in (2..=400u32).step_by(2) {
822            r.feed_data(q, Duration::ZERO);
823        }
824        let naks: Vec<Vec<u8>> = r
825            .tick(Duration::from_secs(1))
826            .into_iter()
827            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
828            .collect();
829        assert!(naks.len() >= 2);
830        for nak in &naks {
831            assert!(nak.len() + IP_UDP_HEADER_LEN <= 576);
832        }
833    }
834
835    /// A loss run that straddles the 31-bit wrap is one range in the periodic
836    /// NAK (the loss list is ordered by raw value, which would split it at
837    /// the wrap).
838    #[test]
839    fn periodic_nak_coalesces_a_loss_run_across_the_wrap() {
840        const MAX: u32 = crate::packet::SEQ_NUMBER_MASK;
841        let mut r = Receiver::new(PEER, MAX - 2, MAX_FLOW_WINDOW);
842        r.feed_data(MAX - 2, Duration::ZERO);
843        let imm = r.feed_data(2, Duration::ZERO); // MAX-1, MAX, 0, 1 lost
844        assert_eq!(
845            nak_entries(&imm.nak.expect("gap NAK")),
846            alloc::vec![LossListEntry::Range(MAX - 1, 1)]
847        );
848        let naks: Vec<Vec<u8>> = r
849            .tick(Duration::from_secs(1))
850            .into_iter()
851            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
852            .collect();
853        assert_eq!(naks.len(), 1);
854        assert_eq!(
855            nak_entries(&naks[0]),
856            alloc::vec![LossListEntry::Range(MAX - 1, 1)]
857        );
858    }
859
860    /// After a DROPREQ moves the ack point past packets this receiver never
861    /// saw, the next gap is measured from the ack point, not from a stale
862    /// `highest_received` (which would NAK sequence numbers the sender gave
863    /// up on).
864    #[cfg(feature = "tokio")]
865    #[test]
866    fn gap_after_a_dropreq_starts_at_the_ack_point() {
867        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
868        r.feed_data(0, Duration::ZERO);
869        r.skip_range(1, 99); // sender gave up on 1..=99
870        assert_eq!(r.ack_point(), 100);
871        let out = r.feed_data(105, Duration::ZERO);
872        assert_eq!(
873            nak_entries(&out.nak.expect("gap NAK")),
874            alloc::vec![LossListEntry::Range(100, 104)]
875        );
876        assert_eq!(r.loss_list_len(), 5);
877    }
878}