irontide-engine 1.2.1

IronTide engine runtime: the per-torrent actor, peer I/O loops, and the non-leaf engine infrastructure (disk I/O, tracker management, alerts, streaming, extensions, SSL) — the renamed irontide-torrent-actor
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
use std::collections::HashSet;
use std::net::SocketAddr;

// ---------------------------------------------------------------------------
// Algorithm enums — lifted to irontide-core (M242), re-exported for stability
// ---------------------------------------------------------------------------
pub use irontide_core::{ChokingAlgorithm, SeedChokingAlgorithm};

// ---------------------------------------------------------------------------
// PeerInfo
// ---------------------------------------------------------------------------

/// Information about a peer used by the choking algorithm.
#[derive(Debug, Clone)]
pub(crate) struct PeerInfo {
    pub addr: SocketAddr,
    /// Bytes/sec they are uploading TO us.
    pub download_rate: u64,
    /// Bytes/sec we are uploading TO them.
    pub upload_rate: u64,
    /// Peer is interested in our data.
    pub interested: bool,
    /// BEP 21: peer declared upload-only status.
    pub upload_only: bool,
    /// Whether this peer is a seed (has all pieces).
    pub is_seed: bool,
}

// ---------------------------------------------------------------------------
// ChokeDecision
// ---------------------------------------------------------------------------

/// Result of a choking decision.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ChokeDecision {
    /// Peers that should be unchoked.
    pub to_unchoke: Vec<SocketAddr>,
    /// Peers that should be choked.
    pub to_choke: Vec<SocketAddr>,
}

// ---------------------------------------------------------------------------
// ChokerStrategy trait
// ---------------------------------------------------------------------------

/// Trait for pluggable choking strategies.
pub(crate) trait ChokerStrategy: Send + Sync {
    /// Given the current peer list, decide who to unchoke/choke.
    fn decide(
        &mut self,
        peers: &[PeerInfo],
        unchoke_slots: usize,
        seed_mode: bool,
    ) -> ChokeDecision;

    /// Rotate the optimistic unchoke peer.
    fn rotate_optimistic(&mut self, peers: &[PeerInfo]);

    /// Observe current throughput for rate-based slot adjustment.
    /// No-op by default (fixed-slots strategies ignore this).
    fn observe_throughput(&mut self, _throughput: u64) {}

    /// Return the dynamically computed slot count, if this strategy manages its own.
    /// Returns `None` by default (fixed-slots strategies defer to the `Choker`'s `unchoke_slots`).
    #[allow(dead_code)] // Part of the trait API; called by RateBasedStrategy but not dispatched externally yet.
    fn dynamic_slots(&self) -> Option<usize> {
        None
    }
}

// ---------------------------------------------------------------------------
// FixedSlotsStrategy
// ---------------------------------------------------------------------------

/// Fixed-slots choking strategy.
///
/// Leech mode: tit-for-tat (sort by download rate descending).
/// Seed mode: configurable via [`SeedChokingAlgorithm`].
pub(crate) struct FixedSlotsStrategy {
    optimistic_peer: Option<SocketAddr>,
    seed_algorithm: SeedChokingAlgorithm,
    round_robin_offset: usize,
    /// Addresses that held a *regular* (rate-earned) unchoke slot in the
    /// previous `decide()` cycle. An incumbent in this set wins an *exact rate
    /// tie* against a challenger (it is the secondary sort key), so the marginal
    /// slot does not chop on `HashMap`-iteration-order nondeterminism. A
    /// challenger with a strictly higher rate still wins immediately — there is
    /// no rate margin, so tie-stability costs no steady-state throughput. Empty
    /// on the first cycle, so the first decision is identical to pure top-N.
    /// Implements "the marginal slot moves, not the whole set" (M257d).
    unchoked: HashSet<SocketAddr>,
}

// Incumbency tie-break (M257d). The choker ranks interested peers by rate and
// keeps the top N. On an *exact* rate tie the input order decides the marginal
// slot — and in production that order is `HashMap` iteration order, which varies
// run to run. That nondeterminism drove the `contended` profile's rechoke churn
// and an intermittent throughput collapse (a bimodal ~5× slowdown that an n=3
// sample missed at M257f). The fix is a secondary sort key: a peer that held a
// regular slot last cycle (`incumbents.contains(&addr)`, the `unchoked` set)
// wins the tie. No rate margin is applied — a strictly faster challenger always
// wins — so the bad tie-break outcomes go away without costing throughput. A
// cold incumbent (rate 0) ties only other rate-0 peers and still yields to any
// productive challenger. An A/B (margin 0 vs an earlier 20% bonus) confirmed the
// margin was counterproductive over-pinning: tie-break-only is collapse-free at
// 0/11 runs *and* higher mean throughput. See the M257d evidence doc.

impl FixedSlotsStrategy {
    pub fn new(seed_algorithm: SeedChokingAlgorithm) -> Self {
        Self {
            optimistic_peer: None,
            seed_algorithm,
            round_robin_offset: 0,
            unchoked: HashSet::new(),
        }
    }

    /// Select an optimistic unchoke peer.
    ///
    /// If the current optimistic peer is interested and not in the regular set,
    /// keep it. Otherwise pick the first interested peer not in the regular set.
    fn select_optimistic(
        &self,
        interested: &[&PeerInfo],
        regular_unchokes: &[SocketAddr],
    ) -> Option<SocketAddr> {
        // Keep existing optimistic peer if it qualifies.
        if let Some(opt) = self.optimistic_peer {
            let still_interested = interested.iter().any(|p| p.addr == opt && !p.upload_only);
            let already_regular = regular_unchokes.contains(&opt);
            if still_interested && !already_regular {
                return Some(opt);
            }
        }

        // Pick first interested peer not already in regular unchokes (exclude upload-only).
        interested
            .iter()
            .find(|p| !regular_unchokes.contains(&p.addr) && !p.upload_only)
            .map(|p| p.addr)
    }

    /// Sort interested peers according to the seed-mode algorithm.
    fn sort_seed_mode(
        &mut self,
        interested: &mut [&PeerInfo],
        unchoke_slots: usize,
        incumbents: &HashSet<SocketAddr>,
    ) {
        match self.seed_algorithm {
            SeedChokingAlgorithm::FastestUpload => {
                // Reward the peers we upload to fastest; an incumbent wins an
                // exact upload-rate tie so the marginal seed slot does not chop
                // on HashMap-order nondeterminism (M257d).
                interested.sort_by_key(|p| {
                    std::cmp::Reverse((p.upload_rate, incumbents.contains(&p.addr)))
                });
            }
            SeedChokingAlgorithm::RoundRobin => {
                // Intentional rotation — NO hysteresis (fairness by cycling).
                interested.sort_by_key(|p| p.addr);
                if !interested.is_empty() {
                    let offset = self.round_robin_offset % interested.len();
                    interested.rotate_left(offset);
                    self.round_robin_offset =
                        self.round_robin_offset.wrapping_add(unchoke_slots) % interested.len();
                }
            }
            SeedChokingAlgorithm::AntiLeech => {
                // Deliberate non-seed-before-seed partition is the PRIMARY key
                // and stays untouched; within each partition, rank by upload
                // rate with an incumbent-wins-exact-tie secondary key (M257d).
                interested.sort_by(|a, b| match (a.is_seed, b.is_seed) {
                    (false, true) => std::cmp::Ordering::Less,
                    (true, false) => std::cmp::Ordering::Greater,
                    _ => {
                        let ka = (a.upload_rate, incumbents.contains(&a.addr));
                        let kb = (b.upload_rate, incumbents.contains(&b.addr));
                        kb.cmp(&ka)
                    }
                });
            }
        }
    }
}

impl ChokerStrategy for FixedSlotsStrategy {
    fn decide(
        &mut self,
        peers: &[PeerInfo],
        unchoke_slots: usize,
        seed_mode: bool,
    ) -> ChokeDecision {
        let all_addrs: Vec<SocketAddr> = peers.iter().map(|p| p.addr).collect();

        // Incumbents from the previous cycle (empty on the first call). Taken by
        // value so we can re-record `self.unchoked` later without a borrow clash.
        let incumbents = std::mem::take(&mut self.unchoked);

        // Interested peers sorted by rate descending.
        let mut interested: Vec<&PeerInfo> = peers.iter().filter(|p| p.interested).collect();
        if seed_mode {
            self.sort_seed_mode(&mut interested, unchoke_slots, &incumbents);
        } else {
            // Leech mode: unchoke peers that upload to us fastest (tit-for-tat).
            // The `incumbents.contains` bool is a secondary sort key so an
            // incumbent wins an *exact rate tie* — killing the HashMap-order
            // nondeterminism on the marginal slot (M257d).
            interested.sort_by_key(|p| {
                std::cmp::Reverse((p.download_rate, incumbents.contains(&p.addr)))
            });
        }

        // Regular unchokes: top N.
        let regular_count = unchoke_slots.min(interested.len());
        let regular_unchokes: Vec<SocketAddr> =
            interested[..regular_count].iter().map(|p| p.addr).collect();

        // Record this cycle's regular set as next cycle's incumbents.
        self.unchoked = regular_unchokes.iter().copied().collect();

        // Optimistic unchoke selection.
        let optimistic = self.select_optimistic(&interested, &regular_unchokes);
        self.optimistic_peer = optimistic;

        // Build the final unchoke set.
        let mut to_unchoke = regular_unchokes;
        if let Some(opt) = optimistic
            && !to_unchoke.contains(&opt)
        {
            to_unchoke.push(opt);
        }

        // Everyone not in to_unchoke gets choked.
        let to_choke: Vec<SocketAddr> = all_addrs
            .into_iter()
            .filter(|a| !to_unchoke.contains(a))
            .collect();

        ChokeDecision {
            to_unchoke,
            to_choke,
        }
    }

    fn rotate_optimistic(&mut self, peers: &[PeerInfo]) {
        let mut interested: Vec<&PeerInfo> = peers
            .iter()
            .filter(|p| p.interested && !p.upload_only)
            .collect();
        // Sort ascending by download rate so the first non-optimistic is picked.
        interested.sort_by_key(|p| p.download_rate);

        self.optimistic_peer = interested
            .iter()
            .find(|p| Some(p.addr) != self.optimistic_peer)
            .map(|p| p.addr);
    }
}

// ---------------------------------------------------------------------------
// RateBasedStrategy
// ---------------------------------------------------------------------------

/// Rate-based choking strategy that dynamically adjusts unchoke slots
/// based on observed throughput.
///
/// When throughput increases, adds slots to utilize available bandwidth.
/// When throughput drops significantly (>10%), removes slots to reduce
/// overhead. Respects configured min/max bounds and upload rate limits.
pub(crate) struct RateBasedStrategy {
    /// Underlying fixed-slots strategy for peer ranking and optimistic unchoke.
    inner: FixedSlotsStrategy,
    /// Current number of dynamically-adjusted unchoke slots.
    dynamic_slots: usize,
    /// Previous throughput observation (bytes/sec).
    prev_throughput: u64,
    /// Upload rate limit (bytes/sec). 0 means unlimited.
    upload_rate_limit: u64,
    /// Minimum number of unchoke slots.
    min_slots: usize,
    /// Maximum number of unchoke slots.
    max_slots: usize,
}

impl RateBasedStrategy {
    pub fn new(
        seed_algorithm: SeedChokingAlgorithm,
        upload_rate_limit: u64,
        min_slots: usize,
        max_slots: usize,
    ) -> Self {
        Self {
            inner: FixedSlotsStrategy::new(seed_algorithm),
            dynamic_slots: min_slots.max(2),
            prev_throughput: 0,
            upload_rate_limit,
            min_slots,
            max_slots,
        }
    }

    /// Observe current aggregate throughput and adjust slot count.
    fn observe_throughput_inner(&mut self, throughput: u64) {
        // First observation with throughput > 0: just set baseline.
        if self.prev_throughput == 0 && throughput > 0 {
            self.prev_throughput = throughput;
            return;
        }

        if throughput > self.prev_throughput {
            // Throughput increased — consider adding a slot.
            // But not if we're already at capacity (>90% of upload rate limit).
            let at_capacity =
                self.upload_rate_limit > 0 && throughput > self.upload_rate_limit * 90 / 100;

            if !at_capacity && self.dynamic_slots < self.max_slots {
                self.dynamic_slots += 1;
            }
        } else if self.prev_throughput > 0 {
            // Check for >10% drop.
            let threshold = self.prev_throughput * 90 / 100;
            if throughput < threshold && self.dynamic_slots > self.min_slots {
                self.dynamic_slots -= 1;
            }
        }

        // Check for headroom: if we have spare capacity, try adding a slot.
        if self.upload_rate_limit > 0
            && throughput < self.upload_rate_limit
            && self.dynamic_slots > 0
        {
            let per_slot_avg = throughput / self.dynamic_slots as u64;
            if per_slot_avg > 0 {
                let headroom = self.upload_rate_limit - throughput;
                if headroom > per_slot_avg && self.dynamic_slots < self.max_slots {
                    self.dynamic_slots += 1;
                }
            }
        }

        self.prev_throughput = throughput;
    }

    /// Return the current dynamically-adjusted slot count.
    #[cfg(test)]
    pub fn current_slots(&self) -> usize {
        self.dynamic_slots
    }
}

impl ChokerStrategy for RateBasedStrategy {
    fn decide(
        &mut self,
        peers: &[PeerInfo],
        _unchoke_slots: usize,
        seed_mode: bool,
    ) -> ChokeDecision {
        // Ignore external unchoke_slots — use our dynamic count.
        self.inner.decide(peers, self.dynamic_slots, seed_mode)
    }

    fn rotate_optimistic(&mut self, peers: &[PeerInfo]) {
        self.inner.rotate_optimistic(peers);
    }

    fn observe_throughput(&mut self, throughput: u64) {
        self.observe_throughput_inner(throughput);
    }

    fn dynamic_slots(&self) -> Option<usize> {
        Some(self.dynamic_slots)
    }
}

// ---------------------------------------------------------------------------
// Choker (dispatcher)
// ---------------------------------------------------------------------------

/// Choking algorithm dispatcher.
///
/// Delegates to a pluggable [`ChokerStrategy`] implementation. Backward
/// compatible: `Choker::new(n)` creates a fixed-slots strategy with
/// `FastestUpload` seed algorithm (same behavior as the original `Choker`).
pub(crate) struct Choker {
    strategy: Box<dyn ChokerStrategy>,
    unchoke_slots: usize,
    seed_mode: bool,
    #[allow(dead_code)] // Read via #[cfg(test)] accessor.
    choking_algorithm: ChokingAlgorithm,
}

impl Choker {
    /// Create a choker with the given number of regular unchoke slots.
    ///
    /// Uses [`FixedSlotsStrategy`] with [`SeedChokingAlgorithm::FastestUpload`],
    /// matching the behavior of the original monolithic `Choker`.
    #[cfg(test)]
    pub fn new(unchoke_slots: usize) -> Self {
        Self {
            strategy: Box::new(FixedSlotsStrategy::new(SeedChokingAlgorithm::FastestUpload)),
            unchoke_slots,
            seed_mode: false,
            choking_algorithm: ChokingAlgorithm::FixedSlots,
        }
    }

    /// Create a choker with explicit algorithm configuration.
    pub fn with_algorithms(
        unchoke_slots: usize,
        seed_algorithm: SeedChokingAlgorithm,
        choking_algorithm: ChokingAlgorithm,
        upload_rate_limit: u64,
        min_slots: usize,
        max_slots: usize,
    ) -> Self {
        let strategy: Box<dyn ChokerStrategy> = match choking_algorithm {
            ChokingAlgorithm::FixedSlots => Box::new(FixedSlotsStrategy::new(seed_algorithm)),
            ChokingAlgorithm::RateBased => Box::new(RateBasedStrategy::new(
                seed_algorithm,
                upload_rate_limit,
                min_slots,
                max_slots,
            )),
        };

        Self {
            strategy,
            unchoke_slots,
            seed_mode: false,
            choking_algorithm,
        }
    }

    pub fn set_seed_mode(&mut self, seed_mode: bool) {
        self.seed_mode = seed_mode;
    }

    /// Update the number of regular unchoke slots (used by auto upload slot tuner).
    pub fn set_unchoke_slots(&mut self, n: usize) {
        self.unchoke_slots = n;
    }

    /// Return the current number of regular unchoke slots.
    #[allow(dead_code)] // Used by make_stats() in a later task.
    pub fn unchoke_slots(&self) -> usize {
        self.unchoke_slots
    }

    /// Observe current aggregate throughput for rate-based slot adjustment.
    pub fn observe_throughput(&mut self, throughput: u64) {
        self.strategy.observe_throughput(throughput);
    }

    /// Return the choking algorithm variant.
    #[cfg(test)]
    pub fn choking_algorithm(&self) -> ChokingAlgorithm {
        self.choking_algorithm
    }

    /// Decide which peers to unchoke and choke.
    pub fn decide(&mut self, peers: &[PeerInfo]) -> ChokeDecision {
        self.strategy
            .decide(peers, self.unchoke_slots, self.seed_mode)
    }

    /// Pick a new optimistic peer from interested peers.
    pub fn rotate_optimistic(&mut self, peers: &[PeerInfo]) {
        self.strategy.rotate_optimistic(peers);
    }
}

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

    fn addr(port: u16) -> SocketAddr {
        format!("127.0.0.1:{port}").parse().unwrap()
    }

    fn peer(port: u16, download_rate: u64, interested: bool) -> PeerInfo {
        PeerInfo {
            addr: addr(port),
            download_rate,
            upload_rate: 0,
            interested,
            upload_only: false,
            is_seed: false,
        }
    }

    fn seed_peer(port: u16, upload_rate: u64, interested: bool) -> PeerInfo {
        PeerInfo {
            addr: addr(port),
            download_rate: 0,
            upload_rate,
            interested,
            upload_only: false,
            is_seed: false,
        }
    }

    // -----------------------------------------------------------------------
    // Existing Choker tests (unchanged logic, updated PeerInfo construction)
    // -----------------------------------------------------------------------

    #[test]
    fn unchoke_top_n() {
        let mut choker = Choker::new(4);
        let peers = vec![
            peer(6881, 100, true),
            peer(6882, 500, true),
            peer(6883, 300, true),
            peer(6884, 200, true),
            peer(6885, 400, true),
            peer(6886, 50, true),
        ];

        let decision = choker.decide(&peers);

        // Top 4 by rate: 500, 400, 300, 200 (ports 6882, 6885, 6883, 6884).
        assert!(decision.to_unchoke.contains(&addr(6882)));
        assert!(decision.to_unchoke.contains(&addr(6885)));
        assert!(decision.to_unchoke.contains(&addr(6883)));
        assert!(decision.to_unchoke.contains(&addr(6884)));

        // Optimistic should add one more from the remaining interested peers,
        // so total unchoked should be 5 (4 regular + 1 optimistic).
        assert_eq!(decision.to_unchoke.len(), 5);

        // The remaining peer is choked.
        assert_eq!(decision.to_choke.len(), 1);
    }

    #[test]
    fn optimistic_rotation() {
        let mut choker = Choker::new(4);
        let peers = vec![
            peer(6881, 500, true),
            peer(6882, 400, true),
            peer(6883, 300, true),
            peer(6884, 200, true),
            peer(6885, 100, true),
            peer(6886, 50, true),
        ];

        let decision = choker.decide(&peers);

        // After decide(), there should be an optimistic peer among the unchoked.
        // The top 4 are 6881..6884. Optimistic is from remaining interested.
        assert_eq!(decision.to_unchoke.len(), 5);

        // The optimistic peer is one of the two not in the top-4 regular set.
        let regular = [addr(6881), addr(6882), addr(6883), addr(6884)];
        let opt: Vec<_> = decision
            .to_unchoke
            .iter()
            .filter(|a| !regular.contains(a))
            .copied()
            .collect();
        assert_eq!(opt.len(), 1);
        let first_opt = opt[0];
        assert!(first_opt == addr(6885) || first_opt == addr(6886));

        // After rotation, the optimistic peer should change.
        choker.rotate_optimistic(&peers);
        // Run decide again to reflect the new optimistic.
        let decision2 = choker.decide(&peers);
        let opt2: Vec<_> = decision2
            .to_unchoke
            .iter()
            .filter(|a| !regular.contains(a))
            .copied()
            .collect();
        assert_eq!(opt2.len(), 1);
        assert_ne!(opt2[0], first_opt);
    }

    #[test]
    fn fewer_peers_than_slots() {
        let mut choker = Choker::new(4);
        let peers = vec![peer(6881, 100, true), peer(6882, 200, true)];

        let decision = choker.decide(&peers);

        // Both interested peers should be unchoked.
        assert!(decision.to_unchoke.contains(&addr(6881)));
        assert!(decision.to_unchoke.contains(&addr(6882)));
        assert_eq!(decision.to_unchoke.len(), 2);
        assert!(decision.to_choke.is_empty());
    }

    #[test]
    fn no_interested_peers() {
        let mut choker = Choker::new(4);
        let peers = vec![
            peer(6881, 100, false),
            peer(6882, 200, false),
            peer(6883, 300, false),
        ];

        let decision = choker.decide(&peers);

        assert!(decision.to_unchoke.is_empty());
        // All peers should be in to_choke.
        assert_eq!(decision.to_choke.len(), 3);
        assert!(decision.to_choke.contains(&addr(6881)));
        assert!(decision.to_choke.contains(&addr(6882)));
        assert!(decision.to_choke.contains(&addr(6883)));
    }

    #[test]
    fn choke_below_threshold() {
        let mut choker = Choker::new(2);
        let peers = vec![
            peer(6881, 500, true),
            peer(6882, 400, true),
            peer(6883, 100, true),
            peer(6884, 50, true),
            peer(6885, 200, false), // not interested
        ];

        let decision = choker.decide(&peers);

        // Regular unchokes: top 2 = ports 6881 (500), 6882 (400).
        assert!(decision.to_unchoke.contains(&addr(6881)));
        assert!(decision.to_unchoke.contains(&addr(6882)));

        // Optimistic adds one more interested peer (6883 or 6884).
        assert_eq!(decision.to_unchoke.len(), 3);

        // The non-unchoked peers should be in to_choke.
        // That's 2 from the remaining: one interested + the uninterested peer.
        assert_eq!(decision.to_choke.len(), 2);
        // Uninterested peer is always choked.
        assert!(decision.to_choke.contains(&addr(6885)));
    }

    #[test]
    fn set_unchoke_slots_changes_capacity() {
        let mut choker = Choker::new(2);
        let peers = vec![
            peer(6881, 500, true),
            peer(6882, 400, true),
            peer(6883, 300, true),
            peer(6884, 200, true),
            peer(6885, 100, true),
        ];

        let decision = choker.decide(&peers);
        // 2 regular + 1 optimistic = 3 unchoked
        assert_eq!(decision.to_unchoke.len(), 3);

        // Increase slots to 4
        choker.set_unchoke_slots(4);
        let decision = choker.decide(&peers);
        // 4 regular + 1 optimistic = 5 unchoked
        assert_eq!(decision.to_unchoke.len(), 5);
    }

    // M224: G2-choker — confirm `set_unchoke_slots(n)` caps the regular
    // unchoke set at `n`. This is the precise contract
    // `Settings.max_uploads_per_torrent` relies on when propagated through
    // `handle_update_settings`.
    #[test]
    fn set_unchoke_slots_caps_regular_set_at_m224_value() {
        // 10 interested peers with strictly decreasing download rates so
        // tit-for-tat ordering is unambiguous.
        let peers: Vec<PeerInfo> = (0u16..10)
            .map(|i| peer(6881 + i, 1_000 - u64::from(i) * 100, true))
            .collect();

        // Cap = 1 → exactly 1 regular + 1 optimistic = 2 unchoked.
        let mut choker = Choker::new(1);
        let decision = choker.decide(&peers);
        assert_eq!(
            decision.to_unchoke.len(),
            2,
            "cap=1 must yield 1 regular + 1 optimistic"
        );

        // Bump cap to 3 → 3 regular + 1 optimistic = 4 unchoked.
        choker.set_unchoke_slots(3);
        let decision = choker.decide(&peers);
        assert_eq!(
            decision.to_unchoke.len(),
            4,
            "cap=3 must yield 3 regular + 1 optimistic"
        );

        // Bump cap to 8 → 8 regular + 1 optimistic = 9 unchoked.
        choker.set_unchoke_slots(8);
        let decision = choker.decide(&peers);
        assert_eq!(
            decision.to_unchoke.len(),
            9,
            "cap=8 must yield 8 regular + 1 optimistic"
        );
    }

    #[test]
    fn seed_mode_unchokes_by_upload_rate() {
        let mut choker = Choker::new(2);
        choker.set_seed_mode(true);

        // In seed mode, peers are ranked by upload_rate (how fast we upload TO them)
        let peers = vec![
            seed_peer(6881, 100, true),
            seed_peer(6882, 500, true),
            seed_peer(6883, 300, true),
            seed_peer(6884, 200, true),
        ];

        let decision = choker.decide(&peers);

        // Top 2 by upload rate: 500 (6882), 300 (6883)
        assert!(decision.to_unchoke.contains(&addr(6882)));
        assert!(decision.to_unchoke.contains(&addr(6883)));

        // Plus one optimistic
        assert_eq!(decision.to_unchoke.len(), 3);
    }

    #[test]
    fn upload_only_excluded_from_optimistic() {
        let mut choker = Choker::new(2);
        let peers = vec![
            peer(6881, 500, true),
            peer(6882, 400, true),
            // These two are interested but upload-only — should never get optimistic slot
            PeerInfo {
                addr: addr(6883),
                download_rate: 100,
                upload_rate: 0,
                interested: true,
                upload_only: true,
                is_seed: false,
            },
            PeerInfo {
                addr: addr(6884),
                download_rate: 50,
                upload_rate: 0,
                interested: true,
                upload_only: true,
                is_seed: false,
            },
        ];

        let decision = choker.decide(&peers);

        // Regular unchokes: 6881, 6882 (top 2 by rate)
        // No optimistic: both remaining interested peers are upload-only
        assert_eq!(decision.to_unchoke.len(), 2);
        assert!(decision.to_unchoke.contains(&addr(6881)));
        assert!(decision.to_unchoke.contains(&addr(6882)));

        // Upload-only peers are choked
        assert!(decision.to_choke.contains(&addr(6883)));
        assert!(decision.to_choke.contains(&addr(6884)));
    }

    #[test]
    fn upload_only_still_regular_unchoked() {
        // In seed mode, upload-only peers can earn regular unchoke by upload rate
        let mut choker = Choker::new(2);
        choker.set_seed_mode(true);

        let peers = vec![
            PeerInfo {
                addr: addr(6881),
                download_rate: 0,
                upload_rate: 500,
                interested: true,
                upload_only: true, // upload-only but high upload rate
                is_seed: false,
            },
            seed_peer(6882, 300, true),
            seed_peer(6883, 100, true),
        ];

        let decision = choker.decide(&peers);

        // Upload-only peer at 6881 has highest upload rate, should be in regular unchokes
        assert!(decision.to_unchoke.contains(&addr(6881)));
        assert!(decision.to_unchoke.contains(&addr(6882)));
    }

    // -----------------------------------------------------------------------
    // New tests: algorithm enums
    // -----------------------------------------------------------------------

    #[test]
    fn seed_choking_algorithm_default() {
        assert_eq!(
            SeedChokingAlgorithm::default(),
            SeedChokingAlgorithm::FastestUpload
        );
    }

    #[test]
    fn choking_algorithm_default() {
        assert_eq!(ChokingAlgorithm::default(), ChokingAlgorithm::FixedSlots);
    }

    #[test]
    fn seed_choking_algorithm_serde_round_trip() {
        for variant in [
            SeedChokingAlgorithm::FastestUpload,
            SeedChokingAlgorithm::RoundRobin,
            SeedChokingAlgorithm::AntiLeech,
        ] {
            let json = serde_json::to_string(&variant).unwrap();
            let decoded: SeedChokingAlgorithm = serde_json::from_str(&json).unwrap();
            assert_eq!(decoded, variant);
        }
    }

    #[test]
    fn choking_algorithm_serde_round_trip() {
        for variant in [ChokingAlgorithm::FixedSlots, ChokingAlgorithm::RateBased] {
            let json = serde_json::to_string(&variant).unwrap();
            let decoded: ChokingAlgorithm = serde_json::from_str(&json).unwrap();
            assert_eq!(decoded, variant);
        }
    }

    // -----------------------------------------------------------------------
    // New tests: FixedSlotsStrategy
    // -----------------------------------------------------------------------

    #[test]
    fn fixed_slots_strategy_leech_mode() {
        let mut strategy = FixedSlotsStrategy::new(SeedChokingAlgorithm::FastestUpload);
        let peers = vec![
            peer(6881, 100, true),
            peer(6882, 500, true),
            peer(6883, 300, true),
            peer(6884, 200, true),
            peer(6885, 400, true),
            peer(6886, 50, true),
        ];

        let decision = strategy.decide(&peers, 4, false);

        // Top 4 by download_rate: 500 (6882), 400 (6885), 300 (6883), 200 (6884).
        assert!(decision.to_unchoke.contains(&addr(6882)));
        assert!(decision.to_unchoke.contains(&addr(6885)));
        assert!(decision.to_unchoke.contains(&addr(6883)));
        assert!(decision.to_unchoke.contains(&addr(6884)));

        // 4 regular + 1 optimistic = 5
        assert_eq!(decision.to_unchoke.len(), 5);
        assert_eq!(decision.to_choke.len(), 1);
    }

    #[test]
    fn fixed_slots_round_robin_rotates() {
        let mut strategy = FixedSlotsStrategy::new(SeedChokingAlgorithm::RoundRobin);
        // 5 interested peers, 2 unchoke slots — should rotate through them.
        let peers = vec![
            seed_peer(6881, 100, true),
            seed_peer(6882, 200, true),
            seed_peer(6883, 300, true),
            seed_peer(6884, 400, true),
            seed_peer(6885, 500, true),
        ];

        let d1 = strategy.decide(&peers, 2, true);
        let d2 = strategy.decide(&peers, 2, true);

        // The two rounds should select different regular unchoke sets because
        // the offset advances by unchoke_slots each round.
        // Extract the first two from each (regular unchokes before optimistic).
        // We just need to verify they are not identical sets.
        let set1 = d1.to_unchoke;
        let set2 = d2.to_unchoke;
        assert_ne!(set1, set2, "round-robin should rotate unchoke set");
    }

    #[test]
    fn fixed_slots_anti_leech_prefers_non_seeds() {
        let mut strategy = FixedSlotsStrategy::new(SeedChokingAlgorithm::AntiLeech);
        let peers = vec![
            // Two seed peers (is_seed = true)
            PeerInfo {
                addr: addr(6881),
                download_rate: 0,
                upload_rate: 500,
                interested: true,
                upload_only: false,
                is_seed: true,
            },
            PeerInfo {
                addr: addr(6882),
                download_rate: 0,
                upload_rate: 400,
                interested: true,
                upload_only: false,
                is_seed: true,
            },
            // Two leecher peers (is_seed = false) with lower upload rates
            PeerInfo {
                addr: addr(6883),
                download_rate: 0,
                upload_rate: 100,
                interested: true,
                upload_only: false,
                is_seed: false,
            },
            PeerInfo {
                addr: addr(6884),
                download_rate: 0,
                upload_rate: 50,
                interested: true,
                upload_only: false,
                is_seed: false,
            },
        ];

        // 2 slots: anti-leech should prefer the 2 non-seed peers over seeds.
        let decision = strategy.decide(&peers, 2, true);

        // The regular unchokes should be the two leechers (non-seeds).
        assert!(
            decision.to_unchoke.contains(&addr(6883)),
            "non-seed peer 6883 should be unchoked"
        );
        assert!(
            decision.to_unchoke.contains(&addr(6884)),
            "non-seed peer 6884 should be unchoked"
        );
    }

    // -----------------------------------------------------------------------
    // New tests: RateBasedStrategy
    // -----------------------------------------------------------------------

    #[test]
    fn rate_based_starts_at_min_slots() {
        let strategy = RateBasedStrategy::new(
            SeedChokingAlgorithm::FastestUpload,
            0,  // unlimited
            3,  // min_slots
            10, // max_slots
        );
        // min_slots=3, max(3,2)=3
        assert_eq!(strategy.current_slots(), 3);

        // If min_slots < 2, should start at 2.
        let strategy2 = RateBasedStrategy::new(
            SeedChokingAlgorithm::FastestUpload,
            0,
            1, // min_slots=1
            10,
        );
        assert_eq!(strategy2.current_slots(), 2);
    }

    #[test]
    fn rate_based_increases_slots_on_throughput_increase() {
        let mut strategy = RateBasedStrategy::new(
            SeedChokingAlgorithm::FastestUpload,
            0,  // unlimited
            2,  // min_slots
            10, // max_slots
        );
        assert_eq!(strategy.current_slots(), 2);

        // First observation sets baseline.
        strategy.observe_throughput_inner(1000);
        assert_eq!(strategy.current_slots(), 2);

        // Throughput increased — should add a slot.
        strategy.observe_throughput_inner(1500);
        assert_eq!(strategy.current_slots(), 3);
    }

    #[test]
    fn rate_based_decreases_slots_on_throughput_drop() {
        let mut strategy = RateBasedStrategy::new(
            SeedChokingAlgorithm::FastestUpload,
            0,  // unlimited
            2,  // min_slots
            10, // max_slots
        );

        // Build up to 4 slots.
        strategy.observe_throughput_inner(1000);
        strategy.observe_throughput_inner(2000);
        assert_eq!(strategy.current_slots(), 3);
        strategy.observe_throughput_inner(3000);
        assert_eq!(strategy.current_slots(), 4);

        // Drop >10%: 3000 -> 2000 (33% drop).
        strategy.observe_throughput_inner(2000);
        assert_eq!(strategy.current_slots(), 3);
    }

    #[test]
    fn rate_based_respects_min_max() {
        let mut strategy = RateBasedStrategy::new(
            SeedChokingAlgorithm::FastestUpload,
            0, // unlimited
            2, // min_slots
            3, // max_slots = 3
        );

        // Build up.
        strategy.observe_throughput_inner(1000);
        strategy.observe_throughput_inner(2000);
        assert_eq!(strategy.current_slots(), 3);

        // Try to exceed max — should stay at 3.
        strategy.observe_throughput_inner(5000);
        assert_eq!(strategy.current_slots(), 3);

        // Drop to bring down.
        strategy.observe_throughput_inner(1000);
        assert_eq!(strategy.current_slots(), 2);

        // Drop more — should not go below min.
        strategy.observe_throughput_inner(100);
        assert_eq!(strategy.current_slots(), 2);
    }

    #[test]
    fn rate_based_does_not_add_at_capacity() {
        let mut strategy = RateBasedStrategy::new(
            SeedChokingAlgorithm::FastestUpload,
            10_000, // 10 KB/s limit
            2,
            10,
        );

        // Baseline.
        strategy.observe_throughput_inner(5_000);
        assert_eq!(strategy.current_slots(), 2);

        // Throughput increased but >90% of capacity (9500/10000 = 95%).
        strategy.observe_throughput_inner(9_500);
        // Should NOT add slot because we're at capacity.
        // However, we might still be at 2 because throughput increase check
        // fails the at_capacity guard. The headroom check also shouldn't fire
        // because headroom (500) < per_slot_avg (4750).
        assert_eq!(strategy.current_slots(), 2);
    }

    #[test]
    fn rate_based_ignores_external_unchoke_slots() {
        let mut strategy = RateBasedStrategy::new(SeedChokingAlgorithm::FastestUpload, 0, 2, 10);

        let peers = vec![
            peer(6881, 500, true),
            peer(6882, 400, true),
            peer(6883, 300, true),
            peer(6884, 200, true),
            peer(6885, 100, true),
        ];

        // dynamic_slots = 2 (min). Pass unchoke_slots=10 externally — should be ignored.
        let decision = strategy.decide(&peers, 10, false);

        // Should use dynamic_slots=2, not the external 10.
        // 2 regular + 1 optimistic = 3 unchoked.
        assert_eq!(decision.to_unchoke.len(), 3);
    }

    // -----------------------------------------------------------------------
    // New tests: Choker dispatcher
    // -----------------------------------------------------------------------

    #[test]
    fn choker_with_round_robin() {
        let mut choker = Choker::with_algorithms(
            2,
            SeedChokingAlgorithm::RoundRobin,
            ChokingAlgorithm::FixedSlots,
            0,
            2,
            10,
        );
        choker.set_seed_mode(true);

        let peers = vec![
            seed_peer(6881, 100, true),
            seed_peer(6882, 200, true),
            seed_peer(6883, 300, true),
            seed_peer(6884, 400, true),
            seed_peer(6885, 500, true),
        ];

        let d1 = choker.decide(&peers);
        let d2 = choker.decide(&peers);

        // Round-robin should produce different unchoke sets on successive calls.
        let set1 = d1.to_unchoke;
        let set2 = d2.to_unchoke;
        assert_ne!(set1, set2, "round-robin dispatcher should rotate");
    }

    #[test]
    fn choker_with_rate_based() {
        let mut choker = Choker::with_algorithms(
            4, // this should be ignored by rate-based
            SeedChokingAlgorithm::FastestUpload,
            ChokingAlgorithm::RateBased,
            0,
            2,
            10,
        );
        assert_eq!(choker.choking_algorithm(), ChokingAlgorithm::RateBased);

        let peers = vec![
            peer(6881, 500, true),
            peer(6882, 400, true),
            peer(6883, 300, true),
            peer(6884, 200, true),
            peer(6885, 100, true),
        ];

        // Rate-based starts at min_slots=2, so 2 regular + 1 optimistic = 3.
        let decision = choker.decide(&peers);
        assert_eq!(decision.to_unchoke.len(), 3);

        // Feed throughput to increase slots.
        choker.observe_throughput(1000);
        choker.observe_throughput(2000);
        // Now dynamic_slots should be 3 (increased).
        let decision = choker.decide(&peers);
        assert_eq!(decision.to_unchoke.len(), 4); // 3 regular + 1 optimistic
    }

    #[test]
    fn choker_unchoke_slots_getter() {
        let mut choker = Choker::new(4);
        assert_eq!(choker.unchoke_slots(), 4);

        choker.set_unchoke_slots(7);
        assert_eq!(choker.unchoke_slots(), 7);

        choker.set_unchoke_slots(0);
        assert_eq!(choker.unchoke_slots(), 0);
    }

    #[test]
    fn choker_new_is_backward_compatible() {
        let mut choker = Choker::new(4);
        assert_eq!(choker.choking_algorithm(), ChokingAlgorithm::FixedSlots);

        let peers = vec![
            peer(6881, 500, true),
            peer(6882, 400, true),
            peer(6883, 300, true),
            peer(6884, 200, true),
            peer(6885, 100, true),
            peer(6886, 50, true),
        ];

        let decision = choker.decide(&peers);

        // Same behavior as old Choker: top 4 + 1 optimistic = 5.
        assert_eq!(decision.to_unchoke.len(), 5);
        assert!(decision.to_unchoke.contains(&addr(6882)));
        assert!(decision.to_unchoke.contains(&addr(6885)));
        assert!(decision.to_unchoke.contains(&addr(6883)));
        assert!(decision.to_unchoke.contains(&addr(6884)));

        // set_seed_mode and set_unchoke_slots still work.
        choker.set_seed_mode(true);
        choker.set_unchoke_slots(2);
        let decision = choker.decide(&peers);
        assert_eq!(decision.to_unchoke.len(), 3); // 2 regular + 1 optimistic
    }

    // -----------------------------------------------------------------------
    // M257d — leech-mode incumbent hysteresis
    // -----------------------------------------------------------------------

    #[test]
    fn leech_incumbent_wins_exact_rate_tie() {
        // Cycle 1 establishes A (6881) and B (6882) as the two regular incumbents.
        let mut s = FixedSlotsStrategy::new(SeedChokingAlgorithm::FastestUpload);
        let cycle1 = vec![
            peer(6881, 1000, true), // A — fastest
            peer(6882, 900, true),  // B — second, the marginal incumbent
            peer(6883, 10, true),   // D — sticky optimistic
            peer(6884, 5, true),    // E
        ];
        let d1 = s.decide(&cycle1, 2, false);
        assert!(d1.to_unchoke.contains(&addr(6881)));
        assert!(d1.to_unchoke.contains(&addr(6882)));

        // Cycle 2: challenger C ties B exactly (both 900). The incumbency
        // secondary key keeps B in the regular set; a pure rate sort would let
        // HashMap iteration order decide the marginal slot.
        let cycle2 = vec![
            peer(6881, 1000, true), // A
            peer(6882, 900, true),  // B (incumbent)
            peer(6885, 900, true),  // C — challenger, exact rate tie with B
            peer(6883, 10, true),   // D (sticky optimistic)
            peer(6884, 5, true),    // E
        ];
        let d2 = s.decide(&cycle2, 2, false);

        assert!(d2.to_unchoke.contains(&addr(6881)), "A retained");
        assert!(
            d2.to_unchoke.contains(&addr(6882)),
            "B incumbent wins the exact rate tie"
        );
        assert!(
            d2.to_choke.contains(&addr(6885)),
            "tying challenger C blocked from regular slot"
        );
    }

    #[test]
    fn leech_decisive_challenger_takes_slot() {
        // Guard: any strictly-faster peer wins immediately — there is no rate
        // margin, only an exact-tie break.
        let mut s = FixedSlotsStrategy::new(SeedChokingAlgorithm::FastestUpload);
        let cycle1 = vec![
            peer(6881, 1000, true), // A
            peer(6882, 900, true),  // B (marginal incumbent)
            peer(6883, 10, true),   // D (sticky optimistic)
            peer(6884, 5, true),    // E
        ];
        let _ = s.decide(&cycle1, 2, false); // incumbents = {A, B}

        // C=1500 is strictly faster than both incumbents A=1000 and B=900.
        let cycle2 = vec![
            peer(6881, 1000, true), // A
            peer(6882, 900, true),  // B
            peer(6885, 1500, true), // C — decisive challenger
            peer(6883, 10, true),   // D (sticky optimistic)
            peer(6884, 5, true),    // E
        ];
        let d2 = s.decide(&cycle2, 2, false);

        assert!(
            d2.to_unchoke.contains(&addr(6885)),
            "decisive challenger C wins a slot"
        );
        assert!(
            d2.to_unchoke.contains(&addr(6881)),
            "A retained (second-fastest)"
        );
        assert!(
            d2.to_choke.contains(&addr(6882)),
            "B displaced by decisive challenger"
        );
    }

    #[test]
    fn leech_cold_incumbent_evicted() {
        // Guard: a cold incumbent (rate 0) ties only other rate-0 peers and so
        // yields its slot to any productive challenger.
        let mut s = FixedSlotsStrategy::new(SeedChokingAlgorithm::FastestUpload);
        let cycle1 = vec![
            peer(6881, 1000, true), // A
            peer(6882, 900, true),  // B — will go cold
            peer(6883, 10, true),   // D (sticky optimistic)
            peer(6884, 5, true),    // E
        ];
        let _ = s.decide(&cycle1, 2, false); // incumbents = {A, B}

        let cycle2 = vec![
            peer(6881, 1000, true), // A
            peer(6882, 0, true),    // B — cold incumbent
            peer(6885, 50, true),   // C — small positive challenger
            peer(6883, 10, true),   // D (sticky optimistic)
            peer(6884, 5, true),    // E
        ];
        let d2 = s.decide(&cycle2, 2, false);

        assert!(d2.to_unchoke.contains(&addr(6881)), "A retained");
        assert!(
            d2.to_unchoke.contains(&addr(6885)),
            "challenger takes the cold incumbent's slot"
        );
        assert!(
            d2.to_choke.contains(&addr(6882)),
            "cold incumbent B evicted despite incumbency"
        );
    }

    #[test]
    fn leech_incumbent_wins_tie_regardless_of_input_order() {
        // The nondeterminism fix: on an exact rate tie the incumbent must win
        // even when the challenger is listed FIRST. In production peer order is
        // HashMap iteration order; `sort_by_key` is stable, so without the
        // incumbency secondary key the first-listed peer would take the slot.
        let mut s = FixedSlotsStrategy::new(SeedChokingAlgorithm::FastestUpload);
        // Cycle 1: I (6882) is the sole regular incumbent.
        let cycle1 = vec![
            peer(6882, 100, true), // I — incumbent
            peer(6883, 1, true),   // sticky optimistic
        ];
        let _ = s.decide(&cycle1, 1, false); // incumbents = {I}

        // Cycle 2: C ties I exactly (both 100) and is listed FIRST to bias the
        // stable sort toward C. The incumbency key must still keep I.
        let cycle2 = vec![
            peer(6881, 100, true), // C — challenger, listed first, exact tie
            peer(6882, 100, true), // I — incumbent
            peer(6883, 1, true),   // sticky optimistic
        ];
        let d2 = s.decide(&cycle2, 1, false);

        assert!(
            d2.to_unchoke.contains(&addr(6882)),
            "incumbent wins the tie despite the challenger being listed first"
        );
        assert!(
            d2.to_choke.contains(&addr(6881)),
            "tying challenger blocked despite favourable input order"
        );
    }

    // -----------------------------------------------------------------------
    // M257d — seed-mode hysteresis (FastestUpload / AntiLeech) + RoundRobin guard
    // -----------------------------------------------------------------------

    #[test]
    fn seed_fastest_upload_incumbent_keeps_slot() {
        // Seed mode, FastestUpload: rank by how fast WE upload to each peer.
        let mut s = FixedSlotsStrategy::new(SeedChokingAlgorithm::FastestUpload);
        let cycle1 = vec![
            seed_peer(6881, 1000, true), // A — fastest sink
            seed_peer(6882, 900, true),  // B — marginal incumbent
            seed_peer(6883, 10, true),   // D — sticky optimistic
            seed_peer(6884, 5, true),    // E
        ];
        let d1 = s.decide(&cycle1, 2, true);
        assert!(d1.to_unchoke.contains(&addr(6881)));
        assert!(d1.to_unchoke.contains(&addr(6882)));

        // Cycle 2: challenger C ties B exactly (both 900). The incumbency
        // secondary key keeps B in the regular seed set.
        let cycle2 = vec![
            seed_peer(6881, 1000, true), // A
            seed_peer(6882, 900, true),  // B (incumbent)
            seed_peer(6885, 900, true),  // C — challenger, exact upload-rate tie
            seed_peer(6883, 10, true),   // D (sticky optimistic)
            seed_peer(6884, 5, true),    // E
        ];
        let d2 = s.decide(&cycle2, 2, true);

        assert!(d2.to_unchoke.contains(&addr(6881)), "A retained");
        assert!(
            d2.to_unchoke.contains(&addr(6882)),
            "seed incumbent B wins the exact upload-rate tie"
        );
        assert!(
            d2.to_choke.contains(&addr(6885)),
            "tying seed challenger C blocked from regular slot"
        );
    }

    #[test]
    fn seed_round_robin_keeps_rotating() {
        // Scope guard: RoundRobin is intentional rotation — hysteresis must NOT
        // pin the set. Two identical cycles must yield different unchoke sets.
        let mut s = FixedSlotsStrategy::new(SeedChokingAlgorithm::RoundRobin);
        let peers = vec![
            seed_peer(6881, 100, true),
            seed_peer(6882, 100, true),
            seed_peer(6883, 100, true),
            seed_peer(6884, 100, true),
            seed_peer(6885, 100, true),
            seed_peer(6886, 100, true),
        ];

        let d1 = s.decide(&peers, 2, true);
        let d2 = s.decide(&peers, 2, true);

        let mut u1 = d1.to_unchoke;
        let mut u2 = d2.to_unchoke;
        u1.sort();
        u2.sort();
        assert_ne!(
            u1, u2,
            "RoundRobin must keep rotating the unchoke set across cycles"
        );
    }

    #[test]
    fn seed_anti_leech_incumbent_keeps_slot() {
        // AntiLeech ranks within the non-seed partition by upload_rate with the
        // same incumbency tie-break (the partition itself is untouched). All
        // peers here are non-seeds, so it reduces to a rate-tie test.
        let mut s = FixedSlotsStrategy::new(SeedChokingAlgorithm::AntiLeech);
        let cycle1 = vec![
            seed_peer(6881, 1000, true), // A
            seed_peer(6882, 900, true),  // B — marginal incumbent
            seed_peer(6883, 10, true),   // D — sticky optimistic
            seed_peer(6884, 5, true),    // E
        ];
        let d1 = s.decide(&cycle1, 2, true);
        assert!(d1.to_unchoke.contains(&addr(6881)));
        assert!(d1.to_unchoke.contains(&addr(6882)));

        // Cycle 2: challenger C ties B exactly (both 900).
        let cycle2 = vec![
            seed_peer(6881, 1000, true), // A
            seed_peer(6882, 900, true),  // B (incumbent)
            seed_peer(6885, 900, true),  // C — challenger, exact upload-rate tie
            seed_peer(6883, 10, true),   // D (sticky optimistic)
            seed_peer(6884, 5, true),    // E
        ];
        let d2 = s.decide(&cycle2, 2, true);

        assert!(d2.to_unchoke.contains(&addr(6881)), "A retained");
        assert!(
            d2.to_unchoke.contains(&addr(6882)),
            "AntiLeech incumbent B wins the exact upload-rate tie"
        );
        assert!(
            d2.to_choke.contains(&addr(6885)),
            "tying AntiLeech challenger C blocked from regular slot"
        );
    }
}