zond-engine 0.16.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Hosts
//!
//! A [`Host`] is everything a scan learned about a single device. Nothing fills
//! one in at once. An ARP reply establishes that it is there and gives it a MAC,
//! a neighbour solicitation adds an IPv6 address, a port scan adds ports, and
//! service detection names what is behind them. Each of those arrives on its own
//! schedule, in an order nobody controls.
//!
//! The whole type is therefore built around accumulating evidence, under one
//! rule: later is not better. Status is promoted and never lowered, by
//! [`Host::record_evidence`]. The address a host is reported under is ranked
//! rather than overwritten, by [`Host::consider_primary_ip`]. A MAC is added to
//! those already seen rather than replacing them, by [`Host::record_mac`]. Where
//! two findings are equally good, the one already recorded wins.
//!
//! [`Host::set_hostname`] is the one exception, and says why.
//!
//! Without that rule a report would depend on which probe happened to finish
//! last, and the same scan of the same network would produce a different
//! document twice. [`Host::merge`] applies the same rules between two records of
//! one host, so folding one phase into another gives what a single phase
//! would.

use crate::model::finding::{ClaimId, Finding, MAX_FINDINGS_PER_SUBJECT};
use crate::model::ip::scoped::{ScopedIp, Zone};
use crate::model::mac::MacAddr;
use crate::model::port::{Port, PortState, Protocol};
use std::{
    collections::{BTreeMap, BTreeSet, HashSet},
    net::IpAddr,
    time::SystemTime,
};

pub mod hardware;
pub mod os;
pub mod path;
pub mod protocol;
pub mod status;
pub mod telemetry;

pub use hardware::{HardwareDescription, HardwareInfo};
pub use os::{OsEvidence, OsFingerprint, OsSource};
pub use path::{Hop, NetworkPath};
pub use protocol::{IpProtocolState, ip_protocol_name};
pub use status::{EvidenceSource, HostStatus, StatusProtocol, StatusReason};
pub use telemetry::HostTelemetry;

/// The most ports one host will have recorded against it.
///
/// Every endpoint this build can probe: one whole port space for each transport
/// in [`Protocol::ALL`]. Derived rather than written out, so a transport added
/// there widens this along with it.
///
/// It has to sit here and cannot sit lower, because anything lower truncates a
/// scan somebody deliberately asked for. A thousand is a number an ordinary
/// scan reaches: probing `1-1024` on a host that answers, and a closed port is
/// an answer, records a thousand ports, so a cap there drops the last
/// twenty-four without a word and marks a domestic router as a tarpit. One
/// protocol's port space is not the largest port set a person can write
/// either: [`PortSet`](crate::model::port::PortSet) spells the UDP half, so
/// `1-65535,u:1-65535` is one specification and twice that number, and a cap
/// there drops half of it.
///
/// A host that reaches it is marked [`NetworkRole::Truncated`] and further ports
/// are dropped. **No scan can reach it**, since the map is keyed on a port
/// number and a transport and so holds exactly this many endpoints; what the
/// check still guards is a `Protocol` variant that never reached
/// [`Protocol::ALL`], which would leave this derivation short of the key space
/// it is meant to match. The ports already recorded are real observations either
/// way, and the marking is what says the list is not complete.
///
/// It is not the bound on what a single target can make this process allocate,
/// though it reads like one. That bound is the key space, and it is the map's to
/// enforce rather than this constant's; a host answering on every endpoint of a
/// scan that asked about every endpoint is a large record the operator asked
/// for. [`NetworkRole::Tarpit`] is the claim about the host, and it is a
/// separate one.
pub const MAX_PORTS_PER_HOST: usize = (u16::MAX as usize + 1) * Protocol::ALL.len();

/// How many **open** ports make a host implausible as a host.
///
/// A machine running a thousand distinct listening services does not exist. What
/// does exist is a tarpit answering every SYN to waste a scanner's time, and a
/// middlebox doing the same by accident, and both are worth saying out loud
/// because every port they report is a finding nobody should act on.
///
/// Counted on open ports and nothing else, which is the whole of the difference
/// between this and [`MAX_PORTS_PER_HOST`]. A host with sixty thousand *closed*
/// ports is the ordinary result of a wide scan against a live machine; a host
/// with a thousand open ones is not answering questions, it is answering
/// everything.
pub const TARPIT_OPEN_PORTS: usize = 1_000;

/// What a host turned out to be, beyond an address with ports on it.
///
/// Two kinds of claim share the enum. Most of it names a function the rest of the
/// network depends on, such as forwarding or naming or addressing, and the last
/// three are claims about the record rather than about the machine. Both are
/// things a reader acts on without reading anything else about the host, which
/// is what a role is for.
///
/// A role is never a port number restated. A host with 80 open is not a web
/// server here; that is [`Port::service`](crate::model::port::Port::service),
/// which carries the confidence such an identification needs. Every role is
/// concluded from evidence in its own protocol, whether an advertisement that
/// says it forwards, a DNS message that parses as a response, or a DHCP server
/// naming itself, so a consumer can act on one without asking how sure it is.
/// Letting
/// in a weaker claim would cost the set that property, since a `HashSet` cannot
/// say which of its members was a guess.
///
/// A variant is meant to exist here only once something assigns it: a role
/// nothing can infer would promise every consumer that the engine looks for it,
/// so an empty `roles` array would mean "not one" when it really means "never
/// asked". Where that is not yet true the variant says so in its own
/// documentation, which is the sentence to delete when it stops being true.
///
/// The enum is `#[non_exhaustive]` so that adding one costs a recompile rather
/// than a major version; [`ALL`](Self::ALL) is the list to iterate instead of
/// writing one out.
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum NetworkRole {
    /// Forwards traffic on behalf of other hosts.
    ///
    /// Three independent proofs, and the engine takes whichever the segment
    /// offers, because no one of them covers a whole network:
    ///
    /// 1. A **neighbour advertisement with the R flag** set (RFC 4861 §4.4).
    ///    The host is answering an ordinary discovery probe and saying, in the
    ///    same message, that it routes.
    /// 2. A **router advertisement** (ICMPv6 type 134). Routers send these
    ///    unprompted every few minutes, and a segment sweep is listening
    ///    anyway; it is the one role evidence that arrives without a probe.
    /// 3. **This machine's own routing table.** The address is a default
    ///    gateway of an interface the scan runs on. IPv4 has neither message
    ///    above, so on a v4-only segment this is the only proof available.
    ///
    /// Not called a gateway. A gateway is relational, being somebody's next hop,
    /// and two hosts on one segment can each be one for a different neighbour.
    /// What every proof above establishes is the intrinsic half: this box
    /// forwards. Which of them is a given machine's way out is a question about
    /// that machine's routing table rather than about the network.
    Router,

    /// Answered a query on port 53 with a message that parses as a DNS
    /// response.
    ///
    /// The reply itself is the evidence, not the port: a resolver that answers
    /// is doing the thing, where an open 53 is a socket somebody bound. The
    /// engine's UDP probe for the port carries a real question (the corpus
    /// registers one beside the service's match rules), so an answer is the
    /// ordinary outcome rather than a lucky one.
    ///
    /// Not mDNS or LLMNR. Those answer on 5353 and 5355, and nearly every
    /// laptop and printer on a segment responds to them. Counting one as a name
    /// server would put the role on half a network and make it worthless on the
    /// half that deserves it.
    DnsServer,

    /// Answered a DHCP message as a server.
    ///
    /// Concluded from an exchange in DHCP's own protocol: the engine sends a
    /// `DHCPINFORM`, which asks for configuration without asking for an
    /// address, and reads the server identifier (option 54) out of the reply.
    /// A server names itself there, and the role goes on that address only when
    /// the reply also came from it. Where a relay agent forwards for a server on
    /// another segment the two differ, and neither machine has been shown to
    /// serve DHCP on this one.
    ///
    /// It cannot be concluded from port state. UDP/67 is `open|filtered` on
    /// silence like every other UDP port, and a DHCP server is found by
    /// broadcasting at the segment rather than by connecting to a listener.
    DhcpServer,

    /// Answered with a valid NTP response, so it serves time.
    ///
    /// Nothing assigns this yet. The probe goes out, since the corpus registers a
    /// client packet for port 123, and what is missing is reading the reply as
    /// NTP rather than counting it as something answering. Until that is wired,
    /// the variant is vocabulary rather than a finding.
    NtpServer,

    /// Answered SNMP, so it is managed over it.
    ///
    /// Nothing assigns this yet, for the reason [`NtpServer`](Self::NtpServer)
    /// gives: the probe for port 161 is sent and its reply is already parsed
    /// for operating-system evidence, but no strategy concludes the role from
    /// it.
    SnmpAgent,

    /// Answered a NetBIOS node-status request with a name table holding a
    /// suffix only a domain controller registers.
    ///
    /// `<1C>` is registered as a group name by every controller in a domain and
    /// by nothing else, and `<1B>` as a unique name by the one that is domain
    /// master browser. Either says what the machine is, from one
    /// unauthenticated datagram, before anything has been asked of SMB or LDAP.
    ///
    /// The reply is the evidence and not the port, the same standard
    /// [`DnsServer`](Self::DnsServer) is held to. A host with 137 open has a
    /// socket bound; a host that lists `<1C>` has told a stranger it runs the
    /// domain. It is a role rather than a service because it is a fact about the
    /// machine: the same box says it over SMB, LDAP and Kerberos too, and each
    /// of those is a service of its own.
    ///
    /// Not concluded from `<20>` or `<00>`. The first is the server service and
    /// means the host shares something; the second every NetBIOS host
    /// registers.
    DomainController,

    /// Switches frames on behalf of the machines attached to it.
    ///
    /// Concluded from the device's own announcement, meaning LLDP's bridge
    /// capability or CDP's switch, transparent-bridge or source-route-bridge
    /// bits, and only where the device reports the capability as enabled rather
    /// than merely present. A switch with a routing licence nobody configured
    /// advertises routing as supported and not enabled, and reading the wrong
    /// half of that field puts a router on every access switch in a building.
    ///
    /// This is testimony rather than observed behaviour, which is unlike
    /// [`Router`](Self::Router) and unlike [`DnsServer`](Self::DnsServer), and
    /// like [`DhcpServer`](Self::DhcpServer): a DHCP server is believed because
    /// it named itself in a DHCP server's message, and a switch is believed
    /// because it named itself in the protocol switches announce themselves
    /// over. Anything on a segment can send either, which is why neither is
    /// evidence about a distant machine. See [`crate::protocols::lldp`] for what
    /// a group address does and does not prove.
    ///
    /// Worth a variant despite that, because it is the one role naming
    /// infrastructure that a scan generally cannot see at all: a switch usually
    /// presents no open port to the segment it serves, and often holds no
    /// address on it.
    Switch,

    /// The machine this scan is running from.
    ///
    /// A sweep of the scanning machine's own segment reaches it, and the record
    /// that produces is unlike every other one in it: services answer over the
    /// loopback path a neighbour would never reach, latency is not a network
    /// measurement, and no probe crossed a wire. Saying so is cheaper than every
    /// consumer rediscovering it.
    ///
    /// Read from the addresses assigned to this machine's interfaces, so it is
    /// established without sending anything and holds for an address the scan
    /// never reached.
    Origin,

    /// Reported more ports **open** than any machine plausibly runs services on.
    ///
    /// A claim about the host: past [`TARPIT_OPEN_PORTS`] it is answering
    /// everything rather than answering questions, and every open port it
    /// reported is a finding nobody should act on. A
    /// deliberate tarpit and a middlebox answering everything by accident are
    /// indistinguishable from here, and both make the ports recorded against
    /// this host meaningless.
    Tarpit,

    /// Answered on more ports than this record will hold, so the port list is
    /// incomplete.
    ///
    /// A claim about the *scan* rather than about the host: it says only that
    /// [`MAX_PORTS_PER_HOST`] was reached and that findings past it were
    /// dropped. Kept apart from [`Tarpit`](Self::Tarpit) because conflating the
    /// two is wrong in both directions: an ordinary host probed widely enough
    /// would be reported as a tarpit, and a real tarpit answering a narrow scan
    /// would be reported as nothing at all.
    ///
    /// No scan this build can run assigns it. `MAX_PORTS_PER_HOST` is derived
    /// from the port space and [`Protocol::ALL`], so it equals what a host's
    /// port map can hold and nothing a scan reports can pass it. The variant
    /// exists because the check does: a `Protocol` variant that never
    /// reached `Protocol::ALL` puts the cap below the key space, and this is
    /// what a report would then say about the ports that went missing.
    Truncated,
}

impl NetworkRole {
    /// How a role is written for a person to read.
    ///
    /// Separate from [`network_role_name`](crate::record::wire::network_role_name),
    /// which is the one place a role is spelled for a *machine*. A model that
    /// knew its own wire spelling would be a second vocabulary site, and the
    /// two answer to different masters: this one may be reworded whenever it
    /// reads better, and that one may never change at all.
    ///
    /// An acronym is capitals and a word is not. `DNS` is a name written in
    /// initials and `router` is an ordinary English noun, so capitalising the
    /// second to match the first is shouting rather than spelling, the rule that
    /// also makes `ICMP unreachable` the name of a thing and `ICMP_UNREACHABLE`
    /// a shout. A list mixing the two reads as `router, DNS, DHCP`.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Router => "router",
            Self::DnsServer => "DNS",
            Self::DhcpServer => "DHCP",
            Self::NtpServer => "NTP",
            Self::SnmpAgent => "SNMP",
            // One token, like every other label and like its own wire name: a
            // role is drawn into a space-separated list, so a space here would
            // read as two roles, and `domain controller` also drifted from the
            // hyphenated `network_role_name` a reader greps a record by.
            Self::DomainController => "domain-controller",
            Self::Switch => "switch",
            Self::Origin => "origin",
            Self::Tarpit => "tarpit",
            Self::Truncated => "truncated",
        }
    }

    /// Every role this build knows, in declaration order, which is the order
    /// [`label`](Self::label) spells them in.
    ///
    /// The enum is `#[non_exhaustive]`, so nothing outside the crate can write
    /// an exhaustive list of its own and nothing inside should: a role added
    /// without a name on the wire, or without a place in the schema, is a
    /// finding that survives a scan and disappears on the way to the report.
    /// Every round trip through [`wire`](crate::record::wire) is tested over
    /// this, so a new variant fails those tests until it is spelled everywhere.
    pub const ALL: [NetworkRole; 10] = [
        Self::Router,
        Self::DnsServer,
        Self::DhcpServer,
        Self::NtpServer,
        Self::SnmpAgent,
        Self::DomainController,
        Self::Switch,
        Self::Origin,
        Self::Tarpit,
        Self::Truncated,
    ];
}

/// What the filter in front of a host was shown to be doing.
///
/// A conclusion about the *path to* a host rather than the host itself, which is
/// what keeps it a separate claim from [`NetworkRole`]: a filter sits between the
/// scanner and the machine, and saying a host "is" a middlebox the way it "is" a
/// name server would be a different and usually wrong claim. Like a role, every
/// member is a proven, confidence-free fact, held in a set where there is nowhere
/// to record a maybe, drawn from what a deliberately shaped probe demonstrated
/// rather than from a port number.
///
/// Positive claims only. A probe that drew no reply, or was dropped like an
/// ordinary one, proves nothing; the absence of a filter is not something a scan
/// can establish, so it is never recorded.
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum Filtering {
    /// An inline device answered on the host's behalf.
    ///
    /// Proven by a reply to a probe carrying a deliberately wrong TCP checksum.
    /// A conformant host drops such a segment unread, so a reply to one was not
    /// the host's. It was sent by something in the path that answered without
    /// validating: a firewall, an intrusion-prevention system, a transparent
    /// proxy, a load balancer. One reply is the whole proof, which is why this
    /// is the one filtering conclusion a single probe settles.
    InlineMiddlebox,

    /// A stateful filter: it passes a bare ACK but drops a SYN.
    ///
    /// Proven by an ACK probe reaching the stack, meaning a RST and so
    /// [`PortState::Unfiltered`], for a port the scan found filtered to a SYN. A
    /// filter that lets an ACK through
    /// and refuses a SYN is keeping connection state and opening no new
    /// connections. Comparative: the SYN's fate is the port state the scan
    /// already recorded, and only the ACK is sent here.
    StatefulFilter,

    /// A filter that trusts a source port.
    ///
    /// Proven by a SYN from a port such as 53, 20 or 88 reaching a port the scan
    /// found filtered to a SYN from an ephemeral one. The filter is honouring an
    /// ACL written to let returning traffic back in, which is a door a chosen
    /// source port holds open. Comparative in the same way as
    /// [`StatefulFilter`](Self::StatefulFilter), and against the same recorded
    /// port state.
    PortTrustingAcl,

    /// A stateless filter: it matches on the first fragment and passes the rest.
    ///
    /// Proven by a *fragmented* SYN drawing an answer from a port the scan found
    /// filtered to a whole one. A filter that reassembled would have seen the
    /// same forbidden SYN either way; one that lets the fragments through has
    /// judged only the first, where the ports are but the flags are not yet, and
    /// so is matching without keeping the state reassembly needs. Comparative
    /// against the same recorded port state as
    /// [`StatefulFilter`](Self::StatefulFilter). A fragmented probe can only be
    /// sent over a self-built Ethernet frame, so this is drawn only for a host
    /// that path can reach; one it cannot goes without the conclusion rather than
    /// against it.
    StatelessFilter,
}

impl Filtering {
    /// Every conclusion this build knows, in declaration order, which is the
    /// order they are reported in.
    ///
    /// A set is rendered through this order and the exported schema's list is
    /// built from it, so a conclusion missing from here is one that survives a
    /// scan and disappears on the way to the report.
    ///
    /// The array's length is not the check against that, though it can read
    /// as one. It catches an entry added here without the number being
    /// raised, and nothing else; a variant added to the enum and not to this
    /// list compiles, and was measured doing so. What the compiler does refuse
    /// is a variant with no wire name, in
    /// [`record::wire`](crate::record::wire), which is a function whose round
    /// trip is driven by this list. The order and the absence of repeats are
    /// held by `model`'s own test. Completeness is held by neither, and closing
    /// it needs a derive macro this crate does not carry.
    pub const ALL: [Filtering; 4] = [
        Self::InlineMiddlebox,
        Self::StatefulFilter,
        Self::PortTrustingAcl,
        Self::StatelessFilter,
    ];
}

/// What one source concluded, reduced to the parts that make it a *distinct*
/// claim.
///
/// The identity of a piece of operating-system evidence for the purpose of
/// counting it: two readings that say the same thing are one thing learned
/// twice, whatever produced them, and two that say different things are two
/// pieces of evidence even where one kind of source produced both.
///
/// Deliberately not the confidence or the evidence line. The first varies with
/// how a rule was weighted and the second is prose; neither changes what is
/// being claimed, and keying on either would let one claim in under several
/// spellings.
type OsClaim = (
    OsSource,
    Option<String>,
    Option<String>,
    Option<String>,
    Option<String>,
    Option<String>,
    Option<String>,
);

/// The most distinct operating-system claims one host retains.
///
/// A host running many identifiable services can offer one claim each, and
/// combining enough of them approaches a certainty none of them stated. Eight is
/// past any host this has been seen on and short of where the arithmetic stops
/// meaning anything.
const MAX_OS_EVIDENCE: usize = 8;

/// A single machine, and what a scan established about it.
///
/// Identity first: the addresses it answers at, its name and its hardware. Then
/// what was found on it.
///
/// A host holds every address it is known by. A dual-stack machine answering at
/// three of them is one device, and reporting it as three is the failure this
/// type is shaped to avoid. See
/// [`consider_primary_ip`](Self::consider_primary_ip) for which address leads.
#[must_use]
#[derive(Debug, Clone)]
pub struct Host {
    /// The primary IP address used to target or identify this host.
    primary_ip: IpAddr,

    /// All known IP addresses for this host (multi-homed support).
    ips: BTreeSet<IpAddr>,

    /// The resolved hostname (FQDN or local network name).
    hostname: Option<String>,

    /// The current reachability status.
    status: HostStatus,

    /// Aggregated evidence explaining the current reachability status.
    reasons: HashSet<StatusReason>,

    /// Identified operating system metadata.
    ///
    /// Boxed. [`OsFingerprint`] is both the largest thing a host can carry and
    /// one of the rarest, since most hosts in a scan never get one, so holding
    /// it by reference keeps a `Host` cheap to move in collections of thousands.
    os: Option<Box<OsFingerprint>>,

    /// What each source concluded about this host's operating system, kept so a
    /// later source can **corroborate** an earlier one instead of competing with
    /// it.
    ///
    /// The reason this is retained rather than collapsed on arrival: combining
    /// evidence is only meaningful over the evidence itself. A stack reading and
    /// a service banner are independent, and two independent sources agreeing on
    /// a family are worth more than either, which is the design of
    /// [`resolve`](crate::fingerprint::os::resolve). Keeping only the resulting
    /// [`OsFingerprint`] would throw that away: a banner arriving after the
    /// stack reading scores lower on its own and would be discarded whole,
    /// taking the release it alone could name with it.
    ///
    /// One item per distinct claim, which is not one per source.
    ///
    /// Keyed per source, an SSH banner naming `Debian 12` and an SNMP agent
    /// naming `kernel 6.1.0` are both `ServiceBanner`, so the second would evict
    /// the first and a host that had told this engine two different things
    /// about itself would be reported from whichever arrived last. They are two
    /// services, on two ports, read from two protocols: two pieces of evidence
    /// by any reading.
    ///
    /// Keyed on the claim, a stack read forty times, which is what a host with
    /// forty open ports produces, is forty identical claims and still collapses
    /// to one. That is the property that has to hold: repeating
    /// an observation must never look like corroboration, because the
    /// arithmetic downstream cannot tell the difference.
    ///
    /// Bounded by [`MAX_OS_EVIDENCE`], because a host running many distinct
    /// services can otherwise accumulate one item per service, and enough
    /// agreeing items approach a certainty no single source stated.
    os_evidence: BTreeMap<OsClaim, OsEvidence>,

    /// Physical hardware (MAC) and vendor information.
    hardware: Option<HardwareInfo>,

    /// The interface this host was observed through, when one is known.
    ///
    /// Recorded by the strategies that work at the link layer, which are the
    /// only ones that can know it: a routed probe crosses whatever path the
    /// kernel chose and says nothing about which interface it left by.
    ///
    /// It is not decoration. An IPv6 link-local address is meaningless without
    /// it, because `fe80::1` names a different machine on every segment and a
    /// socket cannot be opened to one without the interface's scope id. This is
    /// what makes the addresses local discovery finds usable by everything that
    /// runs after it. See [`ScopedIp`].
    zone: Option<Zone>,

    /// Network performance and path telemetry.
    telemetry: HostTelemetry,

    /// The routers between this machine and this host, when a trace ran.
    ///
    /// Empty unless a trace was asked for. A path costs one probe per hop per
    /// host and nothing else in a scan needs one, so it is never gathered as a
    /// side effect. See
    /// [`ZondConfig::traceroute`](crate::config::ZondConfig::traceroute).
    ///
    /// Held here rather than on [`HostTelemetry`] beside the round-trip time,
    /// which is the tempting place for it. A telemetry reading is one number
    /// about this host, updated as replies arrive; a path is a sequence of
    /// findings about *other* machines, each with its own provenance, and the
    /// two have nothing in common but the word "path".
    path: NetworkPath,

    /// Inferred roles based on network location or discovered services.
    network_roles: HashSet<NetworkRole>,

    /// What the filter in front of this host was shown to be doing, if anything.
    filtering: HashSet<Filtering>,

    /// Which IP protocols the host's stack was shown to take delivery of.
    ///
    /// Empty unless a scan asked, which is a pass of its own: see
    /// [`ZondConfig::ip_protocols`](crate::config::ZondConfig::ip_protocols).
    /// Kept here rather than among the ports because a protocol number is not a
    /// port and the numbers include the transports; [`protocol`] is the whole
    /// argument.
    ///
    /// A plain map rather than an alias for one. `IpProtocols` is already the
    /// name of a v4/v6 pair of next-header values over in
    /// [`transport::probe`](crate::transport::probe::IpProtocols), and two public
    /// types of one name meaning different things is a worse cost than spelling
    /// the map out.
    ip_protocols: BTreeMap<u8, IpProtocolState>,

    /// What a detection concluded was wrong with this host, keyed on the claim so
    /// that the same finding reached twice records once.
    ///
    /// Host-level findings are the cross-cutting ones, whether a weakness
    /// inferred from several ports together or a correlation over the host as a
    /// whole, as distinct from the per-port findings a [`Port`] carries. Bounded
    /// by
    /// [`MAX_FINDINGS_PER_SUBJECT`], and keyed like [`os_evidence`](Self::os_evidence)
    /// so that a detection re-firing corroborates rather than accumulates.
    findings: BTreeMap<ClaimId, Finding>,

    /// The timestamp of the first discovery event for this host.
    first_seen: SystemTime,

    /// The timestamp of the most recent discovery or update event.
    last_seen: SystemTime,

    /// The ports found on this host, in a stable order, bounded by
    /// [`MAX_PORTS_PER_HOST`].
    ///
    /// Keyed on the number and the protocol, since a number names one endpoint
    /// per transport and a scan can be asked about both: `PortSet` spells the UDP
    /// half `u:53`, and the raw TCP and UDP scanners report into this map
    /// independently. Keyed on the number alone, whichever arrived
    /// second would be merged into the first and reported under its protocol.
    ///
    /// Ordered by number first, so a report lists a host's ports the way a
    /// reader expects to read them, with the two transports of one number
    /// adjacent.
    ports: BTreeMap<(u16, Protocol), Port>,

    /// How many of [`ports`](Self::ports) are [`PortState::Open`], maintained as
    /// they are recorded rather than counted on demand.
    ///
    /// [`add_port`](Self::add_port) is the only way a port enters or changes
    /// here, and a port's state only ever promotes, so the count can be kept
    /// incrementally and can never drift downward. Counting on demand would be
    /// a walk of the map per recorded port, which on a wide scan is quadratic in
    /// the thing the walk exists to bound.
    open_ports: usize,
}

/// How well an address identifies the host holding it: lower leads.
///
/// The ordering behind [`Host::consider_primary_ip`], kept beside it as a free
/// function so the comparison is one expression rather than a branch that grows
/// a case each time a family is added.
///
/// Rank 1 is what the documentation there calls globally scoped: an address that
/// names the host from off its segment. That is
/// [`is_global_unicast`](crate::model::ip::is_global_unicast) and unique-local,
/// tested for rather than inferred from not being link-local, which also admits
/// loopback, multicast and the unspecified address, none of which name this host
/// to anyone.
fn identity_rank(ip: &IpAddr) -> u8 {
    match ip {
        IpAddr::V4(_) => 0,
        IpAddr::V6(v6) if crate::model::ip::is_globally_scoped(v6) => 1,
        IpAddr::V6(_) => 2,
    }
}

impl Host {
    /// Creates a new `Host` centered around a primary IP address.
    ///
    /// The initial status is always [`HostStatus::Unknown`].
    pub fn new(primary_ip: IpAddr) -> Self {
        let mut ips = BTreeSet::new();
        ips.insert(primary_ip);
        let now = SystemTime::now();

        Self {
            primary_ip,
            ips,
            hostname: None,
            status: HostStatus::Unknown,
            reasons: HashSet::new(),
            os: None,
            os_evidence: BTreeMap::new(),
            hardware: None,
            zone: None,
            telemetry: HostTelemetry::default(),
            path: NetworkPath::new(),
            network_roles: HashSet::new(),
            filtering: HashSet::new(),
            ip_protocols: BTreeMap::new(),
            findings: BTreeMap::new(),
            first_seen: now,
            last_seen: now,
            ports: BTreeMap::new(),
            open_ports: 0,
        }
    }

    /// Returns the primary IP address for this host.
    pub fn primary_ip(&self) -> IpAddr {
        self.primary_ip
    }

    /// Returns all known IP addresses for this host.
    pub fn ips(&self) -> &BTreeSet<IpAddr> {
        &self.ips
    }

    /// Returns the resolved hostname, if any.
    pub fn hostname(&self) -> Option<&str> {
        self.hostname.as_deref()
    }

    /// Returns the current reachability status.
    pub fn status(&self) -> HostStatus {
        self.status
    }

    /// Returns all aggregated evidence for the current status.
    pub fn reasons(&self) -> &HashSet<StatusReason> {
        &self.reasons
    }

    /// Returns the identified operating system, if any.
    pub fn os(&self) -> Option<&OsFingerprint> {
        self.os.as_deref()
    }

    /// Returns physical hardware information, if any.
    pub fn hardware(&self) -> Option<&HardwareInfo> {
        self.hardware.as_ref()
    }

    /// Returns the interface this host was observed through, if known.
    pub fn zone(&self) -> Option<&Zone> {
        self.zone.as_ref()
    }

    /// Records the interface this host was observed through.
    ///
    /// Only the first is kept. A host reachable through two interfaces is a
    /// real situation, and picking the earlier sighting is arbitrary but stable.
    /// Overwriting would make the address a scan reports depend on which
    /// strategy happened to finish last.
    pub fn set_zone(&mut self, zone: Zone) {
        self.zone.get_or_insert(zone);
        self.last_seen = SystemTime::now();
    }

    /// This host's primary address, carrying the interface it is valid on.
    ///
    /// The address to hand anything that intends to *reach* the host, rather
    /// than merely name it: [`ScopedIp::to_socket_addr`] refuses rather than
    /// building a socket address that cannot be connected to.
    pub fn scoped_ip(&self) -> ScopedIp {
        match &self.zone {
            Some(zone) => ScopedIp::scoped(self.primary_ip, zone.clone()),
            None => ScopedIp::unscoped(self.primary_ip),
        }
    }

    /// Returns network performance and path telemetry.
    pub fn telemetry(&self) -> &HostTelemetry {
        &self.telemetry
    }

    /// The routers between this machine and this host. Empty unless a trace ran.
    pub fn path(&self) -> &NetworkPath {
        &self.path
    }

    /// Records the hop counter a reply from this host arrived with.
    ///
    /// Cheap and unconditional: every captured reply carries one, and the
    /// alternative to keeping it is a probe sent later purely to re-obtain it.
    pub fn record_hop_counter(&mut self, arrived: u8) {
        self.telemetry.record_hop_counter(arrived);
    }

    /// Records one router on the way here.
    ///
    /// Additive and idempotent in the way [`NetworkPath::record`] describes:
    /// what is known about a distance only ever gets stronger, so a trace whose
    /// replies arrive out of order, or twice, converges on the same path.
    pub fn record_hop(&mut self, hop: Hop) {
        self.path.record(hop);
        self.last_seen = SystemTime::now();
    }

    /// Returns inferred roles based on network location or discovered services.
    pub fn network_roles(&self) -> &HashSet<NetworkRole> {
        &self.network_roles
    }

    /// What the filter in front of this host was shown to be doing.
    pub fn filtering(&self) -> &HashSet<Filtering> {
        &self.filtering
    }

    /// What a scan concluded about each IP protocol it asked this host about,
    /// ascending by number.
    ///
    /// Empty for every scan that did not ask, which is most of them. A protocol
    /// present at [`IpProtocolState::Unasked`] is one the scan named and did not
    /// reach, which is a different thing from one it never named.
    pub fn ip_protocols(&self) -> &BTreeMap<u8, IpProtocolState> {
        &self.ip_protocols
    }

    /// Returns the timestamp of the first discovery event.
    pub fn first_seen(&self) -> SystemTime {
        self.first_seen
    }

    /// Returns the timestamp of the most recent discovery or update event.
    pub fn last_seen(&self) -> SystemTime {
        self.last_seen
    }

    /// Restores the times this host was first and last seen.
    ///
    /// Both are stamped by [`new`](Self::new) and moved forward as findings
    /// arrive, which is right for a host a scan is discovering and wrong for one
    /// being rebuilt from a record: a scan resumed the next morning would report
    /// having first seen every host that morning.
    ///
    /// Taken together rather than as two setters, since a `first_seen` after a
    /// `last_seen` describes nothing that could have happened. They are swapped
    /// if given that way.
    pub fn restore_seen(&mut self, first_seen: SystemTime, last_seen: SystemTime) {
        let (first_seen, last_seen) = if first_seen <= last_seen {
            (first_seen, last_seen)
        } else {
            (last_seen, first_seen)
        };
        self.first_seen = first_seen;
        self.last_seen = last_seen;
    }

    /// Offers `candidate` as the address this host is reported under, taking it
    /// only if it identifies the host better than the current one.
    ///
    /// Returns whether the primary address changed.
    ///
    /// The rule, in one place. A dual-stack host answers at several
    /// addresses and something has to choose which one names it. Left to
    /// whichever probe replied first, the same machine is reported under its
    /// IPv4 address on one run and its link-local on the next. For an inventory
    /// that is worse than an ugly address: it is one device appearing as two.
    ///
    /// So addresses are ranked, and the ranking only ever moves upward:
    ///
    /// 1. **IPv4**, because it is what a person recognises and types.
    /// 2. **Globally scoped IPv6**, meaning global unicast or unique-local,
    ///    which names the host from anywhere and needs nothing else to be
    ///    usable.
    /// 3. **Link-local IPv6**, which names a different machine on every segment
    ///    and is meaningless without the zone that
    ///    [`scoped_ip`](Self::scoped_ip) supplies.
    ///
    /// Ties keep the incumbent, so a host with two global addresses does not
    /// flip between them as replies arrive. Nothing is discarded either way:
    /// every address stays in [`ips`](Self::ips), and this decides only which
    /// one leads.
    pub fn consider_primary_ip(&mut self, candidate: IpAddr) -> bool {
        self.add_ip(candidate);

        if identity_rank(&candidate) >= identity_rank(&self.primary_ip) {
            return false;
        }

        self.primary_ip = candidate;
        self.last_seen = SystemTime::now();
        true
    }

    /// Adds a new IP address to the host's record and bumps `last_seen`.
    /// Returns `true` if the IP was newly added.
    pub fn add_ip(&mut self, ip: IpAddr) -> bool {
        let is_new = self.ips.insert(ip);
        self.last_seen = SystemTime::now();
        is_new
    }

    /// Adds multiple IP addresses to the host's record and bumps `last_seen`.
    pub fn extend_ips(&mut self, ips: impl IntoIterator<Item = IpAddr>) {
        self.ips.extend(ips);
        self.last_seen = SystemTime::now();
    }

    /// Drops every address `keep` refuses, and returns whether any is left.
    ///
    /// For the exclusion policy, which holds for every address a host is known
    /// by and not only for the one it was found at. The primary goes too if it
    /// is refused, and the best of what remains takes its place, ranked the way
    /// [`consider_primary_ip`](Self::consider_primary_ip) ranks, so a host is
    /// reported under whichever of its reportable addresses identifies it best.
    ///
    /// A host every address of which is refused is left as it was, and this
    /// returns `false`: a host always has an address, and what becomes of one
    /// with none it may be reported under is the caller's decision.
    pub(crate) fn retain_ips(&mut self, keep: impl Fn(&IpAddr) -> bool) -> bool {
        if self.ips.iter().all(&keep) {
            return true;
        }
        let kept: BTreeSet<IpAddr> = self.ips.iter().copied().filter(&keep).collect();
        let Some(best) = kept.iter().copied().min_by_key(identity_rank) else {
            return false;
        };
        if !kept.contains(&self.primary_ip) {
            self.primary_ip = best;
        }
        self.ips = kept;
        true
    }

    /// Withholds the address of every router or middlebox this host's record
    /// names that `keep` refuses, and returns whether it withheld any.
    ///
    /// The other half of [`retain_ips`](Self::retain_ips) for the exclusion
    /// policy, and a different treatment because an intermediary is a different
    /// claim. This host's own address, refused, takes the finding with it. An
    /// intermediary refused leaves the finding behind, since it is a fact about
    /// this host, and goes unnamed. That covers the two places a record names
    /// one: a router on the path, which keeps the distance it answered at (see
    /// [`Hop::withheld`]), and the sender of second-hand evidence, which keeps
    /// the reason it sent (see [`EvidenceSource::Withheld`]).
    pub(crate) fn withhold_intermediaries(&mut self, keep: impl Fn(&IpAddr) -> bool) -> bool {
        let routers = self.path.withhold(&keep);

        // A reason is its own hash key, so one whose sender changes has to be
        // taken out and put back. Asked first because this runs on every
        // finding a scan under a policy records, and the answer is almost
        // always that nothing needs to move.
        let refused = |reason: &StatusReason| {
            reason
                .source
                .address()
                .is_some_and(|address| !keep(&address))
        };
        let senders = self.reasons.iter().any(refused);
        if senders {
            self.reasons = std::mem::take(&mut self.reasons)
                .into_iter()
                .map(|mut reason| {
                    reason.source.withhold(&keep);
                    reason
                })
                .collect();
        }

        routers || senders
    }

    /// Records the name this host resolved to, replacing any already recorded.
    ///
    /// The one field that is overwritten. Unlike a status or an address, a
    /// hostname has no ordering that says which of two answers knows more, and a
    /// caller passing `None` is clearing a name rather than declining to set one.
    /// [`merge`](Self::merge) keeps the incumbent instead, since there neither
    /// record is the later word and the two are accounts of one host.
    pub fn set_hostname(&mut self, hostname: Option<String>) {
        self.hostname = hostname;
        self.last_seen = SystemTime::now();
    }

    /// Raises the reachability status to `status`, if that is an improvement.
    ///
    /// Promotes and never lowers, the same rule
    /// [`record_evidence`](Self::record_evidence) applies and for the same
    /// reason: probes answer in an order nobody controls, and a late ICMP
    /// unreachable must not overwrite proof the host answered for itself. This
    /// is the entry point for a caller that has a status and no
    /// [`StatusReason`] to attach to it; where there is a reason, prefer
    /// `record_evidence`, which keeps the audit trail as well.
    pub fn set_status(&mut self, status: HostStatus) {
        if status > self.status {
            self.status = status;
        }
        self.last_seen = SystemTime::now();
    }

    /// Adds a status reason and bumps `last_seen`.
    pub fn add_reason(&mut self, reason: StatusReason) {
        self.reasons.insert(reason);
        self.last_seen = SystemTime::now();
    }

    /// Records one piece of liveness evidence: the status it establishes, and
    /// the reason it establishes it.
    ///
    /// This is how a scanner reports what it saw, and the one to reach for: it
    /// records the verdict and the evidence together, which
    /// [`set_status`](Self::set_status) and [`add_reason`](Self::add_reason) do
    /// separately for the callers that genuinely have only one of the two.
    /// The status is **promoted, never lowered**, on the
    /// semantic ordering of [`HostStatus`]. [`Host::merge`](Host::merge)
    /// applies the same rule between two records of one host, for the same
    /// reason: a scan learns about a host from several probes arriving in an
    /// order nobody controls, and an ICMP unreachable from a router that happens
    /// to land after an ARP reply must not overwrite proof the host answered for
    /// itself.
    ///
    /// The reason is kept whether or not the status moved. A host that is
    /// already `Up` still gains the audit trail of everything else that saw it,
    /// which is the whole purpose of [`StatusReason`].
    ///
    /// Callers must only pass evidence backed by a received packet. Silence is
    /// not evidence and has no status to record; see [`HostStatus::Unknown`].
    pub fn record_evidence(&mut self, status: HostStatus, reason: StatusReason) {
        if status > self.status {
            self.status = status;
        }
        self.reasons.insert(reason);
        self.last_seen = SystemTime::now();
    }

    /// What each source has concluded about this host's operating system.
    ///
    /// The input [`resolve`](crate::fingerprint::os::resolve) is run over, and
    /// the reason a late-arriving source can raise a verdict rather than merely
    /// fail to displace it.
    pub fn os_evidence(&self) -> impl Iterator<Item = &OsEvidence> {
        self.os_evidence.values()
    }

    /// This host's findings, in a stable order.
    ///
    /// The cross-host conclusions, meaning a weakness of the host as a whole
    /// rather than of one of its ports, where a port's own findings are on the
    /// [`Port`]. Ordered by claim,
    /// so two runs that found the same things render them the same way.
    pub fn findings(&self) -> impl Iterator<Item = &Finding> {
        self.findings.values()
    }

    /// Files what one source concluded, keeping the strongest reading per
    /// source.
    ///
    /// Returns whether this changed what is on record, so a caller can tell a
    /// genuine new finding from the same one arriving again.
    ///
    /// Per source rather than per observation, which is what makes the arithmetic
    /// downstream safe. A stack read once and a stack read forty times, which is
    /// what a host with forty open ports produces, are one piece of evidence, and
    /// counting them separately would turn one observation into certainty.
    pub fn record_os_evidence(&mut self, evidence: OsEvidence) -> bool {
        let claim: OsClaim = (
            evidence.source,
            evidence.family.clone(),
            evidence.device.clone(),
            evidence.vendor.clone(),
            evidence.product.clone(),
            evidence.version.clone(),
            evidence.kernel.clone(),
        );

        // The ceiling is read before the map is borrowed to edit, because a
        // claim already on record occupies room it does not have to ask for.
        let full = self.os_evidence.len() >= MAX_OS_EVIDENCE;

        match self.os_evidence.get_mut(&claim) {
            // The same claim reached again, not necessarily by the same route.
            // A stack read once off a port scan's reply and again as a series of
            // them concludes the identical thing and shows different working for
            // it, and the series reading is the one that cannot be
            // got back. So the claim is not new and the reading may be: keep the
            // strongest confidence and every distinct line behind it.
            Some(existing) => {
                let joined = os::join_readings(&existing.evidence, &evidence.evidence);
                let changed = joined != existing.evidence;

                existing.evidence = joined;
                existing.confidence = existing.confidence.max(evidence.confidence);
                changed
            }
            // The ceiling only turns away something new.
            None if full => false,
            None => {
                self.os_evidence.insert(claim, evidence);
                true
            }
        }
    }

    /// Records a finding about this host, and reports whether it was new
    /// information: a claim not seen before, or a stronger reading of one that
    /// was.
    ///
    /// A finding reached again by the same detection is not a second finding: it
    /// folds into the one on record through [`Finding::corroborate`], keeping the
    /// strongest confidence and the newest verdict. The ceiling turns away only a
    /// genuinely new claim, so a subject already at the limit still updates the
    /// findings it holds. Mirrors [`record_os_evidence`](Self::record_os_evidence).
    pub fn add_finding(&mut self, finding: Finding) -> bool {
        let claim = finding.claim_id();

        // The ceiling is read before the map is borrowed to edit, because a claim
        // already on record occupies room it does not have to ask for.
        let full = self.findings.len() >= MAX_FINDINGS_PER_SUBJECT;

        match self.findings.get_mut(&claim) {
            Some(existing) => existing.corroborate(finding),
            None if full => false,
            None => {
                self.findings.insert(claim, finding);
                true
            }
        }
    }

    /// Records a finding about one of this host's ports, and reports whether it
    /// was new. `false` if no such port is on record.
    ///
    /// The path a report-level pass such as CVE correlation takes: it reads a
    /// port's service identification, concludes something about the software
    /// behind it, and hands the finding back to the port it is about, named by
    /// number and protocol. The host owns its ports, so the finding arrives
    /// through it rather than through a loose mutable handle.
    ///
    /// `None` where this host has no such port, which is a different answer from
    /// `Some(false)`, which means the port has the claim already or is at
    /// [`MAX_FINDINGS_PER_SUBJECT`]. A `bool` said the same thing about a
    /// detection that fired against a port nothing recorded and a detection that
    /// found nothing new, and only the first is worth a caller's attention.
    pub fn add_port_finding(
        &mut self,
        number: u16,
        protocol: Protocol,
        finding: Finding,
    ) -> Option<bool> {
        self.ports
            .get_mut(&(number, protocol))
            .map(|port| port.add_finding(finding))
    }

    /// Replaces this host's operating-system fingerprint outright, whatever was
    /// there before, and stamps the host as seen now.
    ///
    /// For a caller holding a complete [`OsFingerprint`], such as one read back
    /// from a report. Folding a second opinion into what is on record is what
    /// [`merge`](Self::merge) does instead.
    pub fn set_os(&mut self, os: OsFingerprint) {
        self.os = Some(Box::new(os));
        self.last_seen = SystemTime::now();
    }

    /// Withdraws this host's operating-system fingerprint.
    ///
    /// For a caller that has re-resolved the evidence and found it no longer
    /// supports what is on record. Nothing else should reach for this: a scan
    /// that discards a finding it cannot currently reproduce would lose every
    /// answer a later phase happens not to re-derive.
    pub fn clear_os(&mut self) {
        self.os = None;
        self.last_seen = SystemTime::now();
    }

    /// Replaces this host's hardware record wholesale.
    ///
    /// For a caller holding a complete [`HardwareInfo`], such as one read back
    /// from a report. A single sighting goes through [`record_mac`](Self::record_mac),
    /// which adds to the record instead of discarding what is already in it.
    pub fn set_hardware(&mut self, hardware: HardwareInfo) {
        self.hardware = Some(hardware);
        self.last_seen = SystemTime::now();
    }

    /// Builder method to record a MAC sighting and return Self.
    pub fn with_mac(mut self, mac: MacAddr) -> Self {
        self.record_mac(mac);
        self
    }

    /// Records a sighting of `mac` for this host, keeping every address seen.
    ///
    /// Works by reference, unlike [`with_mac`](Self::with_mac), so a host
    /// created by the port scanner, which has no MAC, can still be enriched by a
    /// scanner that learned one, whichever ran first.
    ///
    /// Adds rather than replaces, and that is what [`HardwareInfo`] is for.
    /// A device with two interfaces on one segment answers under two addresses,
    /// and a device randomizing its MAC answers under a series of them; both are
    /// one host, and which address it is currently using is a different question
    /// from which it has ever used. Overwriting would answer neither, since it
    /// leaves whichever probe replied last: [`most_recent_mac`] would report a
    /// sighting order rather than a timeline, and [`prune_stale_macs`] would
    /// have nothing to prune.
    ///
    /// Repeating a MAC already on record is not a no-op: it refreshes that
    /// address's last-seen time, which is what makes the two methods above mean
    /// anything.
    ///
    /// Bounded by [`MAX_MACS_PER_HOST`](hardware::MAX_MACS_PER_HOST), because a
    /// source address is a field in a frame and a series has no natural end.
    ///
    /// [`most_recent_mac`]: HardwareInfo::most_recent_mac
    /// [`prune_stale_macs`]: HardwareInfo::prune_stale_macs
    pub fn record_mac(&mut self, mac: MacAddr) {
        match &mut self.hardware {
            Some(hardware) => hardware.add_mac(mac),
            None => self.hardware = Some(HardwareInfo::new(mac)),
        }
        self.last_seen = SystemTime::now();
    }

    /// Adds a single RTT measurement and bumps `last_seen`.
    pub fn add_rtt(&mut self, rtt: std::time::Duration) {
        self.telemetry.add_rtt(rtt);
        self.last_seen = SystemTime::now();
    }

    /// The same, from a caller that knows which probe drew the reply.
    ///
    /// Worth saying, because the probe decides what the figure measures. An ARP
    /// reply comes off the link layer; a SYN/ACK crosses the target's IP and TCP
    /// stacks. Both are round trips to the same host and neither is the other.
    pub fn add_rtt_from(&mut self, rtt: std::time::Duration, protocol: StatusProtocol) {
        self.telemetry.add_rtt_from(rtt, protocol);
        self.last_seen = SystemTime::now();
    }

    /// Which probe this host's round trips were measured from, where they agree
    /// on one.
    ///
    /// See [`HostTelemetry::rtt_protocol`](crate::model::host::telemetry::HostTelemetry::rtt_protocol).
    #[must_use]
    pub fn rtt_protocol(&self) -> Option<StatusProtocol> {
        self.telemetry.rtt_protocol()
    }

    /// Adds a round trip measured against a probe the whole segment was asked,
    /// which this host will report only if it produced no better sample.
    ///
    /// See [`RttSource`](crate::model::host::telemetry::RttSource) for
    /// why the two are kept apart.
    pub fn add_segment_wide_rtt(&mut self, rtt: std::time::Duration) {
        self.telemetry.add_segment_wide_rtt(rtt);
        self.last_seen = SystemTime::now();
    }

    /// The same, from a caller that knows which probe drew the reply.
    pub fn add_segment_wide_rtt_from(
        &mut self,
        rtt: std::time::Duration,
        protocol: StatusProtocol,
    ) {
        self.telemetry.add_segment_wide_rtt_from(rtt, protocol);
        self.last_seen = SystemTime::now();
    }

    /// Builder method to add a single RTT measurement and return Self.
    pub fn with_rtt(mut self, rtt: std::time::Duration) -> Self {
        self.add_rtt(rtt);
        self
    }

    /// Records several round-trip measurements at once.
    pub fn add_rtts(&mut self, rtts: impl IntoIterator<Item = std::time::Duration>) {
        for rtt in rtts {
            self.telemetry.add_rtt(rtt);
        }
        self.last_seen = SystemTime::now();
    }

    /// Records a role for this host, returning whether it is one the record did
    /// not already carry.
    ///
    /// The return is what a caller announces on. A role is concluded from
    /// whatever evidence turns up, and the same evidence turns up repeatedly,
    /// since a router advertises on a timer and a name server answers every
    /// lookup, so recording one and learning one are different events and only
    /// the second is news. Bumps `last_seen` either way: the host was heard from.
    pub fn add_network_role(&mut self, role: NetworkRole) -> bool {
        let is_new = self.network_roles.insert(role);
        self.last_seen = SystemTime::now();
        is_new
    }

    /// Records a filtering conclusion drawn about the path to this host,
    /// returning whether it is one not already held.
    ///
    /// Bumps `last_seen`, as [`add_network_role`](Self::add_network_role) does
    /// and for the same reason: the host was heard from, whatever the evidence
    /// re-established.
    pub fn add_filtering(&mut self, filtering: Filtering) -> bool {
        let is_new = self.filtering.insert(filtering);
        self.last_seen = SystemTime::now();
        is_new
    }

    /// Raises what is recorded about `number` to `state`, if that establishes
    /// more, and returns whether the record changed.
    ///
    /// Promotes and never lowers, on [`IpProtocolState`]'s own ordering and for
    /// the reason [`Port::set_state`] promotes: a second probe that learned less
    /// does not get to unlearn what the first established. A pass cut short
    /// after naming a protocol and before reaching it therefore leaves
    /// [`Unasked`](IpProtocolState::Unasked) standing only where nothing else
    /// was ever recorded.
    ///
    /// Bumps `last_seen` only where the host itself answered. A silence and a
    /// router's refusal are not the host being heard from, which is the same
    /// distinction [`record_evidence`](Self::record_evidence) draws.
    pub fn record_ip_protocol(&mut self, number: u8, state: IpProtocolState) -> bool {
        let recorded = match self.ip_protocols.get_mut(&number) {
            Some(held) if state > *held => {
                *held = state;
                true
            }
            Some(_) => false,
            // Recorded even at `Unasked`, which is a protocol the scan named and
            // did not reach. Leaving it off would make that indistinguishable
            // from one nobody named.
            None => {
                self.ip_protocols.insert(number, state);
                true
            }
        };

        if matches!(state, IpProtocolState::Open | IpProtocolState::Closed) {
            self.last_seen = SystemTime::now();
        }
        recorded
    }

    /// Returns the minimum recorded RTT.
    pub fn min_rtt(&self) -> Option<std::time::Duration> {
        self.telemetry.min_rtt()
    }

    /// Returns the maximum recorded RTT.
    pub fn max_rtt(&self) -> Option<std::time::Duration> {
        self.telemetry.max_rtt()
    }

    /// Returns the average recorded RTT.
    pub fn average_rtt(&self) -> Option<std::time::Duration> {
        self.telemetry.average_rtt()
    }

    /// Returns the median recorded RTT, a summary of typical latency that is
    /// robust against outliers. See [`HostTelemetry::median_rtt`].
    pub fn median_rtt(&self) -> Option<std::time::Duration> {
        self.telemetry.median_rtt()
    }

    /// Returns the most recent MAC address, if hardware info is available.
    pub fn mac(&self) -> Option<MacAddr> {
        self.hardware.as_ref().and_then(|h| h.most_recent_mac())
    }

    /// Returns the hardware vendor, if hardware info is available.
    pub fn vendor(&self) -> Option<&str> {
        self.hardware.as_ref().and_then(HardwareInfo::vendor)
    }

    /// Returns `true` if this host is confirmed to be on the network
    /// (either fully responding or filtered).
    pub fn is_alive(&self) -> bool {
        self.status.is_alive()
    }

    /// Returns an iterator over all discovered ports in sorted order.
    pub fn ports(&self) -> impl Iterator<Item = &Port> {
        self.ports.values()
    }

    /// Returns the total number of recorded ports for this host.
    pub fn port_count(&self) -> usize {
        self.ports.len()
    }

    /// Records a port finding, merging it with what is already known about that
    /// port.
    ///
    /// Returns whether the finding was recorded. `false` means the host is at
    /// [`MAX_PORTS_PER_HOST`] and has been marked [`NetworkRole::Truncated`];
    /// the caller is told rather than left to assume the port list is complete.
    /// No scan reaches that cap, for the reason
    /// [`Truncated`](NetworkRole::Truncated) gives, so a caller checking this
    /// return is checking a guard rather than an outcome.
    ///
    /// A host that crosses [`TARPIT_OPEN_PORTS`] open ports is marked
    /// [`NetworkRole::Tarpit`] and keeps recording. That is a different claim
    /// from truncation and is not a reason to stop: the ports are
    /// still what the host said, and a caller that wants to discard them can,
    /// where a caller handed a silently shortened list cannot.
    pub fn add_port(&mut self, new_port: Port) -> bool {
        let key = (new_port.number(), new_port.protocol());
        let existing = self.ports.get(&key);

        if existing.is_none() && self.ports.len() >= MAX_PORTS_PER_HOST {
            self.network_roles.insert(NetworkRole::Truncated);
            return false;
        }

        let was_open = existing.is_some_and(|port| port.state() == PortState::Open);

        // Matched on the entry rather than `and_modify` beside `or_insert`,
        // which needs the value in both closures and so cloned it on every
        // re-probe. `new_port` is owned and a `Port` is not cheap to copy: a
        // findings map, a service with its identifiers, a security record with
        // its certificate and every name on it.
        let recorded = match self.ports.entry(key) {
            std::collections::btree_map::Entry::Occupied(slot) => {
                let recorded = slot.into_mut();
                recorded.merge(new_port);
                recorded
            }
            std::collections::btree_map::Entry::Vacant(slot) => slot.insert(new_port),
        };

        // A state only ever promotes, so this counts up and never has to count
        // back down; see `open_ports`.
        if !was_open && recorded.state() == PortState::Open {
            self.open_ports += 1;
            if self.open_ports >= TARPIT_OPEN_PORTS {
                self.network_roles.insert(NetworkRole::Tarpit);
            }
        }

        self.last_seen = SystemTime::now();
        true
    }

    /// How many of this host's ports are open.
    pub fn open_port_count(&self) -> usize {
        self.open_ports
    }

    /// Folds another record of this host into this one.
    ///
    /// This is how findings from separate scan stages become a single record.
    /// Status is promoted and never lowered, telemetry and OS data merge by
    /// their own rules, and the port cap still applies.
    ///
    /// The address the merged record leads with is decided by
    /// [`consider_primary_ip`](Self::consider_primary_ip), not by which of the
    /// two happened to be `self`. Two records of one host are two probes'
    /// accounts of it, and the ranking exists precisely because the order they
    /// arrive in is nobody's to control. A merge that kept the incumbent address
    /// unconditionally would reintroduce between phases the same
    /// machine-reported-as-two that the ranking prevents within one.
    pub fn merge(&mut self, other: Host) {
        // Destructured rather than reached through `other.…`, so a field added
        // to this struct is a compile error here and not a value that is
        // quietly dropped at every call site this has.
        let Host {
            primary_ip: other_primary,
            ips,
            hostname,
            status,
            reasons,
            os,
            os_evidence,
            hardware,
            zone,
            telemetry,
            path,
            network_roles,
            filtering,
            ip_protocols,
            findings,
            first_seen: other_first_seen,
            last_seen: other_last_seen,
            ports,
            // Derived, and maintained by `add_port` as the ports below arrive.
            open_ports: _,
        } = other;

        // Taken before anything else, and restored at the end.
        //
        // Every mutator below stamps `last_seen` with the current time, because
        // each of them is normally a scanner reporting something it just saw.
        // A merge is not a sighting: it folds two records that were each
        // observed earlier. Left alone, the stamps would overwrite both
        // records' observation times with the moment they happened to be folded
        // together, and `last_seen` would answer "when was this record last
        // touched" to a reader who asked when the host was last heard from.
        let first_seen = self.first_seen.min(other_first_seen);
        let last_seen = self.last_seen.max(other_last_seen);

        self.ips.extend(ips);
        self.consider_primary_ip(other_primary);

        if self.hostname.is_none() {
            self.hostname = hostname;
        }

        if status > self.status {
            self.status = status;
        }
        self.reasons.extend(reasons);

        if let Some(other_os) = os {
            if let Some(ref mut self_os) = self.os {
                self_os.merge(*other_os);
            } else {
                self.os = Some(other_os);
            }
        }

        // Through `record_os_evidence` rather than by extending the map, so two
        // records of one claim keep the strongest confidence and every distinct
        // line behind it, and the ceiling still turns away only what is new.
        for evidence in os_evidence.into_values() {
            self.record_os_evidence(evidence);
        }

        if let Some(other_hw) = hardware {
            if let Some(ref mut self_hw) = self.hardware {
                self_hw.merge(other_hw);
            } else {
                self.hardware = Some(other_hw);
            }
        }

        if let Some(other_zone) = zone {
            self.zone.get_or_insert(other_zone);
        }

        self.telemetry.merge(telemetry);

        // Hop by hop rather than by taking whichever path looks fuller, so the
        // "only ever gets stronger" rule in `NetworkPath::record` decides each
        // distance: a measurement beats an inference, an answer beats silence,
        // and neither side has to be the winner as a whole.
        //
        // A merge is where a path is most easily lost. A port scan snapshots its
        // hosts once for the liveness phase and again at the end, then folds the
        // two together, and the trace runs between those moments, so the earlier
        // record has no path at all. Left out here, the empty half wins and the
        // scan reports a path it measured and then discarded.
        for hop in path.hops() {
            self.path.record(*hop);
        }

        self.network_roles.extend(network_roles);

        // A conclusion about the filter in front of a host is drawn by a
        // comparative probe that only one of two records will have run, so a
        // fold that dropped the other side's would discard the whole finding.
        self.filtering.extend(filtering);

        // Through the recorder rather than by extending the map, so a record
        // that only got as far as naming a protocol cannot lower one that
        // reached it. Two sittings of a job routinely disagree that way: the
        // second is cut short and holds `Unasked` where the first holds a
        // verdict.
        for (number, state) in ip_protocols {
            self.record_ip_protocol(number, state);
        }

        // Findings accumulate: a claim missing from one record is a detection
        // that did not run there, never a retraction, so a fold adds and never
        // removes. A claim on both corroborates through `add_finding`.
        for finding in findings.into_values() {
            self.add_finding(finding);
        }

        for port in ports.into_values() {
            self.add_port(port);
        }

        self.first_seen = first_seen;
        self.last_seen = last_seen;
    }
}

impl std::fmt::Display for Host {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ({})", self.primary_ip, self.status)?;
        if let Some(ref os) = self.os {
            write!(f, " - {}", os)?;
        }

        // Listed in `NetworkRole::ALL` order rather than the set's, so two runs
        // that found the same things print the same line. A `HashSet` iterates
        // in whatever order its hashing produced.
        let mut roles = NetworkRole::ALL
            .iter()
            .filter(|role| self.network_roles.contains(role))
            .peekable();
        if roles.peek().is_some() {
            write!(f, " [")?;
            for (n, role) in roles.enumerate() {
                if n > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}", role.label())?;
            }
            write!(f, "]")?;
        }

        // A latency beside a host whose port list is meaningless invites the
        // reader to act on the rest of the line, so the two markings that say
        // "do not" take the space instead.
        if !self.network_roles.contains(&NetworkRole::Tarpit)
            && !self.network_roles.contains(&NetworkRole::Truncated)
        {
            write!(f, " [{}]", self.telemetry)?;
        }
        Ok(())
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::port::{Port, PortState, Protocol};
    use std::net::Ipv4Addr;

    static IP_ADDR: IpAddr = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 100));

    /// Refusing the address a host leads with hands the lead to the best of the
    /// rest, by the same ranking that chose it: a global IPv6 address over a
    /// link-local, whichever was learned first.
    #[test]
    fn a_refused_lead_passes_to_the_best_address_left() {
        let v4: IpAddr = "192.0.2.60".parse().expect("literal");
        let global: IpAddr = "2001:db8::5".parse().expect("literal");
        let link_local: IpAddr = "fe80::10".parse().expect("literal");

        let mut host = Host::new(link_local);
        host.add_ip(global);
        host.consider_primary_ip(v4);
        assert_eq!(host.primary_ip(), v4, "test premise");

        assert!(host.retain_ips(|ip| *ip != v4));
        assert_eq!(host.primary_ip(), global);
        assert_eq!(
            host.ips().iter().copied().collect::<Vec<_>>(),
            vec![global, link_local]
        );
    }

    /// A host with nothing left to be reported under is not left without an
    /// address: it is handed back as it was, and the caller decides.
    #[test]
    fn a_host_every_address_of_which_is_refused_is_left_as_it_was() {
        let mut host = Host::new(IP_ADDR);
        host.add_ip("192.0.2.61".parse().expect("literal"));
        let before = host.ips().clone();

        assert!(!host.retain_ips(|_| false));
        assert_eq!(host.primary_ip(), IP_ADDR);
        assert_eq!(*host.ips(), before);
    }

    /// A pass that only got as far as naming a protocol must not unlearn one
    /// that reached it, in either direction: a promotion is a promotion and a
    /// merge is two of them.
    #[test]
    fn a_protocol_verdict_is_promoted_and_never_lowered() {
        use crate::model::host::IpProtocolState;

        let mut host = Host::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)));

        assert!(host.record_ip_protocol(47, IpProtocolState::Unasked));
        assert_eq!(
            host.ip_protocols().get(&47),
            Some(&IpProtocolState::Unasked)
        );

        assert!(host.record_ip_protocol(47, IpProtocolState::Closed));
        assert!(
            !host.record_ip_protocol(47, IpProtocolState::OpenFiltered),
            "a weaker verdict is not news"
        );
        assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Closed));

        assert!(host.record_ip_protocol(47, IpProtocolState::Open));
        assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Open));
    }

    /// The same rule across a fold. Two sittings of one job disagree exactly
    /// this way when the second is cut short.
    #[test]
    fn merging_keeps_the_stronger_protocol_verdict_from_either_side() {
        use crate::model::host::IpProtocolState;

        let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));

        let mut reached = Host::new(ip);
        reached.record_ip_protocol(47, IpProtocolState::Open);
        reached.record_ip_protocol(89, IpProtocolState::Unasked);

        let mut cut_short = Host::new(ip);
        cut_short.record_ip_protocol(47, IpProtocolState::Unasked);
        cut_short.record_ip_protocol(89, IpProtocolState::Closed);
        cut_short.record_ip_protocol(50, IpProtocolState::OpenFiltered);

        let mut folded = reached.clone();
        folded.merge(cut_short.clone());
        let mut other_way = cut_short;
        other_way.merge(reached);

        for host in [&folded, &other_way] {
            assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Open));
            assert_eq!(host.ip_protocols().get(&89), Some(&IpProtocolState::Closed));
            assert_eq!(
                host.ip_protocols().get(&50),
                Some(&IpProtocolState::OpenFiltered),
                "a protocol only one side asked about survives the fold"
            );
        }
    }

    /// Every field of the record being folded in, not merely the ones somebody
    /// remembered.
    ///
    /// A `merge` consuming `other` field by field drops any field it never
    /// names, at every call site it has: without `filtering` and `os_evidence`,
    /// a resumed scan would keep only the first journal record's and a report
    /// assembled from two records would lose the second's. Destructuring
    /// `other` is what stops a field going that way; this asserts those two.
    #[test]
    fn a_merge_keeps_every_field_of_the_record_it_folds_in() {
        let ip: IpAddr = "192.0.2.1".parse().expect("an address");
        let mut incumbent = Host::new(ip);
        let mut arriving = Host::new(ip);

        arriving.add_filtering(Filtering::StatefulFilter);
        arriving.add_filtering(Filtering::InlineMiddlebox);
        arriving.record_os_evidence(OsEvidence {
            source: OsSource::ServiceBanner,
            family: Some("Linux".to_string()),
            device: None,
            vendor: None,
            product: None,
            version: None,
            kernel: Some("6.1.0".to_string()),
            arch: None,
            cpe: None,
            confidence: 0.9,
            evidence: "ssh banner".to_string(),
        });

        incumbent.merge(arriving);

        assert_eq!(
            incumbent.filtering().len(),
            2,
            "a filtering conclusion is drawn by a comparative probe only one \
             record will have run, so dropping it loses the whole finding"
        );
        assert_eq!(
            incumbent.os_evidence().count(),
            1,
            "os evidence is what corroboration is computed over, and the \
             fold is where a second source's reading arrives"
        );
    }

    /// A merge folds in what only one side of it knows.
    ///
    /// A port scan snapshots its hosts twice, once for the liveness phase and
    /// once at the end, and folds the two together, so anything learned between
    /// those moments exists on only the later record. A field left out of `merge`
    /// is
    /// then silently discarded, and the scan reports having found nothing of
    /// something it measured in full. The path and the hop counter both shipped
    /// with exactly that bug: the trace ran, recorded every router, and the
    /// empty earlier snapshot won.
    ///
    /// Asserted in the direction the port scan merges, with the record lacking
    /// the finding on the left, since that is the direction that loses it.
    #[test]
    fn a_merge_keeps_what_only_the_other_record_learned() {
        let mut earlier = Host::new(IP_ADDR);
        earlier.set_status(HostStatus::Up);

        let mut later = Host::new(IP_ADDR);
        later.record_hop_counter(59);
        later.record_hop(path::Hop::answered(
            1,
            IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1)),
            None,
        ));
        later.record_hop(path::Hop::silent(2));

        earlier.merge(later);

        assert_eq!(
            earlier.path().hops().len(),
            2,
            "the trace ran between the two snapshots and only the later one has it"
        );
        assert_eq!(earlier.path().length(), Some(2));
        assert_eq!(earlier.telemetry().hop_counter(), Some(59));
    }

    /// Merging two paths settles each distance on its own terms.
    ///
    /// Not "whichever path is longer wins": two records can each know a
    /// different half, and a distance one of them only inferred may be one the
    /// other actually measured. `NetworkPath::record` already holds that rule,
    /// so the merge has to go through it hop by hop rather than choosing a side.
    #[test]
    fn merging_paths_keeps_the_stronger_claim_at_every_distance() {
        let router = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1));

        let mut inherited = Host::new(IP_ADDR);
        inherited.record_hop(path::Hop::answered(1, router, None).as_inferred());
        inherited.record_hop(path::Hop::silent(2));

        let mut measured = Host::new(IP_ADDR);
        measured.record_hop(path::Hop::answered(
            1,
            router,
            Some(std::time::Duration::from_millis(3)),
        ));

        inherited.merge(measured);

        let hops = inherited.path().hops();
        assert_eq!(hops.len(), 2, "the distance only one side knew survives");
        assert!(!hops[0].inferred(), "a measurement replaces an inference");
        assert_eq!(hops[0].rtt(), Some(std::time::Duration::from_millis(3)));
    }

    /// A status only ever improves. The rule lives on every entry point that
    /// can set one, not just on `record_evidence`, or a caller reaching for the
    /// plain setter quietly opts out of it.
    #[test]
    fn a_status_is_never_lowered_by_the_plain_setter() {
        let mut host = Host::new(IP_ADDR);

        host.set_status(HostStatus::Up);
        host.set_status(HostStatus::Down);
        assert_eq!(host.status(), HostStatus::Up);

        let mut climbing = Host::new(IP_ADDR);
        climbing.set_status(HostStatus::Down);
        climbing.set_status(HostStatus::Up);
        assert_eq!(climbing.status(), HostStatus::Up);
    }

    /// A port number names two endpoints, and a scan can be asked about both:
    /// `PortSet` spells the UDP half `u:53`, and the raw TCP and UDP scanners
    /// each report their findings here. Keyed on the number alone, the second
    /// arrival merges into the first, so one result is lost and the survivor is
    /// reported under the other's protocol with a state maximised across two
    /// unrelated questions.
    #[test]
    fn a_port_number_holds_one_endpoint_per_protocol() {
        let mut host = Host::new(IP_ADDR);
        host.add_port(Port::new(53, Protocol::Tcp, PortState::Closed));
        host.add_port(Port::new(53, Protocol::Udp, PortState::Open));

        let ports: Vec<_> = host.ports().collect();
        assert_eq!(ports.len(), 2, "TCP/53 and UDP/53 are two endpoints");
        assert_eq!(
            (ports[0].protocol(), ports[0].state()),
            (Protocol::Tcp, PortState::Closed)
        );
        assert_eq!(
            (ports[1].protocol(), ports[1].state()),
            (Protocol::Udp, PortState::Open),
            "neither finding was folded into the other"
        );

        // And a repeat of one of them still merges with its own protocol.
        host.add_port(Port::new(53, Protocol::Tcp, PortState::Open));
        assert_eq!(host.port_count(), 2);
        assert_eq!(
            host.ports().next().expect("tcp/53").state(),
            PortState::Open
        );
    }

    /// Roles are held in a `HashSet`, which iterates in whatever order its
    /// hashing produced, so a line built by walking it directly differs between
    /// two runs that found the same things and between two machines reading the
    /// same journal. A report a reader diffs by eye has to be stable.
    #[test]
    fn a_host_prints_its_roles_in_one_order_however_they_were_recorded() {
        let expected = "203.0.113.100 (Up) [router, DNS, origin]";

        for order in [
            [
                NetworkRole::Router,
                NetworkRole::DnsServer,
                NetworkRole::Origin,
            ],
            [
                NetworkRole::Origin,
                NetworkRole::Router,
                NetworkRole::DnsServer,
            ],
            [
                NetworkRole::DnsServer,
                NetworkRole::Origin,
                NetworkRole::Router,
            ],
        ] {
            let mut host = Host::new(IP_ADDR);
            host.set_status(HostStatus::Up);
            for role in order {
                host.add_network_role(role);
            }

            let line = host.to_string();
            let (roles, _telemetry) = line.rsplit_once(" [").expect("telemetry follows the roles");
            assert_eq!(roles, expected, "recorded as {order:?}");
        }
    }

    /// A latency printed beside a host whose port list is meaningless invites
    /// the reader to act on the rest of the line, so the two markings that say
    /// not to take the space instead.
    #[test]
    fn a_tarpit_prints_the_marking_where_the_latency_would_be() {
        let mut host = Host::new(IP_ADDR);
        host.set_status(HostStatus::Up);
        host.add_network_role(NetworkRole::Tarpit);

        assert_eq!(host.to_string(), "203.0.113.100 (Up) [tarpit]");
    }

    /// The largest scan a person can write, recorded whole.
    ///
    /// `1-65535,u:1-65535` is one port specification, and against a host that
    /// answers on all of it, and a closed port is an answer, it is
    /// `MAX_PORTS_PER_HOST` endpoints. Every one has to be kept and the record
    /// has to say it is complete.
    ///
    /// A cap of one protocol's port space, where the map holds two, would have
    /// this scan record its TCP half, refuse all 65 536 UDP findings, and report
    /// the host as truncated, telling the operator the list was short and not
    /// which half was missing.
    #[test]
    fn a_full_scan_of_both_transports_is_recorded_whole() {
        let mut host = Host::new(IP_ADDR);

        for protocol in Protocol::ALL {
            for port in u16::MIN..=u16::MAX {
                assert!(
                    host.add_port(Port::new(port, protocol, PortState::Closed)),
                    "{protocol:?}/{port} was refused by a scan that asked for it"
                );
            }
        }

        assert_eq!(host.port_count(), MAX_PORTS_PER_HOST);
        assert!(
            !host.network_roles().contains(&NetworkRole::Truncated),
            "a complete port list was reported as truncated"
        );
    }

    /// The cap sits exactly at what the map can hold, so no scan reaches it.
    ///
    /// Pinned because that is the property, not an accident of the number: the
    /// map is keyed on a port number and a transport, and the cap is derived
    /// from the same two. A cap written as a literal, or one that does not
    /// count the transports, is a scan silently cut short.
    #[test]
    fn the_cap_is_what_the_port_map_can_hold() {
        let endpoints = (usize::from(u16::MAX) + 1) * Protocol::ALL.len();
        assert_eq!(MAX_PORTS_PER_HOST, endpoints);
    }

    /// Why the two markings are kept apart.
    ///
    /// Probing the well-known range on a host that answers records a thousand
    /// ports, because a closed port is an answer. Were that the cap, under one
    /// marking for both, the last findings would be dropped without a word and
    /// a domestic router would come back labelled a tarpit. Nothing about a
    /// wide scan of an ordinary machine says either thing.
    #[test]
    fn a_wide_scan_of_an_ordinary_host_is_neither_truncated_nor_a_tarpit() {
        let mut host = Host::new(IP_ADDR);
        for port in 1..=1024u16 {
            let state = match port {
                53 | 80 => PortState::Open,
                _ => PortState::Closed,
            };
            assert!(host.add_port(Port::new(port, Protocol::Tcp, state)));
        }

        assert_eq!(host.port_count(), 1024, "every finding was kept");
        assert!(host.network_roles().is_empty(), "and nothing was inferred");
    }

    /// A thousand *open* ports is not a machine, and saying so is the whole
    /// purpose of the role. It is a claim about the host, so recording does not
    /// stop: a caller handed the ports can discard them, where a caller handed a
    /// silently shortened list cannot.
    #[test]
    fn a_host_answering_open_on_everything_is_called_what_it_is() {
        let mut host = Host::new(IP_ADDR);
        for port in 0..TARPIT_OPEN_PORTS {
            host.add_port(Port::new(port as u16, Protocol::Tcp, PortState::Open));
        }

        assert!(host.network_roles().contains(&NetworkRole::Tarpit));
        assert!(!host.network_roles().contains(&NetworkRole::Truncated));
        assert_eq!(host.open_port_count(), TARPIT_OPEN_PORTS);
    }

    /// The count follows promotions, not insertions. A port first seen filtered
    /// and later answered is one more open port, and a second reply about a port
    /// already open is not.
    #[test]
    fn the_open_count_follows_what_the_ports_became() {
        let mut host = Host::new(IP_ADDR);

        host.add_port(Port::new(22, Protocol::Tcp, PortState::Filtered));
        assert_eq!(host.open_port_count(), 0);

        host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
        assert_eq!(host.open_port_count(), 1, "promoted");

        host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
        assert_eq!(host.open_port_count(), 1, "and counted once");
    }

    /// `last_seen` answers when the host was last heard from, so a merge, which
    /// hears from nothing, must not move it. Every mutator a merge runs stamps
    /// the current time, so without care both records' observation times are
    /// replaced by the moment they were folded together.
    ///
    /// Stamped by hand rather than by construction order: `SystemTime` is only
    /// as fine-grained as the platform makes it, and on Windows two
    /// constructions can land on the same tick.
    #[test]
    fn merging_two_records_keeps_the_span_they_were_observed_over() {
        let epoch = SystemTime::UNIX_EPOCH;
        let at = |secs| epoch + std::time::Duration::from_secs(secs);

        let mut early = Host::new(IP_ADDR);
        early.first_seen = at(10);
        early.last_seen = at(20);

        let mut late = Host::new(IP_ADDR);
        late.first_seen = at(30);
        late.last_seen = at(40);

        early.merge(late);

        assert_eq!(early.first_seen(), at(10), "the earlier sighting");
        assert_eq!(early.last_seen(), at(40), "and the later one");
    }

    /// Merge promotes on the same ordering the setters use, so folding one
    /// phase into another gives what a single phase would.
    #[test]
    fn merging_promotes_the_status_without_lowering_it() {
        let mut h1 = Host::new(IP_ADDR);
        h1.set_status(HostStatus::Down);

        let mut h2 = Host::new(IP_ADDR);
        h2.set_status(HostStatus::Filtered);

        h1.merge(h2);
        assert_eq!(h1.status(), HostStatus::Filtered);
    }

    /// Two records of one host are two probes' accounts of it, and which of
    /// them is `self` is an accident of arrival order. A merge that kept the
    /// incumbent address would report the same machine under its link-local on
    /// one run and its IPv4 on the next. That is the failure
    /// [`Host::consider_primary_ip`] exists to prevent, reintroduced one layer
    /// up where phases meet.
    #[test]
    fn merging_two_records_of_one_host_applies_the_same_address_ranking() {
        let v4: IpAddr = "192.0.2.10".parse().unwrap();
        let lla: IpAddr = "fe80::10".parse().unwrap();

        let mut into_link_local = Host::new(lla);
        into_link_local.merge(Host::new(v4));
        assert_eq!(into_link_local.primary_ip(), v4);

        let mut into_v4 = Host::new(v4);
        into_v4.merge(Host::new(lla));
        assert_eq!(
            into_v4.primary_ip(),
            v4,
            "and the ranking never moves back down"
        );

        assert_eq!(into_link_local.ips().len(), 2, "nothing is discarded");
        assert_eq!(into_v4.ips().len(), 2);
    }

    /// A device with two interfaces on one segment, or one randomizing the
    /// address it answers under, is a single host with a history. That history
    /// is the whole of what [`HardwareInfo`] stores. Replacing on each sighting
    /// leaves whichever probe replied last, and makes
    /// [`HardwareInfo::most_recent_mac`] report an arrival order rather than a
    /// timeline.
    #[test]
    fn every_mac_a_host_answers_under_stays_on_its_record() {
        let first = MacAddr::new(0x02, 0, 0, 0, 0, 1);
        let second = MacAddr::new(0x02, 0, 0, 0, 0, 2);

        let mut host = Host::new(IP_ADDR);
        host.record_mac(first);
        host.record_mac(second);

        let hardware = host.hardware().expect("a sighting was recorded");
        assert_eq!(hardware.macs().len(), 2);
        assert!(hardware.macs().contains_key(&first));
        assert!(hardware.macs().contains_key(&second));
        assert_eq!(
            host.mac(),
            Some(second),
            "and the newest is the one the host leads with"
        );
    }

    /// A merge folds one record's ports into another's through the same entry
    /// point, so an overlap is not two ports and an endpoint on the other
    /// transport is not a collision.
    ///
    /// The second half is the one at risk. A UDP endpoint folded into a record
    /// holding the whole of TCP would be refused, and the merged host marked
    /// truncated, by a cap that counted both transports against one
    /// transport's port space.
    #[test]
    fn merging_two_records_keeps_the_union_of_their_ports() {
        // The whole of TCP, half of what the map can hold.
        let mut h1 = Host::new(IP_ADDR);
        for port in u16::MIN..=u16::MAX {
            h1.add_port(Port::new(port, Protocol::Tcp, PortState::Closed));
        }
        assert_eq!(h1.port_count(), usize::from(u16::MAX) + 1);
        assert!(!h1.network_roles.contains(&NetworkRole::Truncated));

        // An overlapping thousand, which adds nothing, and one endpoint on the
        // other transport, which does.
        let mut h2 = Host::new(IP_ADDR);
        for port in 0..1_000u16 {
            h2.add_port(Port::new(port, Protocol::Tcp, PortState::Closed));
        }
        h2.add_port(Port::new(53, Protocol::Udp, PortState::Open));

        h1.merge(h2);

        assert_eq!(
            h1.port_count(),
            usize::from(u16::MAX) + 2,
            "the union: the whole of TCP and one UDP endpoint"
        );
        assert!(
            !h1.network_roles.contains(&NetworkRole::Truncated),
            "nothing was dropped, so nothing here is truncated"
        );
        assert!(
            !h1.network_roles.contains(&NetworkRole::Tarpit),
            "one open port is not a tarpit"
        );
    }

    /// The address a dual-stack host is reported under must not depend on which
    /// probe happened to answer first, or one machine is reported as two across
    /// consecutive runs of the same scan.
    #[test]
    fn the_address_a_host_leads_with_does_not_depend_on_reply_order() {
        let v4: IpAddr = "192.0.2.10".parse().unwrap();
        let gua: IpAddr = "2001:db8::10".parse().unwrap();
        let lla: IpAddr = "fe80::10".parse().unwrap();

        // Every order the three replies could arrive in.
        for order in [
            [v4, gua, lla],
            [v4, lla, gua],
            [gua, v4, lla],
            [gua, lla, v4],
            [lla, v4, gua],
            [lla, gua, v4],
        ] {
            let mut host = Host::new(order[0]);
            for ip in order {
                host.consider_primary_ip(ip);
            }

            assert_eq!(
                host.primary_ip(),
                v4,
                "arrival order {order:?} must not change which address leads"
            );
            assert_eq!(host.ips().len(), 3, "and none of them is discarded");
        }
    }

    /// The ranking's middle tier is "names the host from off its segment", and
    /// only addresses that do belong in it. Written as not link-local it also
    /// admitted loopback, multicast and the unspecified address, none of which
    /// name this host to anybody and each of which would have displaced a genuine
    /// link-local address that at least names it to its own segment.
    #[test]
    fn only_a_globally_scoped_address_outranks_a_link_local_one() {
        let lla: IpAddr = "fe80::10".parse().unwrap();

        for scoped in ["2001:db8::10", "fd00::10"] {
            let mut host = Host::new(lla);
            host.consider_primary_ip(scoped.parse().unwrap());
            assert_eq!(
                host.primary_ip().to_string(),
                scoped,
                "{scoped} names the host"
            );
        }

        for useless in ["::1", "::", "ff02::1"] {
            let mut host = Host::new(lla);
            host.consider_primary_ip(useless.parse().unwrap());
            assert_eq!(
                host.primary_ip(),
                lla,
                "{useless} does not identify the host to anyone"
            );
        }
    }

    /// Without IPv4, a globally scoped address leads over a link-local one: it
    /// names the host from anywhere, where `fe80::…` names a different machine
    /// on every segment.
    #[test]
    fn a_global_address_leads_over_a_link_local_one() {
        let gua: IpAddr = "2001:db8::10".parse().unwrap();
        let lla: IpAddr = "fe80::10".parse().unwrap();

        let mut from_lla = Host::new(lla);
        from_lla.consider_primary_ip(gua);
        assert_eq!(from_lla.primary_ip(), gua);

        let mut from_gua = Host::new(gua);
        from_gua.consider_primary_ip(lla);
        assert_eq!(
            from_gua.primary_ip(),
            gua,
            "and the ranking never moves back down"
        );
    }

    /// A tie keeps the incumbent, so a host with several equally good addresses
    /// does not flip between them as replies arrive.
    #[test]
    fn an_equally_good_address_does_not_displace_the_current_one() {
        let first: IpAddr = "2001:db8::1".parse().unwrap();
        let second: IpAddr = "2001:db8::2".parse().unwrap();

        let mut host = Host::new(first);
        assert!(!host.consider_primary_ip(second));
        assert_eq!(host.primary_ip(), first);
        assert!(
            host.ips().contains(&second),
            "it is still an address it has"
        );
    }

    fn a_finding(detection_id: &str) -> Finding {
        use crate::model::confidence::Confidence;
        use crate::model::finding::{DetectionClass, DetectionId, Severity, Version};
        Finding::new(
            DetectionId::new(detection_id, Version::new(1, 0, 0), "hash").unwrap(),
            "A host-level finding",
            Severity::High,
            Confidence::Certain,
            DetectionClass::ActiveBenign,
        )
        .unwrap()
    }

    #[test]
    fn the_same_finding_recorded_twice_is_one() {
        let mut host = Host::new(IP_ADDR);
        assert!(host.add_finding(a_finding("det-a")), "the first is new");
        assert!(
            !host.add_finding(a_finding("det-a")),
            "an identical re-firing is not new information"
        );
        assert_eq!(host.findings().count(), 1);
    }

    #[test]
    fn a_merge_keeps_both_hosts_findings() {
        // The failure this guards is the silent one: a merge that folds ports and
        // roles but forgets findings reports a clean host that had a finding.
        let mut base = Host::new(IP_ADDR);
        base.add_finding(a_finding("det-a"));

        let mut other = Host::new(IP_ADDR);
        other.add_finding(a_finding("det-b"));

        base.merge(other);

        let ids: Vec<String> = base
            .findings()
            .map(|f| f.detection().id().to_string())
            .collect();
        assert_eq!(ids.len(), 2, "a merge must not drop the other's findings");
        assert!(ids.contains(&"det-a".to_string()));
        assert!(ids.contains(&"det-b".to_string()));
    }
}