rustnet-core 0.6.0

Network analysis library: packet parsing, protocol types, deep packet inspection, link-layer parsers, connection merging, and DNS/GeoIP/OUI lookups: the reusable core of rustnet
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
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
//! Live connection tracking.
//!
//! [`ConnectionTracker`] folds parsed packets into a long-lived, lifecycle-
//! managed table of [`Connection`]s. It owns everything needed to turn a stream
//! of [`ParsedPacket`]s into the same connection view the `rustnet` TUI shows:
//! the active table, an archive of recently-closed ("historic") connections,
//! RTT estimation from TCP, QUIC handshakes, and ICMP echo, plus DNS-shaped
//! response timing, QUIC connection-ID coalescing, and timeout-based cleanup,
//! all without any UI, capture, or process-lookup
//! dependency.
//!
//! This is the piece that makes headless tools easy: pair a capture source with
//! a parser, then feed each parsed packet to [`ConnectionTracker::ingest_at`]
//! and periodically call [`ConnectionTracker::cleanup`]. A Prometheus exporter,
//! a pcap post-processor, or a test harness can all reuse the exact connection
//! semantics of the main application. Offline consumers replaying a saved trace
//! should pass each packet's capture timestamp so connection lifetimes and
//! timeouts follow trace time rather than the replay wall clock.
//!
//! ```no_run
//! use rustnet_core::network::parser::PacketParser;
//! use rustnet_core::network::tracker::ConnectionTracker;
//! use std::time::SystemTime;
//!
//! let parser = PacketParser::new();
//! let tracker = ConnectionTracker::new();
//! # let frames: Vec<Vec<u8>> = Vec::new();
//! for frame in frames {
//!     if let Some(parsed) = parser.parse_packet(&frame) {
//!         tracker.ingest_at(&parsed, SystemTime::now());
//!     }
//! }
//! tracker.cleanup(SystemTime::now()); // expire idle/closed connections
//! for entry in tracker.connections().iter() {
//!     let conn = entry.value();
//!     println!("{} {} -> {}", conn.protocol, conn.local_addr, conn.remote_addr);
//! }
//! ```
//!
//! All methods take `&self` (the internal tables use interior mutability), so a
//! single tracker can be wrapped in an [`std::sync::Arc`] and shared across a
//! capture thread, a cleanup thread, and a reader thread.

use crate::network::dns_analytics::{DnsAnalyticsSnapshot, DnsAnalyticsTracker};
use crate::network::dns_attribution::DnsAttributionCache;
use crate::network::merge::{
    TcpMergeEvents, create_connection_from_packet, merge_packet_into_connection,
};
use crate::network::neighbors::{NeighborCache, NeighborEntry};
use crate::network::parser::ParsedPacket;
use crate::network::types::{
    ApplicationProtocol, AttributionSource, Connection, ConnectionKey, Protocol, ProtocolState,
    QuicPacketType, RequestHealthEvents, RttTracker,
};
use dashmap::DashMap;
use rustc_hash::FxBuildHasher;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, RwLock};
use std::time::{Duration, SystemTime};

/// Recently archived TCP tuples remain tombstoned briefly so delayed teardown
/// packets do not create phantom established connections.
const RECENTLY_CLOSED_TTL: Duration = Duration::from_secs(30);

/// Tombstone capacity floor. `max_historic` sizes the user-facing archive,
/// but tombstones guard correctness, so a tiny or zero `max_historic` must
/// not strip them and reopen the phantom-connection window. Entries are a
/// key and a timestamp; the TTL above bounds how long any of them live.
const RECENTLY_CLOSED_MIN_ENTRIES: usize = 1024;

/// Whether a QUIC packet belongs to the handshake exchange that RTT timing
/// pairs up.
///
/// 0-RTT is deliberately excluded: it is client-only application data sent
/// alongside the Initial, so treating it as a fresh send would restart the
/// timer and report a fraction of the real round trip. 1-RTT packets carry a
/// short header and reveal nothing to time against.
fn is_quic_handshake_packet(packet_type: QuicPacketType) -> bool {
    matches!(
        packet_type,
        QuicPacketType::Initial
            | QuicPacketType::Handshake
            | QuicPacketType::Retry
            | QuicPacketType::VersionNegotiation
    )
}

/// Whether a UDP packet's DPI classification is one the RTT tracker times.
/// Gates the RTT lock in `measure_timings` so untimed UDP traffic (QUIC 1-RTT
/// bulk data, SSDP, mDNS, ...) never touches the mutex on the packet path.
fn udp_application_is_timed(application: &ApplicationProtocol) -> bool {
    match application {
        ApplicationProtocol::Quic(quic) => is_quic_handshake_packet(quic.packet_type),
        ApplicationProtocol::Dns(_)
        | ApplicationProtocol::Llmnr(_)
        | ApplicationProtocol::NetBios(_)
        | ApplicationProtocol::Stun(_)
        | ApplicationProtocol::Ntp(_) => true,
        _ => false,
    }
}

/// The active connection table: flow key -> connection.
///
/// Keys are compact `Copy` structs, and the map uses FxHash; with a small
/// fixed-size key, hashing is a handful of multiplies instead of SipHash over
/// a formatted string. (Hash-flooding resistance isn't needed here: the table
/// is bounded by `max_connections` and keyed by addresses, not attacker-chosen
/// bytes of arbitrary length.)
pub type ConnectionMap = DashMap<ConnectionKey, Connection, FxBuildHasher>;

/// The historic (recently-closed) connection table.
pub type HistoricMap = DashMap<HistoricKey, Connection, FxBuildHasher>;

/// Identity of an archived (closed) connection: the flow key plus the
/// connection's creation time, so multiple closed connections that reused the
/// same 4-tuple don't clobber each other. (Replaces the former
/// `"<key>:<created_at_nanos>"` string suffix.)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HistoricKey {
    pub key: ConnectionKey,
    pub created_nanos: u128,
}

impl HistoricKey {
    /// The identity `conn` has (or will have) in the historic table.
    pub fn for_connection(key: ConnectionKey, conn: &Connection) -> Self {
        Self {
            key,
            created_nanos: conn
                .created_at
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos(),
        }
    }
}

impl std::fmt::Display for HistoricKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.key, self.created_nanos)
    }
}

/// Tuning knobs for a [`ConnectionTracker`].
#[derive(Debug, Clone)]
pub struct TrackerConfig {
    /// Maximum number of concurrent active connections. New connections beyond
    /// this limit are dropped (existing ones still update) to bound memory
    /// under port scans or connection floods.
    pub max_connections: usize,
    /// Maximum number of recently-closed ("historic") connections retained.
    /// Oldest-closed entries are evicted first.
    pub max_historic: usize,
    /// Maximum number of QUIC connection-ID -> connection-key mappings kept for
    /// coalescing migrated QUIC connections. Cleared wholesale when exceeded.
    pub max_quic_mappings: usize,
    /// Whether [`ConnectionTracker::cleanup`] archives removed connections into
    /// the historic table. Headless tools that don't need a closed-connection
    /// view can set this to `false` to save memory.
    pub keep_historic: bool,
    /// Whether connections without an authoritative hostname (TLS SNI or HTTP
    /// `Host:`) are tagged with the name from a DNS response observed on the
    /// wire shortly before the connection appeared. Purely passive; consumers
    /// that don't display hostnames can set this to `false`.
    pub dns_attribution: bool,
}

impl Default for TrackerConfig {
    fn default() -> Self {
        Self {
            max_connections: 50_000,
            max_historic: 5_000,
            max_quic_mappings: 10_000,
            keep_historic: true,
            dns_attribution: true,
        }
    }
}

/// What happened when a packet was ingested via
/// [`ingest_at`](ConnectionTracker::ingest_at).
///
/// Returned so callers can layer their own concerns (global statistics,
/// structured logging, DNS enrichment) on top of the core table update without
/// the tracker needing to know about them.
#[derive(Debug, Clone)]
pub struct IngestOutcome {
    /// The (possibly QUIC-coalesced) key under which the connection is stored.
    /// `Copy`, and its `Display` form matches the historical string key
    /// (`"TCP:1.2.3.4:80-TCP:5.6.7.8:443"`).
    pub key: ConnectionKey,
    /// `true` if this packet created a new connection entry.
    pub created: bool,
    /// `true` if the packet was dropped because `max_connections` was reached
    /// (the connection did not already exist and was not inserted).
    pub dropped: bool,
    /// `true` when a delayed packet matched a recently archived TCP tuple and
    /// was intentionally not turned into a new active connection.
    pub ignored_late: bool,
    /// Previous live generation archived by a strong new-session signal.
    /// Historic storage receives an immutable snapshot of this connection.
    pub archived: Option<Connection>,
    /// New TCP retransmissions detected by this packet.
    pub retransmits: u64,
    /// New out-of-order TCP segments detected by this packet.
    pub out_of_order: u64,
    /// New TCP fast-retransmits detected by this packet.
    pub fast_retransmits: u64,
    /// An RTT sample, if this packet completed a handshake round trip: a TCP
    /// SYN-ACK matching a prior SYN, or a QUIC handshake packet answering one
    /// sent the other way.
    pub measured_rtt: Option<Duration>,
    /// The latest completed DNS query→response round trip, if this packet was
    /// a response matching a pending query by transaction ID.
    pub dns_response_time: Option<Duration>,
    /// The first completed LLMNR query-to-response round trip, if this packet
    /// was a response matching a pending multicast query by transaction ID.
    pub llmnr_response_time: Option<Duration>,
    /// The latest completed NetBIOS request-to-response round trip, if this
    /// packet matched a pending request by transaction ID.
    pub netbios_response_time: Option<Duration>,
    /// The latest completed ICMP echo round trip, if this packet was a reply
    /// matching an outgoing request by identifier and sequence number.
    pub icmp_echo_rtt: Option<Duration>,
    /// The latest completed STUN request→response round trip, if this packet
    /// was a response matching a pending request by transaction ID.
    pub stun_rtt: Option<Duration>,
    /// The latest completed NTP request→response round trip, if this packet
    /// was a server response echoing a pending client transmit timestamp.
    pub ntp_rtt: Option<Duration>,
}

/// Timing measurements extracted from one packet, carried together through
/// the connection-table update into the resulting [`IngestOutcome`].
#[derive(Clone, Copy, Default)]
struct PacketTimings {
    measured_rtt: Option<Duration>,
    dns_response_time: Option<Duration>,
    llmnr_response_time: Option<Duration>,
    netbios_response_time: Option<Duration>,
    icmp_echo_rtt: Option<Duration>,
    stun_rtt: Option<Duration>,
    ntp_rtt: Option<Duration>,
}

impl PacketTimings {
    /// An [`IngestOutcome`] carrying these timings, with every other field at
    /// its quiescent value for the caller to override via struct update.
    fn outcome(self, key: ConnectionKey) -> IngestOutcome {
        IngestOutcome {
            key,
            created: false,
            dropped: false,
            ignored_late: false,
            archived: None,
            retransmits: 0,
            out_of_order: 0,
            fast_retransmits: 0,
            measured_rtt: self.measured_rtt,
            dns_response_time: self.dns_response_time,
            llmnr_response_time: self.llmnr_response_time,
            netbios_response_time: self.netbios_response_time,
            icmp_echo_rtt: self.icmp_echo_rtt,
            stun_rtt: self.stun_rtt,
            ntp_rtt: self.ntp_rtt,
        }
    }
}

/// Stamp any round trips this packet completed onto its connection.
fn apply_timings(conn: &mut Connection, timings: &PacketTimings) {
    if let Some(rtt) = timings.measured_rtt
        && conn.initial_rtt.is_none()
    {
        conn.initial_rtt = Some(rtt);
    }
    // Last-wins, unlike `initial_rtt`: each completed query refreshes the
    // displayed response time.
    if let Some(rtt) = timings.dns_response_time {
        conn.dns_response_time = Some(rtt);
    }
    if let Some(rtt) = timings.llmnr_response_time {
        conn.llmnr_response_time = Some(rtt);
    }
    if let Some(rtt) = timings.netbios_response_time {
        conn.netbios_response_time = Some(rtt);
    }
    if let Some(rtt) = timings.icmp_echo_rtt {
        conn.icmp_echo_rtt = Some(rtt);
    }
    if let Some(rtt) = timings.stun_rtt {
        conn.stun_rtt = Some(rtt);
    }
    if let Some(rtt) = timings.ntp_rtt {
        conn.ntp_rtt = Some(rtt);
    }
}

/// Count explicit QUIC health signals and mark outgoing timed requests.
fn apply_observed_protocol_health(conn: &mut Connection, parsed: &ParsedPacket) {
    let Some(dpi) = parsed.dpi_result.as_ref() else {
        return;
    };
    match &dpi.application {
        ApplicationProtocol::Quic(quic) => match quic.packet_type {
            QuicPacketType::Retry => {
                conn.protocol_health.quic_retry_count =
                    conn.protocol_health.quic_retry_count.saturating_add(1);
            }
            QuicPacketType::VersionNegotiation => {
                conn.protocol_health.quic_version_negotiation_count = conn
                    .protocol_health
                    .quic_version_negotiation_count
                    .saturating_add(1);
            }
            _ => {}
        },
        ApplicationProtocol::Dns(info) if parsed.is_outgoing && !info.is_response => {
            conn.protocol_health.request_observed = true;
        }
        ApplicationProtocol::Llmnr(info) if parsed.is_outgoing && !info.is_response => {
            conn.protocol_health.request_observed = true;
        }
        ApplicationProtocol::NetBios(info) if parsed.is_outgoing && info.is_request() => {
            conn.protocol_health.request_observed = true;
        }
        ApplicationProtocol::Stun(info)
            if parsed.is_outgoing
                && info.message_class == crate::network::types::StunMessageClass::Request =>
        {
            conn.protocol_health.request_observed = true;
        }
        ApplicationProtocol::Ntp(info)
            if parsed.is_outgoing && info.mode == crate::network::types::NtpMode::Client =>
        {
            conn.protocol_health.request_observed = true;
        }
        _ => {}
    }
}

/// A live, lifecycle-managed table of network connections built from parsed
/// packets. See the [module docs](self) for the intended usage.
pub struct ConnectionTracker {
    connections: ConnectionMap,
    historic: HistoricMap,
    /// Coordinates moves between the active and historic maps with readers
    /// that need one consistent retained-connection view.
    lifecycle: RwLock<()>,
    rtt: Mutex<RttTracker>,
    dns_analytics: Mutex<DnsAnalyticsTracker>,
    quic_map: Mutex<HashMap<String, ConnectionKey>>,
    recently_closed: Mutex<HashMap<ConnectionKey, SystemTime>>,
    config: TrackerConfig,
    /// Active-connection count maintained by `ingest_at`/`cleanup`/`clear`.
    /// Lets the per-packet `max_connections` check be a single atomic load
    /// instead of a `DashMap::len()` (which read-locks every shard) plus an
    /// extra `contains_key` lookup. May transiently lag `connections.len()`
    /// by a few entries under concurrent ingest near the limit, acceptable
    /// for a flood-protection bound.
    active_count: AtomicUsize,
    /// IP -> MAC/vendor mappings learned passively from ingested ARP (IPv4)
    /// and NDP (IPv6) packets. Outlives the connections themselves, so LAN
    /// peers stay identified after their ARP/NDP rows are cleaned up.
    neighbors: NeighborCache,
    /// IP -> domain mappings learned passively from ingested DNS responses,
    /// used to tag SNI-less connections with a hostname. Fed and drained by
    /// `ingest_at`, pruned by `cleanup`.
    dns_attribution: DnsAttributionCache,
}

impl ConnectionTracker {
    /// Create a tracker with default configuration.
    pub fn new() -> Self {
        Self::with_config(TrackerConfig::default())
    }

    /// Create a tracker with custom [`TrackerConfig`].
    pub fn with_config(config: TrackerConfig) -> Self {
        Self {
            connections: ConnectionMap::with_hasher(FxBuildHasher),
            historic: HistoricMap::with_hasher(FxBuildHasher),
            lifecycle: RwLock::new(()),
            rtt: Mutex::new(RttTracker::new()),
            dns_analytics: Mutex::new(DnsAnalyticsTracker::default()),
            quic_map: Mutex::new(HashMap::new()),
            recently_closed: Mutex::new(HashMap::new()),
            config,
            active_count: AtomicUsize::new(0),
            neighbors: NeighborCache::default(),
            dns_attribution: DnsAttributionCache::default(),
        }
    }

    /// Fold a parsed packet into the connection table, creating or updating the
    /// matching connection, stamping the update with the supplied `now`.
    ///
    /// Pass the packet's own capture timestamp: for offline processing (pcap
    /// replay, tests) this keeps `created_at`/`last_activity` and the
    /// [`cleanup`](Self::cleanup) timeout sweep on trace time rather than the
    /// replay wall clock. Live callers should also pass each packet's own
    /// capture timestamp, not one clock read shared across a batch of packets.
    /// Handshake RTT is the difference between two packets' `now` values, so a
    /// shared timestamp collapses every round trip that completes within one
    /// batch to zero.
    pub fn ingest_at(&self, parsed: &ParsedPacket, now: SystemTime) -> IngestOutcome {
        // Harvest IP -> MAC mappings from ARP and NDP packets; only they pay
        // this cost.
        match &parsed.protocol_state {
            ProtocolState::Arp(arp_info) => self.neighbors.learn_from_arp(arp_info, now),
            ProtocolState::Icmp {
                ndp_neighbor: Some(neighbor),
                ..
            } => self.neighbors.learn_from_ndp(neighbor, now),
            _ => {}
        }

        let timings = self.measure_timings(parsed, now);

        if parsed.protocol == Protocol::Udp
            && let Some(dpi) = &parsed.dpi_result
            && let ApplicationProtocol::Dns(dns) = &dpi.application
            && let Ok(mut analytics) = self.dns_analytics.lock()
        {
            analytics.record_packet(
                parsed.connection_key(),
                dns,
                parsed.is_outgoing,
                now,
                timings.dns_response_time,
            );
        }

        // Passive DNS attribution: record answered A/AAAA mappings and collect
        // the connections that were waiting on one of the answered IPs.
        let waiters = if self.config.dns_attribution
            && let Some(dpi) = &parsed.dpi_result
            && let ApplicationProtocol::Dns(dns) = &dpi.application
            && dns.is_response
            && !dns.response_ips.is_empty()
            && let Some(query_name) = &dns.query_name
        {
            self.dns_attribution.record_and_drain_pending(
                query_name,
                &dns.response_ips,
                AttributionSource::CapturedDns,
            )
        } else {
            Vec::new()
        };

        let outcome = self.ingest_update(parsed, now, timings);

        // Tag drained waiters after the table update so the DNS packet's own
        // row never holds an entry lock while a waiter's row is taken.
        for waiter_key in waiters {
            if let Some(mut conn) = self.connections.get_mut(&waiter_key) {
                self.dns_attribution.attribute(&mut conn, waiter_key);
            }
        }

        outcome
    }

    /// The connection-table update half of [`ingest_at`](Self::ingest_at):
    /// resolve the key and fold the packet into the active table, splitting
    /// off a new generation or ignoring a late teardown packet as needed.
    fn ingest_update(
        &self,
        parsed: &ParsedPacket,
        now: SystemTime,
        timings: PacketTimings,
    ) -> IngestOutcome {
        // A read guard makes ordinary packet updates atomic with cleanup. The
        // uncommon generation-split path drops it and reacquires a write guard
        // so retained-source readers also see one consistent move.
        let lifecycle = self
            .lifecycle
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let key = self.resolve_connection_key(parsed);

        // Existing flows need one shard lookup and lock, not separate
        // presence, generation and update lookups. Keep the lifecycle guard
        // until the update finishes so cleanup cannot archive this generation.
        if let Some(mut conn) = self.connections.get_mut(&key) {
            if Self::packet_starts_new_generation(&conn, parsed) {
                // The split takes the lifecycle write lock and rechecks the
                // generation. Never retain a shard guard while upgrading.
                drop(conn);
                drop(lifecycle);
                return self.ingest_new_generation(parsed, now, key, timings);
            }

            let deltas = merge_packet_into_connection(&mut conn, parsed, now);
            apply_timings(&mut conn, &timings);
            apply_observed_protocol_health(&mut conn, parsed);
            drop(conn);
            return self.finish_ingest(key, timings, false, deltas);
        }

        if self.is_recent_late_packet(key, parsed, now) {
            return IngestOutcome {
                ignored_late: true,
                ..timings.outcome(key)
            };
        }

        // Another ingestion caller can insert after the initial miss. Keep
        // the slow path's generation check before its entry-based update.
        let starts_new_generation = self
            .connections
            .get(&key)
            .is_some_and(|conn| Self::packet_starts_new_generation(&conn, parsed));
        if starts_new_generation {
            drop(lifecycle);
            return self.ingest_new_generation(parsed, now, key, timings);
        }

        self.ingest_into_active(parsed, now, key, timings)
    }

    /// Run this packet through the RTT tracker and collect any round trips it
    /// completed.
    fn measure_timings(&self, parsed: &ParsedPacket, now: SystemTime) -> PacketTimings {
        // Track RTT for TCP connections using SYN/SYN-ACK timing, and for QUIC
        // using the long-header handshake exchange. Everything QUIC sends after
        // the handshake is behind header protection, so this initial flight is
        // the only round trip an on-path observer can time.
        let mut measured_rtt: Option<Duration> = None;
        let mut dns_response_time: Option<Duration> = None;
        let mut llmnr_response_time: Option<Duration> = None;
        let mut netbios_response_time: Option<Duration> = None;
        let mut stun_rtt: Option<Duration> = None;
        let mut ntp_rtt: Option<Duration> = None;
        let mut request_health_events = RequestHealthEvents::default();
        let base_key = parsed.connection_key();
        if parsed.protocol == Protocol::Tcp
            && let Some(tcp_header) = &parsed.tcp_header
        {
            if tcp_header.flags.syn && !tcp_header.flags.ack {
                if let Ok(mut tracker) = self.rtt.lock() {
                    tracker.record_syn(base_key, now);
                }
            } else if tcp_header.flags.syn
                && tcp_header.flags.ack
                && let Ok(mut tracker) = self.rtt.lock()
            {
                measured_rtt = tracker.record_syn_ack(&base_key, now);
            }
        } else if parsed.protocol == Protocol::Udp
            && let Some(dpi) = &parsed.dpi_result
            && udp_application_is_timed(&dpi.application)
            && let Ok(mut tracker) = self.rtt.lock()
        {
            // One lock acquisition covers every timed UDP application; a
            // packet carries one DPI result, so at most one arm runs.
            match &dpi.application {
                ApplicationProtocol::Quic(_) => {
                    measured_rtt = tracker.record_quic_handshake(base_key, parsed.is_outgoing, now);
                }
                // Time DNS query→response pairs by transaction ID. Port-53
                // gating already happened in DPI dispatch, so any DNS result
                // here is unicast DNS (mDNS/LLMNR map to their own variants).
                ApplicationProtocol::Dns(dns) => {
                    dns_response_time = tracker.record_dns_packet(
                        base_key,
                        dns.txid,
                        parsed.is_outgoing,
                        dns.is_response,
                        now,
                    );
                }
                // LLMNR uses the DNS transaction ID, but sends the query to a
                // multicast address and receives each response from a unicast
                // address. The RTT tracker returns the multicast request row
                // so both views can carry the first response time.
                ApplicationProtocol::Llmnr(llmnr) => {
                    let completed =
                        tracker.record_llmnr_packet(base_key, llmnr, parsed.is_outgoing, now);
                    if let Some((rtt, request_key)) = completed {
                        llmnr_response_time = Some(rtt);
                        self.stamp_request_row_timing(request_key, base_key, |conn| {
                            conn.llmnr_response_time = Some(rtt);
                        });
                    }
                }
                // NetBIOS Name Service broadcasts are answered from a host's
                // unicast address, so the RTT tracker pairs on local socket,
                // service, and transaction ID rather than the full connection
                // key.
                ApplicationProtocol::NetBios(netbios) => {
                    let completed =
                        tracker.record_netbios_packet(base_key, netbios, parsed.is_outgoing, now);
                    if let Some((rtt, request_key)) = completed {
                        netbios_response_time = Some(rtt);
                        self.stamp_request_row_timing(request_key, base_key, |conn| {
                            conn.netbios_response_time = Some(rtt);
                        });
                    }
                }
                // STUN requests and responses share a 96-bit transaction ID
                // that retransmits reuse, so request→response pairing is
                // exact.
                ApplicationProtocol::Stun(stun) => {
                    stun_rtt = tracker.record_stun(
                        base_key,
                        stun.transaction_id,
                        parsed.is_outgoing,
                        stun.message_class,
                        now,
                    );
                }
                // NTP servers echo the client's transmit timestamp as the
                // originate timestamp, pairing each poll with its response.
                ApplicationProtocol::Ntp(ntp) => {
                    ntp_rtt = tracker.record_ntp(base_key, ntp, parsed.is_outgoing, now);
                }
                _ => {}
            }
            request_health_events = tracker.take_request_health_events();
        }

        self.apply_request_health_events(request_health_events);

        // ICMP echo requests reuse one identifier for the life of a ping
        // process, so sequence number is part of the key. That allows several
        // subsecond requests to be pending at once and replies to arrive out of
        // order without cross-pairing samples.
        let echo_metadata = match &parsed.protocol_state {
            ProtocolState::Icmp {
                icmp_type,
                icmp_id: Some(identifier),
                icmp_sequence: Some(sequence),
                ..
            } => match icmp_type {
                8 | 128 => Some((*identifier, *sequence, false)),
                0 | 129 => Some((*identifier, *sequence, true)),
                _ => None,
            },
            _ => None,
        };
        let mut icmp_echo_rtt: Option<Duration> = None;
        if let Some((identifier, sequence, is_reply)) = echo_metadata
            && let Ok(mut tracker) = self.rtt.lock()
        {
            // Loopback captures classify the reply as outgoing too (both
            // endpoints are local), so reclassify it as incoming to let it
            // match the pending request.
            let is_outgoing = parsed.is_outgoing
                && !(is_reply && parsed.local_addr.ip() == parsed.remote_addr.ip());
            icmp_echo_rtt = tracker.record_icmp_echo(
                base_key,
                (identifier, sequence),
                is_outgoing,
                is_reply,
                now,
            );
        }

        PacketTimings {
            measured_rtt,
            dns_response_time,
            llmnr_response_time,
            netbios_response_time,
            icmp_echo_rtt,
            stun_rtt,
            ntp_rtt,
        }
    }

    /// Stamp a completed broadcast or multicast exchange on its request row.
    /// The response packet's own row is updated later through `PacketTimings`.
    fn stamp_request_row_timing(
        &self,
        request_key: ConnectionKey,
        response_key: ConnectionKey,
        stamp: impl FnOnce(&mut Connection),
    ) {
        if request_key != response_key
            && let Some(mut conn) = self.connections.get_mut(&request_key)
        {
            stamp(&mut conn);
        }
    }

    fn apply_request_health_events(&self, events: RequestHealthEvents) {
        for key in events.retries {
            if let Some(mut conn) = self.connections.get_mut(&key) {
                conn.protocol_health.request_retry_count =
                    conn.protocol_health.request_retry_count.saturating_add(1);
            }
        }
        for key in events.timeouts {
            if let Some(mut conn) = self.connections.get_mut(&key) {
                conn.protocol_health.request_timeout_count =
                    conn.protocol_health.request_timeout_count.saturating_add(1);
            }
        }
    }

    fn ingest_into_active(
        &self,
        parsed: &ParsedPacket,
        now: SystemTime,
        key: ConnectionKey,
        timings: PacketTimings,
    ) -> IngestOutcome {
        // Prevent unbounded growth from port scans or connection floods. Only
        // limit new connections; existing ones always get updated. The fast
        // path is a single atomic load; only when at the cap do we pay a
        // lookup to distinguish update-existing from drop-new. (Never call
        // `len()` here or while holding an entry guard; it read-locks every
        // shard.)
        if self.active_count.load(Ordering::Relaxed) >= self.config.max_connections
            && !self.connections.contains_key(&key)
        {
            return IngestOutcome {
                dropped: true,
                ..timings.outcome(key)
            };
        }

        let mut created = false;
        let mut deltas = TcpMergeEvents::default();
        self.connections
            .entry(key)
            .and_modify(|conn| {
                deltas = merge_packet_into_connection(conn, parsed, now);
                apply_timings(conn, &timings);
                apply_observed_protocol_health(conn, parsed);
            })
            .or_insert_with(|| {
                created = true;
                let mut conn = create_connection_from_packet(parsed, now);
                apply_timings(&mut conn, &timings);
                apply_observed_protocol_health(&mut conn, parsed);
                // Attribute a hostname (or enroll for a later DNS response)
                // at creation. The cache only touches its own maps, so this
                // is safe under the entry's shard lock.
                if self.config.dns_attribution {
                    self.dns_attribution.attribute(&mut conn, key);
                }
                conn
            });
        if created {
            self.active_count.fetch_add(1, Ordering::Relaxed);
        }

        self.finish_ingest(key, timings, created, deltas)
    }

    /// Finish an update after releasing the connection's shard guard. RTT
    /// aggregation must not acquire its mutex while a shard is still locked.
    fn finish_ingest(
        &self,
        key: ConnectionKey,
        timings: PacketTimings,
        created: bool,
        deltas: TcpMergeEvents,
    ) -> IngestOutcome {
        // Feed completed data round trips into the aggregate view, so the
        // average RTT reflects established connections rather than only the
        // handshakes of freshly opened ones.
        if let Some(rtt) = deltas.rtt_sample
            && let Ok(mut tracker) = self.rtt.lock()
        {
            tracker.record_data_rtt(rtt);
        }

        IngestOutcome {
            created,
            retransmits: deltas.retransmits,
            out_of_order: deltas.out_of_order,
            fast_retransmits: deltas.fast_retransmits,
            ..timings.outcome(key)
        }
    }

    fn ingest_new_generation(
        &self,
        parsed: &ParsedPacket,
        now: SystemTime,
        key: ConnectionKey,
        timings: PacketTimings,
    ) -> IngestOutcome {
        let _lifecycle = self
            .lifecycle
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut replacement_now = now;

        let still_needs_split = self
            .connections
            .get(&key)
            .is_some_and(|conn| Self::packet_starts_new_generation(&conn, parsed));
        let archived = if still_needs_split {
            self.connections.remove(&key).map(|(_, conn)| {
                // Historic keys include `created_at`, so two generations of
                // the same tuple must not share a creation timestamp. This is
                // possible when several captured packets use one batch time.
                // Windows SystemTime stores 100 ns ticks, so a smaller step
                // would be rounded away instead of producing a distinct key.
                if replacement_now <= conn.created_at {
                    replacement_now = conn
                        .created_at
                        .checked_add(Duration::from_nanos(100))
                        .unwrap_or(replacement_now);
                }
                self.archive_snapshot(key, &conn, now);
                self.retire(key, &conn, now);
                conn
            })
        } else {
            None
        };

        // Cleanup may have removed the old generation while this packet was
        // waiting to acquire the write guard. Reassociate any visible QUIC ID
        // before creating the replacement.
        self.associate_quic_id(parsed, key);
        let mut outcome = self.ingest_into_active(parsed, replacement_now, key, timings);
        outcome.archived = archived;
        self.enforce_historic_limit();
        self.prune_recently_closed(now);
        outcome
    }

    fn resolve_connection_key(&self, parsed: &ParsedPacket) -> ConnectionKey {
        let mut key = parsed.connection_key();
        let Some(conn_id_hex) = Self::parsed_quic_id(parsed) else {
            return key;
        };
        let Ok(mut mapping) = self.quic_map.lock() else {
            return key;
        };
        if let Some(existing_key) = mapping.get(conn_id_hex) {
            key = *existing_key;
        } else {
            if mapping.len() >= self.config.max_quic_mappings {
                mapping.clear();
            }
            mapping.insert(conn_id_hex.to_string(), key);
        }
        key
    }

    fn parsed_quic_id(parsed: &ParsedPacket) -> Option<&str> {
        let dpi = parsed.dpi_result.as_ref()?;
        let ApplicationProtocol::Quic(quic) = &dpi.application else {
            return None;
        };
        quic.connection_id_hex.as_deref()
    }

    fn associate_quic_id(&self, parsed: &ParsedPacket, key: ConnectionKey) {
        let Some(conn_id_hex) = Self::parsed_quic_id(parsed) else {
            return;
        };
        if let Ok(mut mapping) = self.quic_map.lock() {
            if mapping.len() >= self.config.max_quic_mappings {
                mapping.clear();
            }
            mapping.insert(conn_id_hex.to_string(), key);
        }
    }

    fn packet_starts_new_generation(conn: &Connection, parsed: &ParsedPacket) -> bool {
        if !conn.is_closing_or_terminal() {
            return false;
        }
        match parsed.protocol {
            Protocol::Tcp => parsed
                .tcp_header
                .as_ref()
                .is_some_and(|header| header.flags.syn),
            Protocol::Udp => {
                let Some(new_id) = Self::parsed_quic_id(parsed) else {
                    return false;
                };
                let Some(dpi) = conn.dpi_info.as_ref() else {
                    return false;
                };
                let ApplicationProtocol::Quic(old_quic) = &dpi.application else {
                    return false;
                };
                old_quic
                    .connection_id_hex
                    .as_deref()
                    .is_some_and(|old_id| old_id != new_id)
            }
            _ => false,
        }
    }

    fn is_recent_late_packet(
        &self,
        key: ConnectionKey,
        parsed: &ParsedPacket,
        now: SystemTime,
    ) -> bool {
        if parsed.protocol != Protocol::Tcp {
            return false;
        }
        let Some(header) = parsed.tcp_header.as_ref() else {
            return false;
        };
        let is_teardown_only = !header.flags.syn
            && (header.flags.fin
                || header.flags.rst
                || (header.flags.ack && header.payload_len == 0));
        if !is_teardown_only {
            return false;
        }
        self.recently_closed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(&key)
            .is_some_and(|closed_at| {
                now.duration_since(*closed_at).unwrap_or_default() <= RECENTLY_CLOSED_TTL
            })
    }

    /// Archive a historic copy of `conn`, closed at `now`, when
    /// `keep_historic` is set. The historic key includes created_at so
    /// multiple closed connections sharing a 4-tuple don't clobber each
    /// other. snapshot_clone: historic connections never refresh their rates,
    /// so don't pin the (potentially large) sample buffer in the archive.
    fn archive_snapshot(&self, key: ConnectionKey, conn: &Connection, now: SystemTime) {
        if !self.config.keep_historic {
            return;
        }
        let mut historic = conn.snapshot_clone();
        historic.is_historic = true;
        historic.closed_at = Some(now);
        // Cached rates describe live traffic. Carrying them into a closed
        // record makes Overview and Details report traffic that can no longer
        // occur, and leaves a moving fallback point after the live rate
        // history is retired.
        historic.current_incoming_rate_bps = 0.0;
        historic.current_outgoing_rate_bps = 0.0;
        self.historic
            .insert(HistoricKey::for_connection(key, conn), historic);
    }

    /// Bookkeeping for a connection that has left the active table: the
    /// active count, the recently-closed tombstone, its pending
    /// DNS-attribution enrollment (so a later response cannot surface a dead
    /// key, and a replacement generation enrolls with a fresh timestamp) and
    /// any QUIC connection-ID mappings still pointing at it.
    ///
    /// Must not be called from inside a `connections` shard lock.
    fn retire(&self, key: ConnectionKey, conn: &Connection, now: SystemTime) {
        self.active_count.fetch_sub(1, Ordering::Relaxed);
        self.record_recently_closed(key, conn, now);
        self.dns_attribution
            .forget_pending(conn.remote_addr.ip(), key);
        self.remove_quic_mappings_for_key(key);
    }

    fn enforce_historic_limit(&self) {
        if self.historic.len() <= self.config.max_historic {
            return;
        }
        let mut entries: Vec<(HistoricKey, SystemTime)> = self
            .historic
            .iter()
            .map(|entry| {
                let closed = entry.value().closed_at.unwrap_or(entry.value().created_at);
                (*entry.key(), closed)
            })
            .collect();
        entries.sort_by_key(|(_, closed)| *closed);
        let to_remove = self.historic.len() - self.config.max_historic;
        for (key, _) in entries.into_iter().take(to_remove) {
            self.historic.remove(&key);
        }
    }

    fn record_recently_closed(&self, key: ConnectionKey, conn: &Connection, now: SystemTime) {
        if !conn.is_terminal() {
            return;
        }
        self.recently_closed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(key, now);
    }

    fn prune_recently_closed(&self, now: SystemTime) {
        let mut recently_closed = self
            .recently_closed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        recently_closed.retain(|_, closed_at| {
            now.duration_since(*closed_at).unwrap_or_default() <= RECENTLY_CLOSED_TTL
        });
        let max_entries = self.config.max_historic.max(RECENTLY_CLOSED_MIN_ENTRIES);
        if recently_closed.len() > max_entries {
            let mut entries: Vec<(ConnectionKey, SystemTime)> = recently_closed
                .iter()
                .map(|(key, closed_at)| (*key, *closed_at))
                .collect();
            entries.sort_by_key(|(_, closed_at)| *closed_at);
            let to_remove = recently_closed.len() - max_entries;
            for (key, _) in entries.into_iter().take(to_remove) {
                recently_closed.remove(&key);
            }
        }
    }

    fn remove_quic_mappings_for_key(&self, key: ConnectionKey) {
        if let Ok(mut mapping) = self.quic_map.lock() {
            mapping.retain(|_, conn_key| *conn_key != key);
        }
    }

    /// Remove connections whose protocol-aware timeout has elapsed as of `now`.
    ///
    /// Removed connections are archived into the historic table (when
    /// `keep_historic` is set, subject to `max_historic` eviction) and their
    /// QUIC
    /// mappings are dropped. Returns the removed connections (in their original,
    /// pre-archive form) so callers can emit close events or export them.
    pub fn cleanup(&self, now: SystemTime) -> Vec<Connection> {
        let _lifecycle = self
            .lifecycle
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let request_health_events = self
            .rtt
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .expire_requests(now);
        self.apply_request_health_events(request_health_events);
        let mut removed: Vec<Connection> = Vec::new();
        let mut removed_keys: Vec<ConnectionKey> = Vec::new();

        self.connections.retain(|key, conn| {
            let should_keep = !conn.should_cleanup(now);
            if !should_keep {
                removed_keys.push(*key);
                removed.push(conn.clone());
            }
            should_keep
        });
        // Archive and retire outside the retain closure so no shard lock is
        // held while the tracker's other locks are taken.
        for (key, conn) in removed_keys.iter().zip(&removed) {
            self.archive_snapshot(*key, conn, now);
            self.retire(*key, conn, now);
        }
        self.enforce_historic_limit();
        self.prune_recently_closed(now);
        self.dns_attribution.cleanup_tick(std::time::Instant::now());

        removed
    }

    /// Inspect the active and historic maps as one consistent retained view.
    ///
    /// Cleanup cannot move a connection between the maps while `inspect` is
    /// running. Packet updates may still update active rows through DashMap's
    /// per-entry locking.
    pub fn with_retained_sources<R>(
        &self,
        inspect: impl FnOnce(&ConnectionMap, &HistoricMap) -> R,
    ) -> R {
        let _lifecycle = self
            .lifecycle
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        inspect(&self.connections, &self.historic)
    }

    /// Number of historic (recently-closed) connections.
    pub fn historic_len(&self) -> usize {
        self.historic.len()
    }

    /// Return passive DNS analytics for the latest rolling 60-second window.
    pub fn dns_analytics_snapshot(&self) -> DnsAnalyticsSnapshot {
        self.dns_analytics_snapshot_at(SystemTime::now())
    }

    /// Return passive DNS analytics relative to a supplied capture time.
    /// Offline consumers can use this to keep the window aligned with a
    /// replayed trace instead of wall-clock time.
    pub fn dns_analytics_snapshot_at(&self, now: SystemTime) -> DnsAnalyticsSnapshot {
        self.dns_analytics
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .snapshot(now)
    }

    /// Drop all active and historic connections and reset RTT, DNS, QUIC,
    /// and learned-neighbor state.
    pub fn clear(&self) {
        let _lifecycle = self
            .lifecycle
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.connections.clear();
        self.active_count.store(0, Ordering::Relaxed);
        self.historic.clear();
        if let Ok(mut tracker) = self.rtt.lock() {
            tracker.clear();
        }
        if let Ok(mut analytics) = self.dns_analytics.lock() {
            analytics.clear();
        }
        if let Ok(mut mapping) = self.quic_map.lock() {
            mapping.clear();
        }
        self.recently_closed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clear();
        self.neighbors.clear();
        self.dns_attribution.clear();
    }

    /// Direct access to the active connection table.
    ///
    /// Use this for in-place enrichment (e.g. attaching process, DNS, or GeoIP
    /// information via `iter_mut`) or custom reads. Lifecycle changes should go
    /// through [`ingest_at`](Self::ingest_at) and [`cleanup`](Self::cleanup) so the
    /// connection-count limit, RTT, and QUIC coalescing stay consistent;
    /// inserting or removing entries directly desyncs the internal counter
    /// backing the `max_connections` check.
    pub fn connections(&self) -> &ConnectionMap {
        &self.connections
    }

    /// Direct access to the historic (recently-closed) connection table.
    pub fn historic(&self) -> &HistoricMap {
        &self.historic
    }

    /// The ARP/NDP-learned MAC/vendor mapping for `ip`, if one has been
    /// observed.
    pub fn neighbor(&self, ip: &std::net::IpAddr) -> Option<NeighborEntry> {
        self.neighbors.get(ip)
    }

    /// Average network RTT (in milliseconds) over the last `window_secs`
    /// seconds of handshake, TCP data, and ICMP echo samples. `None` if no
    /// samples are available.
    pub fn take_average_rtt(&self, window_secs: u64) -> Option<f64> {
        self.rtt
            .lock()
            .ok()
            .and_then(|mut tracker| tracker.take_average_rtt(window_secs))
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::network::parser::PacketParser;
    use crate::network::types::NetBiosOpcode;

    impl ConnectionTracker {
        /// Wall-clock `ingest_at` shorthand for tests that don't exercise
        /// packet timing.
        fn ingest(&self, parsed: &ParsedPacket) -> IngestOutcome {
            self.ingest_at(parsed, SystemTime::now())
        }
    }

    /// A minimal Ethernet+IPv4+UDP frame, parsed into a `ParsedPacket` so we can
    /// exercise the tracker with a realistic input.
    fn udp_frame(src_port: u16, dst_port: u16) -> Vec<u8> {
        let mut f = Vec::new();
        // Ethernet header: dst mac, src mac, ethertype IPv4 (0x0800)
        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 1]);
        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 2]);
        f.extend_from_slice(&[0x08, 0x00]);
        // IPv4 header (20 bytes)
        let ip_total_len = (20 + 8u16).to_be_bytes(); // IP header + UDP header
        f.extend_from_slice(&[0x45, 0x00]);
        f.extend_from_slice(&ip_total_len);
        f.extend_from_slice(&[0, 0, 0, 0]); // id, flags/frag
        f.push(64); // ttl
        f.push(17); // protocol = UDP
        f.extend_from_slice(&[0, 0]); // checksum
        f.extend_from_slice(&[192, 168, 0, 1]); // src ip
        f.extend_from_slice(&[192, 168, 0, 2]); // dst ip
        // UDP header (8 bytes)
        f.extend_from_slice(&src_port.to_be_bytes());
        f.extend_from_slice(&dst_port.to_be_bytes());
        f.extend_from_slice(&8u16.to_be_bytes()); // length
        f.extend_from_slice(&[0, 0]); // checksum
        f
    }

    fn parse(frame: &[u8]) -> ParsedPacket {
        PacketParser::new()
            .parse_packet(frame)
            .expect("frame should parse")
    }

    fn tcp_packet(syn: bool, ack: bool, fin: bool, rst: bool, is_outgoing: bool) -> ParsedPacket {
        use crate::network::protocol::tcp::{TcpFlags, TcpHeaderInfo};
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_tcp(
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2)), 443),
            TcpHeaderInfo {
                seq: 1_000,
                ack: 2_000,
                window: 65_535,
                flags: TcpFlags { syn, ack, fin, rst },
                payload_len: 0,
                window_scale: None,
            },
        );
        packet.is_outgoing = is_outgoing;
        packet.packet_len = 60;
        packet
    }

    fn quic_packet(packet_type: QuicPacketType, is_outgoing: bool) -> ParsedPacket {
        use crate::network::types::QuicInfo;
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut quic = QuicInfo::new(1);
        quic.packet_type = packet_type;

        let mut packet = ParsedPacket::test_udp(
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2)), 443),
            ApplicationProtocol::Quic(Box::new(quic)),
        );
        packet.is_outgoing = is_outgoing;
        packet.packet_len = 1_200;
        packet
    }

    fn dns_packet(txid: u16, is_outgoing: bool, is_response: bool, rcode: u8) -> ParsedPacket {
        use crate::network::types::{DnsInfo, DnsQueryType};
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_udp(
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2)), 53),
            ApplicationProtocol::Dns(DnsInfo {
                query_name: Some("example.com".to_string()),
                query_type: Some(DnsQueryType::A),
                response_ips: Vec::new(),
                is_response,
                txid,
                rcode: is_response.then_some(rcode),
                nodata: None,
            }),
        );
        packet.is_outgoing = is_outgoing;
        packet.packet_len = 80;
        packet
    }

    fn llmnr_packet(
        txid: u16,
        is_outgoing: bool,
        is_response: bool,
        remote_ip: [u8; 4],
    ) -> ParsedPacket {
        use crate::network::types::{AddrKind, DnsQueryType, LlmnrInfo};
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_udp(
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::from(remote_ip)), 5355),
            ApplicationProtocol::Llmnr(LlmnrInfo {
                query_name: Some("workstation".to_string()),
                query_type: Some(DnsQueryType::A),
                is_response,
                response_ips: Vec::new(),
                txid,
            }),
        );
        if remote_ip == [224, 0, 0, 252] {
            packet.remote_addr_kind = AddrKind::Multicast;
        }
        packet.is_outgoing = is_outgoing;
        packet.packet_len = 80;
        packet
    }

    /// An outgoing plain UDP packet (no DPI classification) to
    /// 203.0.113.80:9999, the flow the attribution tests try to name.
    fn plain_udp_packet() -> ParsedPacket {
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_base(
            Protocol::Udp,
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 80)), 9_999),
            ProtocolState::Udp,
        );
        packet.is_outgoing = true;
        packet.packet_len = 60;
        packet
    }

    /// An incoming DNS response answering `query_name` with `response_ips`,
    /// as the passive attribution path sees it.
    fn dns_answer_packet(
        txid: u16,
        query_name: &str,
        response_ips: &[std::net::IpAddr],
    ) -> ParsedPacket {
        use crate::network::types::{DnsInfo, DnsQueryType};
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_udp(
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2)), 53),
            ApplicationProtocol::Dns(DnsInfo {
                query_name: Some(query_name.to_string()),
                query_type: Some(DnsQueryType::A),
                response_ips: response_ips.to_vec(),
                is_response: true,
                txid,
                rcode: Some(0),
                nodata: Some(false),
            }),
        );
        packet.is_outgoing = false;
        packet.packet_len = 120;
        packet
    }

    fn netbios_packet(
        transaction_id: u16,
        is_outgoing: bool,
        opcode: NetBiosOpcode,
        is_response: bool,
        remote_ip: [u8; 4],
    ) -> ParsedPacket {
        use crate::network::types::{AddrKind, NetBiosInfo, NetBiosResponseStatus, NetBiosService};
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_udp(
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 137),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::from(remote_ip)), 137),
            ApplicationProtocol::NetBios(NetBiosInfo {
                service: NetBiosService::NameService,
                opcode,
                name: Some("FILESERVER".to_string()),
                transaction_id,
                is_response,
                response_status: is_response.then_some(NetBiosResponseStatus::NameService(0)),
            }),
        );
        if remote_ip == [255, 255, 255, 255] {
            packet.remote_addr_kind = AddrKind::Broadcast;
        }
        packet.is_outgoing = is_outgoing;
        packet.packet_len = 80;
        packet
    }

    fn icmp_echo_packet(
        identifier: u16,
        sequence: u16,
        is_outgoing: bool,
        is_reply: bool,
    ) -> ParsedPacket {
        use crate::network::types::ProtocolState;
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_base(
            Protocol::Icmp,
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 0),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), 0),
            ProtocolState::Icmp {
                icmp_type: if is_reply { 0 } else { 8 },
                icmp_id: Some(identifier),
                icmp_sequence: Some(sequence),
                ndp_neighbor: None,
            },
        );
        packet.is_outgoing = is_outgoing;
        packet.packet_len = 84;
        packet
    }

    /// Capture time for a packet `millis` into a synthetic trace. Tests drive
    /// `ingest_at` with these rather than the wall clock so an RTT assertion
    /// pins a real duration instead of however long the test loop took.
    fn capture_time(millis: u64) -> SystemTime {
        SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000) + Duration::from_millis(millis)
    }

    fn arp_packet(operation: crate::network::types::ArpOperation) -> ParsedPacket {
        use crate::network::types::{ArpInfo, ProtocolState};
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_base(
            Protocol::Arp,
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 132)), 0),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 0),
            ProtocolState::Arp(ArpInfo {
                operation,
                sender_mac: "04:d9:f5:c5:ed:e8".to_string(),
                sender_ip: IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)),
                target_mac: "68:5e:dd:09:15:5e".to_string(),
                target_ip: IpAddr::V4(Ipv4Addr::new(192, 168, 0, 132)),
                sender_vendor: Some("ASUSTek COMPUTER INC.".to_string()),
                target_vendor: Some("Apple, Inc.".to_string()),
            }),
        );
        packet.packet_len = 42;
        packet
    }

    /// Ingesting an ARP reply must populate the neighbor cache for both the
    /// answering host and the requester, and the mapping must outlive the ARP
    /// connection row itself.
    #[test]
    fn arp_ingest_learns_neighbors() {
        use crate::network::types::ArpOperation;
        use std::net::{IpAddr, Ipv4Addr};

        let tracker = ConnectionTracker::new();
        let gateway = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1));
        let laptop = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 132));
        assert!(tracker.neighbor(&gateway).is_none());

        let outcome = tracker.ingest_at(&arp_packet(ArpOperation::Reply), capture_time(0));

        let entry = tracker.neighbor(&gateway).expect("gateway learned");
        assert_eq!(entry.mac, "04:d9:f5:c5:ed:e8");
        assert_eq!(entry.vendor.as_deref(), Some("ASUSTek COMPUTER INC."));
        assert_eq!(
            tracker.neighbor(&laptop).expect("requester learned").mac,
            "68:5e:dd:09:15:5e"
        );

        // The mapping survives removal of the ARP connection entry.
        tracker.connections().remove(&outcome.key);
        assert!(tracker.neighbor(&gateway).is_some());
    }

    /// A full Ethernet+IPv6 frame carrying an NDP neighbor advertisement,
    /// so the test exercises the parser's hop-limit gate end to end.
    fn ndp_advertisement_frame(hop_limit: u8) -> Vec<u8> {
        let mut f = Vec::new();
        // Ethernet header: dst mac, src mac, ethertype IPv6 (0x86dd)
        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 1]);
        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 2]);
        f.extend_from_slice(&[0x86, 0xdd]);
        // IPv6 header (40 bytes)
        f.extend_from_slice(&[0x60, 0, 0, 0]); // version/tc/flow
        f.extend_from_slice(&32u16.to_be_bytes()); // payload length
        f.push(58); // next header = ICMPv6
        f.push(hop_limit);
        let src: std::net::Ipv6Addr = "fe80::cafe".parse().unwrap();
        let dst: std::net::Ipv6Addr = "ff02::1".parse().unwrap();
        f.extend_from_slice(&src.octets());
        f.extend_from_slice(&dst.octets());
        // ICMPv6 neighbor advertisement: header, target address, then the
        // target link-layer address option.
        f.extend_from_slice(&[136, 0, 0, 0, 0x20, 0, 0, 0]); // override flag
        let target: std::net::Ipv6Addr = "2001:db8::10".parse().unwrap();
        f.extend_from_slice(&target.octets());
        f.extend_from_slice(&[2, 1, 0x68, 0x5e, 0xdd, 0x09, 0x15, 0x5e]);
        f
    }

    /// Ingesting an NDP neighbor advertisement must populate the neighbor
    /// cache for the advertised target address, but only when the frame
    /// arrived with hop limit 255, which proves it was not routed (RFC 4861).
    #[test]
    fn ndp_ingest_learns_advertised_target_at_hop_limit_255_only() {
        let target: std::net::IpAddr = "2001:db8::10".parse().unwrap();

        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&parse(&ndp_advertisement_frame(255)), capture_time(0));
        assert_eq!(
            tracker.neighbor(&target).expect("target learned").mac,
            "68:5e:dd:09:15:5e"
        );

        let routed = ConnectionTracker::new();
        routed.ingest_at(&parse(&ndp_advertisement_frame(64)), capture_time(0));
        assert!(routed.neighbor(&target).is_none());
    }

    /// QUIC's handshake is the only round trip an on-path observer can time,
    /// so the client Initial and the server's reply must pair up into the
    /// connection's initial RTT the way SYN/SYN-ACK does for TCP.
    ///
    /// The RTT must come from the packets' capture timestamps. Capture hands
    /// packets to processing in batches spanning up to 100 packets or 100ms, so
    /// a handshake this quick is processed as one microseconds-wide burst; a
    /// tracker that read its own clock would report 0.0ms here.
    #[test]
    fn quic_handshake_exchange_measures_initial_rtt() {
        let tracker = ConnectionTracker::new();

        let client_initial =
            tracker.ingest_at(&quic_packet(QuicPacketType::Initial, true), capture_time(0));
        assert!(
            client_initial.measured_rtt.is_none(),
            "the opening Initial has nothing to pair with yet"
        );

        let server_initial = tracker.ingest_at(
            &quic_packet(QuicPacketType::Initial, false),
            capture_time(18),
        );
        assert_eq!(
            server_initial.measured_rtt,
            Some(Duration::from_millis(18)),
            "the RTT is the gap between the two capture timestamps"
        );
        assert_eq!(
            tracker
                .connections()
                .get(&server_initial.key)
                .and_then(|conn| conn.initial_rtt),
            Some(Duration::from_millis(18)),
            "the measured RTT should land on the connection"
        );
    }

    /// A repeated client Initial is a retransmission, not a reply, so it must
    /// not be read as a completed round trip.
    #[test]
    fn repeated_quic_initial_in_one_direction_measures_nothing() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&quic_packet(QuicPacketType::Initial, true), capture_time(0));
        let retransmit = tracker.ingest_at(
            &quic_packet(QuicPacketType::Initial, true),
            capture_time(250),
        );
        assert!(retransmit.measured_rtt.is_none());
        assert!(
            tracker
                .connections()
                .get(&retransmit.key)
                .and_then(|conn| conn.initial_rtt)
                .is_none()
        );
    }

    #[test]
    fn quic_retry_and_version_negotiation_packets_are_counted() {
        let tracker = ConnectionTracker::new();
        let retry = tracker.ingest_at(&quic_packet(QuicPacketType::Retry, false), capture_time(0));
        tracker.ingest_at(
            &quic_packet(QuicPacketType::VersionNegotiation, false),
            capture_time(1),
        );

        let conn = tracker.connections().get(&retry.key).unwrap().clone();
        assert_eq!(conn.protocol_health.quic_retry_count, 1);
        assert_eq!(conn.protocol_health.quic_version_negotiation_count, 1);
    }

    /// rustnet watches from an endpoint, so an arriving packet followed by this
    /// host's own answer spans no network at all; it times the local stack's
    /// turnaround. Only an outbound packet may start the clock.
    ///
    /// A server's first flight is several datagrams, so this ordering shows up
    /// on ordinary connections once the first datagram has been paired off.
    #[test]
    fn inbound_quic_handshake_packet_does_not_start_the_clock() {
        let tracker = ConnectionTracker::new();

        tracker.ingest_at(
            &quic_packet(QuicPacketType::Handshake, false),
            capture_time(0),
        );
        let local_reply = tracker.ingest_at(
            &quic_packet(QuicPacketType::Handshake, true),
            capture_time(1),
        );
        assert!(
            local_reply.measured_rtt.is_none(),
            "this host's own turnaround is not a round trip"
        );
        assert!(
            tracker
                .connections()
                .get(&local_reply.key)
                .and_then(|conn| conn.initial_rtt)
                .is_none()
        );
    }

    /// Once the client Initial has been paired with the server's first
    /// datagram, the rest of the server's flight must not overwrite the real
    /// measurement with a local-turnaround one.
    #[test]
    fn later_server_flight_does_not_replace_the_handshake_rtt() {
        let tracker = ConnectionTracker::new();

        tracker.ingest_at(&quic_packet(QuicPacketType::Initial, true), capture_time(0));
        tracker.ingest_at(
            &quic_packet(QuicPacketType::Initial, false),
            capture_time(18),
        );

        // Remainder of the server's first flight, then this host's ACK.
        tracker.ingest_at(
            &quic_packet(QuicPacketType::Handshake, false),
            capture_time(19),
        );
        let ack = tracker.ingest_at(
            &quic_packet(QuicPacketType::Handshake, true),
            capture_time(19),
        );
        assert!(ack.measured_rtt.is_none());

        assert_eq!(
            tracker
                .connections()
                .get(&ack.key)
                .and_then(|conn| conn.initial_rtt),
            Some(Duration::from_millis(18))
        );
    }

    /// A DNS response pairs with its query by transaction ID, and the delta
    /// between the two capture timestamps lands on the connection. The
    /// transport-level `initial_rtt` must stay untouched: DNS time includes
    /// resolver processing.
    #[test]
    fn dns_query_response_measures_response_time() {
        let tracker = ConnectionTracker::new();

        let query = tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));
        assert!(query.dns_response_time.is_none());

        let response = tracker.ingest_at(&dns_packet(0x1234, false, true, 0), capture_time(35));
        assert_eq!(
            response.dns_response_time,
            Some(Duration::from_millis(35)),
            "the response time is the gap between the two capture timestamps"
        );
        let conn = tracker.connections().get(&response.key).unwrap().clone();
        assert_eq!(conn.dns_response_time, Some(Duration::from_millis(35)));
        let analytics = tracker.dns_analytics_snapshot_at(capture_time(35));
        assert_eq!(analytics.lookups, 1);
        assert_eq!(analytics.answered, 1);
        assert_eq!(analytics.noerror, 1);
        assert_eq!(analytics.latency_p95, Some(Duration::from_millis(35)));
        assert!(
            conn.initial_rtt.is_none(),
            "DNS timing must not pollute the transport RTT"
        );
    }

    /// A response whose transaction ID matches no pending query (spoofed,
    /// expired, or captured mid-exchange) measures nothing.
    #[test]
    fn dns_response_with_unknown_txid_measures_nothing() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));
        let response = tracker.ingest_at(&dns_packet(0x9999, false, true, 0), capture_time(20));
        assert!(response.dns_response_time.is_none());
        assert!(
            tracker
                .connections()
                .get(&response.key)
                .and_then(|conn| conn.dns_response_time)
                .is_none()
        );
    }

    /// Stub resolvers reuse one socket for many queries, so each completed
    /// exchange refreshes the connection's response time (last wins, unlike
    /// the one-shot `initial_rtt`).
    #[test]
    fn later_dns_exchange_updates_the_response_time() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&dns_packet(1, true, false, 0), capture_time(0));
        tracker.ingest_at(&dns_packet(1, false, true, 0), capture_time(35));
        tracker.ingest_at(&dns_packet(2, true, false, 0), capture_time(1_000));
        let second = tracker.ingest_at(&dns_packet(2, false, true, 0), capture_time(1_012));
        assert_eq!(second.dns_response_time, Some(Duration::from_millis(12)));
        assert_eq!(
            tracker
                .connections()
                .get(&second.key)
                .and_then(|conn| conn.dns_response_time),
            Some(Duration::from_millis(12))
        );
    }

    /// When the local host is the DNS server, the inbound query followed by
    /// our own answer times the local resolver's turnaround, not the network,
    /// so it must measure nothing (mirrors the QUIC direction rule).
    #[test]
    fn local_dns_server_role_measures_nothing() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&dns_packet(0x1234, false, false, 0), capture_time(0));
        let reply = tracker.ingest_at(&dns_packet(0x1234, true, true, 0), capture_time(1));
        assert!(reply.dns_response_time.is_none());
    }

    /// A re-sent query restarts the timer from the most recent send, so the
    /// measurement reflects the answered attempt, not the retry wait.
    #[test]
    fn retransmitted_dns_query_measures_from_the_last_send() {
        let tracker = ConnectionTracker::new();
        let query = tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));
        tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(1_000));
        let response = tracker.ingest_at(&dns_packet(0x1234, false, true, 0), capture_time(1_018));
        assert_eq!(response.dns_response_time, Some(Duration::from_millis(18)));

        let conn = tracker.connections().get(&query.key).unwrap().clone();
        assert!(conn.protocol_health.request_observed);
        assert_eq!(conn.protocol_health.request_retry_count, 1);
        assert_eq!(conn.protocol_health.request_timeout_count, 0);
    }

    #[test]
    fn unanswered_dns_query_is_counted_as_a_timeout() {
        let tracker = ConnectionTracker::new();
        let query = tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));

        tracker.cleanup(capture_time(10_001));

        let conn = tracker.connections().get(&query.key).unwrap().clone();
        assert!(conn.protocol_health.request_observed);
        assert_eq!(conn.protocol_health.request_retry_count, 0);
        assert_eq!(conn.protocol_health.request_timeout_count, 1);
    }

    /// SERVFAIL is still an answer: the round trip completed, so it is a valid
    /// timing sample. The response code is surfaced separately in the UI.
    #[test]
    fn dns_servfail_response_still_measures_response_time() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));
        let response = tracker.ingest_at(&dns_packet(0x1234, false, true, 2), capture_time(40));
        assert_eq!(response.dns_response_time, Some(Duration::from_millis(40)));
    }

    /// LLMNR sends a query to the link-local multicast group, then each
    /// responder replies via unicast. The first reply should time the lookup
    /// even though it belongs to a different connection-table key, and that
    /// timing should be visible from both rows.
    #[test]
    fn llmnr_multicast_query_measures_first_unicast_response_time() {
        let tracker = ConnectionTracker::new();
        let query = tracker.ingest_at(
            &llmnr_packet(0x1234, true, false, [224, 0, 0, 252]),
            capture_time(0),
        );
        assert!(query.llmnr_response_time.is_none());

        let response = tracker.ingest_at(
            &llmnr_packet(0x1234, false, true, [192, 168, 0, 20]),
            capture_time(27),
        );
        assert_ne!(query.key, response.key);
        assert_eq!(
            response.llmnr_response_time,
            Some(Duration::from_millis(27))
        );

        let response_conn = tracker.connections().get(&response.key).unwrap().clone();
        assert_eq!(
            response_conn.llmnr_response_time,
            Some(Duration::from_millis(27))
        );
        assert!(response_conn.initial_rtt.is_none());

        let query_conn = tracker.connections().get(&query.key).unwrap().clone();
        assert_eq!(
            query_conn.llmnr_response_time,
            Some(Duration::from_millis(27))
        );

        let second_response = tracker.ingest_at(
            &llmnr_packet(0x1234, false, true, [192, 168, 0, 21]),
            capture_time(35),
        );
        assert!(second_response.llmnr_response_time.is_none());
        assert!(
            tracker
                .connections()
                .get(&second_response.key)
                .and_then(|conn| conn.llmnr_response_time)
                .is_none()
        );
    }

    #[test]
    fn llmnr_response_with_unknown_transaction_id_measures_nothing() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(
            &llmnr_packet(0x1234, true, false, [224, 0, 0, 252]),
            capture_time(0),
        );
        let response = tracker.ingest_at(
            &llmnr_packet(0x9999, false, true, [192, 168, 0, 20]),
            capture_time(27),
        );
        assert!(response.llmnr_response_time.is_none());
    }

    /// Name Service requests are normally broadcast, then answered from a
    /// host's unicast address. The transaction still pairs even though the
    /// request and response belong to different connection-table keys.
    #[test]
    fn netbios_broadcast_request_measures_unicast_response_time() {
        let tracker = ConnectionTracker::new();
        let query = tracker.ingest_at(
            &netbios_packet(
                0x1234,
                true,
                NetBiosOpcode::Query,
                false,
                [255, 255, 255, 255],
            ),
            capture_time(0),
        );
        assert!(query.netbios_response_time.is_none());

        let response = tracker.ingest_at(
            &netbios_packet(
                0x1234,
                false,
                NetBiosOpcode::Response,
                true,
                [192, 168, 0, 20],
            ),
            capture_time(27),
        );
        assert_ne!(query.key, response.key);
        assert_eq!(
            response.netbios_response_time,
            Some(Duration::from_millis(27))
        );
        let conn = tracker.connections().get(&response.key).unwrap().clone();
        assert_eq!(conn.netbios_response_time, Some(Duration::from_millis(27)));
        assert!(conn.initial_rtt.is_none());

        // The broadcast row is the one a user naturally inspects, so the
        // round trip must land there as well, not only on the responder.
        let query_conn = tracker.connections().get(&query.key).unwrap().clone();
        assert_eq!(
            query_conn.netbios_response_time,
            Some(Duration::from_millis(27))
        );
    }

    #[test]
    fn netbios_response_with_unknown_transaction_id_measures_nothing() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(
            &netbios_packet(
                0x1234,
                true,
                NetBiosOpcode::Query,
                false,
                [255, 255, 255, 255],
            ),
            capture_time(0),
        );
        let response = tracker.ingest_at(
            &netbios_packet(
                0x9999,
                false,
                NetBiosOpcode::Response,
                true,
                [192, 168, 0, 20],
            ),
            capture_time(27),
        );
        assert!(response.netbios_response_time.is_none());
    }

    /// A WACK extends an NBNS transaction and must not consume its pending
    /// request. The eventual final response completes the original timing.
    #[test]
    fn netbios_wack_keeps_request_pending() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(
            &netbios_packet(
                0x1234,
                true,
                NetBiosOpcode::Registration,
                false,
                [192, 168, 0, 2],
            ),
            capture_time(0),
        );
        let wack = tracker.ingest_at(
            &netbios_packet(0x1234, false, NetBiosOpcode::Wack, false, [192, 168, 0, 2]),
            capture_time(10),
        );
        assert!(wack.netbios_response_time.is_none());

        let response = tracker.ingest_at(
            &netbios_packet(
                0x1234,
                false,
                NetBiosOpcode::Response,
                true,
                [192, 168, 0, 2],
            ),
            capture_time(40),
        );
        assert_eq!(
            response.netbios_response_time,
            Some(Duration::from_millis(40))
        );
    }

    /// Subsecond ping intervals can leave several requests outstanding. The
    /// sequence number keeps each reply attached to its own send timestamp,
    /// even when replies complete out of order.
    #[test]
    fn fast_ping_pairs_each_echo_by_identifier_and_sequence() {
        let tracker = ConnectionTracker::new();

        tracker.ingest_at(&icmp_echo_packet(0x1234, 1, true, false), capture_time(0));
        tracker.ingest_at(&icmp_echo_packet(0x1234, 2, true, false), capture_time(200));
        let second_reply =
            tracker.ingest_at(&icmp_echo_packet(0x1234, 2, false, true), capture_time(225));
        let first_reply =
            tracker.ingest_at(&icmp_echo_packet(0x1234, 1, false, true), capture_time(350));

        assert_eq!(second_reply.icmp_echo_rtt, Some(Duration::from_millis(25)));
        assert_eq!(first_reply.icmp_echo_rtt, Some(Duration::from_millis(350)));

        tracker.ingest_at(&icmp_echo_packet(0x1234, 3, true, false), capture_time(400));
        let third_reply =
            tracker.ingest_at(&icmp_echo_packet(0x1234, 3, false, true), capture_time(418));
        let conn = tracker
            .connections()
            .get(&third_reply.key)
            .expect("ping connection should exist")
            .clone();
        assert_eq!(third_reply.icmp_echo_rtt, Some(Duration::from_millis(18)));
        assert_eq!(conn.icmp_echo_rtt, Some(Duration::from_millis(18)));
        assert_eq!(conn.current_rtt(), Some(Duration::from_millis(18)));
    }

    #[test]
    fn echo_reply_with_unknown_sequence_measures_nothing() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&icmp_echo_packet(7, 10, true, false), capture_time(0));
        let reply = tracker.ingest_at(&icmp_echo_packet(7, 11, false, true), capture_time(12));

        assert!(reply.icmp_echo_rtt.is_none());
        assert!(
            tracker
                .connections()
                .get(&reply.key)
                .and_then(|conn| conn.icmp_echo_rtt)
                .is_none()
        );
    }

    #[test]
    fn local_echo_responder_turnaround_measures_nothing() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&icmp_echo_packet(7, 1, false, false), capture_time(0));
        let reply = tracker.ingest_at(&icmp_echo_packet(7, 1, true, true), capture_time(1));

        assert!(reply.icmp_echo_rtt.is_none());
    }

    fn loopback_echo_packet(identifier: u16, sequence: u16, is_reply: bool) -> ParsedPacket {
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = icmp_echo_packet(identifier, sequence, true, is_reply);
        let loopback = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
        packet.local_addr = loopback;
        packet.remote_addr = loopback;
        packet
    }

    /// Loopback captures classify both the request and its reply as outgoing
    /// because both endpoints are local. The reply must still pair up.
    #[test]
    fn loopback_ping_measures_rtt() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&loopback_echo_packet(9, 1, false), capture_time(0));
        let reply = tracker.ingest_at(&loopback_echo_packet(9, 1, true), capture_time(1));

        assert_eq!(reply.icmp_echo_rtt, Some(Duration::from_millis(1)));
    }

    /// Echo requests reveal who initiated the flow; the Details tab uses the
    /// direction to hide the RTT row on flows this host only answers.
    #[test]
    fn echo_request_sets_connection_direction() {
        let tracker = ConnectionTracker::new();
        let outgoing = tracker.ingest_at(&icmp_echo_packet(7, 1, true, false), capture_time(0));
        let direction = tracker
            .connections()
            .get(&outgoing.key)
            .and_then(|conn| conn.connection_direction);
        assert_eq!(direction, Some(true));

        let tracker = ConnectionTracker::new();
        let inbound = tracker.ingest_at(&icmp_echo_packet(7, 1, false, false), capture_time(0));
        tracker.ingest_at(&icmp_echo_packet(7, 1, true, true), capture_time(1));
        let direction = tracker
            .connections()
            .get(&inbound.key)
            .and_then(|conn| conn.connection_direction);
        assert_eq!(direction, Some(false), "our reply must not flip it");
    }

    fn stun_packet(
        transaction_id: [u8; 12],
        is_outgoing: bool,
        class: crate::network::types::StunMessageClass,
    ) -> ParsedPacket {
        use crate::network::types::{StunInfo, StunMethod};
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_udp(
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 54_000),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 5)), 3478),
            ApplicationProtocol::Stun(StunInfo {
                message_class: class,
                method: StunMethod::Binding,
                transaction_id,
                software: None,
            }),
        );
        packet.is_outgoing = is_outgoing;
        packet.packet_len = 48;
        packet
    }

    /// STUN binding requests and responses pair by transaction ID, giving a
    /// UDP flow with no handshake a real request→response time.
    #[test]
    fn stun_binding_response_measures_rtt() {
        use crate::network::types::StunMessageClass;

        let tracker = ConnectionTracker::new();
        let txid = [3u8; 12];
        tracker.ingest_at(
            &stun_packet(txid, true, StunMessageClass::Request),
            capture_time(0),
        );
        let response = tracker.ingest_at(
            &stun_packet(txid, false, StunMessageClass::SuccessResponse),
            capture_time(31),
        );

        assert_eq!(response.stun_rtt, Some(Duration::from_millis(31)));
        let conn = tracker
            .connections()
            .get(&response.key)
            .expect("STUN connection should exist")
            .clone();
        assert_eq!(conn.stun_rtt, Some(Duration::from_millis(31)));
    }

    fn ntp_packet(
        mode: crate::network::types::NtpMode,
        is_outgoing: bool,
        origin_timestamp: u64,
        transmit_timestamp: u64,
    ) -> ParsedPacket {
        use crate::network::types::NtpInfo;
        use std::net::{IpAddr, Ipv4Addr, SocketAddr};

        let mut packet = ParsedPacket::test_udp(
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 47_000),
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 9)), 123),
            ApplicationProtocol::Ntp(NtpInfo {
                version: 4,
                mode,
                stratum: 2,
                origin_timestamp,
                transmit_timestamp,
            }),
        );
        packet.is_outgoing = is_outgoing;
        packet.packet_len = 90;
        packet
    }

    /// An NTP poll pairs with its response through the originate timestamp
    /// echo, giving the UDP flow a request→response time.
    #[test]
    fn ntp_server_response_measures_rtt() {
        use crate::network::types::NtpMode;

        let tracker = ConnectionTracker::new();
        tracker.ingest_at(
            &ntp_packet(NtpMode::Client, true, 0, 0xAABB),
            capture_time(0),
        );
        let response = tracker.ingest_at(
            &ntp_packet(NtpMode::Server, false, 0xAABB, 0xCCDD),
            capture_time(21),
        );

        assert_eq!(response.ntp_rtt, Some(Duration::from_millis(21)));
        let conn = tracker
            .connections()
            .get(&response.key)
            .expect("NTP connection should exist")
            .clone();
        assert_eq!(conn.ntp_rtt, Some(Duration::from_millis(21)));
    }

    #[test]
    fn stun_response_with_unknown_transaction_measures_nothing() {
        use crate::network::types::StunMessageClass;

        let tracker = ConnectionTracker::new();
        tracker.ingest_at(
            &stun_packet([3u8; 12], true, StunMessageClass::Request),
            capture_time(0),
        );
        let response = tracker.ingest_at(
            &stun_packet([4u8; 12], false, StunMessageClass::SuccessResponse),
            capture_time(31),
        );

        assert!(response.stun_rtt.is_none());
    }

    /// 1-RTT packets carry a short header with nothing timeable in the clear.
    #[test]
    fn quic_one_rtt_packets_do_not_measure_rtt() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(&quic_packet(QuicPacketType::OneRtt, true), capture_time(0));
        let inbound = tracker.ingest_at(
            &quic_packet(QuicPacketType::OneRtt, false),
            capture_time(18),
        );
        assert!(inbound.measured_rtt.is_none());
    }

    /// The TCP handshake is timed from capture timestamps for the same reason
    /// the QUIC one is: SYN and SYN-ACK routinely land in a single batch.
    #[test]
    fn tcp_handshake_rtt_comes_from_capture_timestamps() {
        let tracker = ConnectionTracker::new();

        tracker.ingest_at(
            &tcp_packet(true, false, false, false, true),
            capture_time(0),
        );
        let syn_ack = tracker.ingest_at(
            &tcp_packet(true, true, false, false, false),
            capture_time(12),
        );
        assert_eq!(syn_ack.measured_rtt, Some(Duration::from_millis(12)));
    }

    #[test]
    fn ingest_creates_then_updates() {
        let tracker = ConnectionTracker::new();
        let p = parse(&udp_frame(40000, 53));

        let first = tracker.ingest(&p);
        assert!(first.created, "first packet should create a connection");
        assert!(!first.dropped);
        assert_eq!(tracker.connections().len(), 1);

        let second = tracker.ingest(&p);
        assert!(!second.created, "second packet should update, not create");
        assert_eq!(second.key, first.key);
        assert_eq!(tracker.connections().len(), 1);
    }

    #[test]
    fn distinct_flows_are_separate_connections() {
        let tracker = ConnectionTracker::new();
        tracker.ingest(&parse(&udp_frame(40000, 53)));
        tracker.ingest(&parse(&udp_frame(40001, 53)));
        assert_eq!(tracker.connections().len(), 2);
    }

    #[test]
    fn concurrent_existing_flow_updates_preserve_counters_at_connection_limit() {
        let tracker = ConnectionTracker::with_config(TrackerConfig {
            max_connections: 1,
            ..TrackerConfig::default()
        });
        let packet = parse(&udp_frame(40000, 9999));
        let first = tracker.ingest_at(&packet, capture_time(0));
        let barrier = std::sync::Barrier::new(4);

        std::thread::scope(|scope| {
            for _ in 0..4 {
                scope.spawn(|| {
                    barrier.wait();
                    for _ in 0..1_000 {
                        let outcome = tracker.ingest_at(&packet, capture_time(1));
                        assert!(!outcome.created);
                        assert!(!outcome.dropped);
                        assert!(!outcome.ignored_late);
                        assert!(outcome.archived.is_none());
                        assert_eq!(outcome.key, first.key);
                    }
                });
            }
        });

        let conn = tracker.connections.get(&first.key).unwrap();
        assert_eq!(conn.packets_sent + conn.packets_received, 4_001);
        assert_eq!(
            conn.bytes_sent + conn.bytes_received,
            4_001 * packet.packet_len as u64
        );
        drop(conn);
        assert_eq!(tracker.active_count.load(Ordering::Relaxed), 1);
        assert!(tracker.ingest(&parse(&udp_frame(40001, 9999))).dropped);
    }

    #[test]
    fn existing_terminal_generation_can_be_replaced_at_connection_limit() {
        let tracker = ConnectionTracker::with_config(TrackerConfig {
            max_connections: 1,
            ..TrackerConfig::default()
        });
        let first = tracker.ingest_at(
            &tcp_packet(false, false, false, true, true),
            capture_time(0),
        );
        let replacement = tracker.ingest_at(
            &tcp_packet(true, false, false, false, true),
            capture_time(1),
        );
        assert_eq!(replacement.key, first.key);
        assert!(replacement.created);
        assert!(!replacement.dropped);
        assert!(replacement.archived.is_some());
        assert_eq!(tracker.active_count.load(Ordering::Relaxed), 1);
        assert_eq!(tracker.connections().len(), 1);
        assert_eq!(tracker.historic_len(), 1);

        let update = tracker.ingest_at(
            &tcp_packet(false, true, false, false, true),
            capture_time(2),
        );
        assert!(!update.created);
        assert!(!update.dropped);
        assert!(!update.ignored_late);
        assert!(update.archived.is_none());
        let conn = tracker.connections.get(&first.key).unwrap();
        assert_eq!(conn.packets_sent + conn.packets_received, 2);
    }

    #[test]
    fn existing_flow_updates_publish_tcp_deltas_and_data_rtt() {
        let tracker = ConnectionTracker::new();
        tracker.ingest_at(
            &tcp_packet(false, true, false, false, true),
            capture_time(0),
        );
        let mut data = tcp_packet(false, true, false, false, true);
        data.tcp_header.as_mut().unwrap().payload_len = 100;
        let sent = tracker.ingest_at(&data, capture_time(10));
        assert!(!sent.created);
        assert_eq!(sent.retransmits, 0);

        let mut ack = tcp_packet(false, true, false, false, false);
        ack.tcp_header.as_mut().unwrap().ack = 1_100;
        tracker.ingest_at(&ack, capture_time(35));
        assert_eq!(tracker.take_average_rtt(60), Some(25.0));

        let retransmit = tracker.ingest_at(&data, capture_time(40));
        assert!(!retransmit.created);
        assert_eq!(retransmit.retransmits, 1);
        let conn = tracker.connections.get(&sent.key).unwrap();
        assert_eq!(conn.packets_sent + conn.packets_received, 4);
    }

    #[test]
    fn max_connections_limit_drops_new_only() {
        let tracker = ConnectionTracker::with_config(TrackerConfig {
            max_connections: 1,
            ..TrackerConfig::default()
        });
        let a = tracker.ingest(&parse(&udp_frame(40000, 53)));
        assert!(a.created && !a.dropped);

        // A different flow can't be inserted (limit reached) and is dropped.
        let b = tracker.ingest(&parse(&udp_frame(40001, 53)));
        assert!(b.dropped, "new connection beyond the limit must be dropped");
        assert!(!b.created);
        assert_eq!(tracker.connections().len(), 1);

        // The existing flow still updates despite the limit.
        let a2 = tracker.ingest(&parse(&udp_frame(40000, 53)));
        assert!(!a2.dropped && !a2.created);
    }

    #[test]
    fn connection_limit_recovers_after_cleanup() {
        let tracker = ConnectionTracker::with_config(TrackerConfig {
            max_connections: 1,
            ..TrackerConfig::default()
        });
        assert!(tracker.ingest(&parse(&udp_frame(40000, 53))).created);
        assert!(tracker.ingest(&parse(&udp_frame(40001, 53))).dropped);

        // Expire everything; the limit accounting must follow the removals.
        tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
        assert_eq!(tracker.connections().len(), 0);

        let c = tracker.ingest(&parse(&udp_frame(40002, 53)));
        assert!(
            c.created && !c.dropped,
            "slot freed by cleanup must be reusable"
        );
        assert_eq!(tracker.connections().len(), 1);
    }

    #[test]
    fn connection_limit_recovers_after_clear() {
        let tracker = ConnectionTracker::with_config(TrackerConfig {
            max_connections: 1,
            ..TrackerConfig::default()
        });
        assert!(tracker.ingest(&parse(&udp_frame(40000, 53))).created);
        tracker.clear();
        let b = tracker.ingest(&parse(&udp_frame(40001, 53)));
        assert!(b.created && !b.dropped, "clear() must reset the limit");
    }

    #[test]
    fn cleanup_archives_to_historic() {
        let tracker = ConnectionTracker::new();
        tracker.ingest(&parse(&udp_frame(40000, 53)));
        assert_eq!(tracker.connections().len(), 1);

        for mut entry in tracker.connections().iter_mut() {
            entry.current_incoming_rate_bps = 2048.0;
            entry.current_outgoing_rate_bps = 1024.0;
        }

        // A far-future `now` forces every connection past its timeout.
        let far_future = SystemTime::now() + Duration::from_secs(86_400);
        let removed = tracker.cleanup(far_future);

        assert_eq!(removed.len(), 1, "the idle connection should be removed");
        assert!(!removed[0].is_historic, "returned form is the original");
        assert_eq!(tracker.connections().len(), 0);
        assert_eq!(
            tracker.historic_len(),
            1,
            "removed conn archived as historic"
        );
        let historic = tracker.historic().iter().next().unwrap();
        assert_eq!(historic.current_incoming_rate_bps, 0.0);
        assert_eq!(historic.current_outgoing_rate_bps, 0.0);
    }

    #[test]
    fn traffic_refreshes_a_stale_nonterminal_connection() {
        let tracker = ConnectionTracker::new();
        let packet = parse(&udp_frame(40000, 9999));
        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&packet, started);

        assert!(
            tracker
                .cleanup(started + Duration::from_secs(59))
                .is_empty()
        );
        tracker.ingest_at(&packet, started + Duration::from_secs(59));
        assert!(
            tracker
                .cleanup(started + Duration::from_secs(61))
                .is_empty()
        );
        assert_eq!(tracker.connections().len(), 1);
    }

    #[test]
    fn terminal_retransmissions_do_not_postpone_archival() {
        let tracker = ConnectionTracker::new();
        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
        tracker.ingest_at(
            &tcp_packet(false, true, false, false, false),
            started + Duration::from_secs(10),
        );

        let conn = tracker.connections().iter().next().unwrap();
        assert_eq!(conn.last_activity, started + Duration::from_secs(10));
        assert_eq!(conn.terminal_since, Some(started));
        drop(conn);

        let removed = tracker.cleanup(started + Duration::from_secs(16));
        assert_eq!(removed.len(), 1);
        assert_eq!(tracker.historic_len(), 1);
    }

    #[test]
    fn syn_after_terminal_state_starts_a_new_generation() {
        use crate::network::types::{ProtocolState, TcpState};

        let tracker = ConnectionTracker::new();
        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
        for mut entry in tracker.connections().iter_mut() {
            entry.current_incoming_rate_bps = 2048.0;
            entry.current_outgoing_rate_bps = 1024.0;
        }

        let outcome = tracker.ingest_at(&tcp_packet(true, false, false, false, true), started);
        assert!(outcome.created);
        assert!(outcome.archived.is_some());
        assert_eq!(tracker.connections().len(), 1);
        assert_eq!(tracker.historic_len(), 1);

        let active = tracker.connections().iter().next().unwrap();
        assert!(
            active.created_at > started,
            "a same-batch replacement needs a distinct historic identity"
        );
        assert!(matches!(
            active.protocol_state,
            ProtocolState::Tcp(TcpState::SynSent)
        ));
        assert!(!active.is_historic);
        drop(active);

        let historic = tracker.historic().iter().next().unwrap();
        assert_eq!(historic.created_at, started);
        assert!(historic.is_historic);
        assert_eq!(historic.closed_at, Some(started));
        assert_eq!(
            historic.current_incoming_rate_bps, 0.0,
            "a superseded generation is archived with its rates zeroed, like cleanup"
        );
        assert_eq!(historic.current_outgoing_rate_bps, 0.0);
        drop(historic);

        tracker.cleanup(started + Duration::from_secs(61));
        assert_eq!(
            tracker.historic_len(),
            2,
            "archiving the replacement must not overwrite the old generation"
        );
    }

    #[test]
    fn delayed_ack_after_archival_is_not_a_phantom_connection() {
        let tracker = ConnectionTracker::new();
        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
        tracker.cleanup(started + Duration::from_secs(16));

        let outcome = tracker.ingest_at(
            &tcp_packet(false, true, false, false, false),
            started + Duration::from_secs(17),
        );
        assert!(outcome.ignored_late);
        assert!(!outcome.created);
        assert!(tracker.connections().is_empty());
        assert_eq!(tracker.historic_len(), 1);
    }

    #[test]
    fn payload_after_terminal_archival_starts_a_new_generation() {
        let tracker = ConnectionTracker::new();
        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
        tracker.cleanup(started + Duration::from_secs(16));

        let mut packet = tcp_packet(false, true, false, false, false);
        packet.tcp_header.as_mut().unwrap().payload_len = 100;
        let outcome = tracker.ingest_at(&packet, started + Duration::from_secs(17));

        assert!(!outcome.ignored_late);
        assert!(outcome.created);
        assert_eq!(tracker.connections().len(), 1);
        assert_eq!(tracker.historic_len(), 1);
    }

    #[test]
    fn traffic_after_idle_archival_starts_a_new_generation_immediately() {
        let tracker = ConnectionTracker::new();
        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&tcp_packet(false, true, false, false, true), started);
        tracker.cleanup(started + Duration::from_secs(301));

        let outcome = tracker.ingest_at(
            &tcp_packet(false, true, false, false, false),
            started + Duration::from_secs(302),
        );
        assert!(!outcome.ignored_late);
        assert!(outcome.created);
        assert_eq!(tracker.connections().len(), 1);
        assert_eq!(tracker.historic_len(), 1);
    }

    #[test]
    fn midstream_ack_is_allowed_after_recent_tombstone_expires() {
        use crate::network::types::{ProtocolState, TcpState};

        let tracker = ConnectionTracker::new();
        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
        tracker.cleanup(started + Duration::from_secs(16));

        let outcome = tracker.ingest_at(
            &tcp_packet(false, true, false, false, false),
            started + Duration::from_secs(47),
        );
        assert!(!outcome.ignored_late);
        assert!(outcome.created);
        let active = tracker.connections().iter().next().unwrap();
        assert!(matches!(
            active.protocol_state,
            ProtocolState::Tcp(TcpState::Established)
        ));
    }

    #[test]
    fn new_activity_does_not_mutate_a_historic_snapshot() {
        let tracker = ConnectionTracker::new();
        let packet = parse(&udp_frame(40000, 9999));
        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&packet, started);
        tracker.cleanup(started + Duration::from_secs(61));

        let historic_before = tracker.historic.iter().next().unwrap().value().clone();
        tracker.ingest_at(&packet, started + Duration::from_secs(62));
        tracker.ingest_at(&packet, started + Duration::from_secs(63));
        let historic_after = tracker.historic.iter().next().unwrap().value().clone();

        assert_eq!(historic_after.bytes_sent, historic_before.bytes_sent);
        assert_eq!(
            historic_after.bytes_received,
            historic_before.bytes_received
        );
        assert_eq!(historic_after.last_activity, historic_before.last_activity);
        assert_eq!(historic_after.closed_at, historic_before.closed_at);
        assert_eq!(tracker.connections().len(), 1);
    }

    #[test]
    fn retained_source_view_is_atomic_across_cleanup() {
        let tracker = std::sync::Arc::new(ConnectionTracker::new());
        tracker.ingest(&parse(&udp_frame(40000, 53)));

        let (active_scanned_tx, active_scanned_rx) = std::sync::mpsc::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel();
        let reader_tracker = std::sync::Arc::clone(&tracker);
        let reader = std::thread::spawn(move || {
            reader_tracker.with_retained_sources(|active, historic| {
                let active_count = active.iter().count();
                active_scanned_tx.send(()).unwrap();
                release_rx.recv().unwrap();
                active_count + historic.iter().count()
            })
        });

        active_scanned_rx.recv().unwrap();
        let (cleanup_started_tx, cleanup_started_rx) = std::sync::mpsc::channel();
        let (cleanup_done_tx, cleanup_done_rx) = std::sync::mpsc::channel();
        let cleanup_tracker = std::sync::Arc::clone(&tracker);
        let cleanup = std::thread::spawn(move || {
            cleanup_started_tx.send(()).unwrap();
            let removed = cleanup_tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
            cleanup_done_tx.send(removed.len()).unwrap();
        });

        cleanup_started_rx.recv().unwrap();
        assert!(
            cleanup_done_rx
                .recv_timeout(Duration::from_millis(50))
                .is_err(),
            "cleanup must wait for the retained source view"
        );
        release_tx.send(()).unwrap();

        assert_eq!(reader.join().unwrap(), 1);
        assert_eq!(cleanup_done_rx.recv().unwrap(), 1);
        cleanup.join().unwrap();
        assert_eq!(tracker.connections().len(), 0);
        assert_eq!(tracker.historic_len(), 1);
    }

    #[test]
    fn cleanup_without_keep_historic_skips_archive() {
        let tracker = ConnectionTracker::with_config(TrackerConfig {
            keep_historic: false,
            ..TrackerConfig::default()
        });
        tracker.ingest(&parse(&udp_frame(40000, 53)));
        let far_future = SystemTime::now() + Duration::from_secs(86_400);
        let removed = tracker.cleanup(far_future);
        assert_eq!(removed.len(), 1);
        assert_eq!(tracker.historic_len(), 0, "historic disabled");
    }

    /// `max_historic` sizes the user-facing archive; it must not shrink the
    /// tombstone table below the floor, or closing more flows than the cap
    /// lets delayed teardown packets resurrect phantom connections.
    #[test]
    fn zero_max_historic_keeps_tombstones_for_all_closed_flows() {
        let tracker = ConnectionTracker::with_config(TrackerConfig {
            keep_historic: false,
            max_historic: 0,
            ..TrackerConfig::default()
        });

        let start = SystemTime::now();
        for port in [40_000u16, 40_001] {
            let mut syn = tcp_packet(true, false, false, false, true);
            syn.local_addr.set_port(port);
            tracker.ingest_at(&syn, start);
            let mut rst = tcp_packet(false, false, false, true, true);
            rst.local_addr.set_port(port);
            tracker.ingest_at(&rst, start + Duration::from_secs(1));
        }
        assert_eq!(tracker.connections().len(), 2);

        let closed_at = start + Duration::from_secs(86_400);
        let removed = tracker.cleanup(closed_at);
        assert_eq!(removed.len(), 2);

        for port in [40_000u16, 40_001] {
            let mut late_fin = tcp_packet(false, true, true, false, true);
            late_fin.local_addr.set_port(port);
            let outcome = tracker.ingest_at(&late_fin, closed_at + Duration::from_secs(1));
            assert!(
                outcome.ignored_late,
                "delayed teardown for port {port} must hit a tombstone"
            );
        }
        assert!(
            tracker.connections().is_empty(),
            "no phantom connections may be created"
        );
    }

    #[test]
    fn ingest_at_uses_supplied_time_for_cleanup() {
        // A packet ingested "in the past" must be eligible for cleanup at a
        // `now` only slightly later than its supplied capture time, proving the
        // tracker stamps the connection with the caller's time, not the wall
        // clock. (Wall-clock stamping would make `created_at` ~= real now, so a
        // cleanup at trace-time + a few minutes would NOT expire it.)
        let tracker = ConnectionTracker::new();
        let capture_time = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        tracker.ingest_at(&parse(&udp_frame(40000, 53)), capture_time);
        assert_eq!(tracker.connections().len(), 1);

        // One day after the capture time the UDP flow is well past its timeout.
        let removed = tracker.cleanup(capture_time + Duration::from_secs(86_400));
        assert_eq!(
            removed.len(),
            1,
            "flow stamped at capture time should expire"
        );
        assert_eq!(tracker.connections().len(), 0);
    }

    /// A connection opened right after a captured DNS response to one of the
    /// answered IPs must be tagged with the query name at creation. With
    /// `dns_attribution` disabled, the same traffic must stay untagged.
    #[test]
    fn dns_response_attributes_a_following_connection() {
        let answered_ip: std::net::IpAddr = "203.0.113.80".parse().unwrap();

        let tracker = ConnectionTracker::new();
        tracker.ingest_at(
            &dns_answer_packet(1, "cdn.example", &[answered_ip]),
            capture_time(0),
        );
        let outcome = tracker.ingest_at(&plain_udp_packet(), capture_time(50));
        assert_eq!(
            tracker
                .connections()
                .get(&outcome.key)
                .and_then(|conn| conn.attributed_hostname.as_ref().map(|a| a.name.clone())),
            Some("cdn.example".to_string())
        );

        let disabled = ConnectionTracker::with_config(TrackerConfig {
            dns_attribution: false,
            ..TrackerConfig::default()
        });
        disabled.ingest_at(
            &dns_answer_packet(1, "cdn.example", &[answered_ip]),
            capture_time(0),
        );
        let outcome = disabled.ingest_at(&plain_udp_packet(), capture_time(50));
        assert!(
            disabled
                .connections()
                .get(&outcome.key)
                .unwrap()
                .attributed_hostname
                .is_none(),
            "the config flag must disable attribution"
        );
    }

    /// A connection observed before any matching DNS waits in the pending
    /// index; the DNS response that later answers its remote IP tags it.
    #[test]
    fn late_dns_response_attributes_a_pending_connection() {
        let tracker = ConnectionTracker::new();
        let outcome = tracker.ingest_at(&plain_udp_packet(), capture_time(0));
        assert!(
            tracker
                .connections()
                .get(&outcome.key)
                .unwrap()
                .attributed_hostname
                .is_none()
        );

        let answered_ip: std::net::IpAddr = "203.0.113.80".parse().unwrap();
        tracker.ingest_at(
            &dns_answer_packet(1, "late.example", &[answered_ip]),
            capture_time(200),
        );
        assert_eq!(
            tracker
                .connections()
                .get(&outcome.key)
                .and_then(|conn| conn.attributed_hostname.as_ref().map(|a| a.name.clone())),
            Some("late.example".to_string())
        );
    }

    /// Cleaning up a still-pending connection must drop its enrollment, so a
    /// DNS response arriving after its death finds no waiter and the archived
    /// record stays unattributed.
    #[test]
    fn cleanup_forgets_pending_attribution_enrollments() {
        let tracker = ConnectionTracker::new();
        tracker.ingest(&plain_udp_packet());
        let removed = tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
        assert_eq!(removed.len(), 1);

        let answered_ip: std::net::IpAddr = "203.0.113.80".parse().unwrap();
        tracker.ingest(&dns_answer_packet(1, "posthumous.example", &[answered_ip]));
        assert!(
            tracker
                .historic
                .iter()
                .all(|conn| conn.attributed_hostname.is_none()),
            "a response after death must not label the archived record"
        );
    }

    #[test]
    fn clear_empties_everything() {
        let tracker = ConnectionTracker::new();
        tracker.ingest(&parse(&udp_frame(40000, 53)));
        tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
        assert_eq!(tracker.historic_len(), 1);

        let dns_at = SystemTime::now();
        tracker.ingest_at(&dns_packet(7, true, false, 0), dns_at);
        tracker.ingest_at(
            &dns_packet(7, false, true, 0),
            dns_at + Duration::from_millis(15),
        );
        assert_eq!(
            tracker
                .dns_analytics_snapshot_at(dns_at + Duration::from_millis(15))
                .lookups,
            1
        );

        tracker.clear();
        assert!(tracker.connections().is_empty());
        assert_eq!(tracker.historic_len(), 0);
        assert_eq!(
            tracker.dns_analytics_snapshot_at(dns_at + Duration::from_millis(15)),
            DnsAnalyticsSnapshot::default()
        );
    }
}