Skip to main content

rustflexstack/management/
dcc_adaptive.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Adaptive Decentralized Congestion Control (DCC) algorithm and Gate Keeper.
5//!
6//! Implements the adaptive approach specified in ETSI TS 102 687 V1.2.1 (2018-04)
7//! clause 5.4 and the gate-keeping packet admission mechanism described in
8//! Annex B.
9//!
10//! # Overview
11//! The adaptive algorithm (LIMERIC) maintains a smoothed estimate of the local
12//! Channel Busy Ratio (`cbr_its_s`) and adjusts a *duty-cycle fraction*
13//! parameter `delta` so that the ITS-S's own channel occupancy converges toward
14//! a configurable target CBR. `delta` represents the maximum fraction of the
15//! wireless medium that this ITS-S is allowed to occupy over any given interval.
16//!
17//! The [`DccAdaptive`] struct implements the five algorithmic steps of
18//! clause 5.4 and is intended to be called at every UTC-modulo-200 ms boundary.
19//!
20//! The [`GateKeeper`] struct implements the packet admission logic of Annex B.
21//! It uses the current `delta` value to compute the earliest time at which the
22//! next packet may be admitted to the access layer. When `delta` is updated by
23//! the adaptive algorithm, the gate-opening time is recalculated according to
24//! equation B.2 to avoid synchronised transmissions across stations.
25
26use super::DccError;
27
28/// Tunable parameters of the adaptive DCC algorithm.
29///
30/// Default values are taken from Table 3 of ETSI TS 102 687 V1.2.1 (2018-04)
31/// clause 5.4.
32#[derive(Debug, Clone, PartialEq)]
33pub struct DccAdaptiveParameters {
34    /// Exponential averaging coefficient used in step 3 (equation 4).
35    /// Default: 0.016.
36    pub alpha: f64,
37    /// Proportional gain applied to the CBR error in step 2 (equations 2 and 3).
38    /// Default: 0.0012.
39    pub beta: f64,
40    /// Target Channel Busy Ratio toward which `delta` is steered.
41    /// Default: 0.68.
42    pub cbr_target: f64,
43    /// Hard upper bound on the duty-cycle fraction `delta` (step 4, equation 5).
44    /// Corresponds to the maximum duty cycle permitted by ETSI EN 302 571.
45    /// Default: 0.03.
46    pub delta_max: f64,
47    /// Hard lower bound on `delta` (step 5, equation 6).
48    /// Prevents complete starvation under extreme congestion.
49    /// Default: 0.0006.
50    pub delta_min: f64,
51    /// Upper clamp on the per-step offset when CBR is below the target (equation 2).
52    /// Default: 0.0005.
53    pub delta_up_max: f64,
54    /// Lower clamp on the per-step offset when CBR is at or above the target (equation 3).
55    /// Must be negative. Default: -0.00025.
56    pub delta_down_max: f64,
57}
58
59impl Default for DccAdaptiveParameters {
60    fn default() -> Self {
61        Self {
62            alpha: 0.016,
63            beta: 0.0012,
64            cbr_target: 0.68,
65            delta_max: 0.03,
66            delta_min: 0.0006,
67            delta_up_max: 0.0005,
68            delta_down_max: -0.00025,
69        }
70    }
71}
72
73/// Adaptive DCC algorithm as specified in ETSI TS 102 687 V1.2.1 (2018-04)
74/// clause 5.4 (LIMERIC).
75///
76/// The algorithm shall be evaluated at every UTC-modulo-200 ms boundary
77/// (clause 5.2). Each evaluation executes five ordered steps that update the
78/// duty-cycle fraction `delta`:
79///
80/// - **Step 1** – Compute a smoothed CBR estimate (`cbr_its_s`) from the
81///   two most recent local (or global, if available) CBR measurements.
82/// - **Step 2** – Compute a signed per-step correction (`delta_offset`)
83///   proportional to the distance between `cbr_target` and `cbr_its_s`,
84///   clamped to `[delta_down_max, delta_up_max]`.
85/// - **Step 3** – Apply an exponential filter to blend the new offset into the
86///   current `delta`.
87/// - **Steps 4–5** – Clamp `delta` to `[delta_min, delta_max]`.
88#[derive(Debug, Clone, PartialEq)]
89pub struct DccAdaptive {
90    /// Algorithm tuning parameters.
91    pub parameters: DccAdaptiveParameters,
92    /// Current smoothed CBR estimate (initialised to 0.0).
93    pub cbr_its_s: f64,
94    /// Current duty-cycle fraction (initialised to `parameters.delta_min`).
95    pub delta: f64,
96}
97
98impl Default for DccAdaptive {
99    fn default() -> Self {
100        Self::new(DccAdaptiveParameters::default())
101    }
102}
103
104impl DccAdaptive {
105    /// Initialise the adaptive DCC algorithm with the given parameters.
106    pub fn new(parameters: DccAdaptiveParameters) -> Self {
107        let delta = parameters.delta_min;
108        Self {
109            parameters,
110            cbr_its_s: 0.0,
111            delta,
112        }
113    }
114
115    /// Execute one full adaptive DCC evaluation (steps 1–5 of clause 5.4).
116    ///
117    /// # Parameters
118    /// - `cbr_local`: Most recent local CBR measurement (`CBR_L_0_Hop`).
119    /// - `cbr_local_previous`: Second most recent local CBR measurement (`CBR_L_0_Hop_Previous`).
120    /// - `cbr_global`: Most recent global CBR (`CBR_G`), received from a neighbouring
121    ///   ITS-S via GeoNetworking header. When provided together with `cbr_global_previous`,
122    ///   replaces the local values in step 1.
123    /// - `cbr_global_previous`: Second most recent global CBR (`CBR_G_Previous`).
124    ///
125    /// # Returns
126    /// Updated `delta` value after clamping.
127    ///
128    /// # Errors
129    /// Returns [`DccError::InvalidCbr`] if any CBR argument is outside `[0.0, 1.0]`.
130    pub fn update(
131        &mut self,
132        cbr_local: f64,
133        cbr_local_previous: f64,
134        cbr_global: Option<f64>,
135        cbr_global_previous: Option<f64>,
136    ) -> Result<f64, DccError> {
137        if !(0.0..=1.0).contains(&cbr_local) {
138            return Err(DccError::InvalidCbr {
139                name: "cbr_local",
140                value: cbr_local,
141            });
142        }
143        if !(0.0..=1.0).contains(&cbr_local_previous) {
144            return Err(DccError::InvalidCbr {
145                name: "cbr_local_previous",
146                value: cbr_local_previous,
147            });
148        }
149        if let Some(cg) = cbr_global {
150            if !(0.0..=1.0).contains(&cg) {
151                return Err(DccError::InvalidCbr {
152                    name: "cbr_global",
153                    value: cg,
154                });
155            }
156        }
157        if let Some(cgp) = cbr_global_previous {
158            if !(0.0..=1.0).contains(&cgp) {
159                return Err(DccError::InvalidCbr {
160                    name: "cbr_global_previous",
161                    value: cgp,
162                });
163            }
164        }
165
166        let p = &self.parameters;
167
168        // Step 1 (equation 1) – CBR averaging
169        // Use global CBR if both global measurements are available (NOTE 1).
170        let cbr_avg = match (cbr_global, cbr_global_previous) {
171            (Some(cg), Some(cgp)) => (cg + cgp) / 2.0,
172            _ => (cbr_local + cbr_local_previous) / 2.0,
173        };
174        self.cbr_its_s = 0.5 * self.cbr_its_s + 0.5 * cbr_avg;
175
176        // Step 2 (equations 2–3) – compute delta_offset
177        let diff = p.cbr_target - self.cbr_its_s;
178        let delta_offset = if diff > 0.0 {
179            // CBR below target -> increase delta (more transmission allowed)
180            (p.beta * diff).min(p.delta_up_max)
181        } else {
182            // CBR at or above target -> decrease delta (fewer transmissions)
183            (p.beta * diff).max(p.delta_down_max)
184        };
185
186        // Step 3 (equation 4) – exponential filter
187        self.delta = (1.0 - p.alpha) * self.delta + delta_offset;
188
189        // Steps 4–5 (equations 5–6) – clamp to permitted range
190        if self.delta > p.delta_max {
191            self.delta = p.delta_max;
192        }
193        if self.delta < p.delta_min {
194            self.delta = p.delta_min;
195        }
196
197        Ok(self.delta)
198    }
199
200    /// Convenience wrapper for local-only CBR updates.
201    pub fn update_local(
202        &mut self,
203        cbr_local: f64,
204        cbr_local_previous: f64,
205    ) -> Result<f64, DccError> {
206        self.update(cbr_local, cbr_local_previous, None, None)
207    }
208}
209
210/// Packet admission gate keeper as described in ETSI TS 102 687 V1.2.1 (2018-04) Annex B.
211///
212/// The gate keeper controls which packets may pass from the Network & Transport layer
213/// to the Access layer queue. The gate is **open** when the Access layer will accept
214/// a new packet and **closed** otherwise.
215///
216/// # Lifecycle
217/// 1. A packet arrives at the gate. If the gate is open the packet is *admitted*:
218///    the gate closes and a gate-opening time `t_go` is scheduled using equation B.1.
219/// 2. From time `t_go` onward the gate is open again.
220/// 3. Whenever `delta` is updated by the adaptive algorithm, `t_go` is recalculated
221///    per equation B.2 to preserve relative ordering of gate openings without
222///    introducing synchronisation artefacts.
223///
224/// The minimum inter-admission interval is 25 ms and the maximum is 1 s
225/// (both from constraints in ETSI EN 302 571 referenced in Annex B).
226#[derive(Debug, Clone, PartialEq)]
227pub struct GateKeeper {
228    delta: f64,
229    t_pg: Option<f64>,
230    t_go: Option<f64>,
231}
232
233impl GateKeeper {
234    /// Minimum allowed gate-open interval in seconds (25 ms).
235    pub const GATE_OPEN_MIN_INTERVAL_S: f64 = 0.025;
236    /// Maximum allowed gate-open interval in seconds (1 s).
237    pub const GATE_OPEN_MAX_INTERVAL_S: f64 = 1.0;
238    /// 1 ns tolerance for floating-point rounding.
239    pub const T_EPSILON: f64 = 1e-9;
240
241    /// Initialise the gate keeper with an initial `delta` value.
242    pub fn new(delta: f64) -> Self {
243        Self {
244            delta,
245            t_pg: None,
246            t_go: None,
247        }
248    }
249
250    /// Return the currently configured `delta` duty-cycle fraction.
251    pub fn delta(&self) -> f64 {
252        self.delta
253    }
254
255    /// Return the time when the gate last closed (`t_pg`), if any.
256    pub fn t_pg(&self) -> Option<f64> {
257        self.t_pg
258    }
259
260    /// Return the scheduled gate-opening time (`t_go`), if any.
261    pub fn t_go(&self) -> Option<f64> {
262        self.t_go
263    }
264
265    /// Return `true` if the gate is currently open at time `t`.
266    ///
267    /// The gate is open on first use (before any packet has been admitted)
268    /// and from `t_go` onward after each admission.
269    pub fn is_open(&self, t: f64) -> bool {
270        match self.t_go {
271            None => true,
272            Some(t_go) => t >= t_go - Self::T_EPSILON,
273        }
274    }
275
276    /// Attempt to admit one packet at time `t`.
277    ///
278    /// If the gate is open the packet is accepted, the gate closes, and the
279    /// next gate-opening time is scheduled per equation B.1:
280    ///
281    /// `t_go = t_pg + clamp(T_on_pp / delta, 0.025, 1.0)`
282    ///
283    /// # Parameters
284    /// - `t`: Current time in seconds.
285    /// - `t_on`: Transmission duration of this packet in seconds (`T_on_pp` in Annex B).
286    ///
287    /// # Returns
288    /// `Ok(true)` if the packet was admitted; `Ok(false)` if the gate was closed.
289    ///
290    /// # Errors
291    /// Returns [`DccError::InvalidTon`] if `t_on` is not positive (`<= 0.0`).
292    pub fn admit_packet(&mut self, t: f64, t_on: f64) -> Result<bool, DccError> {
293        if t_on <= 0.0 {
294            return Err(DccError::InvalidTon(t_on));
295        }
296        if !self.is_open(t) {
297            return Ok(false);
298        }
299
300        self.t_pg = Some(t);
301        let interval = (t_on / self.delta).clamp(
302            Self::GATE_OPEN_MIN_INTERVAL_S,
303            Self::GATE_OPEN_MAX_INTERVAL_S,
304        );
305        self.t_go = Some(t + interval);
306        Ok(true)
307    }
308
309    /// Update the duty-cycle fraction and reschedule the gate-opening time.
310    ///
311    /// When `delta` changes, the gate-opening time is recalculated per
312    /// equation B.2 to avoid synchronising gate openings across stations:
313    ///
314    /// `t_go = t_pg + clamp((delta_old / delta_new) * (t_go - t_pg), 0.025, 1.0)`
315    ///
316    /// If the gate is currently open (no packet admitted yet, or `t_go` has already
317    /// passed) only `delta` is updated.
318    ///
319    /// # Parameters
320    /// - `t`: Current time in seconds.
321    /// - `delta_new`: Updated duty-cycle fraction from the adaptive DCC algorithm.
322    ///
323    /// # Errors
324    /// Returns [`DccError::InvalidDelta`] if `delta_new` is not positive (`<= 0.0`).
325    pub fn update_delta(&mut self, t: f64, delta_new: f64) -> Result<(), DccError> {
326        if delta_new <= 0.0 {
327            return Err(DccError::InvalidDelta(delta_new));
328        }
329
330        let delta_old = self.delta;
331        self.delta = delta_new;
332
333        // Gate is already open -> no rescheduling needed
334        if self.t_pg.is_none() || self.t_go.is_none() || self.is_open(t) {
335            return Ok(());
336        }
337
338        // B.2 – rescale remaining closed interval by delta ratio
339        let t_pg = self.t_pg.unwrap();
340        let t_go = self.t_go.unwrap();
341        let old_interval = t_go - t_pg;
342        let new_interval = (delta_old / delta_new) * old_interval;
343        let interval = new_interval.clamp(
344            Self::GATE_OPEN_MIN_INTERVAL_S,
345            Self::GATE_OPEN_MAX_INTERVAL_S,
346        );
347        self.t_go = Some(t_pg + interval);
348
349        Ok(())
350    }
351}
352
353// ---------------------------------------------------------------------------
354// Unit tests
355// ---------------------------------------------------------------------------
356
357#[cfg(test)]
358#[allow(clippy::float_cmp)]
359mod tests {
360    use super::*;
361
362    macro_rules! assert_almost_eq {
363        ($a:expr, $b:expr) => {
364            assert!(
365                ($a - $b).abs() < 1e-9,
366                "assertion failed: ({} - {}) < 1e-9 (left: {}, right: {})",
367                stringify!($a),
368                stringify!($b),
369                $a,
370                $b
371            );
372        };
373        ($a:expr, $b:expr, $eps:expr) => {
374            assert!(
375                ($a - $b).abs() < $eps,
376                "assertion failed: ({} - {}) < {} (left: {}, right: {})",
377                stringify!($a),
378                stringify!($b),
379                stringify!($eps),
380                $a,
381                $b
382            );
383        };
384    }
385
386    // ── Initialisation ────────────────────────────────────────────────────
387
388    #[test]
389    fn test_default_parameters() {
390        let alg = DccAdaptive::default();
391        let p = &alg.parameters;
392        assert_almost_eq!(p.alpha, 0.016);
393        assert_almost_eq!(p.beta, 0.0012);
394        assert_almost_eq!(p.cbr_target, 0.68);
395        assert_almost_eq!(p.delta_max, 0.03);
396        assert_almost_eq!(p.delta_min, 0.0006);
397        assert_almost_eq!(p.delta_up_max, 0.0005);
398        assert_almost_eq!(p.delta_down_max, -0.00025);
399    }
400
401    #[test]
402    fn test_initial_cbr_its_s_is_zero() {
403        let alg = DccAdaptive::default();
404        assert_almost_eq!(alg.cbr_its_s, 0.0);
405    }
406
407    #[test]
408    fn test_initial_delta_is_delta_min() {
409        let alg = DccAdaptive::default();
410        assert_almost_eq!(alg.delta, alg.parameters.delta_min);
411    }
412
413    #[test]
414    fn test_custom_parameters_accepted() {
415        let params = DccAdaptiveParameters {
416            alpha: 0.1,
417            beta: 0.05,
418            cbr_target: 0.5,
419            ..Default::default()
420        };
421        let alg = DccAdaptive::new(params);
422        assert_almost_eq!(alg.parameters.alpha, 0.1);
423        assert_almost_eq!(alg.parameters.cbr_target, 0.5);
424    }
425
426    // ── Step 1: CBR Smoothing ─────────────────────────────────────────────
427
428    #[test]
429    fn test_cbr_its_s_uses_local_average() {
430        let mut alg = DccAdaptive::default();
431        alg.update_local(0.4, 0.4).unwrap();
432        // 0.5*0.0 + 0.5*(0.4+0.4)/2 = 0.5*0.4 = 0.2
433        assert_almost_eq!(alg.cbr_its_s, 0.2);
434    }
435
436    #[test]
437    fn test_cbr_its_s_accumulates_over_calls() {
438        let mut alg = DccAdaptive::default();
439        alg.update_local(0.4, 0.4).unwrap();
440        // After first call: cbr_its_s = 0.2
441        alg.update_local(0.4, 0.4).unwrap();
442        // After second call: 0.5*0.2 + 0.5*0.4 = 0.1 + 0.2 = 0.3
443        assert_almost_eq!(alg.cbr_its_s, 0.3);
444    }
445
446    #[test]
447    fn test_cbr_its_s_uses_global_when_provided() {
448        let mut alg = DccAdaptive::default();
449        alg.update(0.1, 0.1, Some(0.6), Some(0.6)).unwrap();
450        // 0.5*0.0 + 0.5*(0.6+0.6)/2 = 0.5*0.6 = 0.3
451        assert_almost_eq!(alg.cbr_its_s, 0.3);
452    }
453
454    #[test]
455    fn test_cbr_its_s_ignores_global_when_only_one_provided() {
456        let mut alg = DccAdaptive::default();
457        alg.update(0.4, 0.4, Some(0.9), None).unwrap();
458        // Falls back to local: 0.5*(0.4+0.4)/2 = 0.2
459        assert_almost_eq!(alg.cbr_its_s, 0.2);
460    }
461
462    // ── Step 2: delta_offset Clamping ─────────────────────────────────────
463
464    #[test]
465    fn test_positive_diff_uses_equation_2() {
466        let mut alg = DccAdaptive {
467            cbr_its_s: 0.0,
468            ..Default::default()
469        };
470        alg.update_local(0.0, 0.0).unwrap();
471        let expected_delta = (1.0 - 0.016) * 0.0006 + 0.0005;
472        assert_almost_eq!(alg.delta, expected_delta, 1e-10);
473    }
474
475    #[test]
476    fn test_negative_diff_uses_equation_3() {
477        let mut alg = DccAdaptive {
478            cbr_its_s: 1.0,
479            ..Default::default()
480        };
481        let initial_delta = alg.delta;
482        alg.update_local(1.0, 1.0).unwrap();
483        let expected_delta = ((1.0 - 0.016) * initial_delta + (-0.00025_f64)).clamp(0.0006, 0.03);
484        assert_almost_eq!(alg.delta, expected_delta, 1e-10);
485    }
486
487    #[test]
488    fn test_small_positive_diff_not_clamped() {
489        let p = DccAdaptiveParameters::default();
490        let mut alg = DccAdaptive {
491            parameters: p.clone(),
492            cbr_its_s: 0.679,
493            delta: 0.01,
494        };
495        alg.update_local(0.679, 0.679).unwrap();
496        let diff = 0.68 - 0.679;
497        let expected_offset = p.beta * diff;
498        let expected_delta = (1.0 - p.alpha) * 0.01 + expected_offset;
499        assert_almost_eq!(alg.delta, expected_delta, 1e-10);
500    }
501
502    #[test]
503    fn test_large_negative_diff_clamped_to_down_max() {
504        let mut alg = DccAdaptive {
505            cbr_its_s: 0.99,
506            delta: 0.02,
507            ..Default::default()
508        };
509        alg.update_local(0.99, 0.99).unwrap();
510        let expected_delta = (1.0 - 0.016) * 0.02 + (-0.00025);
511        assert_almost_eq!(alg.delta, expected_delta, 1e-10);
512    }
513
514    // ── Steps 3–5: Filter and Clamping ────────────────────────────────────
515
516    #[test]
517    fn test_step3_exponential_filter() {
518        let mut alg = DccAdaptive {
519            cbr_its_s: 0.68,
520            delta: 0.01,
521            ..Default::default()
522        };
523        alg.update_local(0.68, 0.68).unwrap();
524        let expected = (1.0 - 0.016) * 0.01 + 0.0;
525        assert_almost_eq!(alg.delta, expected, 1e-10);
526    }
527
528    #[test]
529    fn test_step4_clamps_delta_to_max() {
530        let mut alg = DccAdaptive {
531            delta: 0.029,
532            cbr_its_s: 0.0,
533            ..Default::default()
534        };
535        alg.update_local(0.0, 0.0).unwrap();
536        assert!(alg.delta <= alg.parameters.delta_max);
537    }
538
539    #[test]
540    fn test_step5_clamps_delta_to_min() {
541        let mut alg = DccAdaptive {
542            cbr_its_s: 1.0,
543            ..Default::default()
544        };
545        alg.delta = alg.parameters.delta_min;
546        alg.update_local(1.0, 1.0).unwrap();
547        assert!(alg.delta >= alg.parameters.delta_min);
548    }
549
550    #[test]
551    fn test_delta_converges_toward_target() {
552        let mut alg = DccAdaptive::default();
553        let cbr = 0.68;
554        for _ in 0..500 {
555            alg.update_local(cbr, cbr).unwrap();
556        }
557        assert!(alg.delta >= alg.parameters.delta_min);
558        assert!(alg.delta <= alg.parameters.delta_max);
559    }
560
561    #[test]
562    fn test_delta_increases_when_cbr_below_target() {
563        let mut alg = DccAdaptive::default();
564        let prev_delta = alg.delta;
565        for _ in 0..50 {
566            alg.update_local(0.0, 0.0).unwrap();
567        }
568        assert!(alg.delta > prev_delta);
569    }
570
571    #[test]
572    fn test_delta_decreases_when_cbr_above_target() {
573        let mut alg = DccAdaptive {
574            delta: 0.02,
575            ..Default::default()
576        };
577        for _ in 0..200 {
578            alg.update_local(1.0, 1.0).unwrap();
579        }
580        assert_almost_eq!(alg.delta, alg.parameters.delta_min);
581    }
582
583    // ── Input Validation ──────────────────────────────────────────────────
584
585    #[test]
586    fn test_cbr_local_below_zero_raises() {
587        let mut alg = DccAdaptive::default();
588        let res = alg.update_local(-0.01, 0.5);
589        assert!(matches!(
590            res,
591            Err(DccError::InvalidCbr {
592                name: "cbr_local",
593                ..
594            })
595        ));
596    }
597
598    #[test]
599    fn test_cbr_local_above_one_raises() {
600        let mut alg = DccAdaptive::default();
601        let res = alg.update_local(1.01, 0.5);
602        assert!(matches!(
603            res,
604            Err(DccError::InvalidCbr {
605                name: "cbr_local",
606                ..
607            })
608        ));
609    }
610
611    #[test]
612    fn test_cbr_local_previous_below_zero_raises() {
613        let mut alg = DccAdaptive::default();
614        let res = alg.update_local(0.5, -0.01);
615        assert!(matches!(
616            res,
617            Err(DccError::InvalidCbr {
618                name: "cbr_local_previous",
619                ..
620            })
621        ));
622    }
623
624    #[test]
625    fn test_cbr_local_previous_above_one_raises() {
626        let mut alg = DccAdaptive::default();
627        let res = alg.update_local(0.5, 1.01);
628        assert!(matches!(
629            res,
630            Err(DccError::InvalidCbr {
631                name: "cbr_local_previous",
632                ..
633            })
634        ));
635    }
636
637    #[test]
638    fn test_boundary_values_valid() {
639        let mut alg = DccAdaptive::default();
640        assert!(alg.update_local(0.0, 0.0).is_ok());
641        assert!(alg.update_local(1.0, 1.0).is_ok());
642    }
643
644    // ── GateKeeper Initialisation ─────────────────────────────────────────
645
646    #[test]
647    fn test_gate_is_open_initially() {
648        let gk = GateKeeper::new(0.01);
649        assert!(gk.is_open(0.0));
650    }
651
652    #[test]
653    fn test_gate_is_open_at_any_time_initially() {
654        let gk = GateKeeper::new(0.01);
655        for &t in &[0.0, 100.0, -1.0] {
656            assert!(gk.is_open(t));
657        }
658    }
659
660    // ── GateKeeper Admission ──────────────────────────────────────────────
661
662    #[test]
663    fn test_first_packet_admitted() {
664        let mut gk = GateKeeper::new(0.01);
665        assert!(gk.admit_packet(0.0, 0.001).unwrap());
666    }
667
668    #[test]
669    fn test_gate_closed_after_admission() {
670        let mut gk = GateKeeper::new(0.01);
671        gk.admit_packet(0.0, 0.001).unwrap();
672        assert!(!gk.is_open(0.0));
673    }
674
675    #[test]
676    fn test_second_packet_rejected_when_gate_closed() {
677        let mut gk = GateKeeper::new(0.01);
678        assert!(gk.admit_packet(0.0, 0.001).unwrap());
679        assert!(!gk.admit_packet(0.0, 0.001).unwrap());
680    }
681
682    #[test]
683    fn test_gate_opens_after_t_go() {
684        let mut gk = GateKeeper::new(0.01);
685        gk.admit_packet(0.0, 0.001).unwrap(); // t_go = 0.0 + 0.1 = 0.1
686        assert!(!gk.is_open(0.099));
687        assert!(gk.is_open(0.1));
688    }
689
690    #[test]
691    fn test_minimum_interval_enforced() {
692        let mut gk = GateKeeper::new(1.0);
693        gk.admit_packet(0.0, 0.001).unwrap();
694        assert!(!gk.is_open(0.024));
695        assert!(gk.is_open(0.025));
696    }
697
698    #[test]
699    fn test_maximum_interval_enforced() {
700        let mut gk = GateKeeper::new(0.0006);
701        gk.admit_packet(0.0, 0.001).unwrap();
702        assert!(!gk.is_open(0.99));
703        assert!(gk.is_open(1.0));
704    }
705
706    #[test]
707    fn test_t_on_zero_raises() {
708        let mut gk = GateKeeper::new(0.01);
709        assert!(matches!(
710            gk.admit_packet(0.0, 0.0),
711            Err(DccError::InvalidTon(_))
712        ));
713    }
714
715    #[test]
716    fn test_t_on_negative_raises() {
717        let mut gk = GateKeeper::new(0.01);
718        assert!(matches!(
719            gk.admit_packet(0.0, -0.001),
720            Err(DccError::InvalidTon(_))
721        ));
722    }
723
724    // ── GateKeeper Update Delta ───────────────────────────────────────────
725
726    #[test]
727    fn test_update_delta_when_gate_open_only_changes_delta() {
728        let mut gk = GateKeeper::new(0.01);
729        gk.update_delta(0.0, 0.02).unwrap();
730        assert!(gk.is_open(0.0));
731    }
732
733    #[test]
734    fn test_update_delta_rescales_interval_when_delta_increases() {
735        let mut gk = GateKeeper::new(0.01);
736        gk.admit_packet(0.0, 0.001).unwrap(); // t_go = 0.1
737        gk.update_delta(0.0, 0.02).unwrap(); // t_go -> 0.05
738        assert!(!gk.is_open(0.049));
739        assert!(gk.is_open(0.05));
740    }
741
742    #[test]
743    fn test_update_delta_rescales_interval_when_delta_decreases() {
744        let mut gk = GateKeeper::new(0.02);
745        gk.admit_packet(0.0, 0.001).unwrap(); // t_go = 0.05
746        gk.update_delta(0.0, 0.01).unwrap(); // t_go -> 0.1
747        assert!(!gk.is_open(0.099));
748        assert!(gk.is_open(0.1));
749    }
750
751    #[test]
752    fn test_update_delta_minimum_interval_enforced() {
753        let mut gk = GateKeeper::new(0.01);
754        gk.admit_packet(0.0, 0.001).unwrap();
755        gk.update_delta(0.0, 0.1).unwrap();
756        assert!(!gk.is_open(0.024));
757        assert!(gk.is_open(0.025));
758    }
759
760    #[test]
761    fn test_update_delta_maximum_interval_enforced() {
762        let mut gk = GateKeeper::new(0.02);
763        gk.admit_packet(0.0, 0.001).unwrap();
764        gk.update_delta(0.0, 0.0001).unwrap();
765        assert!(!gk.is_open(0.99));
766        assert!(gk.is_open(1.0));
767    }
768
769    #[test]
770    fn test_update_delta_zero_raises() {
771        let mut gk = GateKeeper::new(0.01);
772        assert!(matches!(
773            gk.update_delta(0.0, 0.0),
774            Err(DccError::InvalidDelta(_))
775        ));
776    }
777
778    #[test]
779    fn test_update_delta_negative_raises() {
780        let mut gk = GateKeeper::new(0.01);
781        assert!(matches!(
782            gk.update_delta(0.0, -0.01),
783            Err(DccError::InvalidDelta(_))
784        ));
785    }
786
787    #[test]
788    fn test_update_after_gate_reopens_no_rescheduling() {
789        let mut gk = GateKeeper::new(0.01);
790        gk.admit_packet(0.0, 0.001).unwrap(); // t_go = 0.1
791        gk.update_delta(0.5, 0.005).unwrap();
792        assert!(gk.is_open(0.5));
793    }
794
795    // ── Integration ───────────────────────────────────────────────────────
796
797    #[test]
798    fn test_gate_keeper_uses_updated_delta() {
799        let mut gk = GateKeeper::new(0.01);
800        gk.admit_packet(0.0, 0.001).unwrap(); // t_go = 0.1
801
802        assert!(gk.is_open(0.1));
803        gk.update_delta(0.1, 0.02).unwrap();
804        gk.admit_packet(0.1, 0.001).unwrap(); // t_go = 0.1 + 0.001/0.02 = 0.1 + 0.05 = 0.15
805        assert!(!gk.is_open(0.14));
806        assert!(gk.is_open(0.15));
807    }
808}