adaptive-timeout 0.0.1-alpha.4

Adaptive timeout computation based on observed latency percentiles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::hash::{BuildHasher, Hash};
use std::time::Duration;

use crate::clock;
use crate::config::TimeoutConfig;
use crate::tracker::LatencyTracker;

/// Computes adaptive timeouts based on observed latency quantiles.
///
/// For each destination, queries the tracker for a high quantile (default:
/// P99.99), applies a safety factor and exponential backoff, clamps between
/// floor and ceiling, and takes the maximum across all destinations.
///
/// Falls back to pure exponential backoff when histogram data is insufficient.
///
/// # Example
///
/// ```
/// use std::time::{Duration, Instant};
/// use adaptive_timeout::{AdaptiveTimeout, LatencyTracker};
///
/// let now = Instant::now();
/// let mut tracker = LatencyTracker::<u32, Instant>::default();
/// let timeout = AdaptiveTimeout::default();
///
/// // No data yet — falls back to exponential backoff (min_timeout).
/// let t = timeout.select_timeout(&mut tracker, &[1u32], 1, now);
/// assert_eq!(t, Duration::from_millis(250));
/// ```
#[derive(Default, Clone)]
pub struct AdaptiveTimeout {
    config: TimeoutConfig,
}

impl AdaptiveTimeout {
    /// Creates a new `AdaptiveTimeout` with the given configuration.
    pub fn new(config: TimeoutConfig) -> Self {
        Self { config }
    }

    /// Computes an adaptive timeout for a request to the given destinations.
    ///
    /// Returns the maximum timeout across all destinations, clamped to
    /// `[min_timeout, max_timeout]`. `attempt` is 1-based; higher attempts
    /// produce longer timeouts via exponential backoff.
    #[inline]
    pub fn select_timeout<'a, D, I, H, const N: usize>(
        &self,
        tracker: &mut LatencyTracker<D, I, H, N>,
        destinations: impl IntoIterator<Item = &'a D>,
        attempt: u32,
        now: I,
    ) -> Duration
    where
        D: Hash + Eq + Clone + 'a,
        I: clock::Instant,
        H: BuildHasher,
    {
        Duration::from_millis(self.select_timeout_ms(tracker, destinations, attempt, now))
    }

    /// Computes an adaptive timeout in milliseconds.
    /// See [`select_timeout`](Self::select_timeout).
    pub fn select_timeout_ms<'a, D, I, H, const N: usize>(
        &self,
        tracker: &mut LatencyTracker<D, I, H, N>,
        destinations: impl IntoIterator<Item = &'a D>,
        attempt: u32,
        now: I,
    ) -> u64
    where
        D: Hash + Eq + Clone + 'a,
        I: clock::Instant,
        H: BuildHasher,
    {
        let multiplier = Self::attempt_multiplier(attempt);
        let floor = self.config.backoff.min_ms.get() as u64;
        let ceiling = self.config.backoff.max_ms.get() as u64;
        let fallback = (floor * multiplier).min(ceiling);
        let mut selected = fallback;

        for dest in destinations.into_iter() {
            if let Some(estimate_ms) = tracker.quantile_ms(dest, self.config.quantile, now) {
                let adaptive_ms = self.compute_adaptive_ms(estimate_ms, multiplier);
                let clamped = adaptive_ms.max(floor).min(ceiling);
                selected = selected.max(clamped);
            }
        }

        selected
    }

    /// Pure exponential backoff: `min_timeout * 2^(attempt - 1)`, clamped to
    /// `max_timeout`. Fallback when histogram data is insufficient.
    #[inline]
    pub fn exponential_backoff(&self, attempt: u32) -> Duration {
        Duration::from_millis(self.exponential_backoff_ms(attempt))
    }

    /// Pure exponential backoff in milliseconds.
    #[inline]
    pub fn exponential_backoff_ms(&self, attempt: u32) -> u64 {
        let multiplier = Self::attempt_multiplier(attempt);
        let base = self.config.backoff.min_ms.get() as u64;
        let ceiling = self.config.backoff.max_ms.get() as u64;
        (base * multiplier).min(ceiling)
    }

    /// `2^(attempt - 1)`, capped at `2^20`.
    #[inline]
    fn attempt_multiplier(attempt: u32) -> u64 {
        let exponent = attempt.saturating_sub(1).min(20);
        1u64 << exponent
    }

    /// `safety_factor * estimate_ms * multiplier`.
    #[inline]
    fn compute_adaptive_ms(&self, estimate_ms: u64, multiplier: u64) -> u64 {
        let base = estimate_ms.saturating_mul(multiplier);
        (self.config.safety_factor * base as f64) as u64
    }

    /// Returns a reference to the timeout configuration.
    #[inline]
    pub fn config(&self) -> &TimeoutConfig {
        &self.config
    }

    // -----------------------------------------------------------------------
    // SyncLatencyTracker variants (feature = "sync")
    // -----------------------------------------------------------------------

    /// Like [`select_timeout`](Self::select_timeout) but for
    /// [`SyncLatencyTracker`](crate::SyncLatencyTracker).
    ///
    /// Takes `&tracker` (shared reference) instead of `&mut tracker`.
    #[cfg(feature = "sync")]
    #[inline]
    pub fn select_timeout_sync<'a, D, I, H, const N: usize>(
        &self,
        tracker: &crate::sync_tracker::SyncLatencyTracker<D, I, H, N>,
        destinations: impl IntoIterator<Item = &'a D>,
        attempt: u32,
        now: I,
    ) -> Duration
    where
        D: Hash + Eq + Clone + Send + Sync + 'a,
        I: clock::Instant,
        H: BuildHasher + Clone,
    {
        Duration::from_millis(self.select_timeout_sync_ms(tracker, destinations, attempt, now))
    }

    /// Like [`select_timeout_ms`](Self::select_timeout_ms) but for
    /// [`SyncLatencyTracker`](crate::SyncLatencyTracker).
    #[cfg(feature = "sync")]
    pub fn select_timeout_sync_ms<'a, D, I, H, const N: usize>(
        &self,
        tracker: &crate::sync_tracker::SyncLatencyTracker<D, I, H, N>,
        destinations: impl IntoIterator<Item = &'a D>,
        attempt: u32,
        now: I,
    ) -> u64
    where
        D: Hash + Eq + Clone + Send + Sync + 'a,
        I: clock::Instant,
        H: BuildHasher + Clone,
    {
        let multiplier = Self::attempt_multiplier(attempt);
        let floor = self.config.backoff.min_ms.get() as u64;
        let ceiling = self.config.backoff.max_ms.get() as u64;
        let fallback = (floor * multiplier).min(ceiling);
        let mut selected = fallback;

        for dest in destinations.into_iter() {
            if let Some(estimate_ms) = tracker.quantile_ms(dest, self.config.quantile, now) {
                let adaptive_ms = self.compute_adaptive_ms(estimate_ms, multiplier);
                let clamped = adaptive_ms.max(floor).min(ceiling);
                selected = selected.max(clamped);
            }
        }

        selected
    }
}

#[cfg(test)]
mod tests {
    use std::time::Instant;

    use super::*;
    use crate::config::TrackerConfig;
    use crate::parse::BackoffInterval;

    fn make_tracker_and_timeout<I: clock::Instant>() -> (LatencyTracker<u32, I>, AdaptiveTimeout) {
        let tracker_config = TrackerConfig {
            min_samples: 5,
            ..TrackerConfig::default()
        };
        let timeout_config = TimeoutConfig {
            backoff: "10ms..60s".parse::<BackoffInterval>().unwrap(),
            quantile: 0.99,
            safety_factor: 2.0,
        };
        (
            LatencyTracker::new(tracker_config),
            AdaptiveTimeout::new(timeout_config),
        )
    }

    #[test]
    fn fallback_exponential_backoff_no_data() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        let t1 = timeout.select_timeout(&mut tracker, &[1u32], 1, now);
        assert_eq!(t1, Duration::from_millis(10));

        let t2 = timeout.select_timeout(&mut tracker, &[1u32], 2, now);
        assert_eq!(t2, Duration::from_millis(20));

        let t3 = timeout.select_timeout(&mut tracker, &[1u32], 3, now);
        assert_eq!(t3, Duration::from_millis(40));
    }

    #[test]
    fn exponential_backoff_capped_at_max() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        let t = timeout.select_timeout(&mut tracker, &[1u32], 100, now);
        assert_eq!(t, Duration::from_secs(60));
    }

    #[test]
    fn adaptive_timeout_with_data() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        for _ in 0..100 {
            tracker.record_latency(&1u32, Duration::from_millis(50), now);
        }

        // p99 ~50ms, safety_factor=2, attempt=1: 2 * 50 * 1 = 100ms
        let t = timeout.select_timeout(&mut tracker, &[1u32], 1, now);
        assert_eq!(t, Duration::from_millis(100));
    }

    #[test]
    fn adaptive_timeout_respects_floor() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        for _ in 0..100 {
            tracker.record_latency(&1u32, Duration::from_millis(1), now);
        }

        let t = timeout.select_timeout(&mut tracker, &[1u32], 1, now);
        assert_eq!(t, Duration::from_millis(10));
    }

    #[test]
    fn adaptive_timeout_respects_ceiling() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        for _ in 0..100 {
            tracker.record_latency(&1u32, Duration::from_millis(50_000), now);
        }

        let t = timeout.select_timeout(&mut tracker, &[1u32], 1, now);
        assert_eq!(t, Duration::from_secs(60));
    }

    #[test]
    fn max_across_destinations() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        for _ in 0..100 {
            tracker.record_latency(&1u32, Duration::from_millis(10), now);
            tracker.record_latency(&2u32, Duration::from_millis(500), now);
        }

        let t = timeout.select_timeout(&mut tracker, &[1u32, 2u32], 1, now);
        assert!(
            t >= Duration::from_millis(990) && t <= Duration::from_millis(1010),
            "timeout was {t:?}"
        );
    }

    #[test]
    fn attempt_multiplier_increases_timeout() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        for _ in 0..100 {
            tracker.record_latency(&1u32, Duration::from_millis(50), now);
        }

        let t1 = timeout.select_timeout(&mut tracker, &[1u32], 1, now);
        let t2 = timeout.select_timeout(&mut tracker, &[1u32], 2, now);
        let t3 = timeout.select_timeout(&mut tracker, &[1u32], 3, now);

        assert_eq!(t1, Duration::from_millis(100));
        assert_eq!(t2, Duration::from_millis(200));
        assert_eq!(t3, Duration::from_millis(400));
    }

    #[test]
    fn mixed_data_and_no_data_destinations() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        for _ in 0..100 {
            tracker.record_latency(&1u32, Duration::from_millis(50), now);
        }

        let t = timeout.select_timeout(&mut tracker, &[1u32, 2u32], 1, now);
        assert_eq!(t, Duration::from_millis(100));
    }

    #[test]
    fn ms_variants_match_duration_variants() {
        let now = Instant::now();
        let (mut tracker, timeout) = make_tracker_and_timeout();

        for _ in 0..100 {
            tracker.record_latency(&1u32, Duration::from_millis(50), now);
        }

        let dur = timeout.select_timeout(&mut tracker, &[1u32], 1, now);
        let ms = timeout.select_timeout_ms(&mut tracker, &[1u32], 1, now);
        assert_eq!(dur, Duration::from_millis(ms));

        let dur_fb = timeout.exponential_backoff(3);
        let ms_fb = timeout.exponential_backoff_ms(3);
        assert_eq!(dur_fb, Duration::from_millis(ms_fb));
    }

    // -----------------------------------------------------------------------
    // SyncLatencyTracker tests (feature = "sync")
    // -----------------------------------------------------------------------

    #[cfg(feature = "sync")]
    mod sync_tests {
        use std::time::{Duration, Instant};

        use crate::config::{TimeoutConfig, TrackerConfig};
        use crate::parse::BackoffInterval;
        use crate::sync_tracker::SyncLatencyTracker;
        use crate::timeout::AdaptiveTimeout;

        fn make_sync_tracker_and_timeout() -> (SyncLatencyTracker<u32>, AdaptiveTimeout) {
            let tracker_config = TrackerConfig {
                min_samples: 5,
                ..TrackerConfig::default()
            };
            let timeout_config = TimeoutConfig {
                backoff: "10ms..60s".parse::<BackoffInterval>().unwrap(),
                quantile: 0.99,
                safety_factor: 2.0,
            };
            (
                SyncLatencyTracker::new(tracker_config),
                AdaptiveTimeout::new(timeout_config),
            )
        }

        #[test]
        fn sync_fallback_exponential_backoff_no_data() {
            let now = Instant::now();
            let (tracker, timeout) = make_sync_tracker_and_timeout();

            let t1 = timeout.select_timeout_sync(&tracker, &[1u32], 1, now);
            assert_eq!(t1, Duration::from_millis(10));

            let t2 = timeout.select_timeout_sync(&tracker, &[1u32], 2, now);
            assert_eq!(t2, Duration::from_millis(20));

            let t3 = timeout.select_timeout_sync(&tracker, &[1u32], 3, now);
            assert_eq!(t3, Duration::from_millis(40));
        }

        #[test]
        fn sync_adaptive_timeout_with_data() {
            let now = Instant::now();
            let (tracker, timeout) = make_sync_tracker_and_timeout();

            for _ in 0..100 {
                tracker.record_latency(&1u32, Duration::from_millis(50), now);
            }

            // p99 ~50ms, safety_factor=2, attempt=1: 2 * 50 * 1 = 100ms
            let t = timeout.select_timeout_sync(&tracker, &[1u32], 1, now);
            assert_eq!(t, Duration::from_millis(100));
        }

        #[test]
        fn sync_respects_floor_and_ceiling() {
            let now = Instant::now();
            let (tracker, timeout) = make_sync_tracker_and_timeout();

            // Floor: tiny latency clamped to min_timeout
            for _ in 0..100 {
                tracker.record_latency(&1u32, Duration::from_millis(1), now);
            }
            let t = timeout.select_timeout_sync(&tracker, &[1u32], 1, now);
            assert_eq!(t, Duration::from_millis(10));

            // Ceiling: huge latency clamped to max_timeout
            for _ in 0..100 {
                tracker.record_latency(&2u32, Duration::from_millis(50_000), now);
            }
            let t = timeout.select_timeout_sync(&tracker, &[2u32], 1, now);
            assert_eq!(t, Duration::from_secs(60));
        }

        #[test]
        fn sync_max_across_destinations() {
            let now = Instant::now();
            let (tracker, timeout) = make_sync_tracker_and_timeout();

            for _ in 0..100 {
                tracker.record_latency(&1u32, Duration::from_millis(10), now);
                tracker.record_latency(&2u32, Duration::from_millis(500), now);
            }

            let t = timeout.select_timeout_sync(&tracker, &[1u32, 2u32], 1, now);
            assert!(
                t >= Duration::from_millis(990) && t <= Duration::from_millis(1010),
                "timeout was {t:?}"
            );
        }

        #[test]
        fn sync_ms_variants_match_duration_variants() {
            let now = Instant::now();
            let (tracker, timeout) = make_sync_tracker_and_timeout();

            for _ in 0..100 {
                tracker.record_latency(&1u32, Duration::from_millis(50), now);
            }

            let dur = timeout.select_timeout_sync(&tracker, &[1u32], 1, now);
            let ms = timeout.select_timeout_sync_ms(&tracker, &[1u32], 1, now);
            assert_eq!(dur, Duration::from_millis(ms));
        }

        #[test]
        fn sync_matches_mutable_tracker_results() {
            use crate::tracker::LatencyTracker;

            let now = Instant::now();
            let tracker_config = TrackerConfig {
                min_samples: 5,
                ..TrackerConfig::default()
            };
            let timeout_config = TimeoutConfig {
                backoff: "10ms..60s".parse::<BackoffInterval>().unwrap(),
                quantile: 0.99,
                safety_factor: 2.0,
            };

            let mut mutable_tracker = LatencyTracker::<u32, Instant>::new(tracker_config);
            let sync_tracker = SyncLatencyTracker::<u32>::new(tracker_config);
            let timeout = AdaptiveTimeout::new(timeout_config);

            // Same data in both trackers.
            for _ in 0..100 {
                mutable_tracker.record_latency(&1u32, Duration::from_millis(50), now);
                sync_tracker.record_latency(&1u32, Duration::from_millis(50), now);
            }

            let ms_mut = timeout.select_timeout_ms(&mut mutable_tracker, &[1u32], 1, now);
            let ms_sync = timeout.select_timeout_sync_ms(&sync_tracker, &[1u32], 1, now);
            assert_eq!(ms_mut, ms_sync);
        }
    }
}