iroh/socket/
biased_rtt_path_selector.rs

1//! Default [`PathSelector`] implementation.
2//!
3//! [`BiasedRttPathSelector`] preserves iroh's historical "lowest biased RTT wins, with
4//! stickiness against flapping" behaviour and is what's installed when no custom
5//! selector is provided.
6
7use std::{sync::Arc, time::Duration};
8
9use rustc_hash::FxHashMap;
10use tracing::trace;
11
12use super::{
13    remote_map::{PathSelection, PathSelectionContext, PathSelectionData, PathSelector},
14    transports::AddrKind,
15};
16use crate::socket::transports::FourTuple;
17
18/// How much do we prefer IPv6 over IPv4 by default.
19const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
20
21/// Stickiness threshold for biased RTT comparisons.  Switching to a same-tier path only
22/// happens when its biased RTT is at least this much better than the current path's.
23const RTT_SWITCHING_MIN: Duration = Duration::from_millis(5);
24
25/// Whether a transport is a primary path or a backup.
26///
27/// Primary paths are used preferentially.  Backup paths are only used when no primary
28/// path is available.  This is independent of the QUIC `PathStatus`; today the only
29/// transport classified as backup is the relay transport.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
31enum TransportType {
32    /// A primary path: used whenever available.
33    Primary,
34    /// A backup path: only used when no primary path is available.
35    Backup,
36}
37
38/// Bias configuration for a single transport kind.
39///
40/// Used by [`BiasedRttPathSelector`] to bias path selection per address kind.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
42pub(crate) struct TransportBias {
43    transport_type: TransportType,
44    /// RTT bias in nanoseconds.  Negative values make this transport more preferred.
45    rtt_bias: i128,
46}
47
48impl TransportBias {
49    /// Creates a primary transport bias with no RTT advantage.
50    pub(crate) fn primary() -> Self {
51        Self {
52            transport_type: TransportType::Primary,
53            rtt_bias: 0,
54        }
55    }
56
57    /// Creates a backup transport bias with no RTT advantage.
58    fn backup() -> Self {
59        Self {
60            transport_type: TransportType::Backup,
61            rtt_bias: 0,
62        }
63    }
64
65    /// Adds an RTT advantage to this transport, making it more preferred.
66    pub(crate) fn with_rtt_advantage(mut self, advantage: Duration) -> Self {
67        self.rtt_bias -= advantage.as_nanos() as i128;
68        self
69    }
70
71    /// Adds an RTT disadvantage to this transport, making it less preferred.
72    #[cfg(all(test, feature = "unstable-custom-transports"))]
73    pub(crate) fn with_rtt_disadvantage(mut self, disadvantage: Duration) -> Self {
74        self.rtt_bias += disadvantage.as_nanos() as i128;
75        self
76    }
77}
78
79/// The default [`PathSelector`] used by iroh.
80///
81/// Sorts paths by `(transport_type, biased_rtt)` (primary tier wins, then lowest biased
82/// RTT).  Within the same tier, switching only happens once a candidate's biased RTT is
83/// at least 5ms better than the currently-selected path — this avoids flapping under
84/// jitter.  Across tiers, switching is immediate.
85///
86/// The biases are configured per [`AddrKind`].  Defaults: IPv4 and IPv6 are primary
87/// (IPv6 has a 3ms RTT advantage), Relay is backup, custom transports are primary with
88/// no advantage.
89#[derive(Debug, Clone)]
90pub(crate) struct BiasedRttPathSelector {
91    biases: Arc<FxHashMap<AddrKind, TransportBias>>,
92}
93
94impl Default for BiasedRttPathSelector {
95    fn default() -> Self {
96        let mut map = FxHashMap::default();
97        map.insert(AddrKind::IpV4, TransportBias::primary());
98        map.insert(
99            AddrKind::IpV6,
100            TransportBias::primary().with_rtt_advantage(IPV6_RTT_ADVANTAGE),
101        );
102        map.insert(AddrKind::Relay, TransportBias::backup());
103        Self {
104            biases: Arc::new(map),
105        }
106    }
107}
108
109impl BiasedRttPathSelector {
110    /// Returns a new selector with the given bias added or updated for `kind`.
111    #[cfg(all(test, feature = "unstable-custom-transports"))]
112    pub(crate) fn with_bias(self, kind: AddrKind, bias: TransportBias) -> Self {
113        let mut map = (*self.biases).clone();
114        map.insert(kind, bias);
115        Self {
116            biases: Arc::new(map),
117        }
118    }
119
120    /// Looks up the bias for an address.  Defaults to primary with no RTT bias.
121    fn bias_for(&self, addr: &FourTuple) -> TransportBias {
122        self.biases
123            .get(&addr.addr_kind())
124            .copied()
125            .unwrap_or_else(TransportBias::primary)
126    }
127
128    /// Computes the sort key for a path: lower is better.
129    fn sort_key(&self, addr: &FourTuple, rtt: Duration) -> (TransportType, i128) {
130        let bias = self.bias_for(addr);
131        let biased_rtt = (rtt.as_nanos() as i128).saturating_add(bias.rtt_bias);
132        (bias.transport_type, biased_rtt)
133    }
134}
135
136impl PathSelector for BiasedRttPathSelector {
137    fn select(&self, ctx: &PathSelectionContext<'_>) -> PathSelection {
138        // Single pass: track the best candidate by sort key, and the best (lowest)
139        // sort key seen for the currently-selected address.  When the same address
140        // appears multiple times (one path per connection), `min` over `sort_key`
141        // naturally picks the lowest-RTT instance — no separate aggregation needed.
142        let current = ctx.current();
143        let mut best: Option<(PathSelectionData<'_>, (TransportType, i128))> = None;
144        let mut current_key: Option<(TransportType, i128)> = None;
145
146        trace!("dumping path RTTs");
147        for psd in ctx.paths() {
148            let network_path = psd.network_path();
149            // Skip paths whose stats can't be read (e.g. closed concurrently with select).
150            let Some(stats) = psd.stats() else {
151                continue;
152            };
153            let rtt = stats.rtt;
154            trace!(%network_path, ?rtt);
155            let key = self.sort_key(network_path, rtt);
156
157            if Some(network_path) == current && current_key.is_none_or(|c| key < c) {
158                current_key = Some(key);
159            }
160            if best.as_ref().is_none_or(|(_, b)| key < *b) {
161                best = Some((psd, key));
162            }
163        }
164
165        let mut selection = PathSelection::none();
166        let Some((best_psd, (best_tier, best_biased))) = best else {
167            return selection;
168        };
169
170        // If we have no current path or no data for it, switch to the best.
171        let Some((current_tier, current_biased)) = current_key else {
172            selection.set(&best_psd);
173            return selection;
174        };
175
176        if current_tier != best_tier {
177            // Always switch across tiers (e.g. relay -> primary).
178            selection.set(&best_psd);
179        } else if best_biased + RTT_SWITCHING_MIN.as_nanos() as i128 <= current_biased {
180            // For the same tier, only switch when biased RTT is meaningfully better.
181            selection.set(&best_psd);
182        }
183        selection
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
190
191    use iroh_base::{EndpointId, RelayUrl};
192    use noq::PathStats;
193
194    use super::*;
195    use crate::socket::{
196        remote_map::{PathSelectionContext, PathSelectionData},
197        transports::{self, Addr},
198    };
199
200    fn v4(port: u16) -> transports::FourTuple {
201        transports::FourTuple::from_remote(Addr::Ip(SocketAddr::V4(SocketAddrV4::new(
202            Ipv4Addr::LOCALHOST,
203            port,
204        ))))
205    }
206
207    fn v6(port: u16) -> transports::FourTuple {
208        transports::FourTuple::from_remote(Addr::Ip(SocketAddr::V6(SocketAddrV6::new(
209            Ipv6Addr::LOCALHOST,
210            port,
211            0,
212            0,
213        ))))
214    }
215
216    fn relay(port: u16) -> transports::FourTuple {
217        let url = format!("https://relay{port}.iroh.computer")
218            .parse::<RelayUrl>()
219            .unwrap();
220        transports::FourTuple::from_remote(Addr::Relay(
221            url,
222            EndpointId::from_bytes(&[0u8; 32]).unwrap(),
223        ))
224    }
225
226    fn psd(addr: &transports::FourTuple, rtt_ms: u64) -> PathSelectionData<'_> {
227        // PathStats is #[non_exhaustive], so build via Default + field assignment.
228        let mut stats = PathStats::default();
229        stats.rtt = Duration::from_millis(rtt_ms);
230        PathSelectionData::for_test(addr, Some(stats))
231    }
232
233    /// Runs [`BiasedRttPathSelector::default`] against the given paths and current
234    /// selection, returning the selector's primary pick (cloned, for easier asserts).
235    fn select_with_default(
236        current: Option<&transports::FourTuple>,
237        paths: Vec<PathSelectionData<'_>>,
238    ) -> Option<transports::FourTuple> {
239        let ctx = PathSelectionContext::for_test(current, paths);
240        BiasedRttPathSelector::default()
241            .select(&ctx)
242            .selected()
243            .cloned()
244    }
245
246    #[test]
247    fn ipv6_wins_over_ipv4_within_bias() {
248        let v4 = v4(1);
249        let v6 = v6(1);
250
251        // Equal RTTs: IPv6 wins because of the bias advantage.
252        let chosen = select_with_default(None, vec![psd(&v4, 10), psd(&v6, 10)]);
253        assert_eq!(chosen.as_ref(), Some(&v6));
254
255        // IPv6 still wins when 2ms slower (within the 3ms bias).
256        let chosen = select_with_default(None, vec![psd(&v4, 10), psd(&v6, 12)]);
257        assert_eq!(chosen.as_ref(), Some(&v6));
258
259        // IPv4 wins when IPv6 is 10ms slower (exceeds 3ms bias).
260        let chosen = select_with_default(None, vec![psd(&v4, 10), psd(&v6, 20)]);
261        assert_eq!(chosen.as_ref(), Some(&v4));
262    }
263
264    #[test]
265    fn primary_wins_over_backup_regardless_of_rtt() {
266        let v4 = v4(1);
267        let relay = relay(1);
268
269        // Primary tier beats backup tier even when the backup has a much lower RTT.
270        let chosen = select_with_default(None, vec![psd(&v4, 100), psd(&relay, 10)]);
271        assert!(matches!(
272            chosen.as_ref().map(|t| t.remote()),
273            Some(Addr::Ip(_))
274        ));
275
276        // Even more extreme: 1000ms primary still wins over 1ms backup.
277        let chosen = select_with_default(None, vec![psd(&v4, 1000), psd(&relay, 1)]);
278        assert!(matches!(
279            chosen.as_ref().map(|t| t.remote()),
280            Some(Addr::Ip(_))
281        ));
282    }
283
284    #[test]
285    fn same_tier_only_switches_with_significant_rtt_diff() {
286        let v4_1 = v4(1);
287        let v4_2 = v4(2);
288
289        // 2ms diff < 5ms threshold → keep current (no switch, primary() == None).
290        let chosen = select_with_default(Some(&v4_1), vec![psd(&v4_1, 20), psd(&v4_2, 18)]);
291        assert_eq!(chosen, None);
292
293        // 4ms diff < 5ms → keep current.
294        let chosen = select_with_default(Some(&v4_1), vec![psd(&v4_1, 20), psd(&v4_2, 16)]);
295        assert_eq!(chosen, None);
296
297        // 5ms diff hits the threshold (the condition is `<=`) → switch.
298        let chosen = select_with_default(Some(&v4_1), vec![psd(&v4_1, 20), psd(&v4_2, 15)]);
299        assert_eq!(chosen.as_ref(), Some(&v4_2));
300
301        // 6ms diff > 5ms → switch.
302        let chosen = select_with_default(Some(&v4_1), vec![psd(&v4_1, 20), psd(&v4_2, 14)]);
303        assert_eq!(chosen.as_ref(), Some(&v4_2));
304    }
305
306    #[test]
307    fn no_current_path_selects_best() {
308        let v4_1 = v4(1);
309        let v4_2 = v4(2);
310        let chosen = select_with_default(None, vec![psd(&v4_1, 20), psd(&v4_2, 10)]);
311        assert_eq!(chosen.as_ref(), Some(&v4_2));
312    }
313
314    #[test]
315    fn empty_paths_returns_none() {
316        // No current, no candidates: nothing to pick.
317        assert_eq!(select_with_default(None, vec![]), None);
318
319        // Current is set but there are no candidates: keep current (primary() == None).
320        let v4 = v4(1);
321        assert_eq!(select_with_default(Some(&v4), vec![]), None);
322    }
323}