ipfrs-network 0.2.0

Peer-to-peer networking layer with libp2p and QUIC for IPFRS
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
//! TCP-inspired multi-algorithm congestion controller for IPFRS peer data streams.
//!
//! Implements SlowStart, CongestionAvoidance, FastRecovery, and Idle phases with
//! five distinct algorithms: Reno, Cubic, BBR, Vegas, and Westwood.
//!
//! # Legacy API
//!
//! The original per-peer `PeerCongestionController` and `MultiPeerCongestionManager`
//! are retained for backwards compatibility.
//!
//! # New API
//!
//! Use [`CongestionController`] for full multi-algorithm support.

use std::collections::{HashMap, VecDeque};

// ─── type aliases ────────────────────────────────────────────────────────────

/// Connection identifier type alias.
pub type CccConnId = u64;
/// Main congestion controller type alias.
pub type CccCongestionController = CongestionController;
/// Decision returned from ack/loss/timeout handlers.
pub type CccDecision = Decision;

// ─── inline PRNG for deterministic jitter ────────────────────────────────────

#[inline]
fn xorshift64(state: &mut u64) -> u64 {
    let mut x = *state;
    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;
    *state = x;
    x
}

// ─── Algorithm ───────────────────────────────────────────────────────────────

/// Congestion control algorithm selection.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum CccAlgorithm {
    /// TCP Reno: AIMD additive-increase/multiplicative-decrease.
    #[default]
    Reno,
    /// TCP CUBIC: cubic growth function for high-BDP networks.
    Cubic,
    /// BBR: Bottleneck Bandwidth and RTT model-based control.
    Bbr,
    /// TCP Vegas: RTT-based proactive congestion avoidance.
    Vegas,
    /// Westwood+: bandwidth estimation on loss for fast recovery.
    Westwood,
}

// ─── State ───────────────────────────────────────────────────────────────────

/// Congestion controller FSM state.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum CccState {
    /// Exponential window growth until ssthresh is reached.
    SlowStart,
    /// Linear (or algorithm-defined) window growth.
    #[default]
    CongestionAvoidance,
    /// Recovering from packet loss via limited retransmit.
    FastRecovery,
    /// Connection is quiescent (no in-flight data).
    Idle,
}

// ─── EventType ───────────────────────────────────────────────────────────────

/// Kinds of congestion events logged in the event ring.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CccEventType {
    /// An ACK arrived.
    AckReceived,
    /// A packet was declared lost.
    PacketLost,
    /// Retransmission timeout triggered.
    Timeout,
    /// Fast retransmit triggered (3 DUP-ACKs).
    FastRetransmit,
    /// Controller entered slow-start.
    SlowStartEnter,
    /// Controller entered congestion avoidance.
    CaEnter,
}

// ─── Event ───────────────────────────────────────────────────────────────────

/// A single congestion event record.
#[derive(Clone, Debug)]
pub struct CccEvent {
    /// Monotonic timestamp (ms since controller creation, from connection `last_ts`).
    pub ts: u64,
    /// Connection this event belongs to.
    pub conn_id: CccConnId,
    /// What happened.
    pub event_type: CccEventType,
    /// Congestion window before the event.
    pub cwnd_before: u64,
    /// Congestion window after the event.
    pub cwnd_after: u64,
}

// ─── Decision ────────────────────────────────────────────────────────────────

/// Result returned by `on_ack`, `on_loss`, and `on_timeout`.
#[derive(Clone, Debug, PartialEq)]
pub struct Decision {
    /// New congestion window (bytes).
    pub new_cwnd: u64,
    /// New slow-start threshold (bytes).
    pub new_ssthresh: u64,
    /// New FSM state.
    pub new_state: CccState,
    /// Recommended sending rate (bytes/sec), if RTT is known.
    pub sending_rate: Option<f64>,
}

// ─── Connection ──────────────────────────────────────────────────────────────

/// Per-connection congestion state.
#[derive(Clone, Debug)]
pub struct CccConnection {
    /// Unique connection identifier.
    pub id: CccConnId,
    /// Current congestion window (bytes).
    pub cwnd: u64,
    /// Slow-start threshold (bytes).
    pub ssthresh: u64,
    /// Current FSM state.
    pub state: CccState,
    /// Smoothed RTT (ms), exponential weighted moving average.
    pub rtt_ms: f64,
    /// RTT variance (ms).
    pub rtt_var: f64,
    /// Bytes currently in flight.
    pub in_flight: u64,
    /// Total bytes acknowledged.
    pub bytes_acked: u64,
    /// Total bytes lost.
    pub bytes_lost: u64,
    /// Timestamp of the last event (monotonic ms counter, internal).
    pub last_ts: u64,
    // ── Cubic-specific ──────────────────────────────────────────────────────
    /// Time (in RTTs) since last congestion event (for Cubic).
    cubic_k: f64,
    /// Window size at last congestion event (for Cubic).
    cubic_w_max: f64,
    // ── BBR-specific ─────────────────────────────────────────────────────────
    /// Estimated bottleneck bandwidth (bytes/sec).
    bbr_bw: f64,
    /// Minimum observed RTT for BBR (ms).
    bbr_min_rtt: f64,
    // ── Vegas-specific ────────────────────────────────────────────────────────
    /// Minimum observed RTT for Vegas (ms).
    vegas_base_rtt: f64,
    // ── Westwood-specific ────────────────────────────────────────────────────
    /// Bandwidth estimate (bytes/sec) for Westwood.
    westwood_bw: f64,
    /// Internal PRNG state for jitter.
    prng_state: u64,
}

impl CccConnection {
    fn new(id: CccConnId, config: &CccControllerConfig) -> Self {
        Self {
            id,
            cwnd: config.initial_cwnd,
            ssthresh: config.ssthresh,
            state: CccState::SlowStart,
            rtt_ms: 0.0,
            rtt_var: 0.0,
            in_flight: 0,
            bytes_acked: 0,
            bytes_lost: 0,
            last_ts: 0,
            cubic_k: 0.0,
            cubic_w_max: config.initial_cwnd as f64,
            bbr_bw: 0.0,
            bbr_min_rtt: f64::MAX,
            vegas_base_rtt: 0.0,
            westwood_bw: 0.0,
            prng_state: id.wrapping_add(1).max(1),
        }
    }

    /// Update the EWMA-smoothed RTT.
    fn update_rtt(&mut self, new_rtt_ms: f64, alpha: f64) {
        if self.rtt_ms == 0.0 {
            self.rtt_ms = new_rtt_ms;
            self.rtt_var = new_rtt_ms / 2.0;
        } else {
            let diff = (new_rtt_ms - self.rtt_ms).abs();
            self.rtt_var = (1.0 - 0.25) * self.rtt_var + 0.25 * diff;
            self.rtt_ms = (1.0 - alpha) * self.rtt_ms + alpha * new_rtt_ms;
        }
        if new_rtt_ms < self.bbr_min_rtt {
            self.bbr_min_rtt = new_rtt_ms;
        }
        if self.vegas_base_rtt == 0.0 || new_rtt_ms < self.vegas_base_rtt {
            self.vegas_base_rtt = new_rtt_ms;
        }
    }

    /// Sending rate in bytes/sec given current cwnd and RTT.
    fn rate(&self) -> Option<f64> {
        if self.rtt_ms > 0.0 {
            Some(self.cwnd as f64 / (self.rtt_ms / 1000.0))
        } else {
            None
        }
    }

    /// Apply a small random jitter (±1 %) to the congestion window.
    ///
    /// Used by algorithms that need to break synchronisation among multiple
    /// flows.  The magnitude is bounded so cwnd never leaves `[min, max]`.
    pub fn apply_cwnd_jitter(&mut self, min_cwnd: u64, max_cwnd: u64) {
        let r = xorshift64(&mut self.prng_state);
        // Map to ±1 % of cwnd.
        let pct = (r % 201) as i64 - 100; // -100 … +100
        let delta = (self.cwnd as i64 * pct / 10_000).unsigned_abs();
        if pct >= 0 {
            self.cwnd = self.cwnd.saturating_add(delta).min(max_cwnd);
        } else {
            self.cwnd = self.cwnd.saturating_sub(delta).max(min_cwnd);
        }
    }
}

// ─── Config ──────────────────────────────────────────────────────────────────

/// Configuration for the multi-connection [`CongestionController`].
#[derive(Clone, Debug)]
pub struct CccControllerConfig {
    /// Congestion control algorithm to apply.
    pub algorithm: CccAlgorithm,
    /// Initial congestion window (bytes). Default: 64 KB.
    pub initial_cwnd: u64,
    /// Minimum congestion window (bytes). Default: 1 MTU = 1 448 B.
    pub min_cwnd: u64,
    /// Maximum congestion window (bytes). Default: 16 MB.
    pub max_cwnd: u64,
    /// Initial slow-start threshold (bytes). Default: 1 MB.
    pub ssthresh: u64,
    /// EWMA smoothing factor for RTT. Typical: 0.125.
    pub rtt_alpha: f64,
}

impl Default for CccControllerConfig {
    fn default() -> Self {
        Self {
            algorithm: CccAlgorithm::Reno,
            initial_cwnd: 65_536,
            min_cwnd: 1_448,
            max_cwnd: 16_777_216,
            ssthresh: 1_048_576,
            rtt_alpha: 0.125,
        }
    }
}

// ─── Stats ───────────────────────────────────────────────────────────────────

/// Aggregate statistics for the entire controller.
#[derive(Clone, Debug, Default)]
pub struct CccControllerStats {
    /// Total ACK events processed across all connections.
    pub total_acks: u64,
    /// Total loss events processed across all connections.
    pub total_losses: u64,
    /// Average congestion window across active connections (bytes).
    pub avg_cwnd: f64,
    /// Average smoothed RTT across active connections (ms).
    pub avg_rtt: f64,
    /// Number of active connections.
    pub active_connections: usize,
}

// ─── CongestionController ────────────────────────────────────────────────────

/// Multi-connection, multi-algorithm TCP-inspired congestion controller.
///
/// Manages per-connection congestion state and emits [`Decision`] structs
/// that callers use to pace their sends.
pub struct CongestionController {
    /// Per-connection state.
    connections: HashMap<CccConnId, CccConnection>,
    /// Bounded ring buffer of recent events (max 1 000).
    events: VecDeque<CccEvent>,
    /// Controller-wide configuration.
    config: CccControllerConfig,
    /// Aggregate ACK counter.
    total_acks: u64,
    /// Aggregate loss counter.
    total_losses: u64,
    /// Monotonic internal tick (incremented on every mutating call).
    tick: u64,
}

impl CongestionController {
    /// Create a new controller with the given configuration.
    pub fn new(config: CccControllerConfig) -> Self {
        Self {
            connections: HashMap::new(),
            events: VecDeque::with_capacity(1_000),
            config,
            total_acks: 0,
            total_losses: 0,
            tick: 0,
        }
    }

    /// Create a new controller with default configuration.
    pub fn with_defaults() -> Self {
        Self::new(CccControllerConfig::default())
    }

    // ── Connection management ────────────────────────────────────────────────

    /// Register a new connection.  If the connection already exists this is a no-op.
    pub fn add_connection(&mut self, id: CccConnId) {
        self.connections
            .entry(id)
            .or_insert_with(|| CccConnection::new(id, &self.config));
    }

    /// Remove a tracked connection.  Returns `true` if it existed.
    pub fn remove_connection(&mut self, id: CccConnId) -> bool {
        self.connections.remove(&id).is_some()
    }

    /// Reset a connection to its initial state (keeps the entry).
    ///
    /// Returns an error if the connection does not exist.
    pub fn reset_connection(&mut self, id: CccConnId) -> Result<(), &'static str> {
        let config = &self.config;
        let conn = self
            .connections
            .get_mut(&id)
            .ok_or("connection not found")?;
        *conn = CccConnection::new(id, config);
        Ok(())
    }

    // ── Core operations ──────────────────────────────────────────────────────

    /// Process an ACK for `bytes_acked` bytes on `conn_id` with the measured RTT.
    ///
    /// Returns the new [`Decision`], or an error if `conn_id` is unknown.
    pub fn on_ack(
        &mut self,
        conn_id: CccConnId,
        bytes_acked: u64,
        rtt_ms: f64,
    ) -> Result<CccDecision, &'static str> {
        self.tick = self.tick.wrapping_add(1);
        let ts = self.tick;

        let conn = self
            .connections
            .get_mut(&conn_id)
            .ok_or("connection not found")?;

        let cwnd_before = conn.cwnd;
        conn.update_rtt(rtt_ms, self.config.rtt_alpha);
        conn.bytes_acked = conn.bytes_acked.saturating_add(bytes_acked);
        conn.last_ts = ts;

        // Update bandwidth estimate (Westwood / BBR).
        if rtt_ms > 0.0 {
            let sample_bw = bytes_acked as f64 / (rtt_ms / 1_000.0);
            if conn.westwood_bw == 0.0 {
                conn.westwood_bw = sample_bw;
            } else {
                conn.westwood_bw = 0.875 * conn.westwood_bw + 0.125 * sample_bw;
            }
            if conn.bbr_bw == 0.0 {
                conn.bbr_bw = sample_bw;
            } else {
                conn.bbr_bw = conn.bbr_bw.max(sample_bw);
            }
        }

        let min_cwnd = self.config.min_cwnd;
        let max_cwnd = self.config.max_cwnd;

        let new_cwnd = match self.config.algorithm {
            CccAlgorithm::Reno => reno_on_ack(conn, bytes_acked, min_cwnd, max_cwnd),
            CccAlgorithm::Cubic => cubic_on_ack(conn, bytes_acked, rtt_ms, min_cwnd, max_cwnd),
            CccAlgorithm::Bbr => bbr_on_ack(conn, min_cwnd, max_cwnd),
            CccAlgorithm::Vegas => vegas_on_ack(conn, min_cwnd, max_cwnd),
            CccAlgorithm::Westwood => westwood_on_ack(conn, bytes_acked, min_cwnd, max_cwnd),
        };

        conn.cwnd = new_cwnd.clamp(min_cwnd, max_cwnd);
        self.total_acks += 1;

        // Extract values before releasing the borrow.
        let cwnd_after = conn.cwnd;
        let new_ssthresh = conn.ssthresh;
        let new_state = conn.state;
        let sending_rate = conn.rate();

        self.push_event(CccEvent {
            ts,
            conn_id,
            event_type: CccEventType::AckReceived,
            cwnd_before,
            cwnd_after,
        });

        Ok(Decision {
            new_cwnd: cwnd_after,
            new_ssthresh,
            new_state,
            sending_rate,
        })
    }

    /// Process a packet loss event on `conn_id`.
    ///
    /// Applies multiplicative decrease and enters fast recovery.
    pub fn on_loss(
        &mut self,
        conn_id: CccConnId,
        lost_bytes: u64,
    ) -> Result<CccDecision, &'static str> {
        self.tick = self.tick.wrapping_add(1);
        let ts = self.tick;

        let conn = self
            .connections
            .get_mut(&conn_id)
            .ok_or("connection not found")?;

        let cwnd_before = conn.cwnd;
        conn.bytes_lost = conn.bytes_lost.saturating_add(lost_bytes);
        conn.last_ts = ts;

        let min_cwnd = self.config.min_cwnd;
        let max_cwnd = self.config.max_cwnd;

        let new_cwnd = match self.config.algorithm {
            CccAlgorithm::Reno => reno_on_loss(conn, min_cwnd),
            CccAlgorithm::Cubic => cubic_on_loss(conn, min_cwnd),
            CccAlgorithm::Bbr => bbr_on_loss(conn, min_cwnd),
            CccAlgorithm::Vegas => vegas_on_loss(conn, min_cwnd),
            CccAlgorithm::Westwood => westwood_on_loss(conn, min_cwnd),
        };

        conn.cwnd = new_cwnd.clamp(min_cwnd, max_cwnd);
        conn.state = CccState::FastRecovery;
        self.total_losses += 1;

        // Extract values before releasing the borrow.
        let cwnd_after = conn.cwnd;
        let new_ssthresh = conn.ssthresh;
        let sending_rate = conn.rate();

        self.push_event(CccEvent {
            ts,
            conn_id,
            event_type: CccEventType::PacketLost,
            cwnd_before,
            cwnd_after,
        });

        Ok(Decision {
            new_cwnd: cwnd_after,
            new_ssthresh,
            new_state: CccState::FastRecovery,
            sending_rate,
        })
    }

    /// Process a retransmission timeout on `conn_id`.
    ///
    /// Resets cwnd to min_cwnd, halves ssthresh, re-enters slow start.
    pub fn on_timeout(&mut self, conn_id: CccConnId) -> Result<CccDecision, &'static str> {
        self.tick = self.tick.wrapping_add(1);
        let ts = self.tick;

        let conn = self
            .connections
            .get_mut(&conn_id)
            .ok_or("connection not found")?;

        let cwnd_before = conn.cwnd;
        conn.last_ts = ts;

        let min_cwnd = self.config.min_cwnd;

        conn.ssthresh = (conn.cwnd / 2).max(min_cwnd);
        conn.cwnd = min_cwnd;
        conn.state = CccState::SlowStart;
        // Reset Cubic state on timeout.
        conn.cubic_k = 0.0;
        conn.cubic_w_max = min_cwnd as f64;
        self.total_losses += 1;

        // Extract values before releasing the borrow.
        let cwnd_after = conn.cwnd;
        let new_ssthresh = conn.ssthresh;
        let sending_rate = conn.rate();

        self.push_event(CccEvent {
            ts,
            conn_id,
            event_type: CccEventType::Timeout,
            cwnd_before,
            cwnd_after,
        });
        self.push_event(CccEvent {
            ts,
            conn_id,
            event_type: CccEventType::SlowStartEnter,
            cwnd_before: cwnd_after,
            cwnd_after,
        });

        Ok(Decision {
            new_cwnd: cwnd_after,
            new_ssthresh,
            new_state: CccState::SlowStart,
            sending_rate,
        })
    }

    // ── Queries ──────────────────────────────────────────────────────────────

    /// Current sending rate for a connection, in bytes/sec.
    ///
    /// Returns `None` if the connection is unknown or RTT has not been measured.
    pub fn sending_rate(&self, conn_id: CccConnId) -> Option<f64> {
        self.connections.get(&conn_id).and_then(|c| c.rate())
    }

    /// Aggregate statistics across all active connections.
    pub fn controller_stats(&self) -> CccControllerStats {
        let n = self.connections.len();
        if n == 0 {
            return CccControllerStats {
                total_acks: self.total_acks,
                total_losses: self.total_losses,
                avg_cwnd: 0.0,
                avg_rtt: 0.0,
                active_connections: 0,
            };
        }
        let sum_cwnd: u64 = self.connections.values().map(|c| c.cwnd).sum();
        let sum_rtt: f64 = self.connections.values().map(|c| c.rtt_ms).sum();
        CccControllerStats {
            total_acks: self.total_acks,
            total_losses: self.total_losses,
            avg_cwnd: sum_cwnd as f64 / n as f64,
            avg_rtt: sum_rtt / n as f64,
            active_connections: n,
        }
    }

    /// Immutable reference to a connection, if it exists.
    pub fn connection(&self, conn_id: CccConnId) -> Option<&CccConnection> {
        self.connections.get(&conn_id)
    }

    /// Read-only view of the event log.
    pub fn events(&self) -> &VecDeque<CccEvent> {
        &self.events
    }

    // ── Internal ─────────────────────────────────────────────────────────────

    fn push_event(&mut self, event: CccEvent) {
        if self.events.len() >= 1_000 {
            self.events.pop_front();
        }
        self.events.push_back(event);
    }
}

// ─── Reno ────────────────────────────────────────────────────────────────────

/// Reno on-ACK: AIMD with slow-start below ssthresh.
fn reno_on_ack(conn: &mut CccConnection, bytes_acked: u64, min_cwnd: u64, max_cwnd: u64) -> u64 {
    match conn.state {
        CccState::SlowStart | CccState::Idle => {
            let new_cwnd = conn.cwnd.saturating_add(bytes_acked).min(max_cwnd);
            if new_cwnd >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance;
            }
            new_cwnd
        }
        CccState::CongestionAvoidance => {
            // Additive increase: +MSS per RTT ≈ MSS² / cwnd per ACK.
            let mss: u64 = 1_448;
            let increase = if conn.cwnd > 0 {
                (mss.saturating_mul(mss)).saturating_div(conn.cwnd).max(1)
            } else {
                mss
            };
            conn.cwnd.saturating_add(increase).min(max_cwnd)
        }
        CccState::FastRecovery => {
            // Deflate window: exit recovery once cwnd climbs back to ssthresh.
            let new_cwnd = conn.cwnd.saturating_add(bytes_acked / 2).min(max_cwnd);
            if new_cwnd >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance;
            }
            new_cwnd
        }
    }
    .max(min_cwnd)
}

/// Reno on-loss: multiplicative decrease, halve cwnd.
fn reno_on_loss(conn: &mut CccConnection, min_cwnd: u64) -> u64 {
    conn.ssthresh = (conn.cwnd / 2).max(min_cwnd);
    conn.ssthresh
}

// ─── Cubic ───────────────────────────────────────────────────────────────────

/// Cubic growth constant C (standard value 0.4).
const CUBIC_C: f64 = 0.4;
/// Cubic beta (standard 0.7 for CUBIC).
const CUBIC_BETA: f64 = 0.7;

/// Cubic on-ACK: cubic growth function around W_max.
fn cubic_on_ack(
    conn: &mut CccConnection,
    bytes_acked: u64,
    rtt_ms: f64,
    min_cwnd: u64,
    max_cwnd: u64,
) -> u64 {
    match conn.state {
        CccState::SlowStart | CccState::Idle => {
            let new_cwnd = conn.cwnd.saturating_add(bytes_acked).min(max_cwnd);
            if new_cwnd >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance;
                // Compute K: cubic root of (W_max * (1-beta) / C).
                let w_max = conn.cubic_w_max;
                conn.cubic_k = ((w_max * (1.0 - CUBIC_BETA)) / CUBIC_C).cbrt();
            }
            new_cwnd.max(min_cwnd)
        }
        CccState::CongestionAvoidance => {
            let rtt_s = (rtt_ms / 1_000.0).max(0.001);
            // t = elapsed RTTs since last congestion (approximated by one RTT per call).
            let t = rtt_s;
            let k = conn.cubic_k;
            let w_max = conn.cubic_w_max;
            // W_cubic(t) = C*(t-K)^3 + W_max
            let delta = t - k;
            let w_cubic = CUBIC_C * delta * delta * delta + w_max;
            let target = w_cubic.max(conn.cwnd as f64);
            let new_cwnd = (target as u64).clamp(min_cwnd, max_cwnd);
            if new_cwnd >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance; // stays
            }
            new_cwnd
        }
        CccState::FastRecovery => {
            let new_cwnd = conn.cwnd.saturating_add(bytes_acked / 2).min(max_cwnd);
            if new_cwnd >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance;
            }
            new_cwnd.max(min_cwnd)
        }
    }
}

/// Cubic on-loss: W_max = current cwnd, new cwnd = cwnd * beta.
fn cubic_on_loss(conn: &mut CccConnection, min_cwnd: u64) -> u64 {
    conn.cubic_w_max = conn.cwnd as f64;
    let new_cwnd = ((conn.cwnd as f64 * CUBIC_BETA) as u64).max(min_cwnd);
    conn.ssthresh = new_cwnd;
    // Reset cubic K after loss so next CA phase recomputes it.
    conn.cubic_k = 0.0;
    new_cwnd
}

// ─── BBR ─────────────────────────────────────────────────────────────────────

/// BBR on-ACK: pacing window = BDP = bw × min_rtt.
fn bbr_on_ack(conn: &mut CccConnection, min_cwnd: u64, max_cwnd: u64) -> u64 {
    if conn.bbr_bw > 0.0 && conn.bbr_min_rtt < f64::MAX && conn.bbr_min_rtt > 0.0 {
        let bdp = conn.bbr_bw * (conn.bbr_min_rtt / 1_000.0);
        // Add 1.25× gain for probing.
        let target = (bdp * 1.25) as u64;
        // BBR never reduces cwnd on an ACK: the BDP estimate can only raise it.
        let new_cwnd = target.max(conn.cwnd).clamp(min_cwnd, max_cwnd);
        if conn.state == CccState::SlowStart && new_cwnd >= conn.ssthresh {
            conn.state = CccState::CongestionAvoidance;
        }
        new_cwnd
    } else {
        // Fallback to Reno slow-start until we have measurements.
        let new_cwnd = conn.cwnd.saturating_add(1_448).min(max_cwnd);
        if new_cwnd >= conn.ssthresh {
            conn.state = CccState::CongestionAvoidance;
        }
        new_cwnd.max(min_cwnd)
    }
}

/// BBR on-loss: do not reduce cwnd; BBR relies on rate not loss.
/// We do a mild 10% reduction to prevent starvation.
fn bbr_on_loss(conn: &mut CccConnection, min_cwnd: u64) -> u64 {
    conn.ssthresh = (conn.cwnd * 9 / 10).max(min_cwnd);
    conn.ssthresh
}

// ─── Vegas ───────────────────────────────────────────────────────────────────

/// Vegas alpha/beta thresholds (packets).
const VEGAS_ALPHA: f64 = 2.0;
const VEGAS_BETA: f64 = 4.0;

/// Vegas on-ACK: compare actual throughput to expected throughput.
fn vegas_on_ack(conn: &mut CccConnection, min_cwnd: u64, max_cwnd: u64) -> u64 {
    if conn.vegas_base_rtt == 0.0 || conn.rtt_ms == 0.0 {
        // No RTT sample yet — behave like Reno slow-start.
        let new_cwnd = conn.cwnd.saturating_add(1_448).min(max_cwnd);
        if new_cwnd >= conn.ssthresh {
            conn.state = CccState::CongestionAvoidance;
        }
        return new_cwnd.max(min_cwnd);
    }

    let expected = conn.cwnd as f64 / conn.vegas_base_rtt;
    let actual = conn.cwnd as f64 / conn.rtt_ms;
    let diff = expected - actual;
    let mss: f64 = 1_448.0;

    let new_cwnd: u64 = match conn.state {
        CccState::SlowStart | CccState::Idle => {
            let grown = conn.cwnd.saturating_add(1_448).min(max_cwnd);
            if grown >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance;
            }
            grown
        }
        CccState::CongestionAvoidance => {
            if diff < VEGAS_ALPHA {
                // Too little queuing — increase.
                (conn.cwnd as f64 + mss * mss / conn.cwnd as f64) as u64
            } else if diff > VEGAS_BETA {
                // Too much queuing — decrease.
                conn.cwnd
                    .saturating_sub((mss * mss / conn.cwnd as f64) as u64)
            } else {
                conn.cwnd
            }
        }
        CccState::FastRecovery => {
            let grown = conn.cwnd.saturating_add(1_448 / 2).min(max_cwnd);
            if grown >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance;
            }
            grown
        }
    };
    new_cwnd.clamp(min_cwnd, max_cwnd)
}

/// Vegas on-loss: same as Reno multiplicative decrease.
fn vegas_on_loss(conn: &mut CccConnection, min_cwnd: u64) -> u64 {
    conn.ssthresh = (conn.cwnd / 2).max(min_cwnd);
    conn.ssthresh
}

// ─── Westwood ────────────────────────────────────────────────────────────────

/// Westwood on-ACK: AIMD but uses bandwidth estimate.
fn westwood_on_ack(
    conn: &mut CccConnection,
    bytes_acked: u64,
    min_cwnd: u64,
    max_cwnd: u64,
) -> u64 {
    match conn.state {
        CccState::SlowStart | CccState::Idle => {
            let new_cwnd = conn.cwnd.saturating_add(bytes_acked).min(max_cwnd);
            if new_cwnd >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance;
            }
            new_cwnd.max(min_cwnd)
        }
        CccState::CongestionAvoidance => {
            let mss: u64 = 1_448;
            let increase = if conn.cwnd > 0 {
                (mss.saturating_mul(mss)).saturating_div(conn.cwnd).max(1)
            } else {
                mss
            };
            conn.cwnd
                .saturating_add(increase)
                .min(max_cwnd)
                .max(min_cwnd)
        }
        CccState::FastRecovery => {
            let new_cwnd = conn.cwnd.saturating_add(bytes_acked / 2).min(max_cwnd);
            if new_cwnd >= conn.ssthresh {
                conn.state = CccState::CongestionAvoidance;
            }
            new_cwnd.max(min_cwnd)
        }
    }
}

/// Westwood on-loss: set ssthresh = BDP estimate.
fn westwood_on_loss(conn: &mut CccConnection, min_cwnd: u64) -> u64 {
    if conn.westwood_bw > 0.0 && conn.rtt_ms > 0.0 {
        let bdp = (conn.westwood_bw * conn.rtt_ms / 1_000.0) as u64;
        conn.ssthresh = bdp.max(min_cwnd);
    } else {
        conn.ssthresh = (conn.cwnd / 2).max(min_cwnd);
    }
    conn.ssthresh
}

// ═══════════════════════════════════════════════════════════════════════════════
// LEGACY API (retained for backwards compatibility)
// ═══════════════════════════════════════════════════════════════════════════════

/// Phases of the congestion control state machine (legacy).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CongestionState {
    /// Exponential growth phase: window doubles per RTT.
    SlowStart,
    /// Linear growth phase: additive increase.
    CongestionAvoidance,
    /// Recovering from a detected packet loss event.
    FastRecovery,
}

/// Events that drive congestion controller state transitions (legacy).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CongestionEvent {
    /// A successful acknowledgment was received for `bytes` of data.
    AckReceived {
        /// Number of bytes acknowledged.
        bytes: u64,
    },
    /// Packet loss was detected (triggers window reduction).
    PacketLoss,
    /// Retransmit timeout — severe reduction, resets to SlowStart.
    Timeout,
    /// Explicit Congestion Notification mark received.
    EcnMark,
}

/// A snapshot of the current congestion window state for a peer (legacy).
#[derive(Clone, Debug)]
pub struct WindowStats {
    /// Current congestion window size in bytes.
    pub current_window: u64,
    /// Slow-start threshold in bytes.
    pub slow_start_threshold: u64,
    /// Current congestion control phase.
    pub state: CongestionState,
    /// Cumulative number of ACK events processed.
    pub total_acks: u64,
    /// Cumulative number of loss/ECN events processed.
    pub total_losses: u64,
}

impl WindowStats {
    /// Returns the fraction of the total capacity represented by the current window.
    ///
    /// Returns `0.0` when both `current_window` and `slow_start_threshold` are zero.
    pub fn utilization(&self) -> f64 {
        let denom = self.current_window + self.slow_start_threshold;
        if denom == 0 {
            return 0.0;
        }
        self.current_window as f64 / denom as f64
    }
}

/// Configuration parameters for a congestion controller (legacy).
#[derive(Clone, Debug)]
pub struct CongestionConfig {
    /// Initial congestion window size (bytes). Default: 64 KB.
    pub initial_window: u64,
    /// Maximum congestion window size (bytes). Default: 16 MB.
    pub max_window: u64,
    /// Minimum congestion window size (bytes). Default: 1 MTU (1 448 B).
    pub min_window: u64,
    /// Initial slow-start threshold (bytes). Default: 1 MB.
    pub slow_start_threshold: u64,
}

impl Default for CongestionConfig {
    fn default() -> Self {
        Self {
            initial_window: 65_536,
            max_window: 16_777_216,
            min_window: 1_448,
            slow_start_threshold: 1_048_576,
        }
    }
}

/// Per-peer CUBIC-inspired congestion controller (legacy).
pub struct PeerCongestionController {
    /// Identifier of the remote peer.
    pub peer_id: String,
    /// Current congestion window (bytes).
    pub window: u64,
    /// Slow-start threshold (bytes).
    pub ssthresh: u64,
    /// Current state of the congestion control state machine.
    pub state: CongestionState,
    /// Configuration parameters.
    pub config: CongestionConfig,
    /// Total number of ACK events received.
    pub total_acks: u64,
    /// Total number of loss/ECN events received.
    pub total_losses: u64,
}

impl PeerCongestionController {
    /// Create a new controller for `peer_id`, starting in [`CongestionState::SlowStart`].
    pub fn new(peer_id: String, config: CongestionConfig) -> Self {
        let window = config.initial_window;
        let ssthresh = config.slow_start_threshold;
        Self {
            peer_id,
            window,
            ssthresh,
            state: CongestionState::SlowStart,
            config,
            total_acks: 0,
            total_losses: 0,
        }
    }

    /// Process a network event and update window / state accordingly.
    pub fn on_event(&mut self, event: CongestionEvent) {
        match event {
            CongestionEvent::AckReceived { bytes } => self.handle_ack(bytes),
            CongestionEvent::PacketLoss => self.handle_packet_loss(),
            CongestionEvent::Timeout => self.handle_timeout(),
            CongestionEvent::EcnMark => self.handle_ecn(),
        }
    }

    fn handle_ack(&mut self, bytes: u64) {
        match self.state {
            CongestionState::SlowStart => {
                self.window = self
                    .window
                    .saturating_add(bytes)
                    .min(self.config.max_window);
                if self.window >= self.ssthresh {
                    self.state = CongestionState::CongestionAvoidance;
                }
                self.total_acks += 1;
            }
            CongestionState::CongestionAvoidance => {
                let increase = if self.window > 0 {
                    (bytes.saturating_mul(bytes)).saturating_div(self.window)
                } else {
                    bytes
                };
                self.window = self
                    .window
                    .saturating_add(increase)
                    .min(self.config.max_window);
                self.total_acks += 1;
            }
            CongestionState::FastRecovery => {
                self.window = self
                    .window
                    .saturating_add(bytes / 2)
                    .min(self.config.max_window);
                if self.window >= self.ssthresh {
                    self.state = CongestionState::CongestionAvoidance;
                }
                self.total_acks += 1;
            }
        }
    }

    fn handle_packet_loss(&mut self) {
        self.ssthresh = (self.window / 2).max(self.config.min_window);
        self.window = self.ssthresh;
        self.state = CongestionState::FastRecovery;
        self.total_losses += 1;
    }

    fn handle_timeout(&mut self) {
        self.ssthresh = (self.window / 2).max(self.config.min_window);
        self.window = self.config.initial_window.max(self.config.min_window);
        self.state = CongestionState::SlowStart;
        self.total_losses += 1;
    }

    fn handle_ecn(&mut self) {
        self.ssthresh = ((self.window * 7) / 8).max(self.config.min_window);
        self.window = self.ssthresh;
        self.state = CongestionState::CongestionAvoidance;
        self.total_losses += 1;
    }

    /// Return a snapshot of the current window statistics.
    pub fn window_stats(&self) -> WindowStats {
        WindowStats {
            current_window: self.window,
            slow_start_threshold: self.ssthresh,
            state: self.state,
            total_acks: self.total_acks,
            total_losses: self.total_losses,
        }
    }

    /// Returns `true` if the caller may send `bytes` given the current window.
    pub fn can_send(&self, bytes: u64) -> bool {
        bytes <= self.window
    }
}

/// Manages [`PeerCongestionController`] instances for multiple peers (legacy).
pub struct MultiPeerCongestionManager {
    /// Per-peer controllers, keyed by peer ID string.
    pub controllers: HashMap<String, PeerCongestionController>,
    /// Default configuration applied to newly created controllers.
    pub config: CongestionConfig,
}

impl MultiPeerCongestionManager {
    /// Create a new manager with the given default configuration.
    pub fn new(config: CongestionConfig) -> Self {
        Self {
            controllers: HashMap::new(),
            config,
        }
    }

    /// Return a mutable reference to the controller for `peer_id`.
    pub fn get_or_create(&mut self, peer_id: &str) -> &mut PeerCongestionController {
        self.controllers
            .entry(peer_id.to_owned())
            .or_insert_with(|| {
                PeerCongestionController::new(peer_id.to_owned(), self.config.clone())
            })
    }

    /// Deliver a congestion event to the controller for `peer_id`.
    pub fn on_event(&mut self, peer_id: &str, event: CongestionEvent) {
        let ctrl = self.get_or_create(peer_id);
        ctrl.on_event(event);
    }

    /// Remove the controller for `peer_id`.
    pub fn remove_peer(&mut self, peer_id: &str) -> bool {
        self.controllers.remove(peer_id).is_some()
    }

    /// Return the sum of all managed peer windows.
    pub fn total_window(&self) -> u64 {
        self.controllers.values().map(|c| c.window).sum()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    // ── helpers ──────────────────────────────────────────────────────────────

    fn default_config() -> CongestionConfig {
        CongestionConfig::default()
    }

    fn legacy_ctrl(peer: &str) -> PeerCongestionController {
        PeerCongestionController::new(peer.to_owned(), default_config())
    }

    fn make_ctrl(algo: CccAlgorithm) -> CongestionController {
        CongestionController::new(CccControllerConfig {
            algorithm: algo,
            ..CccControllerConfig::default()
        })
    }

    // ══ LEGACY TESTS (1–24) ══════════════════════════════════════════════════

    #[test]
    fn test_new_starts_in_slow_start() {
        let ctrl = legacy_ctrl("peer-a");
        assert_eq!(ctrl.state, CongestionState::SlowStart);
        assert_eq!(ctrl.window, 65_536);
        assert_eq!(ctrl.ssthresh, 1_048_576);
    }

    #[test]
    fn test_slow_start_ack_grows_window() {
        let mut ctrl = legacy_ctrl("p");
        let before = ctrl.window;
        ctrl.on_event(CongestionEvent::AckReceived { bytes: 1_000 });
        assert_eq!(ctrl.window, before + 1_000);
    }

    #[test]
    fn test_slow_start_caps_at_max() {
        let cfg = CongestionConfig {
            initial_window: 16_777_000,
            ..Default::default()
        };
        let mut ctrl = PeerCongestionController::new("p".into(), cfg.clone());
        ctrl.on_event(CongestionEvent::AckReceived { bytes: 1_000_000 });
        assert_eq!(ctrl.window, cfg.max_window);
    }

    #[test]
    fn test_slow_start_transitions_at_ssthresh() {
        let cfg = CongestionConfig {
            initial_window: 500_000,
            slow_start_threshold: 600_000,
            ..Default::default()
        };
        let mut ctrl = PeerCongestionController::new("p".into(), cfg);
        ctrl.on_event(CongestionEvent::AckReceived { bytes: 200_000 });
        assert_eq!(ctrl.state, CongestionState::CongestionAvoidance);
    }

    #[test]
    fn test_congestion_avoidance_increase_smaller() {
        let cfg = CongestionConfig {
            initial_window: 100_000,
            slow_start_threshold: 50_000,
            ..Default::default()
        };
        let mut ctrl = PeerCongestionController::new("p".into(), cfg);
        ctrl.state = CongestionState::CongestionAvoidance;
        let bytes: u64 = 1_000;
        let before = ctrl.window;
        ctrl.on_event(CongestionEvent::AckReceived { bytes });
        let ca_increase = ctrl.window - before;
        assert!(ca_increase < bytes);
        assert_eq!(ca_increase, (bytes * bytes) / 100_000);
    }

    #[test]
    fn test_fast_recovery_ack_grows_half() {
        let mut ctrl = legacy_ctrl("p");
        ctrl.state = CongestionState::FastRecovery;
        ctrl.ssthresh = ctrl.window + 100_000;
        let before = ctrl.window;
        ctrl.on_event(CongestionEvent::AckReceived { bytes: 2_000 });
        assert_eq!(ctrl.window, before + 1_000);
    }

    #[test]
    fn test_fast_recovery_transitions_to_ca() {
        let cfg = CongestionConfig {
            initial_window: 50_000,
            slow_start_threshold: 60_000,
            ..Default::default()
        };
        let mut ctrl = PeerCongestionController::new("p".into(), cfg);
        ctrl.state = CongestionState::FastRecovery;
        ctrl.ssthresh = 51_000;
        ctrl.on_event(CongestionEvent::AckReceived { bytes: 10_000 });
        assert_eq!(ctrl.state, CongestionState::CongestionAvoidance);
    }

    #[test]
    fn test_packet_loss_sets_ssthresh_and_state() {
        let mut ctrl = legacy_ctrl("p");
        let orig_window = ctrl.window;
        ctrl.on_event(CongestionEvent::PacketLoss);
        assert_eq!(ctrl.ssthresh, orig_window / 2);
        assert_eq!(ctrl.window, orig_window / 2);
        assert_eq!(ctrl.state, CongestionState::FastRecovery);
    }

    #[test]
    fn test_packet_loss_floors_at_min() {
        let cfg = CongestionConfig {
            initial_window: 2_000,
            min_window: 1_448,
            ..Default::default()
        };
        let mut ctrl = PeerCongestionController::new("p".into(), cfg.clone());
        ctrl.on_event(CongestionEvent::PacketLoss);
        assert_eq!(ctrl.window, cfg.min_window);
        assert_eq!(ctrl.ssthresh, cfg.min_window);
    }

    #[test]
    fn test_timeout_resets_window_and_state() {
        let mut ctrl = legacy_ctrl("p");
        ctrl.window = 500_000;
        ctrl.on_event(CongestionEvent::Timeout);
        assert_eq!(ctrl.window, 65_536);
        assert_eq!(ctrl.state, CongestionState::SlowStart);
    }

    #[test]
    fn test_ecn_mark() {
        let mut ctrl = legacy_ctrl("p");
        ctrl.window = 800_000;
        ctrl.on_event(CongestionEvent::EcnMark);
        assert_eq!(ctrl.ssthresh, (800_000u64 * 7) / 8);
        assert_eq!(ctrl.window, ctrl.ssthresh);
        assert_eq!(ctrl.state, CongestionState::CongestionAvoidance);
    }

    #[test]
    fn test_total_acks_increments() {
        let mut ctrl = legacy_ctrl("p");
        assert_eq!(ctrl.total_acks, 0);
        ctrl.on_event(CongestionEvent::AckReceived { bytes: 100 });
        ctrl.on_event(CongestionEvent::AckReceived { bytes: 100 });
        assert_eq!(ctrl.total_acks, 2);
    }

    #[test]
    fn test_total_losses_increments() {
        let mut ctrl = legacy_ctrl("p");
        assert_eq!(ctrl.total_losses, 0);
        ctrl.on_event(CongestionEvent::PacketLoss);
        ctrl.on_event(CongestionEvent::EcnMark);
        ctrl.on_event(CongestionEvent::Timeout);
        assert_eq!(ctrl.total_losses, 3);
    }

    #[test]
    fn test_can_send_within_window() {
        let ctrl = legacy_ctrl("p");
        assert!(ctrl.can_send(ctrl.window));
        assert!(ctrl.can_send(1));
    }

    #[test]
    fn test_can_send_exceeds_window() {
        let ctrl = legacy_ctrl("p");
        assert!(!ctrl.can_send(ctrl.window + 1));
    }

    #[test]
    fn test_utilization() {
        let ctrl = legacy_ctrl("p");
        let stats = ctrl.window_stats();
        let expected = stats.current_window as f64
            / (stats.current_window + stats.slow_start_threshold) as f64;
        let diff = (stats.utilization() - expected).abs();
        assert!(diff < 1e-12);
    }

    #[test]
    fn test_utilization_zero() {
        let stats = WindowStats {
            current_window: 0,
            slow_start_threshold: 0,
            state: CongestionState::SlowStart,
            total_acks: 0,
            total_losses: 0,
        };
        assert_eq!(stats.utilization(), 0.0);
    }

    #[test]
    fn test_manager_creates_on_first_access() {
        let mut mgr = MultiPeerCongestionManager::new(default_config());
        let ctrl = mgr.get_or_create("peer-1");
        assert_eq!(ctrl.state, CongestionState::SlowStart);
        assert_eq!(ctrl.window, 65_536);
    }

    #[test]
    fn test_manager_routes_event() {
        let mut mgr = MultiPeerCongestionManager::new(default_config());
        mgr.get_or_create("a");
        mgr.get_or_create("b");
        let initial_a = mgr.controllers["a"].window;
        let initial_b = mgr.controllers["b"].window;
        mgr.on_event("a", CongestionEvent::AckReceived { bytes: 5_000 });
        assert_eq!(mgr.controllers["a"].window, initial_a + 5_000);
        assert_eq!(mgr.controllers["b"].window, initial_b);
    }

    #[test]
    fn test_remove_peer() {
        let mut mgr = MultiPeerCongestionManager::new(default_config());
        mgr.get_or_create("x");
        assert!(mgr.remove_peer("x"));
        assert!(!mgr.remove_peer("x"));
    }

    #[test]
    fn test_total_window() {
        let mut mgr = MultiPeerCongestionManager::new(default_config());
        mgr.get_or_create("a");
        mgr.get_or_create("b");
        let expected = mgr.controllers["a"].window + mgr.controllers["b"].window;
        assert_eq!(mgr.total_window(), expected);
    }

    #[test]
    fn test_ssthresh_floor_on_loss() {
        let cfg = CongestionConfig {
            initial_window: 1_500,
            min_window: 1_448,
            ..Default::default()
        };
        let mut ctrl = PeerCongestionController::new("p".into(), cfg.clone());
        ctrl.on_event(CongestionEvent::PacketLoss);
        assert!(ctrl.ssthresh >= cfg.min_window);
        assert!(ctrl.window >= cfg.min_window);
    }

    #[test]
    fn test_state_machine_full_cycle() {
        let mut ctrl = legacy_ctrl("p");
        assert_eq!(ctrl.state, CongestionState::SlowStart);
        for _ in 0..20 {
            ctrl.on_event(CongestionEvent::AckReceived { bytes: 100_000 });
        }
        assert_eq!(ctrl.state, CongestionState::CongestionAvoidance);
        ctrl.on_event(CongestionEvent::PacketLoss);
        assert_eq!(ctrl.state, CongestionState::FastRecovery);
        for _ in 0..30 {
            ctrl.on_event(CongestionEvent::AckReceived { bytes: 100_000 });
        }
        assert_eq!(ctrl.state, CongestionState::CongestionAvoidance);
        ctrl.on_event(CongestionEvent::Timeout);
        assert_eq!(ctrl.state, CongestionState::SlowStart);
    }

    #[test]
    fn test_ca_aimd_formula() {
        let cfg = CongestionConfig {
            initial_window: 200_000,
            slow_start_threshold: 100_000,
            ..Default::default()
        };
        let mut ctrl = PeerCongestionController::new("p".into(), cfg);
        ctrl.state = CongestionState::CongestionAvoidance;
        let window_before = ctrl.window;
        let bytes: u64 = 4_000;
        ctrl.on_event(CongestionEvent::AckReceived { bytes });
        let expected_increase = (bytes * bytes) / window_before;
        assert_eq!(ctrl.window, window_before + expected_increase);
    }

    // ══ NEW API TESTS (25+) ══════════════════════════════════════════════════

    // ── add / remove / reset connection ─────────────────────────────────────

    #[test]
    fn test_add_connection_creates_entry() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        assert!(cc.connection(1).is_some());
    }

    #[test]
    fn test_add_connection_idempotent() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        let cwnd1 = cc.connection(1).map(|c| c.cwnd);
        cc.add_connection(1); // should not reset
        let cwnd2 = cc.connection(1).map(|c| c.cwnd);
        assert_eq!(cwnd1, cwnd2);
    }

    #[test]
    fn test_remove_connection_returns_true() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(10);
        assert!(cc.remove_connection(10));
    }

    #[test]
    fn test_remove_connection_missing_returns_false() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        assert!(!cc.remove_connection(99));
    }

    #[test]
    fn test_reset_connection_restores_defaults() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(5);
        // Drive cwnd up.
        cc.on_ack(5, 500_000, 10.0).expect("ack ok");
        cc.reset_connection(5).expect("reset ok");
        let conn = cc.connection(5).expect("still exists");
        assert_eq!(conn.cwnd, 65_536);
        assert_eq!(conn.state, CccState::SlowStart);
    }

    #[test]
    fn test_reset_connection_unknown_errors() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        assert!(cc.reset_connection(999).is_err());
    }

    // ── on_ack ───────────────────────────────────────────────────────────────

    #[test]
    fn test_on_ack_unknown_errors() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        assert!(cc.on_ack(42, 1_000, 10.0).is_err());
    }

    #[test]
    fn test_reno_slow_start_ack_increases_cwnd() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_ack(1, 1_000, 20.0).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(after > before);
    }

    #[test]
    fn test_reno_transitions_to_ca_after_ssthresh() {
        let mut cc = CongestionController::new(CccControllerConfig {
            algorithm: CccAlgorithm::Reno,
            initial_cwnd: 900_000,
            ssthresh: 1_000_000,
            ..Default::default()
        });
        cc.add_connection(1);
        cc.on_ack(1, 200_000, 10.0).expect("ok");
        let state = cc
            .connection(1)
            .map(|c| c.state)
            .expect("test: connection 1 should exist after add_connection");
        assert_eq!(state, CccState::CongestionAvoidance);
    }

    #[test]
    fn test_reno_ca_smaller_increase_than_ss() {
        let mut cc = CongestionController::new(CccControllerConfig {
            algorithm: CccAlgorithm::Reno,
            initial_cwnd: 200_000,
            ssthresh: 100_000,
            ..Default::default()
        });
        cc.add_connection(1);
        // Force into CA.
        if let Some(c) = cc.connections.get_mut(&1) {
            c.state = CccState::CongestionAvoidance;
        }
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_ack(1, 5_000, 10.0).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        // In CA the increase should be much smaller than 5_000.
        let delta = after - before;
        assert!(delta < 5_000, "delta={delta}");
    }

    #[test]
    fn test_reno_cwnd_capped_at_max() {
        let mut cc = CongestionController::new(CccControllerConfig {
            algorithm: CccAlgorithm::Reno,
            initial_cwnd: 16_776_000,
            max_cwnd: 16_777_216,
            ..Default::default()
        });
        cc.add_connection(1);
        cc.on_ack(1, 500_000, 10.0).expect("ok");
        let cwnd = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(cwnd <= 16_777_216);
    }

    // ── on_loss ──────────────────────────────────────────────────────────────

    #[test]
    fn test_on_loss_unknown_errors() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        assert!(cc.on_loss(42, 1_000).is_err());
    }

    #[test]
    fn test_reno_on_loss_halves_cwnd() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_loss(1, 1_000).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(after <= before / 2 + 1); // allow for min_cwnd floor
    }

    #[test]
    fn test_on_loss_enters_fast_recovery() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_loss(1, 100).expect("ok");
        assert_eq!(
            cc.connection(1).map(|c| c.state),
            Some(CccState::FastRecovery)
        );
    }

    #[test]
    fn test_on_loss_increments_total_losses() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_loss(1, 100).expect("ok");
        cc.on_loss(1, 100).expect("ok");
        assert_eq!(cc.controller_stats().total_losses, 2);
    }

    #[test]
    fn test_on_loss_cwnd_never_below_min() {
        let mut cc = CongestionController::new(CccControllerConfig {
            algorithm: CccAlgorithm::Reno,
            initial_cwnd: 1_448,
            min_cwnd: 1_448,
            ..Default::default()
        });
        cc.add_connection(1);
        cc.on_loss(1, 100).expect("ok");
        let cwnd = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(cwnd >= 1_448);
    }

    // ── on_timeout ───────────────────────────────────────────────────────────

    #[test]
    fn test_on_timeout_unknown_errors() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        assert!(cc.on_timeout(42).is_err());
    }

    #[test]
    fn test_on_timeout_resets_to_slow_start() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_ack(1, 500_000, 10.0).expect("ok");
        cc.on_timeout(1).expect("ok");
        assert_eq!(cc.connection(1).map(|c| c.state), Some(CccState::SlowStart));
    }

    #[test]
    fn test_on_timeout_resets_cwnd_to_min() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_timeout(1).expect("ok");
        let cwnd = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert_eq!(cwnd, 1_448); // min_cwnd
    }

    #[test]
    fn test_on_timeout_halves_ssthresh() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        let before_ssthresh = cc.connection(1).map(|c| c.ssthresh).unwrap_or(0);
        let before_cwnd = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_timeout(1).expect("ok");
        let after_ssthresh = cc.connection(1).map(|c| c.ssthresh).unwrap_or(0);
        assert!(after_ssthresh <= (before_cwnd / 2).max(1_448));
        // ssthresh must be <= what it was (initial cwnd is < initial ssthresh).
        assert!(after_ssthresh <= before_ssthresh);
    }

    #[test]
    fn test_on_timeout_increments_total_losses() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_timeout(1).expect("ok");
        assert_eq!(cc.controller_stats().total_losses, 1);
    }

    // ── sending_rate ─────────────────────────────────────────────────────────

    #[test]
    fn test_sending_rate_none_before_rtt() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        assert_eq!(cc.sending_rate(1), None);
    }

    #[test]
    fn test_sending_rate_some_after_ack() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_ack(1, 1_000, 20.0).expect("ok");
        assert!(cc.sending_rate(1).is_some());
    }

    #[test]
    fn test_sending_rate_unknown_none() {
        let cc = make_ctrl(CccAlgorithm::Reno);
        assert_eq!(cc.sending_rate(999), None);
    }

    #[test]
    fn test_sending_rate_positive() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_ack(1, 10_000, 100.0).expect("ok");
        let rate = cc.sending_rate(1).unwrap_or(0.0);
        assert!(rate > 0.0);
    }

    // ── controller_stats ─────────────────────────────────────────────────────

    #[test]
    fn test_stats_empty_controller() {
        let cc = make_ctrl(CccAlgorithm::Reno);
        let stats = cc.controller_stats();
        assert_eq!(stats.active_connections, 0);
        assert_eq!(stats.total_acks, 0);
        assert_eq!(stats.total_losses, 0);
        assert_eq!(stats.avg_cwnd, 0.0);
        assert_eq!(stats.avg_rtt, 0.0);
    }

    #[test]
    fn test_stats_counts_connections() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.add_connection(2);
        assert_eq!(cc.controller_stats().active_connections, 2);
    }

    #[test]
    fn test_stats_total_acks_aggregated() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.add_connection(2);
        cc.on_ack(1, 1_000, 10.0).expect("ok");
        cc.on_ack(2, 1_000, 10.0).expect("ok");
        assert_eq!(cc.controller_stats().total_acks, 2);
    }

    #[test]
    fn test_stats_avg_cwnd_reasonable() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        let stats = cc.controller_stats();
        assert!(stats.avg_cwnd > 0.0);
    }

    // ── event log ────────────────────────────────────────────────────────────

    #[test]
    fn test_events_populated_on_ack() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_ack(1, 1_000, 10.0).expect("ok");
        assert!(!cc.events().is_empty());
    }

    #[test]
    fn test_events_populated_on_loss() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_loss(1, 100).expect("ok");
        let has_loss = cc
            .events()
            .iter()
            .any(|e| e.event_type == CccEventType::PacketLost);
        assert!(has_loss);
    }

    #[test]
    fn test_events_bounded_at_1000() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        for _ in 0..1_100u32 {
            cc.on_ack(1, 100, 5.0).expect("ok");
        }
        assert!(cc.events().len() <= 1_000);
    }

    #[test]
    fn test_events_timeout_type() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_timeout(1).expect("ok");
        let has_timeout = cc
            .events()
            .iter()
            .any(|e| e.event_type == CccEventType::Timeout);
        assert!(has_timeout);
    }

    #[test]
    fn test_events_record_cwnd_change() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_ack(1, 10_000, 10.0).expect("ok");
        let event = cc.events().iter().last().expect("event");
        // cwnd_before and cwnd_after are both valid u64 values.
        assert!(event.cwnd_after > 0);
    }

    // ── Cubic algorithm ──────────────────────────────────────────────────────

    #[test]
    fn test_cubic_slow_start_grows() {
        let mut cc = make_ctrl(CccAlgorithm::Cubic);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_ack(1, 10_000, 20.0).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(after > before);
    }

    #[test]
    fn test_cubic_loss_reduces_cwnd() {
        let mut cc = make_ctrl(CccAlgorithm::Cubic);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_loss(1, 1_000).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(after <= before);
    }

    #[test]
    fn test_cubic_timeout_resets_to_slowstart() {
        let mut cc = make_ctrl(CccAlgorithm::Cubic);
        cc.add_connection(1);
        cc.on_timeout(1).expect("ok");
        assert_eq!(cc.connection(1).map(|c| c.state), Some(CccState::SlowStart));
    }

    // ── BBR algorithm ────────────────────────────────────────────────────────

    #[test]
    fn test_bbr_grows_cwnd() {
        let mut cc = make_ctrl(CccAlgorithm::Bbr);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_ack(1, 10_000, 20.0).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(after >= before);
    }

    #[test]
    fn test_bbr_loss_mild_reduction() {
        let mut cc = make_ctrl(CccAlgorithm::Bbr);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_loss(1, 1_000).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        // BBR does a mild 10% reduction, so after should be > 0 and <= before.
        assert!(after > 0 && after <= before);
    }

    #[test]
    fn test_bbr_has_sending_rate_after_ack() {
        let mut cc = make_ctrl(CccAlgorithm::Bbr);
        cc.add_connection(1);
        cc.on_ack(1, 50_000, 15.0).expect("ok");
        assert!(cc.sending_rate(1).is_some());
    }

    // ── Vegas algorithm ──────────────────────────────────────────────────────

    #[test]
    fn test_vegas_grows_cwnd_without_rtt() {
        let mut cc = make_ctrl(CccAlgorithm::Vegas);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_ack(1, 1_448, 0.0).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(after >= before);
    }

    #[test]
    fn test_vegas_loss_reduces_cwnd() {
        let mut cc = make_ctrl(CccAlgorithm::Vegas);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_loss(1, 1_000).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(after <= before);
    }

    // ── Westwood algorithm ───────────────────────────────────────────────────

    #[test]
    fn test_westwood_slow_start_grows() {
        let mut cc = make_ctrl(CccAlgorithm::Westwood);
        cc.add_connection(1);
        let before = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        cc.on_ack(1, 5_000, 10.0).expect("ok");
        let after = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(after > before);
    }

    #[test]
    fn test_westwood_loss_uses_bw_estimate() {
        let mut cc = make_ctrl(CccAlgorithm::Westwood);
        cc.add_connection(1);
        // Give it some bandwidth history.
        cc.on_ack(1, 50_000, 20.0).expect("ok");
        cc.on_loss(1, 1_000).expect("ok");
        // After loss with a BW estimate, ssthresh should be the BDP.
        let ssthresh = cc.connection(1).map(|c| c.ssthresh).unwrap_or(0);
        assert!(ssthresh >= 1_448);
    }

    // ── xorshift64 ────────────────────────────────────────────────────────────

    #[test]
    fn test_xorshift64_produces_nonzero() {
        let mut state: u64 = 12345;
        let v = xorshift64(&mut state);
        assert_ne!(v, 0);
    }

    #[test]
    fn test_xorshift64_changes_state() {
        let mut state: u64 = 9999;
        let v1 = xorshift64(&mut state);
        let v2 = xorshift64(&mut state);
        assert_ne!(v1, v2);
    }

    #[test]
    fn test_xorshift64_deterministic() {
        let mut s1: u64 = 42;
        let mut s2: u64 = 42;
        assert_eq!(xorshift64(&mut s1), xorshift64(&mut s2));
    }

    // ── Decision struct ──────────────────────────────────────────────────────

    #[test]
    fn test_decision_new_cwnd_matches_connection() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        let d = cc.on_ack(1, 1_000, 10.0).expect("ok");
        let actual = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert_eq!(d.new_cwnd, actual);
    }

    #[test]
    fn test_decision_state_matches_connection() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        let d = cc.on_loss(1, 100).expect("ok");
        assert_eq!(d.new_state, CccState::FastRecovery);
    }

    #[test]
    fn test_decision_sending_rate_consistency() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        let d = cc.on_ack(1, 1_000, 50.0).expect("ok");
        // Decision sending_rate should match controller's sending_rate.
        assert_eq!(d.sending_rate, cc.sending_rate(1));
    }

    // ── RTT tracking ─────────────────────────────────────────────────────────

    #[test]
    fn test_rtt_updated_on_ack() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_ack(1, 1_000, 30.0).expect("ok");
        let rtt = cc.connection(1).map(|c| c.rtt_ms).unwrap_or(0.0);
        assert!(rtt > 0.0);
    }

    #[test]
    fn test_rtt_ewma_converges() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        for _ in 0..20 {
            cc.on_ack(1, 1_000, 100.0).expect("ok");
        }
        let rtt = cc.connection(1).map(|c| c.rtt_ms).unwrap_or(0.0);
        // After 20 samples of 100ms, EWMA should be close to 100ms.
        assert!((rtt - 100.0).abs() < 20.0, "rtt={rtt}");
    }

    // ── bytes_acked / bytes_lost accounting ───────────────────────────────────

    #[test]
    fn test_bytes_acked_accumulates() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_ack(1, 5_000, 10.0).expect("ok");
        cc.on_ack(1, 3_000, 10.0).expect("ok");
        let ba = cc.connection(1).map(|c| c.bytes_acked).unwrap_or(0);
        assert_eq!(ba, 8_000);
    }

    #[test]
    fn test_bytes_lost_accumulates() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.on_loss(1, 1_000).expect("ok");
        cc.on_loss(1, 500).expect("ok");
        let bl = cc.connection(1).map(|c| c.bytes_lost).unwrap_or(0);
        assert_eq!(bl, 1_500);
    }

    // ── min_cwnd floor guarantee ──────────────────────────────────────────────

    #[test]
    fn test_cwnd_never_below_min_after_many_losses() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        for _ in 0..50 {
            cc.on_loss(1, 100_000).expect("ok");
        }
        let cwnd = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(cwnd >= 1_448);
    }

    // ── max_cwnd ceiling guarantee ────────────────────────────────────────────

    #[test]
    fn test_cwnd_never_above_max_after_many_acks() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        for _ in 0..5_000u32 {
            cc.on_ack(1, 100_000, 5.0).expect("ok");
        }
        let cwnd = cc.connection(1).map(|c| c.cwnd).unwrap_or(0);
        assert!(cwnd <= 16_777_216);
    }

    // ── multi-connection isolation ────────────────────────────────────────────

    #[test]
    fn test_connections_isolated() {
        let mut cc = make_ctrl(CccAlgorithm::Reno);
        cc.add_connection(1);
        cc.add_connection(2);
        let before_2 = cc.connection(2).map(|c| c.cwnd).unwrap_or(0);
        cc.on_loss(1, 10_000).expect("ok");
        let after_2 = cc.connection(2).map(|c| c.cwnd).unwrap_or(0);
        assert_eq!(before_2, after_2);
    }

    // ── CccAlgorithm default ──────────────────────────────────────────────────

    #[test]
    fn test_algorithm_default_is_reno() {
        assert_eq!(CccAlgorithm::default(), CccAlgorithm::Reno);
    }

    // ── CccState default ─────────────────────────────────────────────────────

    #[test]
    fn test_state_default_is_ca() {
        assert_eq!(CccState::default(), CccState::CongestionAvoidance);
    }

    // ── type alias usability ──────────────────────────────────────────────────

    #[test]
    fn test_type_aliases_usable() {
        let mut cc: CccCongestionController = CccCongestionController::with_defaults();
        cc.add_connection(1);
        let d: CccDecision = cc.on_ack(1, 1_000, 10.0).expect("ok");
        assert!(d.new_cwnd > 0);
    }
}