scatter-proxy 0.8.0

Async request scheduler for unreliable SOCKS5 proxies — multi-path race for maximum throughput
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
use dashmap::DashMap;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::time::Instant;

use crate::metrics::ProxyHostStats;

/// Internal entry for a (proxy, host) pair.
struct HealthEntry {
    /// Sliding window of recent results: `true` = success, `false` = failure.
    window: VecDeque<bool>,
    /// Maximum number of results retained in the sliding window.
    window_size: usize,
    /// Lifetime success count.
    total_success: u32,
    /// Lifetime failure count.
    total_fail: u32,
    /// Running sum of latencies (ms) for successful requests.
    latency_sum: f64,
    /// Number of latency samples recorded.
    latency_count: u32,
    /// Current streak of consecutive failures (reset on success).
    consecutive_fails: u32,
    /// Timestamp of the most recent request (success or failure).
    last_access: Option<Instant>,
    /// Timestamp of the most recent successful request.
    last_success: Option<Instant>,
}

impl HealthEntry {
    fn new(window_size: usize) -> Self {
        Self {
            window: VecDeque::with_capacity(window_size),
            window_size,
            total_success: 0,
            total_fail: 0,
            latency_sum: 0.0,
            latency_count: 0,
            consecutive_fails: 0,
            last_access: None,
            last_success: None,
        }
    }

    /// Push a result into the sliding window, evicting the oldest entry if full.
    fn push_result(&mut self, success: bool) {
        if self.window.len() >= self.window_size {
            self.window.pop_front();
        }
        self.window.push_back(success);
        self.last_access = Some(Instant::now());
    }

    /// Success rate within the current sliding window, or `None` if empty.
    fn window_success_rate(&self) -> Option<f64> {
        if self.window.is_empty() {
            return None;
        }
        let successes = self.window.iter().filter(|&&s| s).count() as f64;
        Some(successes / self.window.len() as f64)
    }
}

/// Concurrent health tracker that maintains per-(proxy, host) statistics.
///
/// All public methods take `&self` and are safe to call from multiple threads
/// concurrently thanks to the underlying [`DashMap`].
pub struct HealthTracker {
    entries: DashMap<(String, String), HealthEntry>,
    window_size: usize,
}

impl HealthTracker {
    /// Create a new `HealthTracker` with the given sliding-window size.
    ///
    /// A typical default is 30 (the most recent 30 results per pair).
    pub fn new(window_size: usize) -> Self {
        Self {
            entries: DashMap::new(),
            window_size,
        }
    }

    /// Record a successful request for the given `(proxy, host)` pair.
    ///
    /// Updates the sliding window, accumulates latency, and resets
    /// the consecutive-failure counter.
    pub fn record_success(&self, proxy: &str, host: &str, latency_ms: f64) {
        let key = (proxy.to_string(), host.to_string());
        let mut entry = self
            .entries
            .entry(key)
            .or_insert_with(|| HealthEntry::new(self.window_size));
        entry.push_result(true);
        entry.total_success += 1;
        entry.latency_sum += latency_ms;
        entry.latency_count += 1;
        entry.consecutive_fails = 0;
        entry.last_success = Some(Instant::now());
    }

    /// Record a failed request for the given `(proxy, host)` pair.
    ///
    /// Updates the sliding window and increments the consecutive-failure counter.
    pub fn record_failure(&self, proxy: &str, host: &str) {
        let key = (proxy.to_string(), host.to_string());
        let mut entry = self
            .entries
            .entry(key)
            .or_insert_with(|| HealthEntry::new(self.window_size));
        entry.push_result(false);
        entry.total_fail += 1;
        entry.consecutive_fails += 1;
    }

    /// Return a snapshot of the stats for a `(proxy, host)` pair, or `None`
    /// if no data has been recorded yet.
    #[allow(dead_code)]
    pub fn get_stats(&self, proxy: &str, host: &str) -> Option<ProxyHostStats> {
        let key = (proxy.to_string(), host.to_string());
        self.entries.get(&key).map(|entry| {
            let success_rate = entry.window_success_rate().unwrap_or(0.0);
            let avg_latency_ms = if entry.latency_count > 0 {
                entry.latency_sum / entry.latency_count as f64
            } else {
                0.0
            };
            ProxyHostStats {
                success: entry.total_success,
                fail: entry.total_fail,
                success_rate,
                avg_latency_ms,
                consecutive_fails: entry.consecutive_fails,
            }
        })
    }

    /// Sliding-window success rate for `(proxy, host)`.
    ///
    /// Returns `0.5` when no data exists (optimistic prior).
    pub fn get_affinity(&self, proxy: &str, host: &str) -> f64 {
        let key = (proxy.to_string(), host.to_string());
        self.entries
            .get(&key)
            .and_then(|entry| entry.window_success_rate())
            .unwrap_or(0.5)
    }

    /// Global sliding-window success rate for a proxy across **all** hosts.
    ///
    /// Returns `0.5` when no data exists.
    pub fn get_global_health(&self, proxy: &str) -> f64 {
        let mut total_successes: usize = 0;
        let mut total_samples: usize = 0;
        for entry in self.entries.iter() {
            let (p, _) = entry.key();
            if p == proxy {
                let v = entry.value();
                total_successes += v.window.iter().filter(|&&s| s).count();
                total_samples += v.window.len();
            }
        }
        if total_samples == 0 {
            0.5
        } else {
            total_successes as f64 / total_samples as f64
        }
    }

    /// Seconds elapsed since the last access (success or failure) for `(proxy, host)`.
    ///
    /// Returns [`f64::MAX`] if the pair is unknown or has never been accessed.
    pub fn seconds_since_last_access(&self, proxy: &str, host: &str) -> f64 {
        let key = (proxy.to_string(), host.to_string());
        self.entries
            .get(&key)
            .map(|e| match e.last_access {
                Some(t) => t.elapsed().as_secs_f64(),
                None => f64::MAX,
            })
            .unwrap_or(f64::MAX)
    }

    /// Consecutive failure count for `(proxy, host)`. Returns `0` if unknown.
    pub fn get_consecutive_fails(&self, proxy: &str, host: &str) -> u32 {
        let key = (proxy.to_string(), host.to_string());
        self.entries
            .get(&key)
            .map(|e| e.consecutive_fails)
            .unwrap_or(0)
    }

    /// Minutes elapsed since the last success for `(proxy, host)`.
    ///
    /// Returns [`f64::MAX`] if there has never been a success or if the pair
    /// is unknown.
    pub fn minutes_since_last_success(&self, proxy: &str, host: &str) -> f64 {
        let key = (proxy.to_string(), host.to_string());
        self.entries
            .get(&key)
            .map(|e| match e.last_success {
                Some(t) => t.elapsed().as_secs_f64() / 60.0,
                None => f64::MAX,
            })
            .unwrap_or(f64::MAX)
    }

    /// Average sliding-window success rate across **all proxies** for a given host.
    ///
    /// Returns `0.5` if no proxy has data for this host.
    pub fn avg_success_rate_for_host(&self, host: &str) -> f64 {
        let mut sum = 0.0;
        let mut count = 0usize;
        for entry in self.entries.iter() {
            let (_, h) = entry.key();
            if h == host {
                if let Some(rate) = entry.value().window_success_rate() {
                    sum += rate;
                    count += 1;
                }
            }
        }
        if count == 0 {
            0.5
        } else {
            sum / count as f64
        }
    }

    /// Snapshot of **all** stats as a nested `HashMap<proxy, HashMap<host, stats>>`.
    ///
    /// Useful for persistence / serialisation.
    pub fn get_all_stats(&self) -> HashMap<String, HashMap<String, ProxyHostStats>> {
        let mut result: HashMap<String, HashMap<String, ProxyHostStats>> = HashMap::new();
        for entry in self.entries.iter() {
            let (proxy, host) = entry.key();
            let v = entry.value();
            let success_rate = v.window_success_rate().unwrap_or(0.0);
            let avg_latency_ms = if v.latency_count > 0 {
                v.latency_sum / v.latency_count as f64
            } else {
                0.0
            };
            let stats = ProxyHostStats {
                success: v.total_success,
                fail: v.total_fail,
                success_rate,
                avg_latency_ms,
                consecutive_fails: v.consecutive_fails,
            };
            result
                .entry(proxy.clone())
                .or_default()
                .insert(host.clone(), stats);
        }
        result
    }

    /// Restore a `(proxy, host)` entry from previously persisted data.
    ///
    /// Because the actual sliding window is not persisted, we reconstruct an
    /// approximate window from the success rate and the smaller of
    /// `(success + fail, window_size)`.
    pub fn restore(&self, proxy: &str, host: &str, stats: &ProxyHostStats) {
        let key = (proxy.to_string(), host.to_string());
        let mut entry = HealthEntry::new(self.window_size);
        entry.total_success = stats.success;
        entry.total_fail = stats.fail;
        entry.consecutive_fails = stats.consecutive_fails;

        // Reconstruct latency accumulator so avg_latency_ms is preserved.
        if stats.success > 0 {
            entry.latency_sum = stats.avg_latency_ms * stats.success as f64;
            entry.latency_count = stats.success;
        }

        // Approximate the sliding window from the persisted success rate.
        let total = (stats.success + stats.fail) as usize;
        let window_count = total.min(self.window_size);
        let successes_in_window = (stats.success_rate * window_count as f64).round() as usize;
        // Fill failures first, then successes (order is approximate).
        let failures_in_window = window_count.saturating_sub(successes_in_window);
        for _ in 0..failures_in_window {
            entry.window.push_back(false);
        }
        for _ in 0..successes_in_window {
            entry.window.push_back(true);
        }

        self.entries.insert(key, entry);
    }

    /// Global total success count across all `(proxy, host)` pairs.
    pub fn total_success(&self) -> u64 {
        self.entries
            .iter()
            .map(|e| e.value().total_success as u64)
            .sum()
    }

    /// Global total failure count across all `(proxy, host)` pairs.
    pub fn total_fail(&self) -> u64 {
        self.entries
            .iter()
            .map(|e| e.value().total_fail as u64)
            .sum()
    }

    /// Global average latency (ms) across all `(proxy, host)` pairs.
    ///
    /// Returns `0.0` if no latency samples exist.
    pub fn avg_latency_ms(&self) -> f64 {
        let mut total_sum = 0.0f64;
        let mut total_count = 0u64;
        for entry in self.entries.iter() {
            total_sum += entry.value().latency_sum;
            total_count += entry.value().latency_count as u64;
        }
        if total_count == 0 {
            0.0
        } else {
            total_sum / total_count as f64
        }
    }

    /// Total number of samples (success + fail) for a proxy across all hosts.
    pub fn total_samples_for_proxy(&self, proxy: &str) -> u32 {
        let mut total = 0u32;
        for entry in self.entries.iter() {
            let (p, _) = entry.key();
            if p == proxy {
                let v = entry.value();
                total += v.total_success + v.total_fail;
            }
        }
        total
    }

    /// Global success rate for a proxy (lifetime, not windowed).
    ///
    /// Returns `0.0` if no samples exist. Used for eviction decisions.
    pub fn global_success_rate_for_proxy(&self, proxy: &str) -> f64 {
        let mut total_success = 0u64;
        let mut total_samples = 0u64;
        for entry in self.entries.iter() {
            let (p, _) = entry.key();
            if p == proxy {
                let v = entry.value();
                total_success += v.total_success as u64;
                total_samples += (v.total_success + v.total_fail) as u64;
            }
        }
        if total_samples == 0 {
            0.0
        } else {
            total_success as f64 / total_samples as f64
        }
    }
}

impl Default for HealthTracker {
    fn default() -> Self {
        Self::new(30)
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    const PROXY_A: &str = "socks5://1.2.3.4:1080";
    const PROXY_B: &str = "socks5://5.6.7.8:9050";
    const HOST_X: &str = "yunhq.sse.com.cn";
    const HOST_Y: &str = "www.szse.cn";

    fn tracker() -> HealthTracker {
        HealthTracker::new(5)
    }

    // ── record_success / record_failure basics ──────────────────────────

    #[test]
    fn record_success_updates_stats() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 120.0);

        let stats = ht.get_stats(PROXY_A, HOST_X).unwrap();
        assert_eq!(stats.success, 1);
        assert_eq!(stats.fail, 0);
        assert!((stats.success_rate - 1.0).abs() < f64::EPSILON);
        assert!((stats.avg_latency_ms - 120.0).abs() < f64::EPSILON);
        assert_eq!(stats.consecutive_fails, 0);
    }

    #[test]
    fn record_failure_updates_stats() {
        let ht = tracker();
        ht.record_failure(PROXY_A, HOST_X);

        let stats = ht.get_stats(PROXY_A, HOST_X).unwrap();
        assert_eq!(stats.success, 0);
        assert_eq!(stats.fail, 1);
        assert!((stats.success_rate).abs() < f64::EPSILON);
        assert_eq!(stats.consecutive_fails, 1);
    }

    #[test]
    fn success_resets_consecutive_fails() {
        let ht = tracker();
        ht.record_failure(PROXY_A, HOST_X);
        ht.record_failure(PROXY_A, HOST_X);
        assert_eq!(ht.get_consecutive_fails(PROXY_A, HOST_X), 2);

        ht.record_success(PROXY_A, HOST_X, 50.0);
        assert_eq!(ht.get_consecutive_fails(PROXY_A, HOST_X), 0);
    }

    #[test]
    fn consecutive_fails_increments() {
        let ht = tracker();
        for _ in 0..5 {
            ht.record_failure(PROXY_A, HOST_X);
        }
        assert_eq!(ht.get_consecutive_fails(PROXY_A, HOST_X), 5);
    }

    // ── Sliding window ──────────────────────────────────────────────────

    #[test]
    fn sliding_window_evicts_oldest() {
        let ht = HealthTracker::new(3);
        // Fill window: [F, F, F]
        ht.record_failure(PROXY_A, HOST_X);
        ht.record_failure(PROXY_A, HOST_X);
        ht.record_failure(PROXY_A, HOST_X);
        assert!((ht.get_affinity(PROXY_A, HOST_X)).abs() < f64::EPSILON);

        // Push successes, evicting old failures: [F, S, S] → [S, S, S]
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);

        assert!((ht.get_affinity(PROXY_A, HOST_X) - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn window_size_respected() {
        let ht = HealthTracker::new(4);
        // 2 successes then 2 failures → window [S, S, F, F] → rate = 0.5
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_failure(PROXY_A, HOST_X);
        ht.record_failure(PROXY_A, HOST_X);
        assert!((ht.get_affinity(PROXY_A, HOST_X) - 0.5).abs() < f64::EPSILON);

        // One more success → window [S, F, F, S] → rate = 0.5
        ht.record_success(PROXY_A, HOST_X, 10.0);
        assert!((ht.get_affinity(PROXY_A, HOST_X) - 0.5).abs() < f64::EPSILON);
    }

    // ── get_affinity ────────────────────────────────────────────────────

    #[test]
    fn affinity_returns_half_when_unknown() {
        let ht = tracker();
        assert!((ht.get_affinity(PROXY_A, HOST_X) - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn affinity_reflects_window() {
        let ht = HealthTracker::new(4);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_failure(PROXY_A, HOST_X);
        assert!((ht.get_affinity(PROXY_A, HOST_X) - 0.75).abs() < f64::EPSILON);
    }

    // ── get_global_health ───────────────────────────────────────────────

    #[test]
    fn global_health_returns_half_when_unknown() {
        let ht = tracker();
        assert!((ht.get_global_health(PROXY_A) - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn global_health_aggregates_across_hosts() {
        let ht = tracker();
        // PROXY_A + HOST_X: 2 successes
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        // PROXY_A + HOST_Y: 1 success, 1 fail
        ht.record_success(PROXY_A, HOST_Y, 10.0);
        ht.record_failure(PROXY_A, HOST_Y);
        // Total window: 3 successes out of 4 = 0.75
        assert!((ht.get_global_health(PROXY_A) - 0.75).abs() < f64::EPSILON);
    }

    #[test]
    fn global_health_ignores_other_proxies() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_failure(PROXY_B, HOST_X);
        // PROXY_A window: [S] → 1.0
        assert!((ht.get_global_health(PROXY_A) - 1.0).abs() < f64::EPSILON);
        // PROXY_B window: [F] → 0.0
        assert!(ht.get_global_health(PROXY_B).abs() < f64::EPSILON);
    }

    // ── minutes_since_last_success ──────────────────────────────────────

    #[test]
    fn minutes_since_last_success_returns_max_when_unknown() {
        let ht = tracker();
        assert_eq!(ht.minutes_since_last_success(PROXY_A, HOST_X), f64::MAX);
    }

    #[test]
    fn minutes_since_last_success_returns_max_when_only_failures() {
        let ht = tracker();
        ht.record_failure(PROXY_A, HOST_X);
        assert_eq!(ht.minutes_since_last_success(PROXY_A, HOST_X), f64::MAX);
    }

    #[test]
    fn minutes_since_last_success_is_small_after_success() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 10.0);
        // Should be very close to 0 minutes.
        assert!(ht.minutes_since_last_success(PROXY_A, HOST_X) < 0.1);
    }

    // ── avg_success_rate_for_host ───────────────────────────────────────

    #[test]
    fn avg_success_rate_for_host_returns_half_when_unknown() {
        let ht = tracker();
        assert!((ht.avg_success_rate_for_host(HOST_X) - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn avg_success_rate_for_host_averages_across_proxies() {
        let ht = HealthTracker::new(10);
        // PROXY_A → HOST_X: 100% (2/2)
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        // PROXY_B → HOST_X: 50% (1/2)
        ht.record_success(PROXY_B, HOST_X, 10.0);
        ht.record_failure(PROXY_B, HOST_X);
        // Average: (1.0 + 0.5) / 2 = 0.75
        assert!((ht.avg_success_rate_for_host(HOST_X) - 0.75).abs() < f64::EPSILON);
    }

    // ── get_stats / get_all_stats ───────────────────────────────────────

    #[test]
    fn get_stats_returns_none_for_unknown_pair() {
        let ht = tracker();
        assert!(ht.get_stats(PROXY_A, HOST_X).is_none());
    }

    #[test]
    fn get_all_stats_returns_empty_when_no_data() {
        let ht = tracker();
        assert!(ht.get_all_stats().is_empty());
    }

    #[test]
    fn get_all_stats_contains_all_pairs() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_failure(PROXY_B, HOST_Y);

        let all = ht.get_all_stats();
        assert_eq!(all.len(), 2); // two proxies
        assert!(all.contains_key(PROXY_A));
        assert!(all.contains_key(PROXY_B));
        assert!(all[PROXY_A].contains_key(HOST_X));
        assert!(all[PROXY_B].contains_key(HOST_Y));
    }

    // ── restore ─────────────────────────────────────────────────────────

    #[test]
    fn restore_recreates_entry() {
        let ht = tracker();
        let stats = ProxyHostStats {
            success: 20,
            fail: 5,
            success_rate: 0.8,
            avg_latency_ms: 100.0,
            consecutive_fails: 2,
        };
        ht.restore(PROXY_A, HOST_X, &stats);

        let restored = ht.get_stats(PROXY_A, HOST_X).unwrap();
        assert_eq!(restored.success, 20);
        assert_eq!(restored.fail, 5);
        assert_eq!(restored.consecutive_fails, 2);
        // Success rate should be approximately 0.8 (window is approximated).
        assert!((restored.success_rate - 0.8).abs() < 0.1);
        // Avg latency should be preserved.
        assert!((restored.avg_latency_ms - 100.0).abs() < f64::EPSILON);
    }

    #[test]
    fn restore_with_zero_success_preserves_zero_latency() {
        let ht = tracker();
        let stats = ProxyHostStats {
            success: 0,
            fail: 3,
            success_rate: 0.0,
            avg_latency_ms: 0.0,
            consecutive_fails: 3,
        };
        ht.restore(PROXY_A, HOST_X, &stats);

        let restored = ht.get_stats(PROXY_A, HOST_X).unwrap();
        assert_eq!(restored.success, 0);
        assert_eq!(restored.fail, 3);
        assert!((restored.avg_latency_ms).abs() < f64::EPSILON);
    }

    #[test]
    fn restore_approximates_window() {
        let ht = HealthTracker::new(10);
        let stats = ProxyHostStats {
            success: 100,
            fail: 0,
            success_rate: 1.0,
            avg_latency_ms: 50.0,
            consecutive_fails: 0,
        };
        ht.restore(PROXY_A, HOST_X, &stats);
        // Window should be full of successes → affinity ≈ 1.0
        assert!((ht.get_affinity(PROXY_A, HOST_X) - 1.0).abs() < f64::EPSILON);
    }

    // ── total_success / total_fail ──────────────────────────────────────

    #[test]
    fn total_success_accumulates_across_all_pairs() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_B, HOST_Y, 10.0);
        assert_eq!(ht.total_success(), 3);
    }

    #[test]
    fn total_fail_accumulates_across_all_pairs() {
        let ht = tracker();
        ht.record_failure(PROXY_A, HOST_X);
        ht.record_failure(PROXY_B, HOST_Y);
        ht.record_failure(PROXY_B, HOST_Y);
        assert_eq!(ht.total_fail(), 3);
    }

    // ── avg_latency_ms ──────────────────────────────────────────────────

    #[test]
    fn avg_latency_ms_zero_when_no_data() {
        let ht = tracker();
        assert!((ht.avg_latency_ms()).abs() < f64::EPSILON);
    }

    #[test]
    fn avg_latency_ms_global_average() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 100.0);
        ht.record_success(PROXY_B, HOST_Y, 200.0);
        assert!((ht.avg_latency_ms() - 150.0).abs() < f64::EPSILON);
    }

    #[test]
    fn avg_latency_ms_ignores_failures() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 100.0);
        ht.record_failure(PROXY_A, HOST_X);
        // Only 1 latency sample of 100.0
        assert!((ht.avg_latency_ms() - 100.0).abs() < f64::EPSILON);
    }

    // ── total_samples_for_proxy ─────────────────────────────────────────

    #[test]
    fn total_samples_for_proxy_counts_across_hosts() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_failure(PROXY_A, HOST_X);
        ht.record_success(PROXY_A, HOST_Y, 10.0);
        assert_eq!(ht.total_samples_for_proxy(PROXY_A), 3);
    }

    #[test]
    fn total_samples_for_proxy_ignores_other_proxies() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_failure(PROXY_B, HOST_X);
        assert_eq!(ht.total_samples_for_proxy(PROXY_A), 1);
    }

    #[test]
    fn total_samples_for_proxy_zero_when_unknown() {
        let ht = tracker();
        assert_eq!(ht.total_samples_for_proxy("unknown"), 0);
    }

    // ── global_success_rate_for_proxy ───────────────────────────────────

    #[test]
    fn global_success_rate_for_proxy_zero_when_unknown() {
        let ht = tracker();
        assert!(ht.global_success_rate_for_proxy("unknown").abs() < f64::EPSILON);
    }

    #[test]
    fn global_success_rate_for_proxy_lifetime_rate() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_failure(PROXY_A, HOST_Y);
        // 2 successes out of 3 total
        let rate = ht.global_success_rate_for_proxy(PROXY_A);
        assert!((rate - 2.0 / 3.0).abs() < f64::EPSILON);
    }

    // ── Default impl ────────────────────────────────────────────────────

    #[test]
    fn default_uses_window_size_30() {
        let ht = HealthTracker::default();
        assert_eq!(ht.window_size, 30);
    }

    // ── Edge cases ──────────────────────────────────────────────────────

    #[test]
    fn window_size_one() {
        let ht = HealthTracker::new(1);
        ht.record_success(PROXY_A, HOST_X, 10.0);
        assert!((ht.get_affinity(PROXY_A, HOST_X) - 1.0).abs() < f64::EPSILON);
        ht.record_failure(PROXY_A, HOST_X);
        assert!(ht.get_affinity(PROXY_A, HOST_X).abs() < f64::EPSILON);
    }

    #[test]
    fn many_records_beyond_window() {
        let ht = HealthTracker::new(3);
        // Record 100 failures then 3 successes
        for _ in 0..100 {
            ht.record_failure(PROXY_A, HOST_X);
        }
        for _ in 0..3 {
            ht.record_success(PROXY_A, HOST_X, 10.0);
        }
        // Window should only reflect the last 3 (all successes)
        assert!((ht.get_affinity(PROXY_A, HOST_X) - 1.0).abs() < f64::EPSILON);
        // But total_fail should be 100
        assert_eq!(ht.get_stats(PROXY_A, HOST_X).unwrap().fail, 100);
    }

    #[test]
    fn separate_pairs_are_independent() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 10.0);
        ht.record_failure(PROXY_A, HOST_Y);
        ht.record_failure(PROXY_B, HOST_X);

        assert!((ht.get_affinity(PROXY_A, HOST_X) - 1.0).abs() < f64::EPSILON);
        assert!(ht.get_affinity(PROXY_A, HOST_Y).abs() < f64::EPSILON);
        assert!(ht.get_affinity(PROXY_B, HOST_X).abs() < f64::EPSILON);
    }

    #[test]
    fn consecutive_fails_for_unknown_is_zero() {
        let ht = tracker();
        assert_eq!(ht.get_consecutive_fails("no", "where"), 0);
    }

    #[test]
    fn latency_average_across_multiple_successes() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 100.0);
        ht.record_success(PROXY_A, HOST_X, 200.0);
        ht.record_success(PROXY_A, HOST_X, 300.0);
        let stats = ht.get_stats(PROXY_A, HOST_X).unwrap();
        assert!((stats.avg_latency_ms - 200.0).abs() < 0.01);
    }

    #[test]
    fn seconds_since_last_access_returns_max_when_unknown() {
        let ht = tracker();
        assert_eq!(ht.seconds_since_last_access(PROXY_A, HOST_X), f64::MAX);
    }

    #[test]
    fn seconds_since_last_access_is_small_after_record() {
        let ht = tracker();
        ht.record_failure(PROXY_A, HOST_X);
        let secs = ht.seconds_since_last_access(PROXY_A, HOST_X);
        assert!(secs < 1.0, "expected < 1s, got {secs}");
    }

    #[test]
    fn seconds_since_last_access_updates_on_success_too() {
        let ht = tracker();
        ht.record_success(PROXY_A, HOST_X, 50.0);
        let secs = ht.seconds_since_last_access(PROXY_A, HOST_X);
        assert!(secs < 1.0, "expected < 1s, got {secs}");
    }
}