Skip to main content

srt_runtime/
filecc.rs

1//! SRT File Transfer Congestion Control (FileCC) — window-based congestion
2//! control, `draft-sharabayko-srt-01` §5.2 (curated at
3//! `private/specs-verified/rules/srt-congestion.md`).
4//!
5//! This is the **file/bulk-transfer mode** sibling of [`crate::livecc::LiveCC`]
6//! (§5.1, the **live/streaming mode**'s pacing-only model). Unlike LiveCC,
7//! which only paces `PKT_SND_PERIOD` from a configured `MAX_BW`, FileCC is "a
8//! hybrid Additive Increase Multiplicative Decrease (AIMD) algorithm"
9//! (`private/specs-verified/rules/srt-congestion.md` L3294-3295) that also grows/shrinks a
10//! congestion window (`CWND_SIZE`), in two strictly-sequential phases: Slow
11//! Start (§5.2.1.1), then Congestion Avoidance (§5.2.1.2) — see [`Phase`].
12//! `PKT_SND_PERIOD` and `CWND_SIZE` are computed independently of and do not
13//! touch LiveCC's state — the two controllers are additive alternatives, not
14//! layered.
15//!
16//! ## Usage
17//!
18//! ```rust
19//! use srt_runtime::filecc::{FileCc, Phase};
20//! use broadcast_core::stage::Instant;
21//! use core::time::Duration;
22//!
23//! let mut cc = FileCc::new(0);
24//! assert_eq!(cc.phase(), Phase::SlowStart);
25//!
26//! // On each full ACK, feed the receiver-reported rate/RTT samples:
27//! cc.on_ack(16, 5_000, 1_000, Duration::from_millis(50), Instant::from_millis(10));
28//!
29//! // A NAK (loss report) ends slow start on the first loss (rule 4/9):
30//! cc.on_loss(8, 16, 0.5);
31//! assert_eq!(cc.phase(), Phase::CongestionAvoidance);
32//! ```
33//!
34//! ## Sans-IO contract
35//!
36//! Like every other engine in this crate, [`FileCc`] never reads a wall
37//! clock: [`FileCc::on_ack`] takes an explicit `now: Instant`; [`FileCc::on_loss`]
38//! and [`FileCc::on_timeout`] are driven purely by caller-reported events.
39//!
40//! ## Shared state, not redefined here
41//!
42//! Per `private/specs-verified/rules/srt-congestion.md`'s header note, the following are
43//! cross-referenced, not redefined by this module:
44//! - `RC_INTERVAL` / `SYN` = 10 ms — reused from [`crate::arq::FULL_ACK_PERIOD`]
45//!   (`private/specs-verified/rules/srt-arq.md` rule 11), which is the same 10 ms value
46//!   (L3421-3425).
47//! - The initial `RTT` estimate (100 ms) — reused from
48//!   [`crate::arq::rtt::INITIAL_RTT`] (`private/specs-verified/rules/srt-arq.md` rule 31)
49//!   before the first ACK sample is fed.
50//!
51//! ## Two implementation-defined gaps, flagged (not fabricated)
52//!
53//! `private/specs-verified/rules/srt-congestion.md` explicitly flags two points the draft
54//! text leaves unspecified. Both are resolved here with a documented choice:
55//!
56//! 1. **EWMA weight for `RECEIVING_RATE`/`EST_LINK_CAPACITY` smoothing**
57//!    (gap, L3678-3681 / doc's "Gaps" section). Chosen: **this engine does
58//!    not smooth them itself** — [`FileCc::on_ack`] takes `receiving_rate_pps`
59//!    and `est_link_capacity_pps` as already-current values and stores them
60//!    verbatim, exactly the same treatment this section already gives `RTT`
61//!    (cross-ref rule/L3409-3411: "receiver-reported and sender-smoothed",
62//!    with the smoothing defined *elsewhere*, not here). This keeps the
63//!    engine's formulas directly hand-computable from fed inputs (no hidden
64//!    internal averaging to reverse-engineer), and leaves the actual
65//!    smoothing decision to the caller/sender loop — consistent with how RTT
66//!    is already layered in this crate ([`crate::arq::rtt::RttEstimator`] is
67//!    a separate, explicit component, not folded into the ARQ sender).
68//! 2. **Packet-pairs probing mechanics** (gap, L3686-3689). Out of scope:
69//!    this module consumes `RECEIVING_RATE`/`EST_LINK_CAPACITY` as inputs: it
70//!    does not implement the receiver-side inter-arrival-time measurement or
71//!    packet-pairs probing described in §5.2.1.3 (rules 30-37) that would
72//!    *produce* those inputs on a real receiver. That measurement pipeline is
73//!    receiver-side and is not part of this sender-side congestion-control
74//!    state machine.
75//!
76//! A third, smaller implementation choice not flagged as a spec gap: the
77//! `DecRandom` *distribution* (uniform in `[1, AvgNAKNum]`, clamped to 1) is
78//! given (rule 23), but no source of randomness is specified. This module
79//! uses a small internal, deterministic xorshift PRNG instead of pulling in
80//! a `rand` dependency for a `no_std` crate — true entropy is not required
81//! for correctness here, `DecRandom` only staggers repeat-decrease timing
82//! across congestion periods (rule 24). `DecRandom` is rounded to the
83//! nearest whole number (`FileCc::next_dec_random`, internal): Step 4's gate
84//! (`NAKCount == DecCount * DecRandom`) compares two integer counters, so a
85//! fractional draw makes that equality unsatisfiable after the first check.
86//!
87//! ## A quirk of the draft's own Step 4 pseudocode (verified, not a bug)
88//!
89//! `NAKCount`/`DecCount` reset to 1 at the start of a congestion period and
90//! are ONLY incremented again *inside* Step 4's own conditional (rule 28) —
91//! never unconditionally per NAK. So once the immediate post-reset check
92//! (`1 == 1*DecRandom`) fails — i.e. whenever the drawn `DecRandom != 1` —
93//! neither counter ever moves again for the rest of the period, and Step 4
94//! goes silent until the next congestion period redraws `DecRandom`. This is
95//! a property of the draft text as transcribed (`private/specs-verified/rules/srt-congestion.md`);
96//! whether other implementations formulate it differently is not recorded
97//! here. Adopting a different formulation would be a spec-posture departure this
98//! crate is not designated for; this implementation stays literal to the
99//! curated draft text. See `filecc::tests::repeat_decrease_is_a_one_shot_per_period_once_dec_random_exceeds_one`.
100
101use broadcast_core::stage::Instant;
102use core::time::Duration;
103
104use crate::arq::FULL_ACK_PERIOD;
105use crate::arq::rtt::INITIAL_RTT;
106use crate::arq::seq::{seq_diff, seq_gt};
107use crate::livecc::MaxBwConfig;
108
109/// `RC_INTERVAL` = `SYN` = 10 ms (`private/specs-verified/rules/srt-congestion.md` L3421-3425),
110/// reused from [`crate::arq::FULL_ACK_PERIOD`] (same value, `srt-arq.md` rule
111/// 11) rather than redefined here.
112const RC_INTERVAL: Duration = FULL_ACK_PERIOD;
113
114/// `S` — "the SRT packet size (in terms of IP payload) in bytes. SRT treats
115/// 1500 bytes as a standard packet size." (`private/specs-verified/rules/srt-congestion.md`
116/// L3539-3540, verbatim). A different quantity from LiveCC's EWMA-derived
117/// `PktSize` — see the module doc's header note.
118const S_BYTES: f64 = 1500.0;
119
120/// Slow start's fixed `PKT_SND_PERIOD` — "1 microsecond ... in order to send
121/// packets as fast as possible, but not at an infinite rate"
122/// (`private/specs-verified/rules/srt-congestion.md` L3338-3340, verbatim; rule 6).
123const SLOW_START_PKT_SND_PERIOD_US: f64 = 1.0;
124
125/// Slow start's initial `CWND_SIZE` — 16 packets (`private/specs-verified/rules/srt-congestion.md`
126/// L3340-3341, rule 7).
127const INITIAL_CWND_SIZE: f64 = 16.0;
128
129/// `LastDecPeriod`'s initial value — 1 microsecond (`private/specs-verified/rules/srt-congestion.md`
130/// L3521-3524).
131const INITIAL_LAST_DEC_PERIOD_US: f64 = 1.0;
132
133/// Default `MAX_CWND_SIZE` — the spec suggests "the maximum receiver buffer
134/// size (12 MB)" as the threshold (`private/specs-verified/rules/srt-congestion.md` L3344-3345,
135/// rule 8), worded as settable/recommended, not a hardwired constant.
136/// Expressed here in packets at the standard packet size `S` (1500 bytes):
137/// `12_000_000 / 1500 = 8000` packets. Override with [`FileCc::set_max_cwnd_size`].
138const DEFAULT_MAX_CWND_SIZE: f64 = 8_000.0;
139
140/// The NAK-tolerance loss-ratio threshold — "less than 2%"
141/// (`private/specs-verified/rules/srt-congestion.md` L3572-3579, rule 16).
142const LOSS_RATIO_TOLERANCE: f64 = 0.02;
143
144/// The repeat-decrease rate-backoff multiplier — `1.03`
145/// (`private/specs-verified/rules/srt-congestion.md` L3602-3604 / L3652-3654, rules 19 & 27).
146const RATE_BACKOFF_FACTOR: f64 = 1.03;
147
148/// The `AvgNAKNum` EWMA weights — `0.97`/`0.03`
149/// (`private/specs-verified/rules/srt-congestion.md` L3606-3608, rule 20, verbatim).
150const AVG_NAK_NUM_OLD_WEIGHT: f64 = 0.97;
151const AVG_NAK_NUM_NEW_WEIGHT: f64 = 0.03;
152
153/// The repeat-decrease `DecCount` ceiling — decreases stop once `DecCount`
154/// exceeds 5 within a congestion period (`private/specs-verified/rules/srt-congestion.md`
155/// L3652-3658, rule "Step 4").
156const MAX_DEC_COUNT: u32 = 5;
157
158/// `inc`'s multiplier in the Step 5 rate-increase formula (`private/specs-verified/rules/srt-congestion.md`
159/// L3498-3517, verbatim: `0.0000015`).
160const INC_SCALE: f64 = 0.0000015;
161
162/// Microseconds per second — the units conversion every `PKT_SND_PERIOD`/rate
163/// formula in this module divides or multiplies by (`private/specs-verified/rules/srt-congestion.md`,
164/// recurring throughout §5.2.1.2's Steps 3/5/6, sourced from the same
165/// L3498-3517 code block as [`INC_SCALE`]).
166const US_PER_SEC: f64 = 1_000_000.0;
167
168/// `lossBandwidth`'s doubling factor in the Step 5 rate-increase formula
169/// (`private/specs-verified/rules/srt-congestion.md` L3498-3517 code block, verbatim:
170/// `lossBandwidth = 2 * (1000000 / LastDecPeriod)`).
171const LOSS_BANDWIDTH_FACTOR: f64 = 2.0;
172
173/// The `linkCapacity / 9` clamp divisor in the Step 5 rate-increase formula
174/// (`private/specs-verified/rules/srt-congestion.md` L3498-3517 code block, verbatim:
175/// `if (... && (linkCapacity / 9) < B) B = linkCapacity / 9;`) — a
176/// spec-mandated tuning constant, not independently derived.
177const LINK_CAPACITY_CLAMP_DIVISOR: f64 = 9.0;
178
179/// Bits per byte, used to convert `S` (packet size in bytes) to bits in the
180/// Step 5 rate-increase formula (`private/specs-verified/rules/srt-congestion.md` L3498-3517
181/// code block, verbatim: `inc = pow(10.0, ceil(log10(B * S * 8))) * 0.0000015 / S`).
182const BITS_PER_BYTE: f64 = 8.0;
183
184/// FileCC algorithm phase (`private/specs-verified/rules/srt-congestion.md` rules 4-5). Slow
185/// Start (§5.2.1.1) runs exactly once at the start of a connection; it
186/// transitions to Congestion Avoidance (§5.2.1.2) on the first loss,
187/// `CWND_SIZE` exceeding its maximum, or a timeout — and never transitions
188/// back (L3323-3326).
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190#[non_exhaustive]
191pub enum Phase {
192    /// §5.2.1.1 — probes for available bandwidth; runs exactly once.
193    SlowStart,
194    /// §5.2.1.2 — entered once slow start ends; the steady-state AIMD phase.
195    CongestionAvoidance,
196}
197
198impl Phase {
199    /// The §5.2 phase name.
200    pub fn name(&self) -> &'static str {
201        match self {
202            Phase::SlowStart => "SlowStart",
203            Phase::CongestionAvoidance => "CongestionAvoidance",
204        }
205    }
206}
207
208broadcast_core::impl_spec_display!(Phase);
209
210/// A minimal, seedable xorshift64* PRNG — see the module doc's third
211/// implementation-choice note (`DecRandom`'s source of randomness is
212/// unspecified by the draft; only its distribution is given, rule 23).
213#[derive(Debug, Clone, Copy)]
214struct XorShift64(u64);
215
216impl XorShift64 {
217    /// A fixed, non-zero default seed. Deterministic on purpose: reproducible
218    /// test/debug behavior, and true entropy is not required for correctness
219    /// (see the module doc).
220    const DEFAULT_SEED: u64 = 0x9E37_79B9_7F4A_7C15;
221
222    /// Marsaglia xorshift64 shifts and multiplier.
223    const XORSHIFT_SHIFT_A: u32 = 13;
224    const XORSHIFT_SHIFT_B: u32 = 7;
225    const XORSHIFT_SHIFT_C: u32 = 17;
226    const XORSHIFT_MULTIPLIER: u64 = 0x2545_F491_4F6C_DD1D;
227
228    /// Mantissa bits a `f64` can hold exactly, taken from the top of the
229    /// 64-bit draw.
230    const MANTISSA_BITS: u32 = 53;
231
232    fn new(seed: u64) -> Self {
233        XorShift64(if seed == 0 { Self::DEFAULT_SEED } else { seed })
234    }
235
236    /// Next pseudo-random value, uniform in `[0.0, 1.0)`.
237    fn next_unit(&mut self) -> f64 {
238        let mut x = self.0;
239        x ^= x << Self::XORSHIFT_SHIFT_A;
240        x ^= x >> Self::XORSHIFT_SHIFT_B;
241        x ^= x << Self::XORSHIFT_SHIFT_C;
242        self.0 = x;
243        let r = x.wrapping_mul(Self::XORSHIFT_MULTIPLIER);
244        // Top 53 bits as a double in [0, 1).
245        (r >> (u64::BITS - Self::MANTISSA_BITS)) as f64
246            * (1.0 / (1u64 << Self::MANTISSA_BITS) as f64)
247    }
248}
249
250/// Half-distance at which [`fround`] rounds away from zero.
251const ROUNDING_THRESHOLD: f64 = 0.5;
252
253/// Radix of the decimal powers [`next_power_of_10`] walks.
254const DECIMAL_BASE: f64 = 10.0;
255
256/// `min(a, b)` for `f64`, without relying on `f64::min` (kept as a plain
257/// comparison so this module has no dependency on any transcendental-math
258/// support — see [`next_power_of_10`]'s doc for why that matters for the
259/// `no_std` build).
260fn fmin(a: f64, b: f64) -> f64 {
261    if a < b { a } else { b }
262}
263
264/// `max(a, b)` for `f64` — see [`fmin`].
265fn fmax(a: f64, b: f64) -> f64 {
266    if a > b { a } else { b }
267}
268
269/// Round-half-away-from-zero for `f64`, matching `f64::round`'s semantics —
270/// without calling it, since `f64::round` is a `std`-only method (`core`
271/// float types don't expose it; see [`fmin`]'s doc for why this module avoids
272/// any transcendental/libm dependency). `as i64` float-to-int casts are
273/// saturating in Rust, so this is safe for any finite input in `i64` range —
274/// `DecRandom` values are always small and positive.
275fn fround(x: f64) -> f64 {
276    let truncated = x as i64 as f64;
277    let diff = x - truncated;
278    if diff >= ROUNDING_THRESHOLD {
279        truncated + 1.0
280    } else if diff <= -ROUNDING_THRESHOLD {
281        truncated - 1.0
282    } else {
283        truncated
284    }
285}
286
287/// `pow(10.0, ceil(log10(x)))` for `x > 0` — the smallest power of 10 that is
288/// `>= x` (`private/specs-verified/rules/srt-congestion.md` Step 5, L3506, verbatim source:
289/// `pow(10.0, ceil(log10(B * S * 8))) * 0.0000015 / S`).
290///
291/// Implemented via repeated multiplication/division instead of calling
292/// `log10`/`powf` directly: those are `libm` functions not available in
293/// `core` (this crate builds `no_std`, including on `thumbv7em-none-eabi`
294/// with no libm), whereas this loop only uses basic arithmetic and
295/// comparisons. Algebraically identical to the spec's formula for `x > 0`.
296fn next_power_of_10(x: f64) -> f64 {
297    debug_assert!(x > 0.0, "next_power_of_10 is only defined for x > 0");
298    let mut p = 1.0_f64;
299    while p < x {
300        p *= DECIMAL_BASE;
301    }
302    while p / DECIMAL_BASE >= x {
303        p /= DECIMAL_BASE;
304    }
305    p
306}
307
308/// SRT File Transfer Congestion Control — sender-side window + pacing state
309/// (`draft-sharabayko-srt-01` §5.2). See the module doc for the full formula
310/// mapping, the sans-IO contract, and the two flagged spec gaps.
311#[derive(Debug, Clone)]
312pub struct FileCc {
313    phase: Phase,
314    /// `CWND_SIZE`, in packets (rule 7; Step 3 of both phases).
315    cwnd_size: f64,
316    /// `MAX_CWND_SIZE` (rule 8) — slow start ends once `cwnd_size` exceeds
317    /// this.
318    max_cwnd_size: f64,
319    /// `PKT_SND_PERIOD`, in microseconds.
320    pkt_snd_period_us: f64,
321    /// `LastRCTime` — `None` until the first ACK (rate-control gate always
322    /// passes on the very first call; the draft does not give an initial
323    /// value, this is the implementation-defined resolution).
324    last_rc_time: Option<Instant>,
325    /// `LAST_ACK_SEQNO` — initialized to the caller-supplied `initial_seqno`
326    /// (representing "no data packet acknowledged yet"; the draft does not
327    /// give LAST_ACK_SEQNO's initial value either).
328    last_ack_seqno: u32,
329    /// `bLoss` — initial value `False` (rule 12).
330    b_loss: bool,
331    /// `LastDecPeriod`, in microseconds — initial value 1 microsecond
332    /// (item under Step 5).
333    last_dec_period_us: f64,
334    /// `LastDecSeq` — `None` until the first Congestion-Avoidance-phase NAK
335    /// (so the very first CA-phase loss always starts a new congestion
336    /// period, rule 25).
337    last_dec_seq: Option<u32>,
338    /// `AvgNAKNum` — initial value 0 (rule "State variables", verbatim def).
339    avg_nak_num: f64,
340    /// `NAKCount` — initial value 0.
341    nak_count: u32,
342    /// `DecCount` — initial value 0.
343    dec_count: u32,
344    /// `DecRandom` — computed per congestion period (rule 23).
345    dec_random: f64,
346    /// `RECEIVING_RATE`, packets/sec — see the module doc's gap-1 resolution
347    /// (stored verbatim from [`FileCc::on_ack`], not smoothed here).
348    receiving_rate_pps: u64,
349    /// `EST_LINK_CAPACITY`, packets/sec — see the module doc's gap-1
350    /// resolution.
351    est_link_capacity_pps: u64,
352    /// `RTT`, sender-smoothed elsewhere (`crate::arq::rtt::RttEstimator`) and
353    /// fed in via [`FileCc::on_ack`]. Initialized to
354    /// [`crate::arq::rtt::INITIAL_RTT`] before the first ACK.
355    rtt: Duration,
356    /// `MAX_BW` — Step 6 clamp (rule 15: file transfer only uses
357    /// `MAXBW_SET`; [`MaxBwConfig::Infinite`] is the state before it is set).
358    max_bw: MaxBwConfig,
359    rng: XorShift64,
360}
361
362impl FileCc {
363    /// A fresh FileCC engine in Slow Start (rule 4: "runs exactly once at
364    /// the beginning of a connection").
365    ///
366    /// `initial_seqno` seeds `LAST_ACK_SEQNO` (see the field doc) — pass the
367    /// connection's initial sequence number (ISN) minus one, or the ISN
368    /// itself if no data has been sent yet; either way the first ACK's
369    /// `CWND_SIZE` growth (Step 3) reflects exactly the packets actually
370    /// acknowledged since then.
371    pub fn new(initial_seqno: u32) -> Self {
372        FileCc {
373            phase: Phase::SlowStart,
374            cwnd_size: INITIAL_CWND_SIZE,
375            max_cwnd_size: DEFAULT_MAX_CWND_SIZE,
376            pkt_snd_period_us: SLOW_START_PKT_SND_PERIOD_US,
377            last_rc_time: None,
378            last_ack_seqno: initial_seqno,
379            b_loss: false,
380            last_dec_period_us: INITIAL_LAST_DEC_PERIOD_US,
381            last_dec_seq: None,
382            avg_nak_num: 0.0,
383            nak_count: 0,
384            dec_count: 0,
385            dec_random: 1.0,
386            receiving_rate_pps: 0,
387            est_link_capacity_pps: 0,
388            rtt: INITIAL_RTT,
389            max_bw: MaxBwConfig::Infinite,
390            rng: XorShift64::new(XorShift64::DEFAULT_SEED),
391        }
392    }
393
394    /// The current algorithm phase.
395    pub fn phase(&self) -> Phase {
396        self.phase
397    }
398
399    /// The current `CWND_SIZE`, in packets.
400    pub fn cwnd_size(&self) -> f64 {
401        self.cwnd_size
402    }
403
404    /// The current `PKT_SND_PERIOD`, in microseconds (as an `f64` — the
405    /// Congestion Avoidance formulas are inherently fractional).
406    pub fn pkt_snd_period_us(&self) -> f64 {
407        self.pkt_snd_period_us
408    }
409
410    /// The current `MAX_CWND_SIZE` (rule 8), in packets.
411    pub fn max_cwnd_size(&self) -> f64 {
412        self.max_cwnd_size
413    }
414
415    /// Reconfigure `MAX_CWND_SIZE` — rule 8 calls the 12 MB-derived default
416    /// a settable/recommended value, not a hardwired constant.
417    pub fn set_max_cwnd_size(&mut self, packets: f64) {
418        self.max_cwnd_size = packets;
419    }
420
421    /// The current `MAX_BW` clamp, in bytes/sec (`None` = unbounded).
422    pub fn max_bw_bytes_per_sec(&self) -> Option<u64> {
423        self.max_bw.max_bw_bytes_per_sec()
424    }
425
426    /// Reconfigure `MAX_BW` (rule 15: `MAXBW_SET` mode only applies to file
427    /// transfer; there is no default, `None` is unbounded). `Some(0)` would
428    /// make the minimum send period infinite, so it is treated as unbounded.
429    #[cfg(test)]
430    pub(crate) fn set_max_bw_bytes_per_sec(&mut self, max_bw: Option<u64>) {
431        self.max_bw = match max_bw.filter(|&bw| bw > 0) {
432            Some(bw) => MaxBwConfig::Set(bw),
433            None => MaxBwConfig::Infinite,
434        };
435    }
436
437    /// The last `RECEIVING_RATE` fed via [`FileCc::on_ack`], packets/sec.
438    pub fn receiving_rate_pps(&self) -> u64 {
439        self.receiving_rate_pps
440    }
441
442    /// The last `EST_LINK_CAPACITY` fed via [`FileCc::on_ack`], packets/sec.
443    pub fn est_link_capacity_pps(&self) -> u64 {
444        self.est_link_capacity_pps
445    }
446
447    /// The last `RTT` fed via [`FileCc::on_ack`] (or the initial 100 ms
448    /// default before the first ACK).
449    pub fn rtt(&self) -> Duration {
450        self.rtt
451    }
452
453    /// `bLoss` — `true` if a loss has been reported since the last rate
454    /// increase (rule 11-12).
455    pub fn b_loss(&self) -> bool {
456        self.b_loss
457    }
458
459    /// `AvgNAKNum` — the average number of NAKs per congestion period
460    /// (rule 20's EWMA).
461    pub fn avg_nak_num(&self) -> f64 {
462        self.avg_nak_num
463    }
464
465    /// `NAKCount` — NAKs received so far in the current congestion period.
466    pub fn nak_count(&self) -> u32 {
467        self.nak_count
468    }
469
470    /// `DecCount` — rate decreases applied so far in the current congestion
471    /// period.
472    pub fn dec_count(&self) -> u32 {
473        self.dec_count
474    }
475
476    /// `LastDecSeq` — the largest sent sequence number at the last rate
477    /// decrease / congestion-period boundary, or `None` if no
478    /// Congestion-Avoidance-phase loss has occurred yet.
479    pub fn last_dec_seq(&self) -> Option<u32> {
480        self.last_dec_seq
481    }
482
483    /// `LastDecPeriod`, in microseconds (item under Step 5; initial value 1
484    /// microsecond).
485    pub fn last_dec_period_us(&self) -> f64 {
486        self.last_dec_period_us
487    }
488
489    /// On full-ACK packet reception (`private/specs-verified/rules/srt-congestion.md`,
490    /// §5.2.1.1 "(1) On ACK packet reception" / §5.2.1.2 "(1) On ACK packet
491    /// reception"). Only full ACKs trigger a rate increase (rule 3,
492    /// L3313-3314) — a light ACK must not be passed to this method.
493    ///
494    /// `now` — the current time (Step 1's `currTime`).
495    /// `ack_seqno` — the ACK's acknowledged sequence number (`ACK_SEQNO`).
496    /// `receiving_rate_pps` / `est_link_capacity_pps` — the ACK-carried,
497    /// receiver-reported rate estimates (§5.2.1.3); see the module doc's
498    /// gap-1 resolution for why these are stored verbatim, not smoothed
499    /// here.
500    /// `rtt` — the current (already-smoothed elsewhere) RTT estimate.
501    pub fn on_ack(
502        &mut self,
503        ack_seqno: u32,
504        receiving_rate_pps: u64,
505        est_link_capacity_pps: u64,
506        rtt: Duration,
507        now: Instant,
508    ) {
509        self.receiving_rate_pps = receiving_rate_pps;
510        self.est_link_capacity_pps = est_link_capacity_pps;
511        self.rtt = rtt;
512
513        // Step 1 (identical gate in both phases, L3365-3371 / L3455-3461):
514        // if (currTime - LastRCTime < RC_INTERVAL) { keep; stop; }
515        if let Some(last) = self.last_rc_time
516            && now.saturating_duration_since(last) < RC_INTERVAL
517        {
518            return;
519        }
520        // Step 2: LastRCTime = currTime.
521        self.last_rc_time = Some(now);
522
523        match self.phase {
524            Phase::SlowStart => self.on_ack_slow_start(ack_seqno),
525            Phase::CongestionAvoidance => self.on_ack_congestion_avoidance(),
526        }
527    }
528
529    /// Slow start's ACK handling, Steps 3-5 (L3381-3401).
530    fn on_ack_slow_start(&mut self, ack_seqno: u32) {
531        // Step 3: CWND_SIZE += ACK_SEQNO - LAST_ACK_SEQNO (wrap-safe delta —
532        // reusing arq::seq, not redefined here, per the crate's existing
533        // sequence-arithmetic convention).
534        let delta = seq_diff(ack_seqno, self.last_ack_seqno);
535        self.cwnd_size += f64::from(delta);
536        // Step 4: LAST_ACK_SEQNO = ACK_SEQNO.
537        self.last_ack_seqno = ack_seqno;
538
539        // Step 5: CWND_SIZE exceeding MAX_CWND_SIZE ends slow start.
540        if self.cwnd_size > self.max_cwnd_size {
541            self.end_slow_start();
542        }
543    }
544
545    /// Congestion Avoidance's ACK handling, Steps 3-6 (L3479-3559).
546    fn on_ack_congestion_avoidance(&mut self) {
547        // Step 3: CWND_SIZE = RECEIVING_RATE*(RTT+RC_INTERVAL)/1000000 + 16
548        // (recomputed directly, not incrementally, unlike slow start).
549        self.cwnd_size = self.receiving_rate_pps as f64 * self.rtt_plus_rc_interval_us()
550            / US_PER_SEC
551            + INITIAL_CWND_SIZE;
552
553        // Step 4: loss-in-flight guard.
554        if self.b_loss {
555            self.b_loss = false;
556            return;
557        }
558
559        // Step 5: rate-increase formula (L3498-3517, verbatim).
560        let loss_bandwidth = LOSS_BANDWIDTH_FACTOR * (US_PER_SEC / self.last_dec_period_us);
561        let link_capacity = fmin(loss_bandwidth, self.est_link_capacity_pps as f64);
562        let mut b = link_capacity - US_PER_SEC / self.pkt_snd_period_us;
563        if self.pkt_snd_period_us > self.last_dec_period_us
564            && (link_capacity / LINK_CAPACITY_CLAMP_DIVISOR) < b
565        {
566            b = link_capacity / LINK_CAPACITY_CLAMP_DIVISOR;
567        }
568        let inc = if b <= 0.0 {
569            1.0 / S_BYTES
570        } else {
571            let raw = next_power_of_10(b * S_BYTES * BITS_PER_BYTE) * INC_SCALE / S_BYTES;
572            fmax(raw, 1.0 / S_BYTES)
573        };
574        let rc_interval_us = RC_INTERVAL.as_micros() as f64;
575        self.pkt_snd_period_us = (self.pkt_snd_period_us * rc_interval_us)
576            / (self.pkt_snd_period_us * inc + rc_interval_us);
577
578        // Step 6: MAX_BW clamp, if configured (rule 15).
579        if let Some(max_bw) = self.max_bw.max_bw_bytes_per_sec() {
580            let min_period_us = US_PER_SEC / (max_bw as f64 / S_BYTES);
581            if self.pkt_snd_period_us < min_period_us {
582                self.pkt_snd_period_us = min_period_us;
583            }
584        }
585    }
586
587    /// `RTT + RC_INTERVAL`, in microseconds — shared by the CWND_SIZE
588    /// formula (Step 3, both event handlers that use it).
589    fn rtt_plus_rc_interval_us(&self) -> f64 {
590        self.rtt.as_micros() as f64 + RC_INTERVAL.as_micros() as f64
591    }
592
593    /// Ends slow start, computing `PKT_SND_PERIOD` per the shared Step 5
594    /// formula (L3392-3401, reused verbatim by rules 9 and 10 — NAK and RTO
595    /// during slow start).
596    fn end_slow_start(&mut self) {
597        self.phase = Phase::CongestionAvoidance;
598        self.pkt_snd_period_us = if self.receiving_rate_pps > 0 {
599            US_PER_SEC / self.receiving_rate_pps as f64
600        } else {
601            self.cwnd_size / self.rtt_plus_rc_interval_us()
602        };
603    }
604
605    /// On a loss report (NAK) packet reception.
606    ///
607    /// - During Slow Start (rule 9): ends slow start; `PKT_SND_PERIOD` is
608    ///   set exactly as in the ACK Step 5 formula. `lost_seqno`,
609    ///   `largest_sent_seqno`, and `loss_ratio` are not consulted by this
610    ///   phase's handling (the draft's rule 9 gives no further formula).
611    /// - During Congestion Avoidance (§5.2.1.2 "(2)", L3568-3658): runs the
612    ///   full bLoss/loss-ratio-tolerance/congestion-period/repeat-decrease
613    ///   state machine.
614    ///
615    /// `lost_seqno` — the sequence number reported lost by this NAK.
616    /// `largest_sent_seqno` — the largest sequence number sent so far
617    /// (recorded as the new `LastDecSeq` on a decrease, rules 22/29).
618    /// `loss_ratio` — the sender's current estimated loss ratio (rule 16's
619    /// "less than 2%" tolerance check), e.g. lost/sent over a recent window.
620    pub fn on_loss(&mut self, lost_seqno: u32, largest_sent_seqno: u32, loss_ratio: f64) {
621        match self.phase {
622            Phase::SlowStart => self.end_slow_start(),
623            Phase::CongestionAvoidance => {
624                self.on_loss_congestion_avoidance(lost_seqno, largest_sent_seqno, loss_ratio)
625            }
626        }
627    }
628
629    /// Congestion Avoidance's NAK handling (L3568-3658).
630    fn on_loss_congestion_avoidance(
631        &mut self,
632        lost_seqno: u32,
633        largest_sent_seqno: u32,
634        loss_ratio: f64,
635    ) {
636        // Step 1: bLoss = True.
637        self.b_loss = true;
638
639        // Step 2: loss-ratio tolerance (rule 16-17).
640        if loss_ratio < LOSS_RATIO_TOLERANCE {
641            self.last_dec_period_us = self.pkt_snd_period_us;
642            return;
643        }
644
645        // Step 3: new congestion period? (rule 25: the lost seq is greater
646        // than LastDecSeq).
647        let is_new_period = match self.last_dec_seq {
648            None => true,
649            Some(last) => seq_gt(lost_seqno, last),
650        };
651
652        if is_new_period {
653            self.last_dec_period_us = self.pkt_snd_period_us;
654            self.pkt_snd_period_us *= RATE_BACKOFF_FACTOR;
655            // rule 20: AvgNAKNum = 0.97*AvgNAKNum + 0.03*NAKCount (using the
656            // just-finished period's NAKCount, before it is reset below).
657            self.avg_nak_num = AVG_NAK_NUM_OLD_WEIGHT * self.avg_nak_num
658                + AVG_NAK_NUM_NEW_WEIGHT * self.nak_count as f64;
659            self.nak_count = 1;
660            self.dec_count = 1;
661            self.last_dec_seq = Some(largest_sent_seqno);
662            self.dec_random = self.next_dec_random();
663            return;
664        }
665
666        // Step 4: repeat decrease within the same congestion period
667        // (rule "Step 4": DecCount<=5 && NAKCount==DecCount*DecRandom).
668        if self.dec_count <= MAX_DEC_COUNT
669            && self.nak_count as f64 == self.dec_count as f64 * self.dec_random
670        {
671            self.pkt_snd_period_us *= RATE_BACKOFF_FACTOR;
672            self.dec_count += 1;
673            self.nak_count += 1;
674            self.last_dec_seq = Some(largest_sent_seqno);
675        }
676    }
677
678    /// `DecRandom` — "a random number between 1 and the average number of
679    /// NAKs per congestion period (AvgNAKNum)", clamped to 1 if the draw is
680    /// below 1 (rule 23). See the module doc for the PRNG source note.
681    ///
682    /// Rounded to the nearest whole number: Step 4's repeat-decrease gate
683    /// (`NAKCount == DecCount * DecRandom`) compares against the integer
684    /// counters `NAKCount`/`DecCount`, so it only means "every `DecRandom`-th
685    /// NAK" — and is satisfiable — when `DecRandom` is itself integer-valued.
686    /// A raw fractional draw (`AvgNAKNum > 1`) makes that equality a
687    /// measure-zero float comparison that (almost) never holds again after
688    /// the congestion period's first decrease, silently disabling repeat
689    /// decrease for the rest of the period.
690    fn next_dec_random(&mut self) -> f64 {
691        let hi = fmax(self.avg_nak_num, 1.0);
692        let r = self.rng.next_unit();
693        let val = fround(1.0 + r * (hi - 1.0));
694        fmax(val, 1.0)
695    }
696
697    /// On a retransmission timeout (RTO) event.
698    ///
699    /// During Slow Start (rule 10): ends slow start, `PKT_SND_PERIOD` set
700    /// exactly as in the ACK Step 5 formula (same as [`FileCc::on_loss`]'s
701    /// slow-start handling). Once in Congestion Avoidance, this section does
702    /// not describe an RTO-specific FileCC reaction (RTO-driven
703    /// retransmission itself is the ARQ engine's concern, `srt-arq.md`) —
704    /// calling this while already in Congestion Avoidance is a no-op.
705    pub fn on_timeout(&mut self) {
706        if self.phase == Phase::SlowStart {
707            self.end_slow_start();
708        }
709    }
710}
711
712impl Default for FileCc {
713    /// A fresh engine with `initial_seqno = 0` (see [`FileCc::new`]).
714    fn default() -> Self {
715        FileCc::new(0)
716    }
717}
718
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    #[test]
724    fn starts_in_slow_start_with_spec_initial_values() {
725        let cc = FileCc::new(0);
726        assert_eq!(cc.phase(), Phase::SlowStart);
727        assert_eq!(cc.cwnd_size(), 16.0);
728        assert_eq!(cc.pkt_snd_period_us(), 1.0);
729        assert_eq!(cc.max_cwnd_size(), 8_000.0);
730        assert!(!cc.b_loss());
731        assert_eq!(cc.avg_nak_num(), 0.0);
732        assert_eq!(cc.nak_count(), 0);
733        assert_eq!(cc.dec_count(), 0);
734        assert_eq!(cc.last_dec_seq(), None);
735        assert_eq!(cc.last_dec_period_us(), 1.0);
736        assert_eq!(cc.rtt(), Duration::from_millis(100));
737        assert_eq!(cc.max_bw_bytes_per_sec(), None);
738    }
739
740    #[test]
741    fn slow_start_cwnd_grows_by_ack_seqno_delta() {
742        let mut cc = FileCc::new(0);
743        cc.on_ack(
744            5,
745            0,
746            0,
747            Duration::from_millis(100),
748            Instant::from_millis(10),
749        );
750        assert_eq!(cc.cwnd_size(), 21.0); // 16 + (5 - 0)
751        assert_eq!(
752            cc.pkt_snd_period_us(),
753            1.0,
754            "fixed at 1us during slow start"
755        );
756    }
757
758    #[test]
759    fn rate_control_gate_blocks_updates_within_rc_interval() {
760        let mut cc = FileCc::new(0);
761        cc.on_ack(
762            5,
763            0,
764            0,
765            Duration::from_millis(100),
766            Instant::from_millis(10),
767        );
768        assert_eq!(cc.cwnd_size(), 21.0);
769        // Only 1ms later (< RC_INTERVAL = 10ms): must be a no-op.
770        cc.on_ack(
771            999,
772            0,
773            0,
774            Duration::from_millis(100),
775            Instant::from_millis(11),
776        );
777        assert_eq!(
778            cc.cwnd_size(),
779            21.0,
780            "gate must block an ACK inside RC_INTERVAL"
781        );
782    }
783
784    #[test]
785    fn loss_during_slow_start_transitions_to_congestion_avoidance() {
786        let mut cc = FileCc::new(0);
787        assert_eq!(cc.phase(), Phase::SlowStart);
788        cc.on_loss(10, 10, 0.9);
789        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
790    }
791
792    #[test]
793    fn timeout_during_slow_start_transitions_to_congestion_avoidance() {
794        let mut cc = FileCc::new(0);
795        cc.on_timeout();
796        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
797    }
798
799    #[test]
800    fn timeout_during_congestion_avoidance_is_a_no_op() {
801        let mut cc = FileCc::new(0);
802        cc.on_loss(10, 10, 0.9);
803        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
804        let period = cc.pkt_snd_period_us();
805        cc.on_timeout();
806        assert_eq!(cc.pkt_snd_period_us(), period);
807    }
808
809    #[test]
810    fn cwnd_exceeding_max_ends_slow_start() {
811        let mut cc = FileCc::new(0);
812        cc.set_max_cwnd_size(20.0);
813        cc.on_ack(
814            10,
815            0,
816            0,
817            Duration::from_millis(100),
818            Instant::from_millis(10),
819        );
820        // CWND = 16 + 10 = 26 > 20 -> slow start ends.
821        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
822    }
823
824    #[test]
825    fn max_bw_clamp_floors_pkt_snd_period() {
826        let mut cc = FileCc::new(0);
827        cc.on_loss(1, 1, 0.9); // -> Congestion Avoidance
828        cc.set_max_bw_bytes_per_sec(Some(1)); // absurdly low MAX_BW
829        cc.on_ack(
830            1,
831            1_000,
832            1_000,
833            Duration::from_millis(50),
834            Instant::from_millis(10),
835        );
836        // MIN_PERIOD = 1_000_000 / (1 / 1500) = 1_500_000_000 us.
837        assert!(cc.pkt_snd_period_us() >= 1_500_000_000.0);
838    }
839
840    #[test]
841    fn zero_max_bw_is_unbounded_not_an_infinite_send_period() {
842        let mut cc = FileCc::new(0);
843        cc.on_loss(1, 1, 0.9);
844        cc.set_max_bw_bytes_per_sec(Some(0));
845        assert_eq!(cc.max_bw_bytes_per_sec(), None);
846        cc.on_ack(
847            1,
848            1_000,
849            1_000,
850            Duration::from_millis(50),
851            Instant::from_millis(10),
852        );
853        assert!(cc.pkt_snd_period_us().is_finite());
854    }
855
856    #[test]
857    fn next_power_of_10_matches_known_values() {
858        assert_eq!(next_power_of_10(1.0), 1.0);
859        assert_eq!(next_power_of_10(9.9), 10.0);
860        assert_eq!(next_power_of_10(10.0), 10.0);
861        assert_eq!(next_power_of_10(10.1), 100.0);
862        assert_eq!(next_power_of_10(100.0), 100.0);
863        assert_eq!(next_power_of_10(0.05), 0.1);
864    }
865
866    #[test]
867    fn xorshift_produces_values_in_unit_range() {
868        let mut rng = XorShift64::new(1);
869        for _ in 0..100 {
870            let v = rng.next_unit();
871            assert!((0.0..1.0).contains(&v), "value out of range: {v}");
872        }
873    }
874
875    #[test]
876    fn dec_random_is_one_when_avg_nak_num_is_zero() {
877        let mut cc = FileCc::new(0);
878        assert_eq!(cc.avg_nak_num(), 0.0);
879        assert_eq!(cc.next_dec_random(), 1.0);
880    }
881
882    /// `DecRandom` must be integer-valued once `AvgNAKNum > 1` (a fractional
883    /// draw makes Step 4's `NAKCount == DecCount * DecRandom` gate a
884    /// measure-zero float comparison that — after the congestion period's
885    /// first decrease — essentially never holds again, silently disabling
886    /// repeat decrease for the rest of the period). This is the bug a
887    /// pre-tag audit found: the un-rounded draw only ever produced an
888    /// integer in the degenerate `AvgNAKNum <= 1` case, which is the only
889    /// case the pre-existing test suite exercised.
890    #[test]
891    fn dec_random_is_integer_valued_once_avg_nak_num_exceeds_one() {
892        let mut cc = FileCc::new(0);
893        cc.avg_nak_num = 6.0;
894        for _ in 0..200 {
895            let v = cc.next_dec_random();
896            assert_eq!(
897                v,
898                v.round(),
899                "DecRandom must be a whole number (got {v}) so Step 4's \
900                 NAKCount == DecCount * DecRandom gate is actually satisfiable"
901            );
902            assert!((1.0..=6.0).contains(&v), "DecRandom out of range: {v}");
903        }
904    }
905
906    /// Documents a genuine quirk of the draft's own literal Step 4
907    /// pseudocode (verified against `private/specs-verified/rules/srt-congestion.md`, not
908    /// assumed): `NAKCount`/`DecCount` are reset to 1 on a new congestion
909    /// period and are ONLY ever touched again *inside* Step 4's own
910    /// `NAKCount == DecCount * DecRandom` conditional (rule 28: "Increase
911    /// DecCount and NAKCount each by 1" — inside the `if`, not unconditional
912    /// per-NAK). So the very next same-period NAK checks `1 == 1*DecRandom`;
913    /// if `DecRandom != 1` that fails, and since neither counter has moved,
914    /// the SAME false check repeats for every subsequent NAK in the period —
915    /// Step 4 cannot fire again until the next congestion period redraws
916    /// `DecRandom`. This is a property of the literal spec text as
917    /// transcribed, not a Rust-side bug: whether other implementations differ is not
918    /// recorded here, and adopting a different formulation would be a spec-posture
919    /// departure this
920    /// crate isn't designated for (see `CLAUDE.md`), so this implementation
921    /// stays literal to the curated draft text. Confirmed here with a fixed
922    /// `dec_random` (bypassing the RNG) so the assertion is deterministic.
923    #[test]
924    fn repeat_decrease_is_a_one_shot_per_period_once_dec_random_exceeds_one() {
925        let mut cc = FileCc::new(0);
926        cc.on_loss(10, 10, 0.9); // end slow start
927        cc.on_loss(20, 20, 0.9); // new congestion period, big decrease
928        assert_eq!(cc.dec_count(), 1);
929
930        // Force a specific integer DecRandom > 1 for this period (bypassing
931        // the RNG so the check below is deterministic, not seed-dependent).
932        cc.dec_random = 3.0;
933        let after_first = cc.pkt_snd_period_us();
934
935        // Many same-period NAKs: per the literal spec pseudocode, NONE of
936        // them can fire Step 4 again, because NAKCount/DecCount are frozen
937        // at (1, 1) and 1 == 1*3 is false — and stays false forever, since
938        // nothing outside Step 4's own conditional advances either counter.
939        for sent in 21..=60u32 {
940            cc.on_loss(15, sent, 0.9);
941        }
942
943        assert_eq!(
944            cc.dec_count(),
945            1,
946            "with the literal spec's Step 4 pseudocode, DecCount must stay \
947             frozen at 1 for the rest of the period once the immediate \
948             post-reset check (NAKCount==DecCount*DecRandom, i.e. 1==1*3) \
949             fails — this is the draft's own one-shot property, not a bug"
950        );
951        assert_eq!(
952            cc.pkt_snd_period_us(),
953            after_first,
954            "PKT_SND_PERIOD must not change further once Step 4 has gone \
955             silent for the rest of the period"
956        );
957    }
958
959    /// The complementary, working case: when the drawn integer `DecRandom`
960    /// rounds to exactly `1`, the immediate post-reset check `1 == 1*1`
961    /// holds, so Step 4 fires on every subsequent same-period NAK (this is
962    /// the case the pre-existing integration test
963    /// `repeated_decrease_backs_off_by_1_03_bounded_by_dec_count` already
964    /// covers end-to-end with `AvgNAKNum == 0`; this unit test additionally
965    /// proves it holds even when `AvgNAKNum` is nonzero but rounds to 1).
966    #[test]
967    fn repeat_decrease_fires_repeatedly_when_dec_random_rounds_to_one() {
968        let mut cc = FileCc::new(0);
969        cc.avg_nak_num = 1.2; // rounds to 1 via next_dec_random's `.round()`
970        cc.on_loss(10, 10, 0.9);
971        cc.on_loss(20, 20, 0.9);
972        assert_eq!(cc.dec_random, 1.0);
973        assert_eq!(cc.dec_count(), 1);
974
975        for sent in 21..=25u32 {
976            cc.on_loss(15, sent, 0.9);
977        }
978        assert_eq!(
979            cc.dec_count(),
980            6,
981            "DecRandom==1 must let Step 4 fire on every same-period NAK"
982        );
983    }
984
985    #[test]
986    fn phase_labels_match_the_spec_names() {
987        assert_eq!(Phase::SlowStart.name(), "SlowStart");
988        assert_eq!(Phase::CongestionAvoidance.name(), "CongestionAvoidance");
989    }
990
991    #[test]
992    fn default_matches_new_zero() {
993        let a = FileCc::default();
994        let b = FileCc::new(0);
995        assert_eq!(a.cwnd_size(), b.cwnd_size());
996        assert_eq!(a.phase(), b.phase());
997    }
998
999    /// A Congestion Avoidance engine with a hand-set period and
1000    /// `LastDecPeriod`, so the Step 5 formula can be evaluated from known
1001    /// inputs (`private/specs-verified/rules/srt-congestion.md` §5.2.1.2 (1)
1002    /// Step 5).
1003    fn ca_engine(pkt_snd_period_us: f64, last_dec_period_us: f64) -> FileCc {
1004        let mut cc = FileCc::new(0);
1005        cc.phase = Phase::CongestionAvoidance;
1006        cc.pkt_snd_period_us = pkt_snd_period_us;
1007        cc.last_dec_period_us = last_dec_period_us;
1008        cc
1009    }
1010
1011    fn one_rc_interval_ack(cc: &mut FileCc, receiving_rate_pps: u64, est_link_capacity_pps: u64) {
1012        cc.on_ack(
1013            0,
1014            receiving_rate_pps,
1015            est_link_capacity_pps,
1016            Duration::from_millis(100),
1017            Instant::from_millis(10),
1018        );
1019    }
1020
1021    #[test]
1022    fn step5_uses_the_minimum_increase_when_available_bandwidth_is_not_positive() {
1023        let mut cc = ca_engine(10.0, 10.0);
1024        one_rc_interval_ack(&mut cc, 5_000, 100_000);
1025        // lossBandwidth = 2 * (1e6/10) = 200000, clamped by EST_LINK_CAPACITY
1026        // to 100000; B = 100000 - 1e6/10 = 0 -> inc = 1/1500;
1027        // PKT_SND_PERIOD = (10*10000)/(10*(1/1500) + 10000).
1028        assert_eq!(cc.pkt_snd_period_us(), 9.999993333337779);
1029        assert_eq!(cc.cwnd_size(), 566.0);
1030    }
1031
1032    #[test]
1033    fn step5_clamps_available_bandwidth_to_ninth_of_link_capacity() {
1034        let mut cc = ca_engine(20.0, 10.0);
1035        one_rc_interval_ack(&mut cc, 5_000, 200_000);
1036        // linkCapacity = min(200000, 200000) = 200000; B = 200000 - 50000 =
1037        // 150000, clamped to 200000/9; inc = 1.0;
1038        // PKT_SND_PERIOD = (20*10000)/(20*1 + 10000).
1039        assert_eq!(cc.pkt_snd_period_us(), 19.960079840319363);
1040    }
1041
1042    #[test]
1043    fn step5_clamp_requires_the_period_to_be_strictly_above_last_dec_period() {
1044        let mut cc = ca_engine(10.0, 10.0);
1045        one_rc_interval_ack(&mut cc, 5_000, 200_000);
1046        // PKT_SND_PERIOD == LastDecPeriod, so the clamp must NOT apply:
1047        // B = 100000, inc = pow10(100000*1500*8)*1.5e-6/1500 = 10.0;
1048        // PKT_SND_PERIOD = (10*10000)/(10*10 + 10000).
1049        assert_eq!(cc.pkt_snd_period_us(), 9.900990099009901);
1050    }
1051
1052    #[test]
1053    fn step5_uses_loss_bandwidth_when_it_is_below_link_capacity() {
1054        let mut cc = ca_engine(100.0, 100.0);
1055        one_rc_interval_ack(&mut cc, 5_000, 1_000_000);
1056        // lossBandwidth = 2 * (1e6/100) = 20000, below EST_LINK_CAPACITY, so
1057        // linkCapacity = 20000 and B = 10000 (the clamp requires
1058        // PKT_SND_PERIOD > LastDecPeriod, which is false here);
1059        // inc = pow10(10000*1500*8)*1.5e-6/1500 = 1.0.
1060        assert_eq!(cc.pkt_snd_period_us(), 99.00990099009901);
1061    }
1062
1063    #[test]
1064    fn step5_does_not_clamp_when_available_bandwidth_is_below_ninth_of_link_capacity() {
1065        let mut cc = ca_engine(1001.0, 1.0);
1066        one_rc_interval_ack(&mut cc, 5_000, 1_000);
1067        // linkCapacity = min(2000000, 1000) = 1000; B = 1000 - 1e6/1001 =
1068        // 0.999... < 1000/9, so the clamp does not fire; inc = 1/1500.
1069        assert_eq!(cc.pkt_snd_period_us(), 1000.9332043908271);
1070    }
1071
1072    #[test]
1073    fn step6_max_bw_clamp_binds_with_the_configured_bandwidth() {
1074        let mut cc = ca_engine(10.0, 10.0);
1075        cc.set_max_bw_bytes_per_sec(Some(3_000));
1076        one_rc_interval_ack(&mut cc, 5_000, 100_000);
1077        // MIN_PERIOD = 1e6/(3000/1500) = 500000 us, above the Step 5 result.
1078        assert_eq!(cc.pkt_snd_period_us(), 500_000.0);
1079        assert_eq!(cc.max_bw_bytes_per_sec(), Some(3_000));
1080    }
1081
1082    #[test]
1083    fn rate_control_gate_passes_at_exactly_rc_interval() {
1084        let mut cc = FileCc::new(0);
1085        cc.on_ack(0, 0, 0, Duration::from_millis(100), Instant::from_millis(0));
1086        cc.on_ack(
1087            10,
1088            0,
1089            0,
1090            Duration::from_millis(100),
1091            Instant::from_millis(10),
1092        );
1093        assert_eq!(
1094            cc.cwnd_size(),
1095            26.0,
1096            "an ACK exactly RC_INTERVAL later must not be gated"
1097        );
1098    }
1099
1100    #[test]
1101    fn slow_start_survives_cwnd_equal_to_max_cwnd_size() {
1102        let mut cc = FileCc::new(0);
1103        cc.set_max_cwnd_size(26.0);
1104        cc.on_ack(
1105            10,
1106            0,
1107            0,
1108            Duration::from_millis(100),
1109            Instant::from_millis(10),
1110        );
1111        assert_eq!(cc.cwnd_size(), 26.0);
1112        assert_eq!(cc.phase(), Phase::SlowStart);
1113        assert_eq!(cc.pkt_snd_period_us(), 1.0);
1114    }
1115
1116    #[test]
1117    fn end_slow_start_uses_receiving_rate_when_known() {
1118        let mut cc = FileCc::new(0);
1119        cc.on_ack(
1120            0,
1121            5_000,
1122            0,
1123            Duration::from_millis(100),
1124            Instant::from_millis(10),
1125        );
1126        assert_eq!(cc.receiving_rate_pps(), 5_000);
1127        cc.on_loss(1, 1, 0.9);
1128        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
1129        assert_eq!(cc.pkt_snd_period_us(), 200.0);
1130    }
1131
1132    #[test]
1133    fn end_slow_start_falls_back_to_cwnd_over_rtt_when_rate_is_unknown() {
1134        let mut cc = FileCc::new(0);
1135        cc.on_ack(
1136            0,
1137            0,
1138            0,
1139            Duration::from_millis(100),
1140            Instant::from_millis(10),
1141        );
1142        assert_eq!(cc.receiving_rate_pps(), 0);
1143        cc.on_timeout();
1144        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
1145        // CWND_SIZE = 16, RTT + RC_INTERVAL = 110000 us.
1146        assert_eq!(cc.pkt_snd_period_us(), 0.00014545454545454546);
1147    }
1148
1149    #[test]
1150    fn loss_ratio_exactly_two_percent_starts_a_new_congestion_period() {
1151        let mut cc = ca_engine(10.0, 1.0);
1152        cc.on_loss(10, 100, 0.02);
1153        assert!(cc.b_loss());
1154        assert_eq!(cc.pkt_snd_period_us(), 10.3);
1155        assert_eq!(cc.last_dec_seq(), Some(100));
1156        assert_eq!(cc.nak_count(), 1);
1157        assert_eq!(cc.dec_count(), 1);
1158    }
1159
1160    #[test]
1161    fn loss_ratio_below_two_percent_only_records_last_dec_period() {
1162        let mut cc = ca_engine(10.0, 1.0);
1163        cc.on_loss(10, 100, 0.019);
1164        assert_eq!(cc.pkt_snd_period_us(), 10.0);
1165        assert_eq!(cc.last_dec_seq(), None);
1166        assert_eq!(cc.last_dec_period_us(), 10.0);
1167        assert_eq!(cc.nak_count(), 0);
1168    }
1169
1170    #[test]
1171    fn new_congestion_period_updates_avg_nak_num_from_the_finished_period() {
1172        let mut cc = ca_engine(10.0, 1.0);
1173        cc.avg_nak_num = 1.5;
1174        cc.nak_count = 7;
1175        cc.on_loss(10, 100, 0.9);
1176        // AvgNAKNum = 0.97*1.5 + 0.03*7 = 1.455 + 0.21 = 1.665.
1177        assert_eq!(cc.avg_nak_num(), 1.665);
1178        assert_eq!(cc.est_link_capacity_pps(), 0);
1179    }
1180
1181    #[test]
1182    fn repeat_decrease_requires_nak_count_to_equal_dec_count_times_dec_random() {
1183        let mut cc = ca_engine(10.0, 1.0);
1184        cc.last_dec_seq = Some(100);
1185        cc.dec_count = 2;
1186        cc.nak_count = 4;
1187        cc.dec_random = 2.0;
1188        cc.on_loss(50, 120, 0.9);
1189        assert_eq!(cc.pkt_snd_period_us(), 10.3);
1190        assert_eq!(cc.dec_count(), 3);
1191        assert_eq!(cc.nak_count(), 5);
1192        assert_eq!(cc.last_dec_seq(), Some(120));
1193    }
1194
1195    #[test]
1196    fn repeat_decrease_does_not_fire_on_a_non_matching_nak_count() {
1197        let mut cc = ca_engine(10.0, 1.0);
1198        cc.last_dec_seq = Some(100);
1199        cc.dec_count = 2;
1200        cc.nak_count = 5;
1201        cc.dec_random = 2.0;
1202        cc.on_loss(50, 120, 0.9);
1203        assert_eq!(cc.pkt_snd_period_us(), 10.0);
1204        assert_eq!(cc.dec_count(), 2);
1205        assert_eq!(cc.nak_count(), 5);
1206        assert_eq!(cc.last_dec_seq(), Some(100));
1207    }
1208
1209    #[test]
1210    fn fmin_and_fmax_pick_the_named_extremum() {
1211        assert_eq!(fmin(1.0, 2.0), 1.0);
1212        assert_eq!(fmin(2.0, 1.0), 1.0);
1213        assert_eq!(fmin(2.0, 3.0), 2.0);
1214        assert_eq!(fmax(2.0, 1.0), 2.0);
1215        assert_eq!(fmax(1.0, 2.0), 2.0);
1216        assert_eq!(fmax(3.0, 2.0), 3.0);
1217    }
1218
1219    #[test]
1220    fn fround_matches_round_half_away_from_zero() {
1221        assert_eq!(fround(-2.5), -3.0);
1222        assert_eq!(fround(2.5), 3.0);
1223        assert_eq!(fround(0.49), 0.0);
1224        assert_eq!(fround(0.5), 1.0);
1225        assert_eq!(fround(-0.5), -1.0);
1226        assert_eq!(fround(7.0), 7.0);
1227    }
1228
1229    #[test]
1230    fn xorshift_seed_one_matches_the_reference_sequence() {
1231        let mut rng = XorShift64::new(1);
1232        assert_eq!(rng.next_unit(), 0.7303895583163529);
1233        assert_eq!(rng.next_unit(), 0.01114514886742557);
1234        assert_eq!(rng.next_unit(), 0.992548190308695);
1235    }
1236
1237    #[test]
1238    fn dec_random_sequence_matches_the_reference_draws() {
1239        let mut cc = FileCc::new(0);
1240        cc.avg_nak_num = 8.0;
1241        assert_eq!(cc.next_dec_random(), 4.0);
1242        assert_eq!(cc.next_dec_random(), 7.0);
1243        assert_eq!(cc.next_dec_random(), 4.0);
1244    }
1245
1246    #[test]
1247    fn dec_random_covers_a_range_of_integer_values() {
1248        let mut cc = FileCc::new(0);
1249        cc.avg_nak_num = 8.0;
1250        let mut seen = [false; 9];
1251        for _ in 0..1_000 {
1252            let v = cc.next_dec_random();
1253            assert_eq!(v, v.round(), "DecRandom must be a whole number (got {v})");
1254            assert!((1.0..=8.0).contains(&v), "DecRandom out of range: {v}");
1255            seen[v as usize] = true;
1256        }
1257        let distinct = seen.iter().filter(|&&s| s).count();
1258        assert!(
1259            distinct >= 4,
1260            "DecRandom must vary across draws (saw {distinct} distinct values)"
1261        );
1262    }
1263
1264    #[test]
1265    fn accessors_report_the_fed_and_configured_values() {
1266        let mut cc = ca_engine(10.0, 1.0);
1267        cc.set_max_bw_bytes_per_sec(Some(1_234));
1268        assert_eq!(cc.max_bw_bytes_per_sec(), Some(1_234));
1269        one_rc_interval_ack(&mut cc, 5_000, 100_000);
1270        assert_eq!(cc.receiving_rate_pps(), 5_000);
1271        assert_eq!(cc.est_link_capacity_pps(), 100_000);
1272        cc.on_loss(10, 100, 0.9);
1273        assert_eq!(cc.last_dec_seq(), Some(100));
1274        assert_eq!(cc.nak_count(), 1);
1275    }
1276}