Skip to main content

subetha_cxc/
sens_unified.rs

1//! Unified Sens-O-Matic endpoint: one transport that carries BOTH erasure
2//! codes and switches between them mid-stream on the loss the receiver
3//! already measures and feeds back.
4//!
5//! Sens-O-Matic treats the erasure code as a swappable detail (like a cipher
6//! suite): the sliding-window Random Linear Code ([`crate::sens_rlc`]) and the
7//! block Cauchy Reed-Solomon code ([`crate::udp_bridge`]) deliver every item
8//! in order, differing only in HOW they recover loss. Their operating regimes
9//! are complementary, and the boundary is a measured loss level:
10//!
11//!  - **RLC wins at low-to-moderate loss** - incremental forward recovery from
12//!    the next repair (no block-wait, no retransmit round trip), so it holds a
13//!    low latency tail, and its sliding window carries less overhead than a
14//!    block code until loss is dense.
15//!  - **RS wins at high sustained loss** - a systematic MDS block code recovers
16//!    any `r` erasures per `k + r` shards, the most parity-efficient recovery
17//!    once loss is dense. Critically, RLC's adaptive redundancy hard-caps at
18//!    one repair per source symbol (50% redundancy, `STEP_MIN = 1` in
19//!    [`crate::rlc_control`]), so above the loss its rate law saturates at it
20//!    cannot provision enough and its goodput collapses; RS's `r` has no such
21//!    ceiling (`k + r <= 256`).
22//!
23//! The crossover sits at roughly **22-25% loss** when both codes are provisioned
24//! for the loss level (RLC's flow window sized to the path BDP, RS's parity
25//! provisioned per loss). It is lower on a high-RTT path because RLC's rate-law
26//! margin grows with the round trip and drives the code to its redundancy
27//! ceiling at a lower loss. The loss-driven switch moves UP to RS at the
28//! crossover (~23.5%, `q8 = 60`) and back DOWN to RLC at ~12% (a wide hysteresis
29//! band, so a loss level hovering at the boundary does not flap). A persistent
30//! RLC flow-block escapes to RS on its own, the backstop for a path whose
31//! crossover sits below the threshold, where RLC would stall before the loss
32//! reading crosses it.
33//!
34//! The switch is driven by the FEEDBACK frame's loss byte (`loss_q8`, the
35//! forward loss quantized to a `u8` as `loss * 256`), which both codes' senders
36//! already receive over the control plane. `CodeSwitchController` applies the
37//! threshold with immediate-up / conservative-down hysteresis (the same shape
38//! as [`crate::rlc_control::RlcController`]): it raises protection - switching
39//! to the stronger high-loss code - the instant the loss sustains above the up
40//! threshold, but only relaxes back to RLC after the loss sustains below the
41//! down threshold for `hold` ticks, since dropping the stronger code under a
42//! brief quiet spell risks a recovery gap.
43
44use std::collections::VecDeque;
45use std::io;
46use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
47use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
48use std::sync::{Arc, Mutex};
49use std::thread::JoinHandle;
50use std::time::{Duration, Instant};
51
52use crate::dgram::{new_demux_queue, DemuxQueue, DgramSock};
53use crate::sens_rlc::{SensOMaticRlcReceiver, SensOMaticRlcSender};
54use crate::udp_bridge::{ReliableUdpReceiver, ReliableUdpSender};
55
56/// Which erasure code the unified transport is currently carrying.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum SensCode {
59    /// Sliding-window Random Linear Code (low-to-moderate loss, low latency).
60    Rlc,
61    /// Block Cauchy Reed-Solomon (high sustained loss, parity-efficient).
62    Rs,
63}
64
65/// How the unified transport selects its erasure code.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum CodePolicy {
68    /// Loss-driven with hysteresis. `up_q8` / `down_q8` are forward-loss
69    /// thresholds (quantized `loss * 256`, matching the FEEDBACK frame):
70    /// switch RLC -> RS when loss sustains above `up_q8`, RS -> RLC when it
71    /// sustains below `down_q8`. `up_q8 > down_q8` is the hysteresis band.
72    Auto { up_q8: u8, down_q8: u8 },
73    /// Force the sliding-window RLC code regardless of loss (operator override).
74    ForceRlc,
75    /// Force the block Reed-Solomon code regardless of loss (operator override).
76    ForceRs,
77}
78
79impl CodePolicy {
80    /// The default loss-driven policy, thresholds set from the measured crossover
81    /// with RS provisioned to cover the loss: switch UP to RS at ~15%
82    /// (`q8 = CROSSOVER_LOSS_Q8 = 38`, where RS overtakes RLC on both throughput
83    /// and bounded tail latency) and back DOWN to RLC at ~10% (`q8 = 26`). RLC
84    /// keeps the sub-crossover regime for its lower TTFD / median; the ~5-point
85    /// hysteresis band keeps a loss level hovering at the boundary from flapping
86    /// the code.
87    pub fn default_auto() -> Self {
88        CodePolicy::Auto { up_q8: CROSSOVER_LOSS_Q8, down_q8: 26 }
89    }
90
91    /// The code this policy starts a connection on. Auto and ForceRlc start on
92    /// RLC (the low-latency primary); ForceRs starts on RS.
93    pub fn initial_code(&self) -> SensCode {
94        match self {
95            CodePolicy::ForceRs => SensCode::Rs,
96            CodePolicy::Auto { .. } | CodePolicy::ForceRlc => SensCode::Rlc,
97        }
98    }
99}
100
101/// Loss in q8 (the FEEDBACK frame's `loss * 256`) at the measured crossover
102/// where block-RS overtakes sliding-window RLC: ~15% (38/256). RS provisions
103/// parity to cover the loss (Encoder::set_parity_covering) and then wins both
104/// throughput and bounded tail latency from ~15% up; RLC keeps the low-loss
105/// edge (lower TTFD / median, incremental delivery). The earlier 23.5% pin was
106/// measured against RS capped at r=8 (33% recovery), which understated RS.
107pub const CROSSOVER_LOSS_Q8: u8 = 38;
108
109/// Immediate-up / conservative-down controller that turns a stream of fed-back
110/// `loss_q8` samples into code-switch decisions under a [`CodePolicy`].
111///
112/// Up-switches (to the stronger high-loss RS code) fire the instant the loss
113/// sustains above the up threshold for `up_hold` samples; down-switches (back
114/// to RLC) require `down_hold` sustained-below samples, a longer streak, so a
115/// brief lull does not strip the stronger code while loss is still bursty.
116#[derive(Debug, Clone)]
117pub struct CodeSwitchController {
118    policy: CodePolicy,
119    code: SensCode,
120    up_streak: u32,
121    down_streak: u32,
122    up_hold: u32,
123    down_hold: u32,
124    switches: u64,
125    /// Set when a flow-block ESCAPE (not a loss-threshold up-switch) moved to RS:
126    /// RLC stalled at this loss, so a down-switch back would just stall again and
127    /// flap. The latch suppresses the down-switch after a stall-escape (the loss
128    /// estimate at a stall-loss can sit below the down threshold, which would
129    /// otherwise pull straight back to a code that cannot keep up).
130    escape_latched: bool,
131}
132
133impl CodeSwitchController {
134    /// A controller under `policy`, starting on the policy's initial code.
135    /// `up_hold` consecutive over-threshold samples confirm an up-switch;
136    /// `down_hold` (typically larger) under-threshold samples confirm the
137    /// relax back to RLC.
138    pub fn new(policy: CodePolicy, up_hold: u32, down_hold: u32) -> Self {
139        Self {
140            policy,
141            code: policy.initial_code(),
142            up_streak: 0,
143            down_streak: 0,
144            up_hold: up_hold.max(1),
145            down_hold: down_hold.max(1),
146            switches: 0,
147            escape_latched: false,
148        }
149    }
150
151    /// A controller with sensible default holds: an up-switch confirms in 3
152    /// feedback intervals (loss spiked and held, robust to window noise), a
153    /// down-switch in 8 (loss must stay low a while before dropping the
154    /// stronger code).
155    pub fn with_policy(policy: CodePolicy) -> Self {
156        Self::new(policy, 3, 8)
157    }
158
159    /// The code currently selected.
160    pub fn code(&self) -> SensCode {
161        self.code
162    }
163
164    /// Total confirmed code switches so far (telemetry).
165    pub fn switches(&self) -> u64 {
166        self.switches
167    }
168
169    /// Feed one fed-back forward-loss sample (`loss_q8 = loss * 256`). Returns
170    /// `Some(new_code)` exactly on the sample that confirms a switch, else
171    /// `None`. A forced policy never switches.
172    pub fn observe(&mut self, loss_q8: u8) -> Option<SensCode> {
173        let (up_q8, down_q8) = match self.policy {
174            CodePolicy::ForceRlc | CodePolicy::ForceRs => return None,
175            CodePolicy::Auto { up_q8, down_q8 } => (up_q8, down_q8),
176        };
177        match self.code {
178            SensCode::Rlc => {
179                if loss_q8 >= up_q8 {
180                    self.up_streak += 1;
181                    self.down_streak = 0;
182                    if self.up_streak >= self.up_hold {
183                        self.code = SensCode::Rs;
184                        self.up_streak = 0;
185                        self.switches += 1;
186                        return Some(SensCode::Rs);
187                    }
188                } else {
189                    self.up_streak = 0;
190                }
191            }
192            SensCode::Rs => {
193                if !self.escape_latched && loss_q8 <= down_q8 {
194                    self.down_streak += 1;
195                    self.up_streak = 0;
196                    if self.down_streak >= self.down_hold {
197                        self.code = SensCode::Rlc;
198                        self.down_streak = 0;
199                        self.switches += 1;
200                        return Some(SensCode::Rlc);
201                    }
202                } else {
203                    self.down_streak = 0;
204                }
205            }
206        }
207        None
208    }
209
210    /// Align the controller to `to` for a switch driven OUTSIDE `observe` (the
211    /// flow-block escape), counting it and resetting the hysteresis streaks so the
212    /// band restarts from the new code. Returns whether it switched: a forced
213    /// policy stays put (returns `false`), as does an already-on-`to` controller.
214    pub fn force(&mut self, to: SensCode) -> bool {
215        if matches!(self.policy, CodePolicy::ForceRlc | CodePolicy::ForceRs) {
216            return false;
217        }
218        if self.code != to {
219            self.code = to;
220            self.switches += 1;
221            self.up_streak = 0;
222            self.down_streak = 0;
223            // A stall-escape to RS latches the code: RLC could not keep up at this
224            // loss, so suppress the down-switch that would flap straight back. A
225            // deliberate return to RLC (operator force) re-arms the down direction.
226            self.escape_latched = to == SensCode::Rs;
227            true
228        } else {
229            false
230        }
231    }
232}
233
234// ---------------------------------------------------------------------------
235// CODE_SWITCH control frame + first-byte demux
236// ---------------------------------------------------------------------------
237
238/// CODE_SWITCH control-frame type byte. Disjoint from RS data (1) / control
239/// (4), the RLC frames (10..=14), and QUIC (first byte has 0x40 set), so one
240/// socket demuxes all of them unambiguously by the first wire byte.
241pub const PKT_CODE_SWITCH: u8 = 9;
242
243/// Wire: `[9][boundary u64-le][to_code u8]`. `boundary` is the count of items
244/// the sender has delivered across both codes up to the switch; the receiver
245/// keeps draining the old decoder until its cumulative delivery reaches it,
246/// then activates `to_code`. 10 bytes.
247fn encode_code_switch(boundary: u64, to: SensCode) -> [u8; 10] {
248    let mut v = [0u8; 10];
249    v[0] = PKT_CODE_SWITCH;
250    v[1..9].copy_from_slice(&boundary.to_le_bytes());
251    v[9] = match to {
252        SensCode::Rlc => 0,
253        SensCode::Rs => 1,
254    };
255    v
256}
257
258fn decode_code_switch(buf: &[u8]) -> Option<(u64, SensCode)> {
259    if buf.len() < 10 || buf[0] != PKT_CODE_SWITCH {
260        return None;
261    }
262    let boundary = u64::from_le_bytes(buf[1..9].try_into().ok()?);
263    let to = if buf[9] == 0 { SensCode::Rlc } else { SensCode::Rs };
264    Some((boundary, to))
265}
266
267/// One CODE_SWITCH the demux reader observed (receiver side).
268pub(crate) type SwitchSignal = Arc<Mutex<Option<(u64, SensCode)>>>;
269
270/// Unified raw-loss feedback frame type byte. Disjoint from RS (1 / 4), RLC
271/// (10..=14), CODE_SWITCH (9), and QUIC (first byte 0x40 set).
272pub const PKT_UNIFIED_FB: u8 = 8;
273
274/// Wire: `[8][received u64-le]` - the receiver's cumulative count of forward
275/// data/repair datagrams seen. The sender pairs it with its own sent count to
276/// get the true raw channel loss, independent of either code's recovery.
277fn encode_unified_fb(received: u64) -> [u8; 9] {
278    let mut v = [0u8; 9];
279    v[0] = PKT_UNIFIED_FB;
280    v[1..9].copy_from_slice(&received.to_le_bytes());
281    v
282}
283
284fn decode_unified_fb(buf: &[u8]) -> Option<u64> {
285    if buf.len() < 9 || buf[0] != PKT_UNIFIED_FB {
286        return None;
287    }
288    Some(u64::from_le_bytes(buf[1..9].try_into().ok()?))
289}
290
291/// How often the receiver reports its cumulative received-datagram count.
292const UNIFIED_FB_PERIOD: Duration = Duration::from_millis(50);
293/// Minimum datagrams sent in a sample window before the raw-loss estimate is
294/// trusted (a tiny window is too noisy to switch on).
295const MIN_LOSS_SAMPLE: u64 = 30;
296
297/// Route one inbound Sens datagram (already classified as non-QUIC) to the
298/// matching per-code queue by its first byte, tallying forward data/repair for
299/// the raw-loss numerator and capturing CODE_SWITCH / UNIFIED_FB control. Shared
300/// by the standalone demux reader thread and the one-port QUIC demux socket.
301#[allow(clippy::too_many_arguments)]
302pub(crate) fn route_sens_inbound(
303    data: Vec<u8>,
304    from: SocketAddr,
305    kts: Option<i128>,
306    rlc_q: &DemuxQueue,
307    rs_q: &DemuxQueue,
308    switch_signal: Option<&SwitchSignal>,
309    fb_received: Option<&AtomicU64>,
310    recv_counter: Option<&AtomicU64>,
311    hs_q: Option<&DemuxQueue>,
312) {
313    let b0 = data.first().copied().unwrap_or(0);
314    if let Some(c) = recv_counter
315        && (b0 == 1 || b0 == 10 || b0 == 11)
316    {
317        c.fetch_add(1, Ordering::Relaxed);
318    }
319    if b0 == 1 || b0 == 4 {
320        rs_q.lock().unwrap().push_back((data, from, kts));
321    } else if (10..=14).contains(&b0)
322        || b0 == crate::sens_rlc::PKT_RLC_PATH_CHALLENGE
323        || b0 == crate::sens_rlc::PKT_RLC_PATH_RESPONSE
324    {
325        // The RLC data range plus the two path-validation frames. Named
326        // rather than folded into the range, which would swallow the crypto
327        // types the next arm routes to the handshake driver.
328        rlc_q.lock().unwrap().push_back((data, from, kts));
329    } else if (b0 == 15 || b0 == 16)
330        && let Some(hq) = hs_q
331    {
332        // PKT_RLC_CRYPTO (15) / PKT_RLC_CRYPTO_ACK (16): the one-port Sens TLS
333        // handshake. The standalone path completes its handshake before the demux
334        // reader starts, so it passes `None` and these never arrive there; the
335        // one-port path routes them to the handshake driver's queue.
336        hq.lock().unwrap().push_back((data, from, kts));
337    } else if b0 == PKT_UNIFIED_FB
338        && let (Some(fb), Some(v)) = (fb_received, decode_unified_fb(&data))
339    {
340        fb.store(v, Ordering::Relaxed);
341    } else if b0 == PKT_CODE_SWITCH
342        && let (Some(sig), Some(p)) = (switch_signal, decode_code_switch(&data))
343    {
344        *sig.lock().unwrap() = Some(p);
345    }
346}
347
348/// splitmix64 step: a cheap, seedable PRNG for the demux loss injector.
349fn next_rand(state: &mut u64) -> u64 {
350    *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
351    let mut z = *state;
352    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
353    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
354    z ^ (z >> 31)
355}
356
357/// Spawn the demux reader: read the one real socket and route each datagram to
358/// the matching code's queue by its first byte. The classification is a single
359/// byte compare per datagram (the hot path stays branch-light; the per-code
360/// decoders carry their own GF(256) SIMD). A `switch_signal` (receiver side)
361/// captures CODE_SWITCH frames; on the sender side it is `None` and any stray
362/// CODE_SWITCH is dropped.
363#[allow(clippy::too_many_arguments)]
364fn spawn_demux(
365    sock: UdpSocket,
366    rlc_q: DemuxQueue,
367    rs_q: DemuxQueue,
368    switch_signal: Option<SwitchSignal>,
369    recv_counter: Option<Arc<AtomicU64>>,
370    fb_received: Option<Arc<AtomicU64>>,
371    loss_pct: u32,
372    seed: u64,
373    stop: Arc<AtomicBool>,
374) -> JoinHandle<()> {
375    std::thread::spawn(move || {
376        let mut buf = vec![0u8; 2048];
377        let mut last_from: Option<SocketAddr> = None;
378        let mut last_fb = Instant::now();
379        let mut rng = seed;
380        while !stop.load(Ordering::Relaxed) {
381            match crate::dgram::udp_recv_with_kts(&sock, &mut buf) {
382                Ok((n, from, kts)) if n > 0 => {
383                    let b0 = buf[0];
384                    last_from = Some(from);
385                    // Uniform link-loss injection on the forward data/repair
386                    // stream (RS data 1, RLC data 10 / repair 11): drop BEFORE
387                    // counting or routing, so the raw-loss estimate AND the codes
388                    // both see a realistic lossy link. Control frames pass.
389                    let is_fwd = b0 == 1 || b0 == 10 || b0 == 11;
390                    let dropped =
391                        loss_pct > 0 && is_fwd && (next_rand(&mut rng) % 100) < loss_pct as u64;
392                    if !dropped {
393                        // QUIC (0x40 bit set) and unknown first bytes are dropped
394                        // by route_sens_inbound; the one-port quinn demux consumes
395                        // QUIC separately.
396                        route_sens_inbound(
397                            buf[..n].to_vec(),
398                            from,
399                            kts,
400                            &rlc_q,
401                            &rs_q,
402                            switch_signal.as_ref(),
403                            fb_received.as_deref(),
404                            recv_counter.as_deref(),
405                            // Standalone path: the handshake completed before this
406                            // reader started, so no crypto frames arrive here.
407                            None,
408                        );
409                    }
410                }
411                Ok(_) => {}
412                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
413                    std::thread::sleep(Duration::from_micros(100));
414                }
415                Err(e) if e.kind() == io::ErrorKind::TimedOut => {}
416                Err(_) => std::thread::sleep(Duration::from_micros(200)),
417            }
418            // Receiver: report the cumulative received-datagram count back so
419            // the sender derives the true raw channel loss (sent vs received),
420            // which neither code's post-recovery feedback reveals.
421            if let (Some(c), Some(dst)) = (&recv_counter, last_from)
422                && last_fb.elapsed() >= UNIFIED_FB_PERIOD
423            {
424                last_fb = Instant::now();
425                let frame = encode_unified_fb(c.load(Ordering::Relaxed));
426                sock.send_to(&frame, dst).ok();
427            }
428        }
429    })
430}
431
432/// How often the sender samples the fed-back loss and asks the controller for a
433/// switch. Time-based (not per-item) so the controller's hold counts track the
434/// receiver's ~10ms feedback cadence rather than the item rate.
435const SWITCH_SAMPLE_PERIOD: Duration = Duration::from_millis(50);
436/// Warmup before the switch is evaluated: the in-flight window ramps from 0 to
437/// the flow window at connection start, and that growth reads as loss; wait for
438/// it to stabilize so the ramp does not trip a spurious switch.
439const SWITCH_WARMUP: Duration = Duration::from_millis(1000);
440/// Feedback windows accumulated AFTER the warmup before the loss estimate is
441/// trusted to move the code. The decaying accumulator is cold at warmup-end (its
442/// first window's raw ratio dominates), so a start-of-stream retransmit burst
443/// reads as a spike that crosses the up threshold and flaps the code. Holding the
444/// switch until a few windows have decayed in lets the estimate mature first.
445const MIN_ACCUM_WINDOWS: u32 = 6;
446/// Drain deadline for a code handover (the in-flight tail of the old code must
447/// be delivered before the new code starts, for in-order delivery).
448const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
449/// How long RLC's DELIVERY FRONTIER may stay stuck (no item delivered while the
450/// send window is full) before the transport gives up on RLC and migrates to RS.
451/// This is the genuine-deadlock backstop: a frontier that does not advance for
452/// this long means RLC cannot decode the loss it is seeing (extreme loss past its
453/// redundancy ceiling), which the loss-driven `maybe_switch` cannot catch because
454/// a stalled sender produces no fresh loss sample. It is measured against frontier
455/// progress (the send loop resets the timer whenever a delivery lands), so a
456/// recoverable hard gap at sub-ceiling loss does NOT trip it - only a true stall.
457/// Measured against frontier progress, so it fires fast (the stalling unified RLC
458/// needs prompt rescue - a slower value starves it into a multi-second stall).
459const RLC_BLOCK_ESCAPE: Duration = Duration::from_millis(750);
460/// Drain deadline for the flow-block escape specifically: the stuck window's
461/// frontier is retransmitted (over a high-loss link, so each copy may also be
462/// lost) until fully delivered, so it must be generous enough to land every item
463/// before RS takes over (no gap = in-order delivery preserved).
464const ESCAPE_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
465/// Hard cap on the sender-side replay ring (items). The ring normally holds only
466/// the un-acked tail `[acked_through, items_total)` (evicted as RLC confirms
467/// delivery), but at extreme loss that tail can grow; this bounds the memory. If
468/// the un-acked tail ever exceeds the cap, the RLC->RS handover falls back to
469/// draining RLC so no item is dropped. 65536 * symbol covers the worst observed
470/// 30%-loss tail with headroom.
471const SENT_RING_CAP: usize = 65536;
472/// Recycled replay-ring buffers held for reuse. A trimmed (delivered) buffer is
473/// returned here instead of freed, and the next seal reuses it instead of
474/// allocating - so the per-item path does no heap alloc/free in steady state.
475/// Sized to the in-flight working set (a few flow-windows) rather than the full
476/// ring cap: the pool only needs to bridge trim-tail to send-head, and capping it
477/// keeps idle memory bounded when the ring shrinks. At small item sizes (where the
478/// item rate, and thus the alloc churn, is highest) this removes ~190k alloc/free
479/// pairs per second from the hot path.
480const RING_POOL_CAP: usize = 1024;
481/// CODE_SWITCH is a one-off control frame sent on the (drained, quiet) path at
482/// the switch point; send it a few times so a single drop does not strand the
483/// receiver on the old decoder.
484const CODE_SWITCH_REPEATS: usize = 6;
485
486// ---------------------------------------------------------------------------
487// Unified sender
488// ---------------------------------------------------------------------------
489
490/// Background reporter for the one-port path: periodically send the cumulative
491/// received-datagram count to the Sens peer (the raw-loss numerator). The QUIC
492/// demux socket feeds the receiver's queues, so there is no demux thread to do
493/// it; this small thread covers just the feedback send.
494fn spawn_fb_reporter(
495    sock: Arc<UdpSocket>,
496    recv_counter: Arc<AtomicU64>,
497    peer: Arc<Mutex<Option<SocketAddr>>>,
498    stop: Arc<AtomicBool>,
499) -> JoinHandle<()> {
500    std::thread::spawn(move || {
501        while !stop.load(Ordering::Relaxed) {
502            std::thread::sleep(UNIFIED_FB_PERIOD);
503            if let Some(dst) = *peer.lock().unwrap() {
504                let frame = encode_unified_fb(recv_counter.load(Ordering::Relaxed));
505                sock.send_to(&frame, dst).ok();
506            }
507        }
508    })
509}
510
511/// Construction parameters shared by the unified sender and receiver.
512#[derive(Debug, Clone, Copy)]
513pub struct UnifiedConfig {
514    /// Erasure-code selection policy (loss-driven Auto, or a forced code).
515    pub policy: CodePolicy,
516    /// Item / symbol size in bytes (matches the application's record size).
517    pub symbol_len: usize,
518    /// Reed-Solomon block geometry: `k` data shards.
519    pub k: usize,
520    /// Reed-Solomon base parity shards `r` (the receiver provisions per loss).
521    pub r: usize,
522    /// RLC sender flow window (outstanding source symbols); 0 = transport
523    /// default. Size it to the path BDP so RLC fills the pipe (the fair-A/B
524    /// config; the default caps RLC ~2x below its capability on a high-BDP path).
525    pub rlc_flow_window: u32,
526    /// Receiver-side diagnostic loss injection (percent, 0 = off) applied to
527    /// BOTH decoders, with `seed` for reproducibility. Drives the loss-based
528    /// switch without a real lossy link.
529    pub debug_loss: u32,
530    /// Seed for the reproducible `debug_loss` drop sequence.
531    pub seed: u64,
532    /// RLC repair cadence: one repair every `rlc_step` source symbols (redundancy
533    /// `1/(rlc_step+1)`). The starting value; the adaptive controller retunes it
534    /// per measured loss unless `rlc_static` pins it.
535    pub rlc_step: u16,
536    /// Pin the RLC coding parameters (disable the adaptive controller), holding a
537    /// fixed code rate instead of letting the sensing plane retune window / step /
538    /// density. The adaptive controller's disable-on-clean state drops coding
539    /// entirely on a quiet assessment and then pays an ARQ round trip on the next
540    /// loss; pinning trades that latency risk for a constant redundancy.
541    pub rlc_static: bool,
542}
543
544impl UnifiedConfig {
545    /// Defaults: loss-driven Auto policy, MTU-sized items, RS (8, 2), RLC flow
546    /// window sized for a filled BDP, no injected loss.
547    pub fn new(symbol_len: usize) -> Self {
548        Self {
549            policy: CodePolicy::default_auto(),
550            symbol_len,
551            k: 8,
552            r: 2,
553            rlc_flow_window: 4096,
554            debug_loss: 0,
555            seed: 1,
556            rlc_step: 4,
557            rlc_static: false,
558        }
559    }
560}
561
562/// Unified Sens-O-Matic sender: carries items over whichever erasure code the
563/// loss-driven controller selects, switching RLC <-> RS mid-stream via a
564/// drain-barrier handover. One real socket is shared by both codes through
565/// per-code demux queues fed by a background reader.
566pub struct UnifiedSensSender {
567    real: Arc<UdpSocket>,
568    peer: SocketAddr,
569    rlc: SensOMaticRlcSender,
570    rs: ReliableUdpSender,
571    active: SensCode,
572    ctrl: CodeSwitchController,
573    /// Cumulative items handed to the application across both codes (the switch
574    /// boundary the receiver keys on).
575    items_total: u64,
576    last_sample: Instant,
577    /// Connection start, for the switch-evaluation warmup.
578    started: Instant,
579    /// Datagrams sent through both codes' demux sockets (raw-loss numerator).
580    sent_counter: Arc<AtomicU64>,
581    /// Receiver's last-reported cumulative received-datagram count.
582    fb_received: Arc<AtomicU64>,
583    /// Sent / received baselines captured at the previous evaluated window.
584    prev_sent: u64,
585    prev_received: u64,
586    /// Size-weighted decaying raw-loss estimate (-1 = uninitialized). Decay the
587    /// lost / sent COUNTS (`loss_acc` / `sent_acc`) and take their ratio, rather
588    /// than EWMA-ing per-window ratios: a small feedback window with one drop
589    /// reads a spuriously high ratio, and an equal-weight EWMA of ratios over-
590    /// weights it, inflating the estimate at low loss (3% read as ~11%). Weighting
591    /// by datagram count makes the estimate track the true channel loss.
592    ewma_loss: f64,
593    /// Decaying sums of lost and sent forward datagrams (the size-weighted
594    /// estimate's numerator / denominator); their ratio is `ewma_loss`.
595    loss_acc: f64,
596    sent_acc: f64,
597    /// Feedback windows accumulated since the warmup ended. The switch is gated on
598    /// this reaching `MIN_ACCUM_WINDOWS` so a cold accumulator cannot flap the code.
599    post_warm_windows: u32,
600    /// Recently-sent item payloads, kept so a code switch can RESEND the un-acked
601    /// tail over the new code instead of slowly draining the old one. Holds the
602    /// global index range `[ring_base, items_total)`; the front is evicted once
603    /// RLC confirms delivery (its `acked_through`) and is hard-capped so a stalled
604    /// receiver cannot grow it without bound. This is the sender-side replay ring.
605    sent_ring: VecDeque<Vec<u8>>,
606    /// Global index of `sent_ring[0]` (the oldest retained item).
607    ring_base: u64,
608    /// Recycled wire-payload buffers (capacity retained, length reset). Trimmed
609    /// ring buffers land here; the next seal pops one instead of allocating.
610    ring_pool: Vec<Vec<u8>>,
611    /// Unified AEAD record layer (TLS feature). When set, every item payload is
612    /// sealed before it enters the replay ring and goes to either code, so the
613    /// RLC<->RS switch is crypto-transparent and the wire is confidential. The
614    /// seal packet number is the item's global index (sealed once, in order), so
615    /// a resend reuses it and the receiver opens by index.
616    #[cfg(feature = "tls")]
617    crypto: Option<crate::rlc_crypto::CryptoState>,
618    stop: Arc<AtomicBool>,
619    demux: Option<JoinHandle<()>>,
620}
621
622impl UnifiedSensSender {
623    /// Bind a local socket, connect to `peer`, and bring up both codes sharing
624    /// it. Starts on the policy's initial code (RLC for Auto / ForceRlc).
625    pub fn connect<A: ToSocketAddrs>(local: A, peer: SocketAddr, cfg: UnifiedConfig) -> io::Result<Self> {
626        let udp = UdpSocket::bind(local)?;
627        udp.set_nonblocking(true)?;
628        Self::assemble(udp, peer, cfg, 0)
629    }
630
631    /// Like [`connect`](Self::connect) but runs a TLS 1.3 handshake to `peer`
632    /// first and AEAD-seals every item: the auto-switching transport made
633    /// confidential for an untrusted WAN. The handshake completes before the
634    /// demux reader takes the socket, so its frames never reach the data path.
635    #[cfg(feature = "tls")]
636    pub fn connect_tls<A: ToSocketAddrs>(
637        local: A,
638        peer: SocketAddr,
639        cfg: UnifiedConfig,
640        tls: std::sync::Arc<rustls::ClientConfig>,
641    ) -> io::Result<Self> {
642        let udp = UdpSocket::bind(local)?;
643        udp.set_nonblocking(true)?;
644        let mut cs = crate::rlc_crypto::CryptoState::new_client(tls)
645            .map_err(io::Error::other)?;
646        let hs = DgramSock::from_udp(udp.try_clone()?);
647        crate::sens_rlc::drive_handshake(&hs, Some(peer), &mut cs, true)?;
648        let mut s = Self::assemble(udp, peer, cfg, crate::rlc_crypto::TAG_LEN)?;
649        s.crypto = Some(cs);
650        Ok(s)
651    }
652
653    /// Build the sender over an already-bound (and, for TLS, already-handshaked)
654    /// socket: bring up both codes sharing it and spawn the demux reader.
655    fn assemble(
656        udp: UdpSocket,
657        peer: SocketAddr,
658        cfg: UnifiedConfig,
659        seal_overhead: usize,
660    ) -> io::Result<Self> {
661        // Both codes carry the wire payload, which is the item plus the AEAD tag
662        // when TLS is on; size their symbols for the sealed width so pack_symbol
663        // and the RS shard split never overflow.
664        let wire_sym = cfg.symbol_len + seal_overhead;
665        // Left UNCONNECTED: the per-code demux sockets send via send_to(peer),
666        // and send_to on a connected socket is rejected on Windows. The demux
667        // reader still only ever hears from `peer` on this private socket.
668        // A clone for the demux thread: UdpSocket is Send, DgramSock is not
669        // (its io_uring variant is not Send), so the thread holds the raw socket.
670        let thread_sock = udp.try_clone()?;
671        thread_sock.set_nonblocking(true)?;
672        let real = Arc::new(udp);
673        let rlc_q = new_demux_queue();
674        let rs_q = new_demux_queue();
675        let sent_counter = Arc::new(AtomicU64::new(0));
676        let fb_received = Arc::new(AtomicU64::new(0));
677
678        let mut rlc = SensOMaticRlcSender::bind("0.0.0.0:0", peer, 32, cfg.rlc_step as usize, 15, wire_sym)?;
679        if cfg.rlc_flow_window > 0 {
680            rlc = rlc.with_flow_window(cfg.rlc_flow_window);
681        }
682        if cfg.rlc_static {
683            rlc = rlc.with_static_params();
684        } else {
685            // The RLC leg is the latency-priority code (the switch hands bulk /
686            // high-loss traffic to block-RS). Keep a light FEC floor on at all
687            // times so an isolated loss recovers in-window instead of falling to
688            // an ARQ round trip that head-of-line-stalls the in-order stream.
689            rlc = rlc.with_latency_priority();
690        }
691        let rlc_sock = DgramSock::demux_counted(
692            Arc::clone(&real),
693            Arc::clone(&rlc_q),
694            Arc::clone(&sent_counter),
695        );
696        rlc_sock.connect(peer).ok();
697        rlc.set_sock(rlc_sock);
698
699        let mut rs = ReliableUdpSender::bind("0.0.0.0:0", peer, cfg.k, cfg.r, wire_sym)?;
700        let rs_sock = DgramSock::demux_counted(
701            Arc::clone(&real),
702            Arc::clone(&rs_q),
703            Arc::clone(&sent_counter),
704        );
705        rs_sock.connect(peer).ok();
706        rs.set_sock(rs_sock);
707
708        let stop = Arc::new(AtomicBool::new(false));
709        let demux = spawn_demux(
710            thread_sock,
711            rlc_q,
712            rs_q,
713            None,
714            None,
715            Some(Arc::clone(&fb_received)),
716            0,
717            1,
718            Arc::clone(&stop),
719        );
720
721        Ok(Self {
722            real,
723            peer,
724            rlc,
725            rs,
726            active: cfg.policy.initial_code(),
727            ctrl: CodeSwitchController::with_policy(cfg.policy),
728            items_total: 0,
729            last_sample: Instant::now(),
730            started: Instant::now(),
731            sent_counter,
732            fb_received,
733            prev_sent: 0,
734            prev_received: 0,
735            ewma_loss: -1.0,
736            loss_acc: 0.0,
737            sent_acc: 0.0,
738            post_warm_windows: 0,
739            sent_ring: VecDeque::new(),
740            ring_base: 0,
741            ring_pool: Vec::new(),
742            #[cfg(feature = "tls")]
743            crypto: None,
744            stop,
745            demux: Some(demux),
746        })
747    }
748
749    /// Fill `buf` (cleared, capacity reused) with the wire payload for `item`:
750    /// AEAD-sealed in place (TLS) or the raw bytes. Sealed once, in send order, so
751    /// the packet number equals the item's global index. Reusing a pooled `buf`
752    /// keeps the per-item send path allocation-free in steady state.
753    fn seal_into(&self, item: &[u8], buf: &mut Vec<u8>) -> io::Result<()> {
754        buf.clear();
755        buf.extend_from_slice(item);
756        #[cfg(feature = "tls")]
757        if let Some(cs) = &self.crypto {
758            cs.seal(buf).map_err(io::Error::other)?;
759        }
760        Ok(())
761    }
762
763    /// The code currently transmitting.
764    pub fn active_code(&self) -> SensCode {
765        self.active
766    }
767
768    /// Confirmed code switches so far.
769    pub fn switches(&self) -> u64 {
770        self.ctrl.switches()
771    }
772
773    /// The RLC leg's live coding parameters `(window, step, dt, coding_on)`
774    /// (telemetry: shows what the adaptive controller settled at vs the baseline).
775    pub fn rlc_coding_params(&self) -> (u16, u16, u8, bool) {
776        self.rlc.coding_params()
777    }
778
779    /// Times the RLC leg's coding parameters changed under feedback (telemetry).
780    pub fn rlc_adapt_count(&self) -> u64 {
781        self.rlc.adapt_count()
782    }
783
784    /// The switch controller's current EWMA raw-loss estimate (sent-vs-received
785    /// datagrams), 0.0..1.0, or a negative value before the first sample. This is
786    /// the signal the up/down thresholds compare against, so it shows whether the
787    /// estimate tracks the true channel loss (telemetry).
788    pub fn raw_loss_estimate(&self) -> f64 {
789        self.ewma_loss
790    }
791
792    /// Cumulative (datagrams sent through both codes' demux sockets, receiver's
793    /// last-reported forward-received count). The raw inputs to the loss estimate;
794    /// `(sent - recv) / sent` should equal the channel loss if the counts are
795    /// clean (telemetry to find a sent-side over-count / recv-side under-count).
796    pub fn raw_sent_recv(&self) -> (u64, u64) {
797        (
798            self.sent_counter.load(Ordering::Relaxed),
799            self.fb_received.load(Ordering::Relaxed),
800        )
801    }
802
803    /// Send one item over the active code, then periodically sample the fed-back
804    /// loss and switch codes if the controller calls for it. The item is recorded
805    /// in the replay ring so a switch can resend the un-acked tail over the new
806    /// code rather than draining the old one.
807    pub fn send_item(&mut self, item: &[u8]) -> io::Result<()> {
808        // Seal to the wire payload once (the packet number is this item's global
809        // index); both codes carry it and the replay ring stores it, so a resend
810        // reuses the same packet number and the switch is crypto-transparent. Seal
811        // into a recycled buffer so the hot path does no per-item heap alloc.
812        let mut payload = self.ring_pool.pop().unwrap_or_default();
813        self.seal_into(item, &mut payload)?;
814        match self.active {
815            SensCode::Rlc => {
816                // Own RLC's flow-window wait here (via the non-blocking
817                // try_send_item) instead of letting rlc.send_item block out of
818                // sight: when the window will not clear, RLC cannot decode the
819                // loss it is seeing (extreme loss past its redundancy ceiling), so
820                // a persistent block IS the trigger to migrate to RS. The loss-
821                // driven maybe_switch cannot catch this - a stalled sender emits no
822                // fresh loss sample, and the stall arrives inside the startup
823                // warmup. The handover resends the un-acked tail over RS (from the
824                // replay ring), so no slow RLC drain is needed.
825                // Progress-aware deadlock detection: escape only when RLC's
826                // delivery frontier is STUCK for RLC_BLOCK_ESCAPE, not merely when
827                // a single send flow-blocks while RLC is still delivering (slow but
828                // recovering). A blocked-but-advancing frontier is RLC working
829                // through loss at its own pace - that is the loss-threshold's job to
830                // switch on, not the deadlock backstop's; escaping there flaps the
831                // code (escape to RS, then the accurate loss estimate, being below
832                // the down threshold, switches straight back).
833                let mut escape_start = Instant::now();
834                let mut last_acked = self.rlc.acked_through();
835                loop {
836                    if self.rlc.try_send_item(&payload)? {
837                        break;
838                    }
839                    self.rlc.pump_once()?;
840                    let acked_now = self.rlc.acked_through();
841                    if acked_now > last_acked {
842                        last_acked = acked_now;
843                        escape_start = Instant::now();
844                    }
845                    if escape_start.elapsed() > RLC_BLOCK_ESCAPE {
846                        if self.ctrl.force(SensCode::Rs) {
847                            // Resend the un-acked tail [acked_through, items_total)
848                            // over RS, then this item.
849                            self.switch_rlc_to_rs()?;
850                            self.send_via_rs(&payload)?;
851                        } else {
852                            // A forced-RLC policy: honor it with the blocking send.
853                            self.rlc.send_item(&payload)?;
854                        }
855                        break;
856                    }
857                    std::thread::sleep(Duration::from_micros(50));
858                }
859            }
860            SensCode::Rs => {
861                self.send_via_rs(&payload)?;
862            }
863        }
864        // Record in the replay ring (global index = items_total), advance, and
865        // trim the delivered front + hard-cap.
866        self.sent_ring.push_back(payload);
867        self.items_total += 1;
868        self.trim_sent_ring();
869        if self.last_sample.elapsed() >= SWITCH_SAMPLE_PERIOD {
870            self.last_sample = Instant::now();
871            self.maybe_switch()?;
872        }
873        Ok(())
874    }
875
876    /// Evict replay-ring items RLC has confirmed delivered (below its cumulative
877    /// frontier) and hard-cap the ring length. Preserves the invariant
878    /// `items_total == ring_base + sent_ring.len()`.
879    fn trim_sent_ring(&mut self) {
880        if self.active == SensCode::Rlc {
881            let frontier = self.rlc.acked_through() as u64;
882            while self.ring_base < frontier && !self.sent_ring.is_empty() {
883                if let Some(buf) = self.sent_ring.pop_front() {
884                    self.recycle(buf);
885                }
886                self.ring_base += 1;
887            }
888        }
889        while self.sent_ring.len() > SENT_RING_CAP {
890            if let Some(buf) = self.sent_ring.pop_front() {
891                self.recycle(buf);
892            }
893            self.ring_base += 1;
894        }
895    }
896
897    /// Return a trimmed wire-payload buffer to the pool for reuse by the next
898    /// seal, capped so a shrinking ring does not pin idle memory.
899    fn recycle(&mut self, buf: Vec<u8>) {
900        if self.ring_pool.len() < RING_POOL_CAP {
901            self.ring_pool.push(buf);
902        }
903    }
904
905    /// RLC -> RS handover by RESEND (not drain): announce the boundary RLC has
906    /// delivered to, switch, and resend the un-acked tail `[boundary,
907    /// items_total)` over RS from the replay ring, in order. RS is reliable, so
908    /// it recovers the tail fast at any loss - no waiting on RLC's slow frontier
909    /// recovery. Falls back to draining RLC only if the cap evicted un-acked
910    /// items (so nothing is ever dropped).
911    fn switch_rlc_to_rs(&mut self) -> io::Result<()> {
912        let boundary = self.rlc.acked_through() as u64;
913        let frame = encode_code_switch(boundary, SensCode::Rs);
914        for _ in 0..CODE_SWITCH_REPEATS {
915            self.real.send_to(&frame, self.peer).ok();
916            std::thread::sleep(Duration::from_millis(2));
917        }
918        self.active = SensCode::Rs;
919        if boundary >= self.ring_base {
920            let start = (boundary - self.ring_base) as usize;
921            let end = self.sent_ring.len();
922            for i in start..end {
923                let item = self.sent_ring[i].clone();
924                self.send_via_rs(&item)?;
925            }
926        } else {
927            // Un-acked tail underflowed the cap: drain RLC so nothing is lost.
928            let target = self.rlc.next_source_id();
929            self.rlc.drain_until_acked(target, ESCAPE_DRAIN_TIMEOUT)?;
930        }
931        Ok(())
932    }
933
934    /// Send one item over RS, waiting out RS flow-control back-pressure (RS's ARQ
935    /// guarantees the window clears, so this wait is bounded by delivery, not by a
936    /// decode cliff). Shared by the RS steady state and the RLC escape handover.
937    fn send_via_rs(&mut self, item: &[u8]) -> io::Result<()> {
938        while self.rs.flow_blocked() {
939            self.rs.pump_feedback().ok();
940            if self.rs.flow_blocked() {
941                std::thread::sleep(Duration::from_micros(50));
942            }
943        }
944        self.rs.send_item(item)
945    }
946
947    /// Sample the active code's fed-back loss and switch codes if the controller
948    /// confirms a crossing of the configured thresholds.
949    fn maybe_switch(&mut self) -> io::Result<()> {
950        // The raw channel loss from sent-vs-received datagram counts: code-
951        // agnostic, so it does not collapse when the active code recovers the
952        // loss (which is what made the active code's own feedback flap).
953        let sent = self.sent_counter.load(Ordering::Relaxed);
954        let recv = self.fb_received.load(Ordering::Relaxed);
955        if recv == 0 {
956            return Ok(()); // no raw-loss report from the receiver yet
957        }
958        // Warmup: the in-flight window ramps 0 -> flow window at start, and that
959        // growth reads as loss; track the baseline but do not evaluate until it
960        // stabilizes, so the ramp does not trip a spurious switch.
961        if self.started.elapsed() < SWITCH_WARMUP {
962            self.prev_sent = sent;
963            self.prev_received = recv;
964            return Ok(());
965        }
966        if self.prev_received == 0 {
967            // First report: set the baseline, evaluate from the next window.
968            self.prev_sent = sent;
969            self.prev_received = recv;
970            return Ok(());
971        }
972        // Align the window to FEEDBACK arrivals: skip ticks with no new report,
973        // so a tick landing between reports does not read a spurious 100% loss
974        // (sent advanced, received not yet updated this window).
975        if recv <= self.prev_received {
976            return Ok(());
977        }
978        let sent_d = sent.saturating_sub(self.prev_sent);
979        if sent_d < MIN_LOSS_SAMPLE {
980            return Ok(()); // window too small to trust; keep accumulating
981        }
982        let recv_d = recv.saturating_sub(self.prev_received);
983        self.prev_sent = sent;
984        self.prev_received = recv;
985        let lost_d = sent_d.saturating_sub(recv_d) as f64;
986        // Size-weighted decaying loss: decay the lost / sent COUNTS and take their
987        // ratio, NOT an equal-weight EWMA of per-window ratios. A small feedback
988        // window with one drop reads a spuriously high ratio, and equal-weight
989        // averaging over-read low loss ~3.5x (3% measured as ~11%); weighting by
990        // datagram count makes large windows dominate so the estimate tracks the
991        // true channel loss. The 0.95 decay (effective window ~20 feedback samples)
992        // keeps it recent yet smooths the retransmit-burst windows that a tighter
993        // decay let spike across the up threshold and flap the code.
994        self.loss_acc = 0.95 * self.loss_acc + lost_d;
995        self.sent_acc = 0.95 * self.sent_acc + sent_d as f64;
996        self.ewma_loss = if self.sent_acc > 0.0 {
997            self.loss_acc / self.sent_acc
998        } else {
999            0.0
1000        };
1001        // Gate the switch until the accumulator has matured past its cold start: at
1002        // warmup-end loss_acc/sent_acc are near-empty, so the first post-warmup
1003        // window's raw ratio (a start-of-stream burst) would otherwise dominate the
1004        // estimate and trip a spurious up-switch. Keep accumulating, just do not act
1005        // on it yet.
1006        if self.post_warm_windows < MIN_ACCUM_WINDOWS {
1007            self.post_warm_windows += 1;
1008            return Ok(());
1009        }
1010        let loss_q8 = (self.ewma_loss * 256.0).clamp(0.0, 255.0) as u8;
1011        if let Some(to) = self.ctrl.observe(loss_q8) {
1012            self.do_switch(to)?;
1013        }
1014        Ok(())
1015    }
1016
1017    /// Code handover. RLC -> RS RESENDS the un-acked tail over RS (RS is reliable
1018    /// and fast at any loss, so it never waits on RLC's slow frontier recovery).
1019    /// RS -> RLC drains RS first (RS's ARQ clears its window quickly), then starts
1020    /// RLC from the fully-delivered boundary. In-order delivery holds either way.
1021    fn do_switch(&mut self, to: SensCode) -> io::Result<()> {
1022        match (self.active, to) {
1023            (SensCode::Rlc, SensCode::Rs) => self.switch_rlc_to_rs(),
1024            _ => self.do_switch_with_drain(to, DRAIN_TIMEOUT),
1025        }
1026    }
1027
1028    /// `do_switch` with an explicit drain deadline. The flow-block escape passes a
1029    /// generous one ([`ESCAPE_DRAIN_TIMEOUT`]) because draining a stuck window
1030    /// over a high-loss link (retransmitting its frontier, each copy itself
1031    /// lossy) takes far longer than a healthy handover.
1032    fn do_switch_with_drain(&mut self, to: SensCode, drain_timeout: Duration) -> io::Result<()> {
1033        match self.active {
1034            SensCode::Rlc => {
1035                let target = self.rlc.next_source_id();
1036                self.rlc.drain_until_acked(target, drain_timeout)?;
1037            }
1038            SensCode::Rs => {
1039                self.rs.flush()?;
1040                self.rs.drain_until_acked(drain_timeout)?;
1041            }
1042        }
1043        let frame = encode_code_switch(self.items_total, to);
1044        for _ in 0..CODE_SWITCH_REPEATS {
1045            self.real.send_to(&frame, self.peer).ok();
1046            std::thread::sleep(Duration::from_millis(2));
1047        }
1048        self.active = to;
1049        // Returning to RLC: another code carried [old RLC frontier, items_total),
1050        // so RLC's source-id stream diverged from the global index. Re-base it to
1051        // the global boundary so the resumed stream's source ids equal the global
1052        // item indices the receiver expects (it re-bases in lockstep on the same
1053        // boundary), instead of stalling on holes RLC will never resend or
1054        // replaying its stale pre-switch buffer.
1055        if to == SensCode::Rlc {
1056            self.rlc.skip_to(self.items_total as u32);
1057        }
1058        Ok(())
1059    }
1060
1061    /// Flush and drain the active code so the final items are delivered. Returns
1062    /// whether everything was acked before the deadline.
1063    pub fn finish(&mut self) -> io::Result<bool> {
1064        match self.active {
1065            SensCode::Rlc => {
1066                let target = self.rlc.next_source_id();
1067                self.rlc.drain_until_acked(target, Duration::from_secs(120))
1068            }
1069            SensCode::Rs => {
1070                self.rs.flush()?;
1071                self.rs.drain_until_acked(Duration::from_secs(120))
1072            }
1073        }
1074    }
1075
1076    /// Force the active code to `to` now (operator override), via the same
1077    /// handover an automatic switch uses (RLC->RS resend / RS->RLC drain), and
1078    /// keep the controller in sync so it does not immediately switch back. No-op
1079    /// if already on `to`.
1080    pub fn force_switch(&mut self, to: SensCode) -> io::Result<()> {
1081        if to != self.active {
1082            self.ctrl.force(to);
1083            self.do_switch(to)?;
1084        }
1085        Ok(())
1086    }
1087}
1088
1089impl Drop for UnifiedSensSender {
1090    fn drop(&mut self) {
1091        self.stop.store(true, Ordering::Relaxed);
1092        if let Some(h) = self.demux.take() {
1093            h.join().ok();
1094        }
1095    }
1096}
1097
1098// ---------------------------------------------------------------------------
1099// Unified receiver
1100// ---------------------------------------------------------------------------
1101
1102/// Unified Sens-O-Matic receiver: demuxes both codes off one socket and
1103/// delivers items in order across mid-stream code switches. The sender's
1104/// drain-barrier guarantees the old code is fully delivered before the new code
1105/// starts, so the receiver simply runs the active decoder and switches at the
1106/// announced boundary.
1107pub struct UnifiedSensReceiver {
1108    real: Arc<UdpSocket>,
1109    rlc: SensOMaticRlcReceiver,
1110    rs: ReliableUdpReceiver,
1111    active: SensCode,
1112    switch_signal: SwitchSignal,
1113    pending_switch: Option<(u64, SensCode)>,
1114    delivered_total: u64,
1115    /// Global index of the next item the RS decoder will deliver. RS delivers in
1116    /// its own local order; this maps that to the global stream so the un-acked
1117    /// tail an RLC->RS handover resends over RS can be deduped against what RLC
1118    /// already delivered. Set to the handover boundary on RLC->RS; advances per RS
1119    /// item thereafter.
1120    rs_next_global: u64,
1121    switches: u64,
1122    /// Unified AEAD record layer (TLS feature). When set, each item a decoder
1123    /// delivers is opened with its global index as the packet number before it
1124    /// reaches the application; duplicates (the resend overlap) are skipped before
1125    /// opening, so the packet number always matches the seal. A `OnceLock` shared
1126    /// with the handshake driver: the one-port server completes its handshake on a
1127    /// thread (the QUIC endpoint owns the socket, so the Sens handshake rides the
1128    /// demux queue) and publishes the keys here once; `bind_tls` sets it inline.
1129    #[cfg(feature = "tls")]
1130    crypto: Arc<std::sync::OnceLock<crate::rlc_crypto::CryptoState>>,
1131    /// TLS is expected on this receiver (set by `bind_tls` / `from_shared_tls`):
1132    /// `poll` withholds delivery until `crypto` is published, so a data frame that
1133    /// races ahead of the handshake completion is never opened with absent keys.
1134    #[cfg(feature = "tls")]
1135    expect_tls: bool,
1136    stop: Arc<AtomicBool>,
1137    demux: Option<JoinHandle<()>>,
1138}
1139
1140impl UnifiedSensReceiver {
1141    /// Bind `local` and bring up both decoders sharing it.
1142    pub fn bind<A: ToSocketAddrs>(local: A, cfg: UnifiedConfig) -> io::Result<Self> {
1143        let udp = UdpSocket::bind(local)?;
1144        udp.set_nonblocking(true)?;
1145        Self::assemble(udp, cfg, 0)
1146    }
1147
1148    /// Like [`bind`](Self::bind) but runs a TLS 1.3 server handshake first and
1149    /// AEAD-opens every delivered item: the WAN-confidential counterpart to
1150    /// [`UnifiedSensSender::connect_tls`]. The handshake completes before the
1151    /// demux reader takes the socket.
1152    #[cfg(feature = "tls")]
1153    pub fn bind_tls<A: ToSocketAddrs>(
1154        local: A,
1155        cfg: UnifiedConfig,
1156        tls: std::sync::Arc<rustls::ServerConfig>,
1157    ) -> io::Result<Self> {
1158        let udp = UdpSocket::bind(local)?;
1159        udp.set_nonblocking(true)?;
1160        let mut cs = crate::rlc_crypto::CryptoState::new_server(tls)
1161            .map_err(io::Error::other)?;
1162        let hs = DgramSock::from_udp(udp.try_clone()?);
1163        crate::sens_rlc::drive_handshake(&hs, None, &mut cs, false)?;
1164        let mut s = Self::assemble(udp, cfg, crate::rlc_crypto::TAG_LEN)?;
1165        s.crypto.set(cs).ok();
1166        s.expect_tls = true;
1167        Ok(s)
1168    }
1169
1170    /// Build the receiver over an already-bound (and, for TLS, already-handshaked)
1171    /// socket: bring up both decoders sharing it and spawn the demux reader.
1172    fn assemble(udp: UdpSocket, cfg: UnifiedConfig, seal_overhead: usize) -> io::Result<Self> {
1173        // The decoder must accept the sealed wire width (item + AEAD tag under
1174        // TLS); the RS decoder learns its shard width from the wire header, so
1175        // only the RLC decoder's symbol size needs widening here.
1176        let wire_sym = cfg.symbol_len + seal_overhead;
1177        let thread_sock = udp.try_clone()?;
1178        thread_sock.set_nonblocking(true)?;
1179        let real = Arc::new(udp);
1180        let rlc_q = new_demux_queue();
1181        let rs_q = new_demux_queue();
1182
1183        // No per-code debug loss: the unified path injects loss uniformly at the
1184        // demux (below), modelling a real lossy link AND letting the raw-loss
1185        // estimate see it (a sub-receiver drop would be invisible to the demux
1186        // count).
1187        let mut rlc = SensOMaticRlcReceiver::bind("0.0.0.0:0", wire_sym)?;
1188        rlc.set_sock(DgramSock::demux(Arc::clone(&real), Arc::clone(&rlc_q)));
1189
1190        let mut rs = ReliableUdpReceiver::bind("0.0.0.0:0")?;
1191        rs.set_sock(DgramSock::demux(Arc::clone(&real), Arc::clone(&rs_q)));
1192
1193        let switch_signal: SwitchSignal = Arc::new(Mutex::new(None));
1194        let recv_counter = Arc::new(AtomicU64::new(0));
1195        let stop = Arc::new(AtomicBool::new(false));
1196        let demux = spawn_demux(
1197            thread_sock,
1198            rlc_q,
1199            rs_q,
1200            Some(Arc::clone(&switch_signal)),
1201            Some(recv_counter),
1202            None,
1203            cfg.debug_loss,
1204            cfg.seed,
1205            Arc::clone(&stop),
1206        );
1207
1208        Ok(Self {
1209            real,
1210            rlc,
1211            rs,
1212            active: cfg.policy.initial_code(),
1213            switch_signal,
1214            pending_switch: None,
1215            delivered_total: 0,
1216            rs_next_global: 0,
1217            switches: 0,
1218            #[cfg(feature = "tls")]
1219            crypto: Arc::new(std::sync::OnceLock::new()),
1220            #[cfg(feature = "tls")]
1221            expect_tls: false,
1222            stop,
1223            demux: Some(demux),
1224        })
1225    }
1226
1227    /// Build a receiver fed by an EXTERNAL demux (the one-port QUIC endpoint's
1228    /// socket routes Sens datagrams into `rlc_q` / `rs_q` / `switch_signal` and
1229    /// tallies `recv_counter`). `send_sock` is a clone of the shared socket for
1230    /// control + raw-loss feedback. No demux thread is spawned (the QUIC socket
1231    /// feeds the queues); a small reporter thread sends the feedback to the peer
1232    /// the QUIC socket records in `sens_peer`.
1233    #[allow(clippy::too_many_arguments)]
1234    pub fn from_shared(
1235        send_sock: Arc<UdpSocket>,
1236        rlc_q: DemuxQueue,
1237        rs_q: DemuxQueue,
1238        switch_signal: SwitchSignal,
1239        recv_counter: Arc<AtomicU64>,
1240        sens_peer: Arc<Mutex<Option<SocketAddr>>>,
1241        cfg: UnifiedConfig,
1242        seal_overhead: usize,
1243    ) -> io::Result<Self> {
1244        // The RLC decoder must accept the sealed wire width (item + AEAD tag under
1245        // TLS) so it frames the symbols the sender shipped; the RS decoder learns
1246        // its shard width from the wire header, so only the RLC width needs it.
1247        let mut rlc = SensOMaticRlcReceiver::bind("0.0.0.0:0", cfg.symbol_len + seal_overhead)?;
1248        rlc.set_sock(DgramSock::demux(Arc::clone(&send_sock), rlc_q));
1249        let mut rs = ReliableUdpReceiver::bind("0.0.0.0:0")?;
1250        rs.set_sock(DgramSock::demux(Arc::clone(&send_sock), rs_q));
1251        let stop = Arc::new(AtomicBool::new(false));
1252        let demux = spawn_fb_reporter(Arc::clone(&send_sock), recv_counter, sens_peer, Arc::clone(&stop));
1253        Ok(Self {
1254            real: send_sock,
1255            rlc,
1256            rs,
1257            active: cfg.policy.initial_code(),
1258            switch_signal,
1259            pending_switch: None,
1260            delivered_total: 0,
1261            rs_next_global: 0,
1262            switches: 0,
1263            #[cfg(feature = "tls")]
1264            crypto: Arc::new(std::sync::OnceLock::new()),
1265            #[cfg(feature = "tls")]
1266            expect_tls: false,
1267            stop,
1268            demux: Some(demux),
1269        })
1270    }
1271
1272    /// Like [`from_shared`](Self::from_shared) but runs a TLS 1.3 server handshake
1273    /// over the demux'd `hs_q`. The one-port QUIC endpoint owns the socket, so the
1274    /// Sens handshake cannot own a recv loop; it rides the same demux queue as data
1275    /// (the demux routes `PKT_RLC_CRYPTO` frames into `hs_q`). The handshake runs
1276    /// on a thread and publishes the 1-RTT keys to the shared `crypto` cell once
1277    /// complete; `poll` withholds delivery until then. Returns immediately so the
1278    /// caller can start the QUIC + Sens clients that drive the handshake.
1279    #[cfg(feature = "tls")]
1280    #[allow(clippy::too_many_arguments)]
1281    pub fn from_shared_tls(
1282        send_sock: Arc<UdpSocket>,
1283        rlc_q: DemuxQueue,
1284        rs_q: DemuxQueue,
1285        hs_q: DemuxQueue,
1286        switch_signal: SwitchSignal,
1287        recv_counter: Arc<AtomicU64>,
1288        sens_peer: Arc<Mutex<Option<SocketAddr>>>,
1289        cfg: UnifiedConfig,
1290        tls: std::sync::Arc<rustls::ServerConfig>,
1291    ) -> io::Result<Self> {
1292        let mut s = Self::from_shared(
1293            Arc::clone(&send_sock),
1294            rlc_q,
1295            rs_q,
1296            switch_signal,
1297            recv_counter,
1298            sens_peer,
1299            cfg,
1300            crate::rlc_crypto::TAG_LEN,
1301        )?;
1302        s.expect_tls = true;
1303        let crypto = Arc::clone(&s.crypto);
1304        let stop = Arc::clone(&s.stop);
1305        let hs_sock = DgramSock::demux(send_sock, hs_q);
1306        std::thread::spawn(move || {
1307            let mut cs = match crate::rlc_crypto::CryptoState::new_server(tls) {
1308                Ok(c) => c,
1309                Err(_) => return,
1310            };
1311            // Drive the server handshake over the demux'd queue (peer learned from
1312            // the first flight); publish the keys once the 1-RTT secrets derive.
1313            if !stop.load(Ordering::Relaxed)
1314                && crate::sens_rlc::drive_handshake(&hs_sock, None, &mut cs, false).is_ok()
1315            {
1316                crypto.set(cs).ok();
1317            }
1318        });
1319        Ok(s)
1320    }
1321
1322    /// The decoder currently delivering.
1323    pub fn active_code(&self) -> SensCode {
1324        self.active
1325    }
1326
1327    /// Code switches the receiver has followed.
1328    pub fn switches(&self) -> u64 {
1329        self.switches
1330    }
1331
1332    /// Whether either decoder adopted a replacement session since this was
1333    /// last called, clearing the flag. Edge-triggered: one report per
1334    /// adoption.
1335    pub fn take_session_changed(&mut self) -> bool {
1336        let rlc = self.rlc.take_session_changed();
1337        let rs = self.rs.take_session_changed();
1338        rlc || rs
1339    }
1340
1341    /// `(adopted, challenges_that_went_unanswered)` for replacement
1342    /// The RLC connection ids holding a decode window, in first-seen order.
1343    /// Empty before any peer is seen.
1344    pub fn live_rlc_sessions(&self) -> Vec<u64> {
1345        self.rlc.live_sessions()
1346    }
1347
1348    /// The block-RS session epochs holding a decode window, in first-seen
1349    /// order.
1350    pub fn live_rs_sessions(&self) -> Vec<u32> {
1351        self.rs.live_sessions()
1352    }
1353
1354    /// Peers refused a decode window on either code.
1355    pub fn session_refusals(&self) -> u64 {
1356        self.rlc.session_refusals() + self.rs.session_refusals()
1357    }
1358
1359    /// sessions, summed over both codes. A refused forgery raises the
1360    /// second without the first.
1361    pub fn session_adoption_counts(&self) -> (u64, u64) {
1362        let (ra, rf) = self.rlc.session_adoption_counts();
1363        let (sa, sf) = self.rs.session_adoption_counts();
1364        (ra + sa, rf + sf)
1365    }
1366
1367    /// The bound local address.
1368    pub fn local_addr(&self) -> io::Result<SocketAddr> {
1369        self.real.local_addr()
1370    }
1371
1372    /// Recover an item from a delivered wire payload: AEAD-open (TLS) with `pn`
1373    /// the item's global index, or pass the bytes through. A failed open (a
1374    /// tampered datagram) surfaces as an error rather than delivering bad data.
1375    #[cfg_attr(not(feature = "tls"), allow(unused_variables, unused_mut))]
1376    fn open_payload(&self, mut payload: Vec<u8>, pn: u64) -> io::Result<Vec<u8>> {
1377        #[cfg(feature = "tls")]
1378        if let Some(cs) = self.crypto.get() {
1379            let n = cs
1380                .open(pn, &mut payload)
1381                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
1382            payload.truncate(n);
1383            return Ok(payload);
1384        }
1385        Ok(payload)
1386    }
1387
1388    /// Drive the active decoder and return the items it delivered this call,
1389    /// each tagged with the identity of the peer that sent it: the RLC
1390    /// connection id, or the block-RS session epoch widened to `u64`.
1391    ///
1392    /// Both codes decode a window per peer. The code-switch layer above them
1393    /// does not: the delivery frontier, the switch boundary and the TLS packet
1394    /// number are per endpoint. A mesh node pins a code and leaves TLS off, or
1395    /// drives [`SensOMaticRlcReceiver`] / [`ReliableUdpReceiver`] directly.
1396    pub fn poll_from(&mut self) -> io::Result<Vec<(u64, Vec<u8>)>> {
1397        self.poll_tagged()
1398    }
1399
1400    /// Drive the active decoder and return the items it delivered this call.
1401    /// Honors a pending CODE_SWITCH once the active decoder has delivered every
1402    /// item up to the announced boundary.
1403    pub fn poll(&mut self) -> io::Result<Vec<Vec<u8>>> {
1404        Ok(self.poll_tagged()?.into_iter().map(|(_, item)| item).collect())
1405    }
1406
1407    /// The one drain both public forms share, carrying each item's peer tag
1408    /// from the decoder that delivered it rather than reconstructing it after.
1409    fn poll_tagged(&mut self) -> io::Result<Vec<(u64, Vec<u8>)>> {
1410        // One-port TLS: the handshake completes asynchronously on a thread (the
1411        // QUIC endpoint owns the socket), so until the keys are published, withhold
1412        // delivery. The decoders keep buffering inbound frames; the peer only sends
1413        // data after ITS handshake finished, so the backlog is at most a few frames
1414        // and they open correctly once the keys land. (bind_tls sets the keys
1415        // inline before returning, so this gate is already clear there.)
1416        #[cfg(feature = "tls")]
1417        if self.expect_tls && self.crypto.get().is_none() {
1418            return Ok(Vec::new());
1419        }
1420        if self.pending_switch.is_none() {
1421            self.pending_switch = self.switch_signal.lock().unwrap().take();
1422        }
1423        let out = match self.active {
1424            SensCode::Rlc => {
1425                // Open each payload with its global index as the packet number.
1426                // The tag rides from the decoder, so an item is attributed to the
1427                // peer that actually sent it rather than to whoever spoke last.
1428                let raw = self.rlc.poll_from()?;
1429                let mut d = Vec::with_capacity(raw.len());
1430                for (cid, payload) in raw {
1431                    let item = self.open_payload(payload, self.delivered_total)?;
1432                    self.delivered_total += 1;
1433                    d.push((cid, item));
1434                }
1435                d
1436            }
1437            SensCode::Rs => {
1438                // RS delivers in its own local order; map each to its global index
1439                // (rs_next_global, advancing per item). After an RLC->RS resend
1440                // handover the leading items overlap what RLC already delivered, so
1441                // drop any whose global index is below the delivery frontier
1442                // (before opening, so the packet number always matches the seal).
1443                //
1444                // The tag is the sending peer's session epoch, widened.
1445                let raw = self.rs.poll_from()?;
1446                let mut d = Vec::with_capacity(raw.len());
1447                for (epoch, payload) in raw {
1448                    if self.rs_next_global >= self.delivered_total {
1449                        let item = self.open_payload(payload, self.rs_next_global)?;
1450                        self.delivered_total += 1;
1451                        d.push((u64::from(epoch), item));
1452                    }
1453                    self.rs_next_global += 1;
1454                }
1455                d
1456            }
1457        };
1458        if let Some((boundary, to)) = self.pending_switch
1459            && self.delivered_total >= boundary
1460        {
1461            // The sender repeats CODE_SWITCH for reliability; only act (and
1462            // count) when the target differs from the active code, so the
1463            // repeats do not inflate the switch tally or re-switch.
1464            if to != self.active {
1465                match to {
1466                    SensCode::Rs => {
1467                        // The RS stream resumes at the boundary (RLC's delivery
1468                        // frontier); index its local order from there.
1469                        self.rs_next_global = boundary;
1470                    }
1471                    SensCode::Rlc => {
1472                        // Returning to RLC: re-base the decoder to the boundary so
1473                        // it delivers the resumed stream from there (whose source
1474                        // ids the sender re-aligned to the global index) and does
1475                        // not replay its stale pre-switch buffer or stall on holes
1476                        // the other code already delivered.
1477                        self.rlc.skip_to(boundary as u32);
1478                    }
1479                }
1480                self.active = to;
1481                self.switches += 1;
1482            }
1483            self.pending_switch = None;
1484        }
1485        Ok(out)
1486    }
1487}
1488
1489impl Drop for UnifiedSensReceiver {
1490    fn drop(&mut self) {
1491        self.stop.store(true, Ordering::Relaxed);
1492        if let Some(h) = self.demux.take() {
1493            h.join().ok();
1494        }
1495    }
1496}
1497
1498#[cfg(test)]
1499mod tests {
1500    use super::*;
1501
1502    #[test]
1503    fn forced_policies_never_switch() {
1504        for policy in [CodePolicy::ForceRlc, CodePolicy::ForceRs] {
1505            let mut c = CodeSwitchController::with_policy(policy);
1506            let start = c.code();
1507            for q in [0u8, 80, 200, 255, 10, 0] {
1508                assert_eq!(c.observe(q), None, "forced policy must not switch");
1509            }
1510            assert_eq!(c.code(), start);
1511            assert_eq!(c.switches(), 0);
1512        }
1513    }
1514
1515    #[test]
1516    fn force_rs_starts_on_rs() {
1517        let c = CodeSwitchController::with_policy(CodePolicy::ForceRs);
1518        assert_eq!(c.code(), SensCode::Rs);
1519    }
1520
1521    #[test]
1522    fn auto_starts_on_rlc_then_up_switches_when_loss_sustains() {
1523        let mut c = CodeSwitchController::new(CodePolicy::default_auto(), 2, 8);
1524        assert_eq!(c.code(), SensCode::Rlc);
1525        // 12% loss (q8 ~30) is below the ~15% up threshold (q8 38): no switch.
1526        assert_eq!(c.observe(30), None);
1527        assert_eq!(c.observe(30), None);
1528        assert_eq!(c.code(), SensCode::Rlc);
1529        // 18% loss (q8 46) above the up threshold: one sample arms, the second
1530        // (up_hold = 2) confirms the switch to RS.
1531        assert_eq!(c.observe(46), None, "first over-threshold sample only arms");
1532        assert_eq!(c.observe(46), Some(SensCode::Rs), "second confirms up-switch");
1533        assert_eq!(c.code(), SensCode::Rs);
1534        assert_eq!(c.switches(), 1);
1535    }
1536
1537    #[test]
1538    fn stall_escape_latches_rs_and_does_not_flap() {
1539        // A flow-block escape to RS (RLC stalled at this loss) must NOT down-switch
1540        // back even when the loss estimate sits below the down threshold: returning
1541        // to a code that just stalled flaps, and the RS->RLC handover then corrupts
1542        // in-order delivery. The latch holds RS after a stall-escape.
1543        let mut c = CodeSwitchController::new(CodePolicy::default_auto(), 2, 4);
1544        assert!(c.force(SensCode::Rs), "stall-escape forces to RS");
1545        assert_eq!(c.code(), SensCode::Rs);
1546        for i in 0..20 {
1547            assert_eq!(c.observe(5), None, "latched RS must not down-switch at tick {i}");
1548        }
1549        assert_eq!(c.code(), SensCode::Rs);
1550        assert_eq!(c.switches(), 1, "no flap: only the one escape switch");
1551    }
1552
1553    #[test]
1554    fn a_single_loss_spike_does_not_flap_the_code() {
1555        let mut c = CodeSwitchController::new(CodePolicy::default_auto(), 2, 8);
1556        // One isolated spike over the threshold then back down: up_hold = 2 is
1557        // not met, so no switch (the streak resets on the low sample).
1558        assert_eq!(c.observe(200), None);
1559        assert_eq!(c.observe(10), None);
1560        assert_eq!(c.observe(200), None);
1561        assert_eq!(c.code(), SensCode::Rlc, "an isolated spike must not switch");
1562        assert_eq!(c.switches(), 0);
1563    }
1564
1565    #[test]
1566    fn down_switch_needs_a_longer_sustained_low_streak() {
1567        let mut c = CodeSwitchController::new(CodePolicy::default_auto(), 2, 8);
1568        // Drive up to RS first.
1569        c.observe(80);
1570        assert_eq!(c.observe(80), Some(SensCode::Rs));
1571        // Loss drops below the 10% down threshold (q8 26). It must SUSTAIN for
1572        // down_hold = 8 samples; a brief low spell does not relax the code.
1573        for _ in 0..7 {
1574            assert_eq!(c.observe(10), None, "down-switch must not fire early");
1575        }
1576        assert_eq!(c.observe(10), Some(SensCode::Rlc), "8th low sample relaxes to RLC");
1577        assert_eq!(c.code(), SensCode::Rlc);
1578        assert_eq!(c.switches(), 2);
1579    }
1580
1581    #[test]
1582    fn hysteresis_band_holds_rs_between_thresholds() {
1583        let mut c = CodeSwitchController::new(CodePolicy::default_auto(), 2, 8);
1584        c.observe(80);
1585        c.observe(80); // now on RS
1586        assert_eq!(c.code(), SensCode::Rs);
1587        // Loss in the band (down_q8=26 < q8=32 < up_q8=38): neither relaxes nor
1588        // re-arms; RS holds across the whole band (no flapping).
1589        for _ in 0..20 {
1590            assert_eq!(c.observe(32), None);
1591        }
1592        assert_eq!(c.code(), SensCode::Rs, "RS holds inside the hysteresis band");
1593    }
1594
1595    // A real two-socket loopback round trip that forces an RLC -> RS handover
1596    // mid-stream and asserts every item is delivered exactly once, in order,
1597    // across the switch. Exercises the demux sockets, the drain-barrier, the
1598    // CODE_SWITCH frame, and the receiver's boundary merge end to end.
1599    /// Two concurrent senders through the unified endpoint, pinned to RLC (the
1600    /// mesh shape, and the code Auto runs at low loss). Every item of both
1601    /// streams must arrive, and `poll_from` must attribute each to the peer
1602    /// that actually sent it.
1603    ///
1604    /// The tag assertion is the point. Delivery alone passes even when every
1605    /// item is labelled with whoever spoke last, which is the misattribution a
1606    /// mesh node cannot detect from its own side.
1607    /// The same two-peer shape pinned to block-RS. The unified endpoint hands
1608    /// its RS half a demux socket, which is shared and fed by a reader that
1609    /// takes every source address, so that receiver has to route by session
1610    /// epoch rather than serve one peer.
1611    /// Three peers through the unified endpoint on block-RS. Two is not enough
1612    /// to exercise admission: one peer always takes the free first-admission
1613    /// slot, so a broken challenge path still delivers both. Three forces two
1614    /// separate challenges, and the challenge answer travels back over the
1615    /// sender's demux socket.
1616    /// Two peers on DIFFERENT codes through one receiver. Under `Auto` each
1617    /// sender runs its own switch controller, so a mesh whose links see
1618    /// different loss can have peers disagree about which code is live.
1619    ///
1620    /// The receiver holds one `active` code and polls only that decoder, so a
1621    /// peer sending the other code is never drained. This is the endpoint-wide
1622    /// switch boundary meeting a per-peer topology.
1623    #[test]
1624    #[ignore = "subetha-11: one active code per endpoint; peers on different codes are not both drained"]
1625    fn unified_peers_on_different_codes_both_deliver() {
1626        use std::sync::mpsc;
1627        let sym = 64usize;
1628        let base = UnifiedConfig {
1629            policy: CodePolicy::default_auto(),
1630            symbol_len: sym,
1631            k: 8,
1632            r: 2,
1633            rlc_flow_window: 256,
1634            debug_loss: 0,
1635            seed: 1,
1636            rlc_step: 4,
1637            rlc_static: false,
1638        };
1639        let recv = UnifiedSensReceiver::bind("127.0.0.1:0", base).unwrap();
1640        let addr = recv.local_addr().unwrap();
1641        let per_peer: u64 = 40;
1642        let total = per_peer * 2;
1643
1644        let (tx, rx) = mpsc::channel();
1645        let rh = std::thread::spawn(move || {
1646            let mut recv = recv;
1647            let mut got: Vec<u64> = Vec::new();
1648            let start = Instant::now();
1649            while (got.len() as u64) < total && start.elapsed() < Duration::from_secs(20) {
1650                let items = recv.poll().unwrap_or_default();
1651                let empty = items.is_empty();
1652                for it in items {
1653                    let mut s = [0u8; 8];
1654                    s.copy_from_slice(&it[..8]);
1655                    got.push(u64::from_le_bytes(s));
1656                }
1657                if empty {
1658                    std::thread::sleep(Duration::from_micros(200));
1659                }
1660            }
1661            tx.send(got).ok();
1662        });
1663
1664        // One peer pinned to each code, which is the steady state a divergent
1665        // Auto switch reaches.
1666        let mut handles = Vec::new();
1667        for (p, policy) in [CodePolicy::ForceRlc, CodePolicy::ForceRs].into_iter().enumerate() {
1668            let mut cfg = base;
1669            cfg.policy = policy;
1670            handles.push(std::thread::spawn(move || {
1671                let mut send = UnifiedSensSender::connect("0.0.0.0:0", addr, cfg).unwrap();
1672                let mut buf = vec![0u8; 8];
1673                for i in 0..per_peer {
1674                    buf[..8].copy_from_slice(&(((p as u64) << 56) | i).to_le_bytes());
1675                    if send.send_item(&buf).is_err() {
1676                        break;
1677                    }
1678                }
1679                send.finish().ok();
1680            }));
1681        }
1682        for h in handles {
1683            h.join().ok();
1684        }
1685
1686        let got = rx.recv_timeout(Duration::from_secs(25)).unwrap();
1687        rh.join().ok();
1688        for p in 0..2u64 {
1689            let mine: Vec<u64> = got
1690                .iter()
1691                .filter(|v| (*v >> 56) == p)
1692                .map(|v| v & 0x00FF_FFFF_FFFF_FFFF)
1693                .collect();
1694            assert_eq!(
1695                mine,
1696                (0..per_peer).collect::<Vec<_>>(),
1697                "peer {p} was not drained; the receiver polls one active code",
1698            );
1699        }
1700    }
1701
1702    /// Three peers through the unified endpoint on ForceRlc, sending SPARSELY -
1703    /// one small item every 300ms - with one going silent partway. The
1704    /// consumer's topology: a heartbeat mesh where a node dies.
1705    ///
1706    /// Combines what the other multi-peer tests each cover separately: the
1707    /// demux socket, sparse traffic that lets the receiver's timers run between
1708    /// frames, and a peer that stops.
1709    #[test]
1710    #[ignore = "harness: poll_from blocks past the loop deadline under sparse traffic, so this \
1711                times out rather than asserting; needs a non-blocking drain before it can judge"]
1712    fn unified_three_sparse_peers_survive_one_going_silent() {
1713        use std::sync::mpsc;
1714        let sym = 64usize;
1715        let cfg = UnifiedConfig {
1716            policy: CodePolicy::ForceRlc,
1717            symbol_len: sym,
1718            k: 8,
1719            r: 2,
1720            rlc_flow_window: 256,
1721            debug_loss: 0,
1722            seed: 1,
1723            rlc_step: 4,
1724            rlc_static: false,
1725        };
1726        let rounds: u64 = 10;
1727        let silent_after: u64 = 3;
1728        let peers: u64 = 3;
1729
1730        let recv = UnifiedSensReceiver::bind("127.0.0.1:0", cfg).unwrap();
1731        let addr = recv.local_addr().unwrap();
1732        let (tx, rx) = mpsc::channel();
1733        let (stop_tx, stop_rx) = mpsc::channel::<()>();
1734        let rh = std::thread::spawn(move || {
1735            let mut recv = recv;
1736            let mut got: Vec<(u64, u64)> = Vec::new();
1737            let start = Instant::now();
1738            while start.elapsed() < Duration::from_secs(15) && stop_rx.try_recv().is_err() {
1739                let batch: Vec<(u64, Vec<u8>)> = recv.poll_from().unwrap_or_default();
1740                for (tag, it) in batch {
1741                    let mut s = [0u8; 8];
1742                    s.copy_from_slice(&it[..8]);
1743                    let v = u64::from_le_bytes(s);
1744                    got.push((tag, v));
1745                }
1746                std::thread::sleep(Duration::from_millis(2));
1747            }
1748            got
1749        });
1750
1751        let mut handles = Vec::new();
1752        for p in 0..peers {
1753            handles.push(std::thread::spawn(move || {
1754                let mut send = UnifiedSensSender::connect("0.0.0.0:0", addr, cfg).unwrap();
1755                let mut buf = vec![0u8; 8];
1756                let n = if p == 2 { silent_after } else { rounds };
1757                for i in 0..n {
1758                    buf[..8].copy_from_slice(&((p << 56) | i).to_le_bytes());
1759                    if send.send_item(&buf).is_err() {
1760                        break;
1761                    }
1762                    std::thread::sleep(Duration::from_millis(300));
1763                }
1764                if p != 2 {
1765                    std::thread::sleep(Duration::from_secs(2));
1766                }
1767                send.finish().ok();
1768            }));
1769        }
1770        for h in handles {
1771            h.join().ok();
1772        }
1773        stop_tx.send(()).ok();
1774        let got: Vec<(u64, u64)> = rx.recv_timeout(Duration::from_secs(20)).unwrap();
1775
1776        let tags: std::collections::BTreeSet<u64> = got.iter().map(|(t, _)| *t).collect();
1777        for p in 0..2u64 {
1778            let mine: Vec<u64> = got
1779                .iter()
1780                .filter(|(_, v)| (*v >> 56) == p)
1781                .map(|(_, v)| v & 0x00FF_FFFF_FFFF_FFFF)
1782                .collect();
1783            assert_eq!(
1784                mine,
1785                (0..rounds).collect::<Vec<_>>(),
1786                "surviving peer {p} stopped being delivered; got {} of {rounds}, \
1787                 tags seen {tags:?}",
1788                mine.len(),
1789            );
1790        }
1791    }
1792
1793    #[test]
1794    fn unified_three_peers_on_block_rs_all_deliver() {
1795        use std::sync::mpsc;
1796        let sym = 64usize;
1797        let cfg = UnifiedConfig {
1798            policy: CodePolicy::ForceRs,
1799            symbol_len: sym,
1800            k: 8,
1801            r: 2,
1802            rlc_flow_window: 256,
1803            debug_loss: 0,
1804            seed: 1,
1805            rlc_step: 4,
1806            rlc_static: false,
1807        };
1808        let recv = UnifiedSensReceiver::bind("127.0.0.1:0", cfg).unwrap();
1809        let addr = recv.local_addr().unwrap();
1810        let per_peer: u64 = 50;
1811        let peers: u64 = 3;
1812        let total = per_peer * peers;
1813
1814        let (tx, rx) = mpsc::channel();
1815        let rh = std::thread::spawn(move || {
1816            let mut recv = recv;
1817            let mut got: Vec<u64> = Vec::with_capacity(total as usize);
1818            let start = Instant::now();
1819            while (got.len() as u64) < total && start.elapsed() < Duration::from_secs(30) {
1820                let items = recv.poll().unwrap_or_default();
1821                let empty = items.is_empty();
1822                for it in items {
1823                    let mut s = [0u8; 8];
1824                    s.copy_from_slice(&it[..8]);
1825                    got.push(u64::from_le_bytes(s));
1826                }
1827                if empty {
1828                    std::thread::sleep(Duration::from_micros(200));
1829                }
1830            }
1831            tx.send(got).ok();
1832        });
1833
1834        let gate = Arc::new(std::sync::Barrier::new(peers as usize));
1835        let mut handles = Vec::new();
1836        for p in 0..peers {
1837            let gate = Arc::clone(&gate);
1838            handles.push(std::thread::spawn(move || {
1839                let mut send = UnifiedSensSender::connect("0.0.0.0:0", addr, cfg).unwrap();
1840                let mut buf = vec![0u8; 8];
1841                gate.wait();
1842                let start = Instant::now();
1843                for i in 0..per_peer {
1844                    if start.elapsed() > Duration::from_secs(20) {
1845                        break;
1846                    }
1847                    buf[..8].copy_from_slice(&((p << 56) | i).to_le_bytes());
1848                    if send.send_item(&buf).is_err() {
1849                        break;
1850                    }
1851                }
1852                send.finish().ok();
1853            }));
1854        }
1855        for h in handles {
1856            h.join().ok();
1857        }
1858
1859        let got = rx.recv_timeout(Duration::from_secs(35)).unwrap();
1860        rh.join().ok();
1861        for p in 0..peers {
1862            let mine: Vec<u64> = got
1863                .iter()
1864                .filter(|v| (*v >> 56) == p)
1865                .map(|v| v & 0x00FF_FFFF_FFFF_FFFF)
1866                .collect();
1867            assert_eq!(
1868                mine,
1869                (0..per_peer).collect::<Vec<_>>(),
1870                "peer {p} of {peers} did not deliver through the unified block-RS path",
1871            );
1872        }
1873    }
1874
1875    #[test]
1876    fn unified_two_peers_on_block_rs_both_deliver() {
1877        use std::sync::mpsc;
1878        let sym = 64usize;
1879        let cfg = UnifiedConfig {
1880            policy: CodePolicy::ForceRs,
1881            symbol_len: sym,
1882            k: 8,
1883            r: 2,
1884            rlc_flow_window: 256,
1885            debug_loss: 0,
1886            seed: 1,
1887            rlc_step: 4,
1888            rlc_static: false,
1889        };
1890        let recv = UnifiedSensReceiver::bind("127.0.0.1:0", cfg).unwrap();
1891        let addr = recv.local_addr().unwrap();
1892        let per_peer: u64 = 60;
1893        let peers: u64 = 2;
1894        let total = per_peer * peers;
1895
1896        let (tx, rx) = mpsc::channel();
1897        let rh = std::thread::spawn(move || {
1898            let mut recv = recv;
1899            let mut got: Vec<u64> = Vec::with_capacity(total as usize);
1900            let start = Instant::now();
1901            while (got.len() as u64) < total && start.elapsed() < Duration::from_secs(25) {
1902                let items = recv.poll().unwrap_or_default();
1903                let empty = items.is_empty();
1904                for it in items {
1905                    let mut s = [0u8; 8];
1906                    s.copy_from_slice(&it[..8]);
1907                    got.push(u64::from_le_bytes(s));
1908                }
1909                if empty {
1910                    std::thread::sleep(Duration::from_micros(200));
1911                }
1912            }
1913            tx.send(got).ok();
1914        });
1915
1916        let gate = Arc::new(std::sync::Barrier::new(peers as usize));
1917        let mut handles = Vec::new();
1918        for p in 0..peers {
1919            let gate = Arc::clone(&gate);
1920            handles.push(std::thread::spawn(move || {
1921                let mut send = UnifiedSensSender::connect("0.0.0.0:0", addr, cfg).unwrap();
1922                let mut buf = vec![0u8; 8];
1923                gate.wait();
1924                let start = Instant::now();
1925                for i in 0..per_peer {
1926                    if start.elapsed() > Duration::from_secs(15) {
1927                        break;
1928                    }
1929                    buf[..8].copy_from_slice(&((p << 56) | i).to_le_bytes());
1930                    if send.send_item(&buf).is_err() {
1931                        break;
1932                    }
1933                }
1934                send.finish().ok();
1935            }));
1936        }
1937        for h in handles {
1938            h.join().ok();
1939        }
1940
1941        let got = rx.recv_timeout(Duration::from_secs(30)).unwrap();
1942        rh.join().ok();
1943        for p in 0..peers {
1944            let mine: Vec<u64> = got
1945                .iter()
1946                .filter(|v| (*v >> 56) == p)
1947                .map(|v| v & 0x00FF_FFFF_FFFF_FFFF)
1948                .collect();
1949            assert_eq!(
1950                mine,
1951                (0..per_peer).collect::<Vec<_>>(),
1952                "block-RS peer {p} must deliver every item alongside the other peer",
1953            );
1954        }
1955    }
1956
1957    #[test]
1958    fn unified_two_peers_deliver_and_are_attributed_separately() {
1959        use std::sync::mpsc;
1960        let sym = 64usize;
1961        let cfg = UnifiedConfig {
1962            policy: CodePolicy::ForceRlc,
1963            symbol_len: sym,
1964            k: 8,
1965            r: 2,
1966            rlc_flow_window: 256,
1967            debug_loss: 0,
1968            seed: 1,
1969            rlc_step: 4,
1970            rlc_static: false,
1971        };
1972        let recv = UnifiedSensReceiver::bind("127.0.0.1:0", cfg).unwrap();
1973        let addr = recv.local_addr().unwrap();
1974        let per_peer: u64 = 150;
1975        let peers: u64 = 2;
1976        let total = per_peer * peers;
1977
1978        let (tx, rx) = mpsc::channel();
1979        let rh = std::thread::spawn(move || {
1980            let mut recv = recv;
1981            let mut got: Vec<(u64, u64)> = Vec::with_capacity(total as usize);
1982            let start = Instant::now();
1983            while (got.len() as u64) < total && start.elapsed() < Duration::from_secs(25) {
1984                let items = recv.poll_from().unwrap_or_default();
1985                let empty = items.is_empty();
1986                for (tag, it) in items {
1987                    let mut s = [0u8; 8];
1988                    s.copy_from_slice(&it[..8]);
1989                    got.push((tag, u64::from_le_bytes(s)));
1990                }
1991                if empty {
1992                    std::thread::sleep(Duration::from_micros(200));
1993                }
1994            }
1995            tx.send(got).ok();
1996        });
1997
1998        let mut handles = Vec::new();
1999        for p in 0..peers {
2000            handles.push(std::thread::spawn(move || {
2001                let mut send = UnifiedSensSender::connect("0.0.0.0:0", addr, cfg).unwrap();
2002                let mut buf = vec![0u8; 8];
2003                let start = Instant::now();
2004                for i in 0..per_peer {
2005                    if start.elapsed() > Duration::from_secs(15) {
2006                        break;
2007                    }
2008                    buf[..8].copy_from_slice(&((p << 56) | i).to_le_bytes());
2009                    if send.send_item(&buf).is_err() {
2010                        break;
2011                    }
2012                }
2013                send.finish().ok();
2014            }));
2015        }
2016        for h in handles {
2017            h.join().ok();
2018        }
2019
2020        let got = rx.recv_timeout(Duration::from_secs(30)).unwrap();
2021        rh.join().ok();
2022
2023        for p in 0..peers {
2024            let mine: Vec<u64> = got
2025                .iter()
2026                .filter(|(_, v)| (v >> 56) == p)
2027                .map(|(_, v)| v & 0x00FF_FFFF_FFFF_FFFF)
2028                .collect();
2029            assert_eq!(
2030                mine,
2031                (0..per_peer).collect::<Vec<_>>(),
2032                "peer {p} must deliver every item in order alongside the other peer",
2033            );
2034            // Every item a peer sent must carry ONE tag, and the two peers'
2035            // tags must differ - otherwise the attribution is a label, not a
2036            // routing fact.
2037            let tags: std::collections::BTreeSet<u64> =
2038                got.iter().filter(|(_, v)| (v >> 56) == p).map(|(t, _)| *t).collect();
2039            assert_eq!(tags.len(), 1, "peer {p} items must all carry one tag, got {tags:?}");
2040        }
2041        let all_tags: std::collections::BTreeSet<u64> = got.iter().map(|(t, _)| *t).collect();
2042        assert_eq!(all_tags.len(), 2, "the two peers must be attributed distinctly");
2043    }
2044
2045    #[test]
2046    fn unified_delivers_in_order_across_a_forced_switch() {
2047        use std::sync::mpsc;
2048        let sym = 64usize;
2049        let cfg = UnifiedConfig {
2050            policy: CodePolicy::default_auto(),
2051            symbol_len: sym,
2052            k: 8,
2053            r: 2,
2054            rlc_flow_window: 256,
2055            debug_loss: 0,
2056            seed: 1,
2057            rlc_step: 4,
2058            rlc_static: false,
2059        };
2060        let recv = UnifiedSensReceiver::bind("127.0.0.1:0", cfg).unwrap();
2061        let addr = recv.local_addr().unwrap();
2062        let n: u64 = 4000;
2063
2064        let (tx, rx) = mpsc::channel();
2065        let rh = std::thread::spawn(move || {
2066            let mut recv = recv;
2067            let mut got: Vec<u64> = Vec::with_capacity(n as usize);
2068            let start = Instant::now();
2069            while (got.len() as u64) < n && start.elapsed() < Duration::from_secs(25) {
2070                let items = recv.poll().unwrap_or_default();
2071                let empty = items.is_empty();
2072                for it in items {
2073                    let mut s = [0u8; 8];
2074                    s.copy_from_slice(&it[..8]);
2075                    got.push(u64::from_le_bytes(s));
2076                }
2077                if empty {
2078                    std::thread::sleep(Duration::from_micros(200));
2079                }
2080            }
2081            tx.send((got, recv.switches())).ok();
2082        });
2083
2084        let mut send = UnifiedSensSender::connect("0.0.0.0:0", addr, cfg).unwrap();
2085        // Items must leave room for the RLC symbol's length prefix
2086        // (item.len() + LEN_PREFIX <= symbol_len), so ship the 8-byte seq.
2087        let mut buf = vec![0u8; 8];
2088        for seq in 0..n / 2 {
2089            buf[..8].copy_from_slice(&seq.to_le_bytes());
2090            send.send_item(&buf).unwrap();
2091        }
2092        send.force_switch(SensCode::Rs).unwrap();
2093        assert_eq!(send.active_code(), SensCode::Rs);
2094        for seq in n / 2..n {
2095            buf[..8].copy_from_slice(&seq.to_le_bytes());
2096            send.send_item(&buf).unwrap();
2097        }
2098        send.finish().unwrap();
2099
2100        let (got, rswitches) = rx.recv_timeout(Duration::from_secs(30)).unwrap();
2101        rh.join().ok();
2102        assert_eq!(got.len() as u64, n, "every item delivered exactly once");
2103        for (i, &v) in got.iter().enumerate() {
2104            assert_eq!(v, i as u64, "delivery in order across the switch at index {i}");
2105        }
2106        assert!(rswitches >= 1, "receiver followed the code switch");
2107    }
2108}