irontide-session 1.0.1

BitTorrent session management: peers, torrents, and piece selection
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
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    reason = "M175: piece selection arithmetic bounded by num_pieces (u32 by construction in Lengths::new); precision loss on rate calc is intentional"
)]

use irontide_core::{FilePriority, Lengths};
use irontide_storage::Bitfield;

#[cfg(test)]
use crate::chunk_mask::ChunkMask;
#[cfg(test)]
use rustc_hash::FxHashMap;
#[cfg(test)]
use std::collections::HashSet;
#[cfg(test)]
use std::net::SocketAddr;

#[cfg(test)]
use std::collections::BTreeSet;

#[cfg(test)]
/// Speed category for a peer based on download rate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum PeerSpeed {
    Slow,
    Medium,
    Fast,
}

#[cfg(test)]
impl PeerSpeed {
    pub fn from_rate(bytes_per_sec: f64) -> Self {
        PeerSpeedClassifier::default().classify(bytes_per_sec)
    }
}

#[cfg(test)]
/// Configurable speed classifier with adjustable thresholds.
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub(crate) struct PeerSpeedClassifier {
    pub slow_threshold: f64,
    pub fast_threshold: f64,
}

#[cfg(test)]
impl Default for PeerSpeedClassifier {
    fn default() -> Self {
        Self {
            slow_threshold: 10_240.0,
            fast_threshold: 102_400.0,
        }
    }
}

#[cfg(test)]
#[allow(dead_code)]
impl PeerSpeedClassifier {
    pub fn classify(&self, bytes_per_sec: f64) -> PeerSpeed {
        if bytes_per_sec < self.slow_threshold {
            PeerSpeed::Slow
        } else if bytes_per_sec < self.fast_threshold {
            PeerSpeed::Medium
        } else {
            PeerSpeed::Fast
        }
    }
}

#[cfg(test)]
/// Tracks which blocks of an in-flight piece are assigned to which peer.
#[derive(Debug, Clone)]
pub(crate) struct InFlightPiece {
    pub assigned_blocks: FxHashMap<(u32, u32), SocketAddr>,
    pub total_blocks: u32,
    pub unassigned: ChunkMask,
}

#[cfg(test)]
impl InFlightPiece {
    pub fn new(total_blocks: u32, unassigned: ChunkMask) -> Self {
        Self {
            assigned_blocks: FxHashMap::default(),
            total_blocks,
            unassigned,
        }
    }

    #[allow(dead_code)]
    pub fn unassigned_count(&self) -> u32 {
        self.total_blocks
            .saturating_sub(self.assigned_blocks.len() as u32)
    }

    pub fn peer_count(&self) -> usize {
        if self.assigned_blocks.len() <= 1 {
            return self.assigned_blocks.len();
        }
        // Stack array covers >99% of cases (pieces rarely have 8+ unique peers).
        // Falls back to HashSet only when exceeded.
        let mut seen: [SocketAddr; 8] = [SocketAddr::from(([0, 0, 0, 0], 0)); 8];
        let mut count = 0usize;

        for addr in self.assigned_blocks.values() {
            let found = seen.iter().take(count).any(|s| s == addr);
            if !found {
                if count >= 8 {
                    // Overflow: fall back to HashSet
                    return self.assigned_blocks.values().collect::<HashSet<_>>().len();
                }
                seen[count] = *addr;
                count += 1;
            }
        }
        count
    }
}

#[cfg(test)]
/// Context for a single peer's pick cycle.
pub(crate) struct PickContext<'a> {
    pub peer_addr: SocketAddr,
    pub peer_has: &'a Bitfield,
    pub peer_speed: PeerSpeed,
    pub peer_is_snubbed: bool,
    pub peer_rate: f64,
    pub we_have: &'a Bitfield,
    pub in_flight_pieces: &'a FxHashMap<u32, InFlightPiece>,
    pub wanted: &'a Bitfield,
    pub streaming_pieces: &'a BTreeSet<u32>,
    pub time_critical_pieces: &'a BTreeSet<u32>,
    pub suggested_pieces: &'a HashSet<u32>,
    pub sequential_download: bool,
    pub completed_count: u32,
    pub initial_picker_threshold: u32,
    #[allow(dead_code)] // Reserved for future per-pick peer-count decisions.
    pub connected_peer_count: usize,
    pub whole_pieces_threshold: u32,
    pub piece_size: u32,
    pub chunk_size: u32,
    pub extent_affinity: bool,
    /// Whether auto-sequential mode is currently active (managed by `TorrentActor`).
    pub auto_sequential_active: bool,
    /// Whether the in-flight piece cap has been reached. When true, the picker
    /// skips new piece selection and only returns blocks from already-in-flight pieces.
    pub cap_reached: bool,
}

#[cfg(test)]
/// Result of a pick: which piece and blocks to request.
#[derive(Debug)]
pub(crate) struct PickResult {
    pub piece: u32,
    pub blocks: Vec<(u32, u32)>,
    #[allow(dead_code)]
    pub exclusive: bool,
}

#[cfg(test)]
/// Rarest-first piece selector with per-piece availability tracking.
///
/// Tracks how many peers have each piece and selects the rarest piece
/// that a given peer has, we don't have, and is not already in flight.
/// Ties are broken by lowest index.
pub(crate) struct PieceSelector {
    availability: Vec<u32>,
    num_pieces: u32,
    seed_count: u32,
}

#[cfg(test)]
impl PieceSelector {
    /// Create a new selector with all availability counts at zero.
    pub fn new(num_pieces: u32) -> Self {
        Self {
            availability: vec![0; num_pieces as usize],
            num_pieces,
            seed_count: 0,
        }
    }

    /// Increment availability for each piece the peer has.
    pub fn add_peer_bitfield(&mut self, bitfield: &Bitfield) {
        for index in bitfield.ones() {
            if (index as usize) < self.availability.len() {
                self.availability[index as usize] += 1;
            }
        }
    }

    /// Decrement (saturating) availability for each piece the peer has.
    pub fn remove_peer_bitfield(&mut self, bitfield: &Bitfield) {
        for index in bitfield.ones() {
            if (index as usize) < self.availability.len() {
                self.availability[index as usize] =
                    self.availability[index as usize].saturating_sub(1);
            }
        }
    }

    /// Increment availability for a single piece (e.g. Have message).
    pub fn increment(&mut self, index: u32) {
        if (index as usize) < self.availability.len() {
            self.availability[index as usize] += 1;
        }
    }

    /// Decrement availability for a single piece (saturating).
    #[allow(dead_code)]
    pub fn decrement(&mut self, index: u32) {
        if (index as usize) < self.availability.len() {
            self.availability[index as usize] = self.availability[index as usize].saturating_sub(1);
        }
    }

    /// Pick the rarest piece that the peer has, we don't have, and is not in flight.
    ///
    /// Returns the piece index with the lowest non-zero availability among
    /// candidates. Ties are broken by lowest index.
    #[allow(dead_code)]
    pub fn pick(
        &self,
        peer_has: &Bitfield,
        we_have: &Bitfield,
        in_flight: &HashSet<u32>,
        wanted: &Bitfield,
    ) -> Option<u32> {
        let mut best_index: Option<u32> = None;
        let mut best_avail: u32 = u32::MAX;

        for i in 0..self.num_pieces {
            // Peer must have it
            if !peer_has.get(i) {
                continue;
            }
            // We must not have it
            if we_have.get(i) {
                continue;
            }
            // Must not be in flight
            if in_flight.contains(&i) {
                continue;
            }
            // Must be wanted
            if !wanted.get(i) {
                continue;
            }
            // Must have non-zero availability
            let avail = self.availability[i as usize];
            if avail == 0 {
                continue;
            }
            // Rarest first, ties broken by lowest index
            if avail < best_avail {
                best_avail = avail;
                best_index = Some(i);
            }
        }

        best_index
    }

    /// Read-only access to the availability counts (for testing/debugging).
    pub fn availability(&self) -> &[u32] {
        &self.availability
    }

    #[allow(dead_code)]
    pub fn add_seed(&mut self) {
        self.seed_count += 1;
    }

    #[allow(dead_code)]
    pub fn remove_seed(&mut self) {
        self.seed_count = self.seed_count.saturating_sub(1);
    }

    pub fn effective_availability(&self, index: u32) -> u32 {
        self.availability.get(index as usize).copied().unwrap_or(0) + self.seed_count
    }

    /// Layered priority piece/block picker.
    ///
    /// Priority layers (highest to lowest):
    /// 1. Streaming window pieces
    /// 2. Time-critical pieces (first/last of High-priority files)
    /// 3. Suggested pieces (BEP 6)
    /// 4. Partial pieces with unassigned blocks (speed affinity)
    /// 5. New piece selection (sequential/random/rarest-first)
    pub fn pick_blocks<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        // Layer 1: Streaming window pieces
        if !ctx.peer_is_snubbed {
            for &piece in ctx.streaming_pieces {
                if !ctx.peer_has.get(piece) || ctx.we_have.get(piece) || !ctx.wanted.get(piece) {
                    continue;
                }
                self.unassigned_blocks(piece, ctx, missing_chunks, scratch);
                if !scratch.is_empty() {
                    return Some(PickResult {
                        piece,
                        blocks: std::mem::take(scratch),
                        exclusive: false,
                    });
                }
            }
        }

        // Layer 2: Time-critical pieces
        if !ctx.peer_is_snubbed {
            for &piece in ctx.time_critical_pieces {
                if !ctx.peer_has.get(piece) || ctx.we_have.get(piece) || !ctx.wanted.get(piece) {
                    continue;
                }
                if ctx.streaming_pieces.contains(&piece) {
                    continue; // already handled in layer 1
                }
                self.unassigned_blocks(piece, ctx, missing_chunks, scratch);
                if !scratch.is_empty() {
                    return Some(PickResult {
                        piece,
                        blocks: std::mem::take(scratch),
                        exclusive: false,
                    });
                }
            }
        }

        // Layer 3: Suggested pieces (skip new pieces if in-flight cap reached)
        if !ctx.cap_reached {
            for &piece in ctx.suggested_pieces {
                if !ctx.peer_has.get(piece) || ctx.we_have.get(piece) || !ctx.wanted.get(piece) {
                    continue;
                }
                if ctx.in_flight_pieces.contains_key(&piece) {
                    continue; // prefer new pieces for suggestions
                }
                let avail = self.effective_availability(piece);
                if avail == 0 {
                    continue;
                }
                missing_chunks(piece, scratch);
                if !scratch.is_empty() {
                    let exclusive = self.should_whole_piece(ctx, scratch);
                    return Some(PickResult {
                        piece,
                        blocks: std::mem::take(scratch),
                        exclusive,
                    });
                }
            }
        }

        // Layer 4: Partial pieces with unassigned blocks (speed affinity)
        if let Some(result) = self.pick_partial(ctx, missing_chunks, scratch) {
            return Some(result);
        }

        // Layer 5: New piece selection (skip if in-flight cap reached)
        if ctx.cap_reached {
            return None; // only partial blocks available when cap reached
        }
        self.pick_new_piece(ctx, missing_chunks, scratch)
    }

    /// Get unassigned blocks for a piece that's already in-flight.
    ///
    /// Fast path: when the piece is in-flight and the `ChunkMask` is empty,
    /// returns immediately — zero allocation, no `retain` filtering.
    /// When the mask is non-empty, enumerates missing chunks and filters
    /// to only unassigned ones using the `ChunkMask` (replaces the old
    /// `assigned_blocks.contains_key` retain with a cheap bit test).
    /// Fallback: when the piece is not in-flight, uses `ChunkTracker` enumeration.
    #[allow(clippy::unused_self, reason = "method on type for API consistency")]
    fn unassigned_blocks<F>(
        &self,
        piece: u32,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        out: &mut Vec<(u32, u32)>,
    ) where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        out.clear();
        if let Some(ifp) = ctx.in_flight_pieces.get(&piece) {
            // Fast path: enumerate unassigned chunks directly from ChunkMask.
            // No missing_chunks_into call, no Vec::extend, no retain — just bit iteration.
            for chunk_idx in ifp.unassigned.iter_set_bits() {
                let offset = chunk_idx * ctx.chunk_size;
                let length = ctx.chunk_size.min(ctx.piece_size.saturating_sub(offset));
                if length > 0 {
                    out.push((offset, length));
                }
            }
        } else {
            // Piece not in-flight: fall back to ChunkTracker enumeration
            missing_chunks(piece, out);
        }
    }

    /// Pick a partial piece (already in-flight) with speed affinity.
    ///
    /// Two-phase approach for zero-alloc scoring:
    /// Phase 1: Score all in-flight pieces using `ChunkMask` metadata only (`count_ones/is_empty`).
    /// Phase 2: Enumerate blocks only for the winning piece.
    fn pick_partial<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        // Phase 1: Score all in-flight pieces — zero alloc, just ChunkMask checks
        let mut best_piece: Option<u32> = None;
        let mut best_score: i32 = i32::MIN;

        for (&piece, ifp) in ctx.in_flight_pieces {
            if !ctx.peer_has.get(piece) || ctx.we_have.get(piece) || !ctx.wanted.get(piece) {
                continue;
            }
            if ifp.unassigned.is_empty() {
                continue; // No unassigned blocks — skip without any allocation
            }
            let score = if ctx.peer_is_snubbed {
                // Snubbed peers avoid busy pieces
                -(ifp.peer_count() as i32)
            } else {
                // Prefer pieces with fewer unassigned blocks (closer to completion)
                -(ifp.unassigned.count_ones() as i32)
            };
            if score > best_score {
                best_score = score;
                best_piece = Some(piece);
            }
        }

        // Phase 2: Only enumerate blocks for the winning piece
        if let Some(piece) = best_piece {
            self.unassigned_blocks(piece, ctx, missing_chunks, scratch);
            if !scratch.is_empty() {
                return Some(PickResult {
                    piece,
                    blocks: std::mem::take(scratch),
                    exclusive: false,
                });
            }
        }

        None
    }

    /// Pick a new piece (not yet in-flight).
    fn pick_new_piece<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        // Snubbed peers: pick highest-availability piece (reverse rarest-first)
        if ctx.peer_is_snubbed {
            return self.pick_reverse_rarest(ctx, missing_chunks, scratch);
        }

        // Initial random threshold: randomize to promote piece diversity
        if ctx.completed_count < ctx.initial_picker_threshold
            && let Some(result) = self.pick_random(ctx, missing_chunks, scratch)
        {
            return Some(result);
        }

        // Sequential mode or auto-sequential
        if ctx.sequential_download || ctx.auto_sequential_active {
            return self.pick_sequential(ctx, missing_chunks, scratch);
        }

        // Default: rarest-first
        self.pick_rarest_new(ctx, missing_chunks, scratch)
    }

    /// Size of an extent group in bytes (4 MiB).
    const EXTENT_SIZE: u64 = 4 * 1024 * 1024;

    /// Compute the extent index for a piece given the piece size.
    pub(crate) fn extent_of(piece: u32, piece_size: u32) -> u32 {
        let byte_offset = u64::from(piece) * u64::from(piece_size);
        (byte_offset / Self::EXTENT_SIZE) as u32
    }

    /// Find the preferred extent based on which extents have pieces currently in-flight.
    #[allow(clippy::unused_self, reason = "method on type for API consistency")]
    fn preferred_extent(&self, ctx: &PickContext<'_>) -> Option<u32> {
        let mut extent_counts: FxHashMap<u32, u32> = FxHashMap::default();
        for &piece in ctx.in_flight_pieces.keys() {
            let extent = Self::extent_of(piece, ctx.piece_size);
            *extent_counts.entry(extent).or_default() += 1;
        }
        extent_counts
            .into_iter()
            .max_by_key(|&(_, count)| count)
            .map(|(extent, _)| extent)
    }

    /// Rarest-first among pieces not in-flight.
    ///
    /// When extent affinity is enabled, tries the preferred extent first,
    /// then falls back to any extent if no candidates remain in that extent.
    fn pick_rarest_new<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        if ctx.extent_affinity
            && let Some(extent) = self.preferred_extent(ctx)
            && let Some(result) = self.pick_rarest_in_extent(ctx, missing_chunks, extent, scratch)
        {
            return Some(result);
        }
        self.pick_rarest_any(ctx, missing_chunks, scratch)
    }

    /// Standard rarest-first picking with no extent filter.
    fn pick_rarest_any<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        let mut best_index: Option<u32> = None;
        let mut best_avail: u32 = u32::MAX;

        for i in 0..self.num_pieces {
            if !ctx.peer_has.get(i) || ctx.we_have.get(i) || !ctx.wanted.get(i) {
                continue;
            }
            if ctx.in_flight_pieces.contains_key(&i) {
                continue;
            }
            let avail = self.effective_availability(i);
            if avail == 0 {
                continue;
            }
            if avail < best_avail {
                best_avail = avail;
                best_index = Some(i);
            }
        }

        best_index.map(|piece| {
            missing_chunks(piece, scratch);
            let exclusive = self.should_whole_piece(ctx, scratch);
            PickResult {
                piece,
                blocks: std::mem::take(scratch),
                exclusive,
            }
        })
    }

    /// Rarest-first picking filtered to pieces within a specific extent.
    fn pick_rarest_in_extent<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        extent: u32,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        let mut best_index: Option<u32> = None;
        let mut best_avail: u32 = u32::MAX;

        for i in 0..self.num_pieces {
            if Self::extent_of(i, ctx.piece_size) != extent {
                continue;
            }
            if !ctx.peer_has.get(i) || ctx.we_have.get(i) || !ctx.wanted.get(i) {
                continue;
            }
            if ctx.in_flight_pieces.contains_key(&i) {
                continue;
            }
            let avail = self.effective_availability(i);
            if avail == 0 {
                continue;
            }
            if avail < best_avail {
                best_avail = avail;
                best_index = Some(i);
            }
        }

        best_index.map(|piece| {
            missing_chunks(piece, scratch);
            let exclusive = self.should_whole_piece(ctx, scratch);
            PickResult {
                piece,
                blocks: std::mem::take(scratch),
                exclusive,
            }
        })
    }

    /// Sequential: pick lowest-index available piece not in-flight.
    fn pick_sequential<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        for i in 0..self.num_pieces {
            if !ctx.peer_has.get(i) || ctx.we_have.get(i) || !ctx.wanted.get(i) {
                continue;
            }
            if ctx.in_flight_pieces.contains_key(&i) {
                continue;
            }
            let avail = self.effective_availability(i);
            if avail == 0 {
                continue;
            }
            missing_chunks(i, scratch);
            if !scratch.is_empty() {
                let exclusive = self.should_whole_piece(ctx, scratch);
                return Some(PickResult {
                    piece: i,
                    blocks: std::mem::take(scratch),
                    exclusive,
                });
            }
        }
        None
    }

    /// Random selection for initial diversity.
    fn pick_random<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        // Collect all eligible pieces, pick one using simple hash-based selection
        let mut candidates = Vec::new();
        for i in 0..self.num_pieces {
            if !ctx.peer_has.get(i) || ctx.we_have.get(i) || !ctx.wanted.get(i) {
                continue;
            }
            if ctx.in_flight_pieces.contains_key(&i) {
                continue;
            }
            let avail = self.effective_availability(i);
            if avail == 0 {
                continue;
            }
            candidates.push(i);
        }
        if candidates.is_empty() {
            return None;
        }
        // Use peer address port as randomization seed for reproducible-per-peer picks
        let idx = (ctx.peer_addr.port() as usize) % candidates.len();
        let piece = candidates[idx];
        missing_chunks(piece, scratch);
        let exclusive = self.should_whole_piece(ctx, scratch);
        Some(PickResult {
            piece,
            blocks: std::mem::take(scratch),
            exclusive,
        })
    }

    /// Snubbed peer: highest-availability piece (reverse rarest-first).
    fn pick_reverse_rarest<F>(
        &self,
        ctx: &PickContext<'_>,
        missing_chunks: &F,
        scratch: &mut Vec<(u32, u32)>,
    ) -> Option<PickResult>
    where
        F: Fn(u32, &mut Vec<(u32, u32)>),
    {
        let mut best_index: Option<u32> = None;
        let mut best_avail: u32 = 0;

        for i in 0..self.num_pieces {
            if !ctx.peer_has.get(i) || ctx.we_have.get(i) || !ctx.wanted.get(i) {
                continue;
            }
            if ctx.in_flight_pieces.contains_key(&i) {
                continue;
            }
            let avail = self.effective_availability(i);
            if avail == 0 {
                continue;
            }
            if avail > best_avail {
                best_avail = avail;
                best_index = Some(i);
            }
        }

        best_index.map(|piece| {
            missing_chunks(piece, scratch);
            PickResult {
                piece,
                blocks: std::mem::take(scratch),
                exclusive: false,
            }
        })
    }

    /// Decide if a fast peer should get exclusive (whole-piece) assignment.
    #[allow(clippy::unused_self, reason = "method on type for API consistency")]
    fn should_whole_piece(&self, ctx: &PickContext<'_>, blocks: &[(u32, u32)]) -> bool {
        if ctx.peer_speed != PeerSpeed::Fast || ctx.peer_rate <= 0.0 {
            return false;
        }
        let total_bytes: u64 = blocks.iter().map(|&(_, len)| u64::from(len)).sum();
        let time_secs = total_bytes as f64 / ctx.peer_rate;
        time_secs <= f64::from(ctx.whole_pieces_threshold)
    }
}

/// Build a bitfield marking which pieces are wanted based on file priorities.
///
/// For each file with priority > Skip, compute its piece range via `Lengths::file_pieces()`
/// and set those bits. Shared pieces (spanning file boundaries) are wanted if **any**
/// overlapping file is non-Skip.
#[must_use]
pub fn build_wanted_pieces(
    file_priorities: &[FilePriority],
    file_lengths: &[u64],
    lengths: &Lengths,
) -> Bitfield {
    let mut wanted = Bitfield::new(lengths.num_pieces());
    let mut offset = 0u64;
    for (i, &file_len) in file_lengths.iter().enumerate() {
        if file_priorities.get(i).copied().unwrap_or_default() > FilePriority::Skip
            && let Some((first, last)) = lengths.file_pieces(offset, file_len)
        {
            for p in first..=last {
                wanted.set(p);
            }
        }
        offset += file_len;
    }
    wanted
}

/// Hysteresis thresholds for auto-sequential mode.
const AUTO_SEQUENTIAL_ACTIVATE_RATIO: f64 = 1.6;
const AUTO_SEQUENTIAL_DEACTIVATE_RATIO: f64 = 1.3;

/// Evaluate auto-sequential hysteresis.
///
/// Returns the new `auto_sequential_active` state. Uses dual thresholds to
/// prevent flapping:
/// - Activates when in-flight / peers > 1.6 (partial-piece explosion)
/// - Deactivates when in-flight / peers < 1.3
/// - Stays in current state between thresholds
pub(crate) fn evaluate_auto_sequential(
    in_flight_count: usize,
    connected_peers: usize,
    currently_active: bool,
) -> bool {
    if connected_peers == 0 {
        return false;
    }
    let ratio = in_flight_count as f64 / connected_peers as f64;
    if currently_active {
        ratio >= AUTO_SEQUENTIAL_DEACTIVATE_RATIO
    } else {
        ratio > AUTO_SEQUENTIAL_ACTIVATE_RATIO
    }
}

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

    #[test]
    fn new_all_zero() {
        let sel = PieceSelector::new(10);
        assert_eq!(sel.availability().len(), 10);
        assert!(sel.availability().iter().all(|&a| a == 0));
    }

    #[test]
    fn add_bitfield_increments() {
        let mut sel = PieceSelector::new(8);
        let mut bf = Bitfield::new(8);
        bf.set(1);
        bf.set(3);
        bf.set(7);

        sel.add_peer_bitfield(&bf);

        assert_eq!(sel.availability()[0], 0);
        assert_eq!(sel.availability()[1], 1);
        assert_eq!(sel.availability()[2], 0);
        assert_eq!(sel.availability()[3], 1);
        assert_eq!(sel.availability()[7], 1);

        // Adding a second peer with overlapping pieces
        let mut bf2 = Bitfield::new(8);
        bf2.set(1);
        bf2.set(5);

        sel.add_peer_bitfield(&bf2);

        assert_eq!(sel.availability()[1], 2);
        assert_eq!(sel.availability()[5], 1);
    }

    #[test]
    fn remove_bitfield_decrements() {
        let mut sel = PieceSelector::new(8);
        let mut bf = Bitfield::new(8);
        bf.set(0);
        bf.set(4);

        sel.add_peer_bitfield(&bf);
        assert_eq!(sel.availability()[0], 1);
        assert_eq!(sel.availability()[4], 1);

        sel.remove_peer_bitfield(&bf);
        assert_eq!(sel.availability()[0], 0);
        assert_eq!(sel.availability()[4], 0);

        // Saturates at zero — removing again should not underflow
        sel.remove_peer_bitfield(&bf);
        assert_eq!(sel.availability()[0], 0);
        assert_eq!(sel.availability()[4], 0);
    }

    #[test]
    fn increment_decrement() {
        let mut sel = PieceSelector::new(4);

        sel.increment(2);
        assert_eq!(sel.availability()[2], 1);

        sel.increment(2);
        assert_eq!(sel.availability()[2], 2);

        sel.decrement(2);
        assert_eq!(sel.availability()[2], 1);

        sel.decrement(2);
        assert_eq!(sel.availability()[2], 0);

        // Saturates at zero
        sel.decrement(2);
        assert_eq!(sel.availability()[2], 0);
    }

    #[test]
    fn pick_rarest() {
        let mut sel = PieceSelector::new(4);

        // Piece 0: avail 3, piece 1: avail 1, piece 2: avail 2, piece 3: avail 1
        sel.availability[0] = 3;
        sel.availability[1] = 1;
        sel.availability[2] = 2;
        sel.availability[3] = 1;

        // Peer has all pieces
        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(4);
        let in_flight = HashSet::new();
        let mut wanted = Bitfield::new(4);
        for i in 0..4 {
            wanted.set(i);
        }

        // Should pick piece 1 (avail=1, lowest index among ties with piece 3)
        let picked = sel.pick(&peer_has, &we_have, &in_flight, &wanted);
        assert_eq!(picked, Some(1));
    }

    #[test]
    fn pick_skips_have() {
        let mut sel = PieceSelector::new(4);
        sel.availability[0] = 1;
        sel.availability[1] = 1;
        sel.availability[2] = 2;
        sel.availability[3] = 3;

        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }

        // We already have piece 0 and 1
        let mut we_have = Bitfield::new(4);
        we_have.set(0);
        we_have.set(1);

        let in_flight = HashSet::new();
        let mut wanted = Bitfield::new(4);
        for i in 0..4 {
            wanted.set(i);
        }

        // Should pick piece 2 (avail=2), since 0 and 1 are already had
        let picked = sel.pick(&peer_has, &we_have, &in_flight, &wanted);
        assert_eq!(picked, Some(2));
    }

    #[test]
    fn pick_skips_inflight() {
        let mut sel = PieceSelector::new(4);
        sel.availability[0] = 1;
        sel.availability[1] = 2;
        sel.availability[2] = 3;
        sel.availability[3] = 4;

        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(4);

        let mut in_flight = HashSet::new();
        in_flight.insert(0);
        let mut wanted = Bitfield::new(4);
        for i in 0..4 {
            wanted.set(i);
        }

        // Piece 0 is rarest but in flight, should pick piece 1
        let picked = sel.pick(&peer_has, &we_have, &in_flight, &wanted);
        assert_eq!(picked, Some(1));
    }

    #[test]
    fn pick_none_available() {
        let mut sel = PieceSelector::new(4);
        // All availability at zero — no peers have announced these pieces
        // through add_peer_bitfield or increment

        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(4);
        let in_flight = HashSet::new();
        let mut wanted = Bitfield::new(4);
        for i in 0..4 {
            wanted.set(i);
        }

        // Zero availability means no peers reported having these pieces
        let picked = sel.pick(&peer_has, &we_have, &in_flight, &wanted);
        assert_eq!(picked, None);

        // Also None when we have everything
        sel.availability[0] = 1;
        sel.availability[1] = 1;
        let mut we_have_all = Bitfield::new(4);
        for i in 0..4 {
            we_have_all.set(i);
        }
        let picked = sel.pick(&peer_has, &we_have_all, &in_flight, &wanted);
        assert_eq!(picked, None);

        // Also None when peer has nothing
        let peer_empty = Bitfield::new(4);
        let we_have_none = Bitfield::new(4);
        let picked = sel.pick(&peer_empty, &we_have_none, &in_flight, &wanted);
        assert_eq!(picked, None);
    }

    #[test]
    fn pick_skips_unwanted() {
        let mut sel = PieceSelector::new(4);
        sel.availability[0] = 1;
        sel.availability[1] = 1;
        sel.availability[2] = 1;
        sel.availability[3] = 1;

        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(4);
        let in_flight = HashSet::new();

        // Only want pieces 2 and 3
        let mut wanted = Bitfield::new(4);
        wanted.set(2);
        wanted.set(3);

        let picked = sel.pick(&peer_has, &we_have, &in_flight, &wanted);
        assert_eq!(picked, Some(2)); // lowest-index wanted piece
    }

    #[test]
    fn pick_all_wanted_is_normal_behavior() {
        let mut sel = PieceSelector::new(4);
        sel.availability[0] = 3;
        sel.availability[1] = 1;
        sel.availability[2] = 2;
        sel.availability[3] = 1;

        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(4);
        let in_flight = HashSet::new();

        let mut wanted = Bitfield::new(4);
        for i in 0..4 {
            wanted.set(i);
        }

        let picked = sel.pick(&peer_has, &we_have, &in_flight, &wanted);
        assert_eq!(picked, Some(1)); // rarest first
    }

    use irontide_core::{FilePriority, Lengths};

    #[test]
    fn build_wanted_all_normal() {
        let priorities = vec![FilePriority::Normal; 2];
        let file_lengths = vec![100, 100];
        let lengths = Lengths::new(200, 100, 50);
        let wanted = super::build_wanted_pieces(&priorities, &file_lengths, &lengths);
        assert_eq!(wanted.count_ones(), 2);
        assert!(wanted.get(0));
        assert!(wanted.get(1));
    }

    #[test]
    fn build_wanted_skip_first_file() {
        let priorities = vec![FilePriority::Skip, FilePriority::Normal];
        let file_lengths = vec![100, 100];
        let lengths = Lengths::new(200, 100, 50);
        let wanted = super::build_wanted_pieces(&priorities, &file_lengths, &lengths);
        assert!(!wanted.get(0));
        assert!(wanted.get(1));
    }

    #[test]
    fn build_wanted_shared_boundary_piece() {
        // File 0: 80 bytes → pieces 0..0, File 1: 80 bytes → pieces 0..1
        // piece_length=100, total=160 → 2 pieces
        // If File 0 is Skip, File 1 is Normal: piece 0 still wanted (shared)
        let priorities = vec![FilePriority::Skip, FilePriority::Normal];
        let file_lengths = vec![80, 80];
        let lengths = Lengths::new(160, 100, 50);
        let wanted = super::build_wanted_pieces(&priorities, &file_lengths, &lengths);
        assert!(wanted.get(0)); // shared boundary piece
        assert!(wanted.get(1));
    }

    #[test]
    fn build_wanted_all_skip() {
        let priorities = vec![FilePriority::Skip; 3];
        let file_lengths = vec![100, 100, 100];
        let lengths = Lengths::new(300, 100, 50);
        let wanted = super::build_wanted_pieces(&priorities, &file_lengths, &lengths);
        assert_eq!(wanted.count_ones(), 0);
    }

    // ── Helper for PickContext-based tests ──────────────────────────────

    // Test helper that mirrors the customizable fields of PickContext —
    // wrapping the 8 borrowed args in a struct would just duplicate the
    // fields without making call sites clearer.
    #[allow(clippy::too_many_arguments)]
    fn default_pick_context<'a>(
        peer_addr: SocketAddr,
        peer_has: &'a Bitfield,
        we_have: &'a Bitfield,
        wanted: &'a Bitfield,
        in_flight_pieces: &'a FxHashMap<u32, InFlightPiece>,
        streaming_pieces: &'a BTreeSet<u32>,
        time_critical_pieces: &'a BTreeSet<u32>,
        suggested_pieces: &'a HashSet<u32>,
    ) -> PickContext<'a> {
        PickContext {
            peer_addr,
            peer_has,
            peer_speed: PeerSpeed::Medium,
            peer_is_snubbed: false,
            peer_rate: 50_000.0,
            we_have,
            in_flight_pieces,
            wanted,
            streaming_pieces,
            time_critical_pieces,
            suggested_pieces,
            sequential_download: false,
            completed_count: 100,
            initial_picker_threshold: 4,
            connected_peer_count: 10,
            whole_pieces_threshold: 20,
            piece_size: 262_144,
            chunk_size: 16_384,
            extent_affinity: false,
            auto_sequential_active: false,
            cap_reached: false,
        }
    }

    fn addr(port: u16) -> SocketAddr {
        SocketAddr::from(([127, 0, 0, 1], port))
    }

    // ── New tests for pick_blocks ──────────────────────────────────────

    #[test]
    fn block_level_two_peers_different_blocks() {
        // 1-piece torrent, piece 0, 2 blocks
        let mut sel = PieceSelector::new(1);
        sel.availability[0] = 2;

        let mut peer_has = Bitfield::new(1);
        peer_has.set(0);
        let we_have = Bitfield::new(1);
        let mut wanted = Bitfield::new(1);
        wanted.set(0);

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        // Peer A picks first — gets both blocks
        let ctx_a = default_pick_context(
            addr(1000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384), (16384, 16384)]);
        };
        let mut scratch = Vec::new();
        let result_a = sel.pick_blocks(&ctx_a, &chunks, &mut scratch).unwrap();
        assert_eq!(result_a.piece, 0);
        assert_eq!(result_a.blocks.len(), 2);

        // Now record peer A's assignment in an InFlightPiece
        let mut ifp = InFlightPiece::new(2, ChunkMask::all(2));
        ifp.assigned_blocks.insert((0, 0), addr(1000));
        ifp.unassigned.clear(0);
        ifp.assigned_blocks.insert((0, 16384), addr(1000));
        ifp.unassigned.clear(1);
        let mut in_flight2 = FxHashMap::default();
        in_flight2.insert(0u32, ifp);

        // Peer B picks — all blocks assigned, so unassigned_blocks is empty
        let ctx_b = default_pick_context(
            addr(2000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight2,
            &streaming,
            &time_critical,
            &suggested,
        );
        let result_b = sel.pick_blocks(&ctx_b, &chunks, &mut scratch);
        // No unassigned blocks remain, so no pick possible (only 1 piece)
        assert!(result_b.is_none());
    }

    #[test]
    fn streaming_window_before_rarest() {
        let mut sel = PieceSelector::new(2);
        sel.availability[0] = 5; // common
        sel.availability[1] = 1; // rarer

        let mut peer_has = Bitfield::new(2);
        peer_has.set(0);
        peer_has.set(1);
        let we_have = Bitfield::new(2);
        let mut wanted = Bitfield::new(2);
        wanted.set(0);
        wanted.set(1);

        let mut streaming = BTreeSet::new();
        streaming.insert(0); // streaming piece 0
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        let ctx = default_pick_context(
            addr(3000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        // Streaming layer picks piece 0 despite piece 1 being rarer
        assert_eq!(result.piece, 0);
    }

    #[test]
    fn streaming_fastest_peer_first() {
        let mut sel = PieceSelector::new(2);
        sel.availability[0] = 2;
        sel.availability[1] = 2;

        let mut peer_has = Bitfield::new(2);
        peer_has.set(0);
        peer_has.set(1);
        let we_have = Bitfield::new(2);
        let mut wanted = Bitfield::new(2);
        wanted.set(0);
        wanted.set(1);

        let mut streaming = BTreeSet::new();
        streaming.insert(0);
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        // Fast peer should get streaming blocks
        let mut ctx_fast = default_pick_context(
            addr(4000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx_fast.peer_speed = PeerSpeed::Fast;
        ctx_fast.peer_rate = 102_400.0;
        ctx_fast.peer_is_snubbed = false;

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result_fast = sel.pick_blocks(&ctx_fast, &chunks, &mut scratch).unwrap();
        assert_eq!(result_fast.piece, 0); // got streaming piece

        // Slow, snubbed peer should NOT get streaming blocks (layer 1 skips snubbed)
        let mut ctx_slow = default_pick_context(
            addr(4001),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx_slow.peer_speed = PeerSpeed::Slow;
        ctx_slow.peer_rate = 1_024.0;
        ctx_slow.peer_is_snubbed = true;

        let result_slow = sel.pick_blocks(&ctx_slow, &chunks, &mut scratch).unwrap();
        // Snubbed peer skips layers 1 & 2, ends up in layer 5 (reverse rarest)
        // Both pieces have avail=2, so it picks the first one with highest avail (both equal, lowest index = 0)
        // But the important thing is it did NOT get picked from the streaming layer
        // (it went through reverse rarest path instead)
        assert!(result_slow.piece <= 1); // valid piece picked from non-streaming path
    }

    #[test]
    fn time_critical_first_last_pieces() {
        let mut sel = PieceSelector::new(10);
        // Piece 5 is rarest but not time-critical
        for i in 0..10 {
            sel.availability[i] = 3;
        }
        sel.availability[5] = 1; // rarest

        let mut peer_has = Bitfield::new(10);
        for i in 0..10 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(10);
        let mut wanted = Bitfield::new(10);
        for i in 0..10 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let mut time_critical = BTreeSet::new();
        time_critical.insert(0); // first piece
        time_critical.insert(9); // last piece
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        let ctx = default_pick_context(
            addr(5000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        // Time-critical pieces 0 or 9 should be picked before rarest piece 5
        assert!(result.piece == 0 || result.piece == 9);
    }

    #[test]
    fn sequential_mode_ascending() {
        let mut sel = PieceSelector::new(5);
        for i in 0..5 {
            sel.availability[i] = 2;
        }
        // Make piece 3 rarest — sequential should ignore this
        sel.availability[3] = 1;

        let mut peer_has = Bitfield::new(5);
        for i in 0..5 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(5);
        let mut wanted = Bitfield::new(5);
        for i in 0..5 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        let mut ctx = default_pick_context(
            addr(6000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.sequential_download = true;
        ctx.completed_count = 100; // past initial threshold

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        assert_eq!(result.piece, 0); // lowest index
    }

    #[test]
    fn initial_random_threshold() {
        let mut sel = PieceSelector::new(10);
        for i in 0..10 {
            sel.availability[i] = (i as u32) + 1;
        }

        let mut peer_has = Bitfield::new(10);
        for i in 0..10 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(10);
        let mut wanted = Bitfield::new(10);
        for i in 0..10 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        let mut ctx = default_pick_context(
            addr(7000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.completed_count = 0; // below threshold
        ctx.initial_picker_threshold = 4;

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        // Random pick — just verify a valid piece was picked
        assert!(result.piece < 10);
        assert!(!result.blocks.is_empty());
    }

    #[test]
    fn whole_piece_threshold_fast_peer() {
        let mut sel = PieceSelector::new(1);
        sel.availability[0] = 1;

        let mut peer_has = Bitfield::new(1);
        peer_has.set(0);
        let we_have = Bitfield::new(1);
        let mut wanted = Bitfield::new(1);
        wanted.set(0);

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        let mut ctx = default_pick_context(
            addr(8000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.peer_speed = PeerSpeed::Fast;
        ctx.peer_rate = 1_048_576.0; // 1 MB/s
        ctx.piece_size = 262_144;
        ctx.whole_pieces_threshold = 20;
        ctx.completed_count = 100; // past initial threshold

        // Blocks total 262144 bytes. Time = 262144/1048576 ≈ 0.25s < 20s
        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 131_072), (131_072, 131_072)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        assert_eq!(result.piece, 0);
        assert!(
            result.exclusive,
            "fast peer should get exclusive=true for small piece"
        );
    }

    #[test]
    fn speed_affinity_slow_avoids_fast_partial() {
        let mut sel = PieceSelector::new(3);
        sel.availability[0] = 2;
        sel.availability[1] = 2;
        sel.availability[2] = 2;

        let mut peer_has = Bitfield::new(3);
        for i in 0..3 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(3);
        let mut wanted = Bitfield::new(3);
        for i in 0..3 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();

        // Piece 0 is partially downloaded by a fast peer (2 blocks assigned out of 3)
        let mut ifp0 = InFlightPiece::new(3, ChunkMask::all(3));
        ifp0.assigned_blocks.insert((0, 0), addr(9000));
        ifp0.unassigned.clear(0);
        ifp0.assigned_blocks.insert((0, 16384), addr(9000));
        ifp0.unassigned.clear(1);

        let mut in_flight = FxHashMap::default();
        in_flight.insert(0u32, ifp0);

        let mut ctx = default_pick_context(
            addr(9001),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.peer_speed = PeerSpeed::Slow;
        ctx.peer_rate = 5_000.0;
        ctx.completed_count = 100; // past initial threshold

        let chunks = |piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            match piece {
                0 => buf.extend_from_slice(&[(0, 16384), (16384, 16384), (32768, 16384)]),
                _ => buf.extend_from_slice(&[(0, 16384), (16384, 16384)]),
            }
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        // Slow peer can pick partial piece 0 (1 unassigned block) or a new piece (1 or 2).
        // Layer 4 (partial) runs first. Piece 0 has 1 unassigned block.
        // Either partial or new is valid — just verify we got a valid piece.
        assert!(result.piece < 3);
        assert!(!result.blocks.is_empty());
    }

    #[test]
    fn snubbed_peer_reverse_picking() {
        let mut sel = PieceSelector::new(3);
        sel.availability[0] = 1;
        sel.availability[1] = 2;
        sel.availability[2] = 3;

        let mut peer_has = Bitfield::new(3);
        for i in 0..3 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(3);
        let mut wanted = Bitfield::new(3);
        for i in 0..3 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        let mut ctx = default_pick_context(
            addr(10000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.peer_is_snubbed = true;

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        // Snubbed peer should pick highest availability (piece 2, avail=3)
        assert_eq!(result.piece, 2);
        assert!(!result.exclusive); // snubbed peers never get exclusive
    }

    #[test]
    fn auto_sequential_on_partial_explosion() {
        let mut sel = PieceSelector::new(15);
        for i in 0..15 {
            sel.availability[i] = 2;
        }
        // Make piece 10 rarest — auto-sequential should override
        sel.availability[10] = 1;

        let mut peer_has = Bitfield::new(15);
        for i in 0..15 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(15);
        let mut wanted = Bitfield::new(15);
        for i in 0..15 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();

        // 10 in-flight pieces with connected_peer_count=4 → 10 > 1.5*4=6
        let mut in_flight = FxHashMap::default();
        for i in 0..10 {
            let mut ifp = InFlightPiece::new(2, ChunkMask::all(2));
            // All blocks assigned so partial won't find unassigned blocks
            ifp.assigned_blocks.insert((i, 0), addr(11000));
            ifp.unassigned.clear(0);
            ifp.assigned_blocks.insert((i, 16384), addr(11000));
            ifp.unassigned.clear(1);
            in_flight.insert(i, ifp);
        }

        let mut ctx = default_pick_context(
            addr(11001),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.connected_peer_count = 4;
        ctx.completed_count = 100; // past initial threshold
        ctx.auto_sequential_active = true;

        let chunks = |piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            if piece < 10 {
                // In-flight pieces — all assigned, return full list
                buf.extend_from_slice(&[(0, 16384), (16384, 16384)]);
            } else {
                buf.extend_from_slice(&[(0, 16384)]);
            }
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        // Auto-sequential: should pick lowest non-in-flight piece = 10
        assert_eq!(result.piece, 10);
    }

    #[test]
    fn seed_counter_no_array_modification() {
        let mut sel = PieceSelector::new(4);
        sel.availability[0] = 1;
        sel.availability[1] = 2;
        sel.availability[2] = 0;
        sel.availability[3] = 3;

        // add_seed twice, remove_seed once → seed_count = 1
        sel.add_seed();
        sel.add_seed();
        sel.remove_seed();

        // Verify availability array is unchanged
        assert_eq!(sel.availability()[0], 1);
        assert_eq!(sel.availability()[1], 2);
        assert_eq!(sel.availability()[2], 0);
        assert_eq!(sel.availability()[3], 3);

        // effective_availability = array value + seed_count(1)
        assert_eq!(sel.effective_availability(0), 2);
        assert_eq!(sel.effective_availability(1), 3);
        assert_eq!(sel.effective_availability(2), 1);
        assert_eq!(sel.effective_availability(3), 4);

        // Out-of-range index: should return seed_count only
        assert_eq!(sel.effective_availability(99), 1);
    }

    #[test]
    fn peer_speed_default_classification() {
        assert_eq!(PeerSpeed::from_rate(0.0), PeerSpeed::Slow);
        assert_eq!(PeerSpeed::from_rate(5_000.0), PeerSpeed::Slow);
        assert_eq!(PeerSpeed::from_rate(10_240.0), PeerSpeed::Medium);
        assert_eq!(PeerSpeed::from_rate(50_000.0), PeerSpeed::Medium);
        assert_eq!(PeerSpeed::from_rate(102_400.0), PeerSpeed::Fast);
        assert_eq!(PeerSpeed::from_rate(1_000_000.0), PeerSpeed::Fast);
    }

    #[test]
    fn peer_speed_custom_classifier() {
        let classifier = PeerSpeedClassifier {
            slow_threshold: 1_000.0,
            fast_threshold: 50_000.0,
        };
        assert_eq!(classifier.classify(500.0), PeerSpeed::Slow);
        assert_eq!(classifier.classify(1_000.0), PeerSpeed::Medium);
        assert_eq!(classifier.classify(50_000.0), PeerSpeed::Fast);
    }

    // ── Extent affinity tests ─────────────────────────────────────────

    #[test]
    fn extent_of_computation() {
        // 256 KiB pieces, 4 MiB extent = 16 pieces per extent
        assert_eq!(PieceSelector::extent_of(0, 262_144), 0);
        assert_eq!(PieceSelector::extent_of(15, 262_144), 0);
        assert_eq!(PieceSelector::extent_of(16, 262_144), 1);
        assert_eq!(PieceSelector::extent_of(31, 262_144), 1);
        assert_eq!(PieceSelector::extent_of(32, 262_144), 2);
        // 1 MiB pieces = 4 pieces per extent
        assert_eq!(PieceSelector::extent_of(0, 1_048_576), 0);
        assert_eq!(PieceSelector::extent_of(3, 1_048_576), 0);
        assert_eq!(PieceSelector::extent_of(4, 1_048_576), 1);
    }

    #[test]
    fn extent_affinity_prefers_active_extent() {
        // Set up 32 pieces across 2 extents. Make piece 20 globally rarest (extent 1),
        // but have in-flight activity in extent 0. With affinity, should pick from extent 0.
        let mut sel = PieceSelector::new(32);
        for i in 0..32 {
            sel.availability[i] = 2;
        }
        sel.availability[20] = 1; // globally rarest, extent 1
        sel.availability[5] = 1; // rarest in extent 0

        let mut peer_has = Bitfield::new(32);
        for i in 0..32 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(32);
        let mut wanted = Bitfield::new(32);
        for i in 0..32 {
            wanted.set(i);
        }

        // Piece 10 in-flight in extent 0 — fully assigned (no unassigned chunks)
        let mut ifp = InFlightPiece::new(2, ChunkMask::all(2));
        ifp.assigned_blocks.insert((10, 0), addr(9999));
        ifp.unassigned.clear(0);
        ifp.unassigned.clear(1);
        let mut in_flight = FxHashMap::default();
        in_flight.insert(10u32, ifp);

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();

        let mut ctx = default_pick_context(
            addr(5555),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.extent_affinity = true;
        ctx.piece_size = 262_144;
        ctx.completed_count = 100;

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        assert_eq!(result.piece, 5); // extent 0, not 20 (extent 1)
    }

    #[test]
    fn extent_affinity_disabled_picks_global_rarest() {
        // Same setup but with affinity disabled — should pick lowest-index rarest
        let mut sel = PieceSelector::new(32);
        for i in 0..32 {
            sel.availability[i] = 2;
        }
        sel.availability[20] = 1;
        sel.availability[5] = 1;

        let mut peer_has = Bitfield::new(32);
        for i in 0..32 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(32);
        let mut wanted = Bitfield::new(32);
        for i in 0..32 {
            wanted.set(i);
        }

        // Piece 10 in-flight — fully assigned (no unassigned chunks)
        let mut ifp = InFlightPiece::new(2, ChunkMask::all(2));
        ifp.assigned_blocks.insert((10, 0), addr(9999));
        ifp.unassigned.clear(0);
        ifp.unassigned.clear(1);
        let mut in_flight = FxHashMap::default();
        in_flight.insert(10u32, ifp);

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();

        let mut ctx = default_pick_context(
            addr(5555),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.extent_affinity = false;
        ctx.piece_size = 262_144;
        ctx.completed_count = 100;

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        assert_eq!(result.piece, 5); // lowest-index rarest (tie-break)
    }

    #[test]
    fn extent_affinity_fallback_when_extent_exhausted() {
        // All pieces in active extent already downloaded — falls back to other extents
        let mut sel = PieceSelector::new(32);
        for i in 0..32 {
            sel.availability[i] = 2;
        }

        let mut peer_has = Bitfield::new(32);
        for i in 0..32 {
            peer_has.set(i);
        }
        let mut we_have = Bitfield::new(32);
        for i in 0..16 {
            we_have.set(i);
        } // have all extent 0
        let mut wanted = Bitfield::new(32);
        for i in 0..32 {
            wanted.set(i);
        }

        let mut ifp = InFlightPiece::new(2, ChunkMask::all(2));
        ifp.assigned_blocks.insert((10, 0), addr(9999));
        ifp.unassigned.clear(0);
        let mut in_flight = FxHashMap::default();
        in_flight.insert(10u32, ifp);

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();

        let mut ctx = default_pick_context(
            addr(5555),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.extent_affinity = true;
        ctx.piece_size = 262_144;
        ctx.completed_count = 100;

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch).unwrap();
        assert!(result.piece >= 16); // falls back to extent 1
    }

    #[test]
    fn auto_sequential_hysteresis_activation() {
        // 4 peers, need > 1.6 * 4 = 6.4 in-flight to activate
        assert!(!evaluate_auto_sequential(6, 4, false)); // 6/4 = 1.5 < 1.6
        assert!(evaluate_auto_sequential(7, 4, false)); // 7/4 = 1.75 > 1.6
    }

    #[test]
    fn auto_sequential_hysteresis_deactivation() {
        // 4 peers, need < 1.3 * 4 = 5.2 in-flight to deactivate
        assert!(evaluate_auto_sequential(6, 4, true)); // 6/4 = 1.5 >= 1.3, stays active
        assert!(!evaluate_auto_sequential(5, 4, true)); // 5/4 = 1.25 < 1.3, deactivates
    }

    #[test]
    fn auto_sequential_hysteresis_band() {
        // In the band between 1.3 and 1.6 — state doesn't change
        // 10 peers: activate > 16, deactivate < 13
        // At 14 in-flight (ratio 1.4): in the band
        assert!(!evaluate_auto_sequential(14, 10, false)); // inactive stays inactive
        assert!(evaluate_auto_sequential(14, 10, true)); // active stays active
    }

    #[test]
    fn auto_sequential_zero_peers() {
        assert!(!evaluate_auto_sequential(10, 0, false));
        assert!(!evaluate_auto_sequential(10, 0, true));
    }

    // ── In-flight cap tests ──────────────────────────────────────────

    #[test]
    fn cap_reached_skips_new_piece_but_allows_partial() {
        // Set up 4 pieces, peer has all, we have none
        let mut sel = PieceSelector::new(4);
        for i in 0..4 {
            sel.availability[i] = 2;
        }

        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(4);
        let mut wanted = Bitfield::new(4);
        for i in 0..4 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();

        // Piece 0 is in-flight with 1 unassigned block
        let mut ifp = InFlightPiece::new(2, ChunkMask::all(2));
        ifp.assigned_blocks.insert((0, 0), addr(12000));
        ifp.unassigned.clear(0);
        let mut in_flight = FxHashMap::default();
        in_flight.insert(0u32, ifp);

        // With cap_reached = true, should still pick partial piece 0
        let mut ctx = default_pick_context(
            addr(12001),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.cap_reached = true;
        ctx.completed_count = 100;

        let chunks = |piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            match piece {
                0 => buf.extend_from_slice(&[(0, 16384), (16384, 16384)]),
                _ => buf.extend_from_slice(&[(0, 16384)]),
            }
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch);
        // Should pick partial piece 0 (1 unassigned block at offset 16384)
        assert!(result.is_some());
        let r = result.unwrap();
        assert_eq!(r.piece, 0);
        assert_eq!(r.blocks, vec![(16384, 16384)]);
    }

    #[test]
    fn cap_reached_returns_none_without_partial() {
        // Set up 4 pieces, peer has all, we have none
        let mut sel = PieceSelector::new(4);
        for i in 0..4 {
            sel.availability[i] = 2;
        }

        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(4);
        let mut wanted = Bitfield::new(4);
        for i in 0..4 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default(); // no in-flight pieces

        // With cap_reached = true and no in-flight pieces, should return None
        let mut ctx = default_pick_context(
            addr(13000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.cap_reached = true;
        ctx.completed_count = 100;

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch);
        // No partial pieces and cap reached — new piece selection skipped
        assert!(result.is_none());
    }

    #[test]
    fn cap_not_reached_picks_new_piece() {
        // Verify normal behavior when cap_reached = false
        let mut sel = PieceSelector::new(4);
        for i in 0..4 {
            sel.availability[i] = 2;
        }

        let mut peer_has = Bitfield::new(4);
        for i in 0..4 {
            peer_has.set(i);
        }
        let we_have = Bitfield::new(4);
        let mut wanted = Bitfield::new(4);
        for i in 0..4 {
            wanted.set(i);
        }

        let streaming = BTreeSet::new();
        let time_critical = BTreeSet::new();
        let suggested = HashSet::new();
        let in_flight = FxHashMap::default();

        let mut ctx = default_pick_context(
            addr(14000),
            &peer_has,
            &we_have,
            &wanted,
            &in_flight,
            &streaming,
            &time_critical,
            &suggested,
        );
        ctx.cap_reached = false;
        ctx.completed_count = 100;

        let chunks = |_piece: u32, buf: &mut Vec<(u32, u32)>| {
            buf.clear();
            buf.extend_from_slice(&[(0, 16384)]);
        };
        let mut scratch = Vec::new();
        let result = sel.pick_blocks(&ctx, &chunks, &mut scratch);
        // Should pick a new piece normally
        assert!(result.is_some());
    }
}