zenkey-model 0.25.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
//! `freshness.v1`: how long a value stays current
//! (`spec/profiles/freshness/v1.md`, #720).
//!
//! The profile's session-free half: the horizon read from a resource's
//! annotations (§2.1–§2.3), and the pure judgement of one observation of a
//! member (§2.5–§2.8), three states and a reason, with the rule that
//! combines several observations (§2.7).
//!
//! ```text
//! horizon(kind, annotations) ─▶ Undeclared │ Ignored │ Invalid │ Never │ Within(ttl)
//! judge(horizon, observation) ─▶ fresh │ stale │ unobservable │ not_asked, + reason
//! combine(judged…)            ─▶ fresh > stale > unobservable > not_asked
//! ```
//!
//! There is no I/O and no clock here. A reader measures what an observation
//! holds (a delivery's age on its monotonic clock, a reply's stamp age
//! against its wall clock, whether that clock is trusted to the delta) and
//! hands it over as values. The owner's re-puts (§2.4) are the runtime's.
//!
//! **A reader's view** ([`View`], #978's F2): the members of one owner's
//! collections for one interface as a reader heard them, and what that
//! owner's heartbeats (core §7.5, [`crate::heartbeat`]) confirmed. A
//! heartbeat whose section's digest is the view's confirms each member it
//! vouches for at its arrival, so [`View::observation`] ages a member from
//! the later of its last put and its last confirmation. `freshness.v2`
//! (`spec/profiles/freshness/v2.md`, #978's F3) adopts the heartbeat: a
//! contract that uses it is confirmed by its owner's heartbeats, never by
//! re-puts ([`uses_v2`]), and its reader's rule is [`View::apply`]'s
//! (`conformance/apply.json`). The judgement is §2.5's, unchanged.

use std::collections::BTreeMap;
use std::fmt;
use std::time::{Duration, SystemTime};

use serde_json::Value;

use crate::authoring::Kind;
use crate::contract::Resource;
use crate::wire::Stamp;

/// The profile's id, as a contract lists it in `uses`.
pub const PROFILE: &str = "freshness.v1";

/// `freshness.v2`'s id (#978's F3): a contract that lists it in `uses` is
/// confirmed by its owner's heartbeats (core §7.5's form 6), one per
/// interface, and its owner re-puts nothing to confirm it (v2 §2.4).
pub const PROFILE_V2: &str = crate::heartbeat::PROFILE;

/// Whether `c` uses `freshness.v2` (v2 §1): its owner confirms its
/// collections by heartbeats, re-puts none of them, and puts them without
/// a Zenoh timestamp, its replies carrying each member's last confirmation
/// (core §4.3's table, row 1). A contract listing both texts is read
/// under v2.
#[must_use]
pub fn uses_v2(c: &crate::contract::Contract) -> bool {
    c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
}

/// The profile's name, as an annotation key's prefix carries it.
pub const NAME: &str = "freshness";

/// The one annotation key (§4).
pub const TTL_S: &str = "freshness.ttl_s";

/// The published vocabulary (§4): the keys under `freshness.`, which W105
/// reads in place of core Appendix D's interim row (core 0.21).
pub const VOCABULARY: &[&str] = &["ttl_s"];

/// The largest horizon, in seconds: 2^53−1, the canonical domain's bound
/// (§2.1, core §9.5).
pub const MAX_TTL_S: u64 = (1 << 53) - 1;

/// The HLC's maximum delta unless the deployment configures another (core
/// §4.1): what a GET reader's trusted clock is trusted to (§2.6).
pub const DEFAULT_DELTA: Duration = Duration::from_millis(500);

/// A resource's staleness horizon, read from its resolved annotations
/// (§2.1–§2.3).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Horizon {
    /// No `freshness.ttl_s`: freshness is not asked (§2.3).
    Undeclared,
    /// A horizon on an event or an operation, which have no freshness
    /// (§2.2): ignored.
    Ignored,
    /// A `freshness.ttl_s` that is not a horizon (§2.1), as JSON text: the
    /// resource's freshness is unobservable.
    Invalid(String),
    /// `0`: never stale (§2.3).
    Never,
    /// A horizon above 0.
    Within(Duration),
}

impl Horizon {
    /// The horizon, when it is one above 0.
    #[must_use]
    pub fn ttl(&self) -> Option<Duration> {
        match self {
            Self::Within(t) => Some(*t),
            _ => None,
        }
    }

    /// The owner's bound between two puts of a member (§2.4): ttl/2, when
    /// the horizon is above 0.
    #[must_use]
    pub fn refresh_bound(&self) -> Option<Duration> {
        self.ttl().map(|t| t / 2)
    }
}

impl fmt::Display for Horizon {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Undeclared => f.write_str("no horizon"),
            Self::Ignored => f.write_str("a horizon this kind ignores"),
            Self::Invalid(v) => write!(f, "{v}, not a horizon"),
            Self::Never => f.write_str("ttl_s = 0, never stale"),
            Self::Within(t) => write!(f, "ttl_s = {}", t.as_secs()),
        }
    }
}

/// Reads the horizon of a resource of `kind` from its resolved annotations
/// (§2.1, §2.2): `[defaults]`, then `[defaults.<kind>]`, then its own, as
/// the contract model merges them (core §9.3).
#[must_use]
pub fn horizon(kind: Kind, annotations: &BTreeMap<String, Value>) -> Horizon {
    let Some(v) = annotations.get(TTL_S) else {
        return Horizon::Undeclared;
    };
    if matches!(kind, Kind::Event | Kind::Operation) {
        return Horizon::Ignored;
    }
    match seconds(v) {
        Some(0) => Horizon::Never,
        Some(n) => Horizon::Within(Duration::from_secs(n)),
        None => Horizon::Invalid(v.to_string()),
    }
}

/// [`horizon`] of a resource of a contract.
#[must_use]
pub fn horizon_of(r: &Resource) -> Horizon {
    horizon(r.kind, &r.annotations)
}

/// A whole number of seconds from 0 to 2^53−1, or `None` (§2.1). An
/// integral float is that integer, as the canonical form writes it: `60.0`
/// is 60, and `-0.0` is 0.
fn seconds(v: &Value) -> Option<u64> {
    let n = v.as_number()?;
    if let Some(u) = n.as_u64() {
        return (u <= MAX_TTL_S).then_some(u);
    }
    if n.is_i64() {
        return None;
    }
    let f = n.as_f64()?;
    // `-0.0 >= 0.0` holds: JCS writes it `0`.
    let max = MAX_TTL_S as f64;
    (f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= max).then_some(f as u64)
}

/// A reply stamp's age at the instant a reader judges it: its clock minus
/// the stamp's time, negative when the stamp is ahead of the reader's clock
/// (§2.6). Nanoseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StampAge(i128);

impl StampAge {
    /// The age at `now` of a stamp whose time is `stamp`.
    #[must_use]
    pub fn between(stamp: SystemTime, now: SystemTime) -> Self {
        match now.duration_since(stamp) {
            Ok(d) => Self::behind(d),
            Err(e) => Self::ahead(e.duration()),
        }
    }

    /// A stamp `d` before the reader's clock.
    #[must_use]
    pub fn behind(d: Duration) -> Self {
        Self(d.as_nanos() as i128)
    }

    /// A stamp `d` ahead of the reader's clock.
    #[must_use]
    pub fn ahead(d: Duration) -> Self {
        Self(-(d.as_nanos() as i128))
    }

    /// Seconds, rounded to the nanosecond: how the fixtures write it.
    #[must_use]
    pub fn from_secs_f64(s: f64) -> Self {
        Self((s * 1e9).round() as i128)
    }

    #[must_use]
    pub fn as_secs_f64(self) -> f64 {
        self.0 as f64 / 1e9
    }

    /// Nanoseconds, negative when the stamp is ahead.
    #[must_use]
    pub fn nanos(self) -> i128 {
        self.0
    }
}

/// Whether a GET reader trusts its clock against the clock that stamped a
/// reply (§2.6).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClockTrust {
    /// The two agree within `delta`: on the deployment's word, or measured.
    Trusted { delta: Duration },
    /// No ground to trust them: a reply's age is unobservable.
    Untrusted,
}

/// What a reader measured of one stamping clock during a reading (§2.6,
/// ground 2, 0.2): the offset closest to its own clock, since transit only
/// adds to an offset, and the offset furthest ahead, since a stamp ahead of
/// the reader's clock by more than the delta proves the clocks disagree
/// whatever the transit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClockMeasure {
    closest: StampAge,
    most_ahead: StampAge,
}

impl ClockMeasure {
    /// A first measurement.
    #[must_use]
    pub fn new(offset: StampAge) -> Self {
        Self {
            closest: offset,
            most_ahead: offset,
        }
    }

    /// Another live put's offset, in the same reading.
    pub fn record(&mut self, offset: StampAge) {
        if offset.nanos().unsigned_abs() < self.closest.nanos().unsigned_abs() {
            self.closest = offset;
        }
        if offset < self.most_ahead {
            self.most_ahead = offset;
        }
    }

    /// Two readers' measurements of one clock, as one reading's.
    #[must_use]
    pub fn merge(mut self, other: Self) -> Self {
        self.record(other.closest);
        self.record(other.most_ahead);
        self
    }

    /// The offset closest to the reader's clock.
    #[must_use]
    pub fn closest(&self) -> StampAge {
        self.closest
    }

    /// The offset furthest ahead (the most negative).
    #[must_use]
    pub fn most_ahead(&self) -> StampAge {
        self.most_ahead
    }

    /// §2.6, ground 2 (0.2): trusted when the closest offset is within
    /// `delta`, and no stamp was ahead by more than `delta`.
    #[must_use]
    pub fn trust(&self, delta: Duration) -> ClockTrust {
        let d = delta.as_nanos() as i128;
        if self.closest.nanos().unsigned_abs() <= delta.as_nanos() && self.most_ahead.nanos() >= -d
        {
            ClockTrust::Trusted { delta }
        } else {
            ClockTrust::Untrusted
        }
    }
}

impl ClockTrust {
    /// §2.6, ground 2 (0.2), over a reading's measurements of one clock:
    /// untrusted when there are none.
    #[must_use]
    pub fn from_offsets(offsets: impl IntoIterator<Item = StampAge>, delta: Duration) -> Self {
        let mut it = offsets.into_iter();
        let Some(first) = it.next() else {
            return Self::Untrusted;
        };
        let mut m = ClockMeasure::new(first);
        it.for_each(|o| m.record(o));
        m.trust(delta)
    }

    /// §2.6, ground 2: a live put whose stamp was `offset` from the reader's
    /// clock at receipt (the receipt minus the stamp) shows the clocks agree
    /// within `delta` when the offset is within it, either way.
    #[must_use]
    pub fn measured(offset: StampAge, delta: Duration) -> Self {
        if offset.0.unsigned_abs() <= delta.as_nanos() {
            Self::Trusted { delta }
        } else {
            Self::Untrusted
        }
    }
}

/// A subscription's last delivery of a member, and how long ago it arrived
/// on the subscriber's monotonic clock (§2.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Last {
    /// A put (a change or a re-put), or a stream sample.
    Put(Duration),
    /// A delete: the member has no value.
    Delete(Duration),
}

/// The owner's reply for a member (§2.6).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reply {
    /// A value, with its stamp's age at the instant of judgement, or `None`
    /// when the reply carries no stamp (which breaks core S2).
    Put { stamp_age: Option<StampAge> },
    /// A `reply_del`: the member is deleted.
    Delete,
}

/// One observation of one member, as a reader made it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Observation {
    /// A subscription (§2.5): its last delivery of the member, how long it
    /// has listened since it was declared, and whether it lost deliveries
    /// (`complete` is false when it did).
    Subscribed {
        last: Option<Last>,
        listened: Duration,
        complete: bool,
    },
    /// A GET to the owner (§2.6): its reply for the member, or `None` when
    /// none came within the timeout, and the reader's trust in its clock
    /// against the reply's stamp.
    Got {
        reply: Option<Reply>,
        clock: ClockTrust,
    },
    /// An archive's answer: last-known, never current (§2.8).
    Archived,
}

/// What a GET reader read of one member from its collection's snapshot
/// (`freshness.v2` §2.6, text 0.7; core §4.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Entry {
    /// The snapshot lists the member neither live nor as a tombstone.
    Omitted,
    /// A tombstone: a `reply_del`.
    Tombstone,
    /// A live entry, with its confirmation's age at the instant of
    /// judgement: the snapshot's time for confirmation 1, the entry's conf
    /// for 2. `None` for confirmation 0, or a time that is unknown: no
    /// stamp.
    Live { stamp_age: Option<StampAge> },
}

impl Observation {
    /// A snapshot's `entry` of one member as a GET's observation (v2 §2.6):
    /// an entry is judged as a reply, its confirmation's time as the stamp,
    /// under the reader's trust in the owner's `clock`, which built the
    /// snapshot. A member a `complete` snapshot omits is deleted, by core
    /// §4.2's omission rule, and one an incomplete snapshot omits is
    /// silent.
    #[must_use]
    pub fn of_entry(complete: bool, entry: Entry, clock: ClockTrust) -> Observation {
        let reply = match entry {
            Entry::Omitted if !complete => None,
            Entry::Omitted | Entry::Tombstone => Some(Reply::Delete),
            Entry::Live { stamp_age } => Some(Reply::Put { stamp_age }),
        };
        Observation::Got { reply, clock }
    }
}

/// The answer to "is this member's value fresh?" (§5). Stale is the
/// finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Verdict {
    Fresh,
    Stale,
    /// The question was put, and the observation could not answer it.
    Unobservable,
    /// Nobody put the question, or its premise does not hold (the reason
    /// says which).
    NotAsked,
}

impl Verdict {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Fresh => "fresh",
            Self::Stale => "stale",
            Self::Unobservable => "unobservable",
            Self::NotAsked => "not_asked",
        }
    }
}

impl fmt::Display for Verdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why a verdict is what it is: the fixture's reason class.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
    /// Fresh: confirmed within the horizon (§2.5, §2.6).
    WithinHorizon,
    /// Fresh: ttl 0 (§2.3).
    NeverStale,
    /// Stale: the last confirmation is older than the horizon.
    BeyondHorizon,
    /// Stale: nothing delivered while listening longer than the horizon.
    NoDelivery,
    /// Unobservable: the `freshness.ttl_s` is not a horizon (§2.1).
    NotAHorizon,
    /// Unobservable: nothing delivered, and listened the horizon or less.
    ListenedTooShort,
    /// Unobservable: deliveries were lost, and none fresh arrived.
    Incomplete,
    /// Unobservable: the GET drew no reply for the member.
    Silent,
    /// Unobservable: the reply carries no stamp.
    NoStamp,
    /// Unobservable: the reader's clock is not trusted to the delta.
    ClockUntrusted,
    /// Unobservable: the stamp is ahead of the reader's clock beyond the
    /// delta.
    ClockDisagrees,
    /// Unobservable: the age is within the delta of the horizon.
    NearHorizon,
    /// Unobservable: no observation to judge.
    NoObservation,
    /// Not asked: no horizon (§2.3).
    NoHorizon,
    /// Not this profile's: an event or an operation (§2.2).
    Kind,
    /// Not asked: an archive's last-known value (§2.8).
    LastKnown,
    /// Not this profile's: the member is deleted.
    Deleted,
}

impl Reason {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::WithinHorizon => "within_horizon",
            Self::NeverStale => "never_stale",
            Self::BeyondHorizon => "beyond_horizon",
            Self::NoDelivery => "no_delivery",
            Self::NotAHorizon => "not_a_horizon",
            Self::ListenedTooShort => "listened_too_short",
            Self::Incomplete => "incomplete",
            Self::Silent => "silent",
            Self::NoStamp => "no_stamp",
            Self::ClockUntrusted => "clock_untrusted",
            Self::ClockDisagrees => "clock_disagrees",
            Self::NearHorizon => "near_horizon",
            Self::NoObservation => "no_observation",
            Self::NoHorizon => "no_horizon",
            Self::Kind => "kind",
            Self::LastKnown => "last_known",
            Self::Deleted => "deleted",
        }
    }

    /// The reason in words, for a tool's message.
    #[must_use]
    pub fn says(self) -> &'static str {
        match self {
            Self::WithinHorizon => "confirmed within its horizon",
            Self::NeverStale => "ttl_s = 0, never stale",
            Self::BeyondHorizon => "not confirmed within its horizon",
            Self::NoDelivery => "nothing delivered for longer than its horizon",
            Self::NotAHorizon => "its freshness.ttl_s is not a horizon",
            Self::ListenedTooShort => {
                "nothing delivered, and not listened to for longer than its horizon"
            }
            Self::Incomplete => "deliveries were lost, and none within the horizon arrived",
            Self::Silent => "no value was read",
            Self::NoStamp => "the reply carries no stamp",
            Self::ClockUntrusted => {
                "this reader's clock is not trusted to the HLC delta against the stamping clock"
            }
            Self::ClockDisagrees => "the stamp is ahead of this reader's clock beyond the delta",
            Self::NearHorizon => "the age is within the delta of the horizon",
            Self::NoObservation => "nothing was observed",
            Self::NoHorizon => "no freshness.ttl_s, so freshness is not asked",
            Self::Kind => "an event or an operation has no freshness",
            Self::LastKnown => "an archive's last-known value is never current",
            Self::Deleted => "deleted, so no value",
        }
    }
}

impl fmt::Display for Reason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A verdict and its reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
    pub verdict: Verdict,
    pub reason: Reason,
}

impl Judged {
    const fn new(verdict: Verdict, reason: Reason) -> Self {
        Self { verdict, reason }
    }
}

/// Judges one observation of a member of a resource whose horizon is `h`,
/// by the order of §2.7: the horizon (§2.3, §2.2), an archive (§2.8), a
/// value that is no horizon (§2.1), then the observation (§2.5, §2.6).
#[must_use]
pub fn judge(h: &Horizon, o: &Observation) -> Judged {
    use Reason as R;
    use Verdict as V;
    match h {
        Horizon::Undeclared => return Judged::new(V::NotAsked, R::NoHorizon),
        Horizon::Ignored => return Judged::new(V::NotAsked, R::Kind),
        _ => {}
    }
    if matches!(o, Observation::Archived) {
        return Judged::new(V::NotAsked, R::LastKnown);
    }
    let ttl = match h {
        Horizon::Invalid(_) => return Judged::new(V::Unobservable, R::NotAHorizon),
        Horizon::Never => None,
        Horizon::Within(t) => Some(*t),
        Horizon::Undeclared | Horizon::Ignored => unreachable!("returned above"),
    };
    match (*o, ttl) {
        (Observation::Archived, _) => unreachable!("returned above"),
        // §2.5.
        (
            Observation::Subscribed {
                last: Some(Last::Delete(_)),
                ..
            },
            _,
        ) => Judged::new(V::NotAsked, R::Deleted),
        (Observation::Subscribed { .. }, None) => Judged::new(V::Fresh, R::NeverStale),
        (
            Observation::Subscribed {
                last,
                listened,
                complete,
            },
            Some(ttl),
        ) => match last {
            Some(Last::Put(a)) if a <= ttl => Judged::new(V::Fresh, R::WithinHorizon),
            _ if !complete => Judged::new(V::Unobservable, R::Incomplete),
            Some(_) => Judged::new(V::Stale, R::BeyondHorizon),
            None if listened > ttl => Judged::new(V::Stale, R::NoDelivery),
            None => Judged::new(V::Unobservable, R::ListenedTooShort),
        },
        // §2.6.
        (Observation::Got { reply: None, .. }, _) => Judged::new(V::Unobservable, R::Silent),
        (
            Observation::Got {
                reply: Some(Reply::Delete),
                ..
            },
            _,
        ) => Judged::new(V::NotAsked, R::Deleted),
        (Observation::Got { .. }, None) => Judged::new(V::Fresh, R::NeverStale),
        (
            Observation::Got {
                reply: Some(Reply::Put { stamp_age }),
                clock,
            },
            Some(ttl),
        ) => {
            let Some(age) = stamp_age else {
                return Judged::new(V::Unobservable, R::NoStamp);
            };
            let ClockTrust::Trusted { delta } = clock else {
                return Judged::new(V::Unobservable, R::ClockUntrusted);
            };
            let (a, t, d) = (age.0, ttl.as_nanos() as i128, delta.as_nanos() as i128);
            if a < -d {
                Judged::new(V::Unobservable, R::ClockDisagrees)
            } else if a + d <= t {
                Judged::new(V::Fresh, R::WithinHorizon)
            } else if a - d > t {
                Judged::new(V::Stale, R::BeyondHorizon)
            } else {
                Judged::new(V::Unobservable, R::NearHorizon)
            }
        }
    }
}

/// Combines the verdicts of several observations of one member (§2.7):
/// fresh when any is fresh, else stale when any is, else unobservable when
/// any is, else not asked. Among equal verdicts the first one's reason
/// stands. No observation at all is unobservable.
#[must_use]
pub fn combine(judged: impl IntoIterator<Item = Judged>) -> Judged {
    let rank = |v: Verdict| match v {
        Verdict::Fresh => 0,
        Verdict::Stale => 1,
        Verdict::Unobservable => 2,
        Verdict::NotAsked => 3,
    };
    judged
        .into_iter()
        .fold(None, |best: Option<Judged>, j| match best {
            Some(b) if rank(b.verdict) <= rank(j.verdict) => Some(b),
            _ => Some(j),
        })
        .unwrap_or(Judged::new(Verdict::Unobservable, Reason::NoObservation))
}

/// [`judge`] each observation, then [`combine`] them. With no observation,
/// §2.7's steps that need none still answer (0.2): no horizon is not
/// asked, an event or operation is not this profile's, a value that is no
/// horizon is unobservable; only a member with a horizon is unobservable
/// for want of an observation.
#[must_use]
pub fn judge_all(h: &Horizon, observations: &[Observation]) -> Judged {
    if observations.is_empty() {
        return match h {
            Horizon::Undeclared => Judged::new(Verdict::NotAsked, Reason::NoHorizon),
            Horizon::Ignored => Judged::new(Verdict::NotAsked, Reason::Kind),
            Horizon::Invalid(_) => Judged::new(Verdict::Unobservable, Reason::NotAHorizon),
            Horizon::Never | Horizon::Within(_) => {
                Judged::new(Verdict::Unobservable, Reason::NoObservation)
            }
        };
    }
    combine(observations.iter().map(|o| judge(h, o)))
}

// --- #978's F2: a reader's view, as heartbeats confirm it ----------------------

/// An instant on a reader's monotonic clock, as a [`View`] keeps it: a
/// delivery's or a heartbeat's arrival.
pub trait Arrival: Copy + Ord {
    /// The time from `earlier` to this instant, zero when `earlier` is
    /// later.
    fn since(self, earlier: Self) -> Duration;
}

impl Arrival for std::time::Instant {
    fn since(self, earlier: Self) -> Duration {
        self.saturating_duration_since(earlier)
    }
}

impl Arrival for crate::timing::Mono {
    fn since(self, earlier: Self) -> Duration {
        self.saturating_since(earlier)
    }
}

/// One member as a [`View`] holds it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Held<T> {
    collection: usize,
    /// The last mutation's in-band stamp; `None` for a put that carried
    /// none, which no digest can count, and for a delete.
    stamp: Option<Stamp>,
    deleted: bool,
    /// The last mutation's arrival.
    at: T,
    /// The last heartbeat that vouched for it, since its last mutation.
    confirmed: Option<T>,
}

/// What one section of a heartbeat did to the [`View`] (#978's design
/// §1.5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SectionRead {
    /// The view does not follow the collection: nothing read.
    NotFollowed,
    /// In a group of an owner heartbeat, a followed collection that is not
    /// of the key's class: not read, whatever its map bit says (v2 §2.5).
    /// A heartbeat's own section is never this.
    OtherClass,
    /// Its map bit is 0: nothing confirmed there.
    Absent,
    /// The digest, or the live count, is not the view's: nothing
    /// confirmed in the collection.
    Diverged,
    /// The digest is the view's: each member vouched for is confirmed at
    /// the heartbeat's arrival, these keys in key order.
    Confirmed(Vec<String>),
}

impl SectionRead {
    /// `not_followed`, `other_class`, `absent`, `diverged` or `confirmed`.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::NotFollowed => "not_followed",
            Self::OtherClass => "other_class",
            Self::Absent => "absent",
            Self::Diverged => "diverged",
            Self::Confirmed(_) => "confirmed",
        }
    }
}

/// What a heartbeat did to the [`View`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Applied {
    /// CH's tag is not the revision the view holds: nothing confirmed.
    Revision,
    /// The body was refused (core §7.5): nothing confirmed.
    Refused(crate::heartbeat::BodyRefusal),
    /// Its key's seq is not after the last heartbeat's, within one run:
    /// nothing confirmed, nothing counted.
    Older,
    /// Read, each collection's section in map order. `gap` says the key's
    /// seqs skipped since the last heartbeat: one or more were lost.
    Read {
        gap: bool,
        sections: Vec<SectionRead>,
    },
}

/// One heartbeat key's sequence, as a reader counts it (v2 §2.5): the
/// stamp of the last heartbeat read on the key, and whether that one
/// followed a lost one. A heartbeat key has one, and so has each owner
/// heartbeat key, whatever its groups cover: older and lost are the
/// key's, never an interface's.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Sequence {
    last: Option<Stamp>,
    gap: bool,
}

/// What [`Sequence::read`] says of a heartbeat that is not older.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sequenced {
    /// Within one run, its seq is not the last read one's plus 1: one or
    /// more were lost.
    pub gap: bool,
    /// It is of another run than the last read one: the sequence starts
    /// again. `false` for the first one read.
    pub run: bool,
}

impl Sequence {
    /// A heartbeat about to be read on the key, one core §7.5 did not
    /// refuse: `None` when, within one run, its seq is not after the last
    /// read one's by core §4.3's serial order (`older`), which moves
    /// nothing; else the sequence moves to it.
    pub fn read(&mut self, stamp: Stamp) -> Option<Sequenced> {
        let read = match self.last {
            Some(l) if l.run == stamp.run => {
                match crate::seed::Order::Serial.seqs(l.seq, stamp.seq) {
                    Some(std::cmp::Ordering::Greater) => Sequenced {
                        gap: stamp.seq.get().wrapping_sub(l.seq.get())
                            & crate::wire::Seq::MAX.get()
                            != 1,
                        run: false,
                    },
                    _ => return None,
                }
            }
            Some(_) => Sequenced {
                gap: false,
                run: true,
            },
            None => Sequenced {
                gap: false,
                run: false,
            },
        };
        self.last = Some(stamp);
        self.gap = read.gap;
        Some(read)
    }

    /// The last heartbeat read on the key: its stamp.
    #[must_use]
    pub fn last(&self) -> Option<Stamp> {
        self.last
    }

    /// Whether the last heartbeat read on the key followed a lost one.
    #[must_use]
    pub fn gap(&self) -> bool {
        self.gap
    }
}

/// What one group of an owner heartbeat did to a reader's views (v2
/// §2.5's "An owner heartbeat", step 3), the first of these that answers.
/// Only [`GroupRead::Read`] counts toward a collection's divergences in a
/// row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GroupRead {
    /// Core §8.6 refuses its index (`unknown_catalog`, `unknown_index`),
    /// or, after the two readings below, core §7.5 its sections (`short`,
    /// `code`, `trailing`): the group confirms nothing.
    Refused(crate::heartbeat::GroupRefusal),
    /// The reader follows no collection of the interface its index names:
    /// skipped.
    NotFollowed,
    /// The revision its index names is not the one the reader holds, or
    /// its tag is not that revision's: the group confirms nothing.
    Revision,
    /// Read, each collection of its interface in map order.
    Read(Vec<SectionRead>),
}

/// One group of a read owner heartbeat: its index, the interface the
/// index names where core §8.6 resolved it, and what it did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GroupApplied {
    pub index: u16,
    pub iface: Option<crate::grammar::IfaceId>,
    pub read: GroupRead,
}

/// What an owner heartbeat did to a reader's [`Views`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OwnerApplied {
    /// Core §7.5 refuses it whole, before any group's sections are read:
    /// nothing confirmed, nothing counted.
    Refused(crate::heartbeat::OwnerRefusal),
    /// Its key's seq is not after the last read owner heartbeat's on that
    /// key, within one run: nothing confirmed, nothing counted.
    Older,
    /// Read, each group alone, in order. `gap` says the key's seqs skipped
    /// since the last one read on it: one or more were lost, for every
    /// collection the key covers.
    Read {
        gap: bool,
        groups: Vec<GroupApplied>,
    },
}

/// A reader's view of one owner's state for one interface, as its
/// deliveries, its reads and that owner's heartbeats make it (core §7.5's
/// heartbeat; #978's F2). No rule adopts the heartbeat yet, so nothing
/// here changes a [`judge`]: a heartbeat that confirms a member is a
/// confirmation of it, as a put is (§2.5), and [`View::observation`] ages
/// the member from the later of the two.
///
/// - **The members** are each collection's that the reader heard: a put
///   with its in-band stamp, a delete, or a read's answer
///   ([`View::replace`]). A put older than the one held, within one run,
///   is not taken.
/// - **A heartbeat** ([`View::apply`]) confirms, in each collection the
///   view follows ([`View::follow`]), each member vouched for, when the
///   section's digest is the view's and its live count is too. A reader
///   follows only a collection it hears whole: one whose template it
///   subscribes with no parameter bound.
/// - **A divergence** confirms nothing in its collection. After two in a
///   row the collection is due a read ([`View::reread_due`]), whose answer
///   replaces what the view holds.
/// - **A gap** in the heartbeat key's seqs is a heartbeat lost: the
///   view's members are incomplete until one arrives in sequence.
#[derive(Debug, Clone)]
pub struct View<T> {
    layout: crate::heartbeat::Layout,
    follows: Vec<bool>,
    members: BTreeMap<String, Held<T>>,
    diverged: Vec<u32>,
    /// Its heartbeat key's sequence. An owner heartbeat key's is
    /// [`Views`]'s.
    seq: Sequence,
    time: Option<crate::heartbeat::Time>,
    heartbeats: u64,
}

impl<T: Arrival> View<T> {
    /// An empty view of a revision's collections, following none.
    #[must_use]
    pub fn new(layout: crate::heartbeat::Layout) -> Self {
        let n = layout.collections.len();
        Self {
            layout,
            follows: vec![false; n],
            members: BTreeMap::new(),
            diverged: vec![0; n],
            seq: Sequence::default(),
            time: None,
            heartbeats: 0,
        }
    }

    /// The revision's layout.
    #[must_use]
    pub fn layout(&self) -> &crate::heartbeat::Layout {
        &self.layout
    }

    /// Follows the collection at `index`; `false` when there is none.
    pub fn follow(&mut self, index: usize) -> bool {
        match self.follows.get_mut(index) {
            Some(f) => {
                *f = true;
                true
            }
            None => false,
        }
    }

    /// Follows the collection named `<kind token>/<template>`; `false`
    /// when it is none.
    pub fn follow_resource(&mut self, resource: &str) -> bool {
        self.layout
            .index_of(resource)
            .is_some_and(|i| self.follow(i))
    }

    /// Whether it follows any collection.
    #[must_use]
    pub fn follows_any(&self) -> bool {
        self.follows.iter().any(|f| *f)
    }

    /// A put of `key` heard at `at`, with its in-band stamp (`None` when it
    /// carried none). A key of no collection is not held, and a put older
    /// than the one held within one run is not taken.
    pub fn put(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
        self.mutation(key, stamp, false, at);
    }

    /// A delete of `key` heard at `at`, with its in-band stamp where its
    /// attachment carried one.
    pub fn delete(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
        self.mutation(key, stamp, true, at);
    }

    fn mutation(&mut self, key: &str, stamp: Option<Stamp>, deleted: bool, at: T) {
        let Some(k) = crate::heartbeat::base_relative(key) else {
            return;
        };
        let Some(collection) = self.layout.collection_of(k) else {
            return;
        };
        if let (Some(h), Some(s)) = (self.members.get(k).and_then(|h| h.stamp), stamp)
            && h.run == s.run
            && s.seq <= h.seq
        {
            return;
        }
        self.members.insert(
            k.to_owned(),
            Held {
                collection,
                stamp,
                deleted,
                at,
                confirmed: None,
            },
        );
    }

    /// A complete read of the collection at `index` (S4's answer, or a
    /// snapshot once #977 lands), at `at`: its live members replace the
    /// view's, a member it left out leaving the view, and the collection
    /// is no longer due a read. A put heard after the read was asked is
    /// the caller's to apply again after it (core §4.2).
    pub fn replace<'k>(
        &mut self,
        index: usize,
        live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
        at: T,
    ) {
        self.members.retain(|_, h| h.collection != index);
        for (key, stamp) in live {
            let Some(k) = crate::heartbeat::base_relative(key) else {
                continue;
            };
            if self.layout.collection_of(k) == Some(index) {
                self.members.insert(
                    k.to_owned(),
                    Held {
                        collection: index,
                        stamp,
                        deleted: false,
                        at,
                        confirmed: None,
                    },
                );
            }
        }
        if let Some(d) = self.diverged.get_mut(index) {
            *d = 0;
        }
    }

    /// A re-read of the collection at `index` (`freshness.v2` §2.5): its
    /// answer, asked at `asked` and arrived at `at`, merged with what the
    /// view heard of the collection from `asked` on, as core §4.2 merges a
    /// late joiner's seed. The answer replaces the collection
    /// ([`View::replace`]); then each member heard live since `asked` is
    /// kept where the answer has none of it, or holds a lower seq of its
    /// run. Across two runs the answer's stands, as core §4.3's consumer
    /// rule accepts another run.
    pub fn reread<'k>(
        &mut self,
        index: usize,
        live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
        asked: T,
        at: T,
    ) {
        let heard: Vec<(String, Held<T>)> = self
            .members
            .iter()
            .filter(|(_, h)| h.collection == index && h.at >= asked)
            .map(|(k, h)| (k.clone(), *h))
            .collect();
        self.replace(index, live, at);
        for (k, h) in heard {
            let keep = match self.members.get(&k) {
                None => true,
                Some(answered) => match (h.stamp, answered.stamp) {
                    (Some(mine), Some(theirs)) => mine.run == theirs.run && mine.seq > theirs.seq,
                    _ => false,
                },
            };
            if keep {
                self.members.insert(k, h);
            }
        }
    }

    /// The live members of a collection the view holds, in key order.
    fn live(&self, index: usize) -> impl Iterator<Item = (&String, &Held<T>)> {
        self.members
            .iter()
            .filter(move |(_, h)| h.collection == index && !h.deleted)
    }

    /// The view's digest of a collection: `None` while it holds a live
    /// member whose put carried no in-band stamp, which no digest counts.
    #[must_use]
    pub fn digest(&self, index: usize) -> Option<crate::heartbeat::Digest> {
        let mut d = crate::heartbeat::Digest::EMPTY;
        for (k, h) in self.live(index) {
            d.toggle(k, h.stamp?);
        }
        Some(d)
    }

    /// A heartbeat heard at `at`: CH's tag, its stamp and its body. See
    /// [`View`]'s doc for what it confirms.
    pub fn apply(&mut self, tag: crate::wire::Tag, stamp: Stamp, body: &[u8], at: T) -> Applied {
        use crate::heartbeat::Heartbeat;
        if tag != self.layout.tag {
            return Applied::Revision;
        }
        let hb = match Heartbeat::parse(body, &self.layout) {
            Ok(hb) => hb,
            Err(r) => return Applied::Refused(r),
        };
        let Some(read) = self.seq.read(stamp) else {
            return Applied::Older;
        };
        self.time = Some(hb.time);
        self.heartbeats += 1;
        let mut sections = Vec::with_capacity(hb.sections.len());
        for (i, section) in hb.sections.iter().enumerate() {
            sections.push(if self.follows[i] {
                self.read_section(i, section.as_ref(), at)
            } else {
                SectionRead::NotFollowed
            });
        }
        Applied::Read {
            gap: read.gap,
            sections,
        }
    }

    /// One followed collection's section, read against the view (v2 §2.5,
    /// step 4): a map bit of 0 ends a row of divergences, a digest or a
    /// live count that is not the view's adds one, and a section in step
    /// confirms each member it vouches for at `at`.
    fn read_section(
        &mut self,
        i: usize,
        section: Option<&crate::heartbeat::Section>,
        at: T,
    ) -> SectionRead {
        use crate::heartbeat::Members;
        let Some(s) = section else {
            self.diverged[i] = 0;
            return SectionRead::Absent;
        };
        let keys: Vec<String> = self.live(i).map(|(k, _)| k.clone()).collect();
        let same_count = match &s.members {
            Members::One { .. } => keys.len() <= 1,
            m => m.live() == Some(keys.len() as u64),
        };
        if self.digest(i) != Some(s.digest) || !same_count {
            self.diverged[i] = self.diverged[i].saturating_add(1);
            return SectionRead::Diverged;
        }
        self.diverged[i] = 0;
        let vouched: Vec<String> = s
            .members
            .vouched()
            .into_iter()
            .filter_map(|r| keys.get(usize::try_from(r).ok()?).cloned())
            .collect();
        for k in &vouched {
            if let Some(h) = self.members.get_mut(k) {
                h.confirmed = Some(at);
            }
        }
        SectionRead::Confirmed(vouched)
    }

    /// One group of a read owner heartbeat of `class`, heard at `at` (v2
    /// §2.5's "An owner heartbeat", step 3 from "Not followed" on): `entry`
    /// is what core §8.6 read its index as ([`crate::heartbeat::Group::entry`]),
    /// and `time` the owner heartbeat's. The caller has read the owner
    /// heartbeat on its key first ([`Views::apply_owner`] does both): this
    /// moves no sequence.
    ///
    /// - **Not followed:** the entry names another interface, or the view
    ///   follows no collection.
    /// - **Another revision:** the entry's revision is not the view's, or
    ///   the group's tag is not that revision's.
    /// - **Refused:** core §7.5 refuses its sections, parsed whole, the
    ///   other class's too.
    /// - **Read:** each followed collection of `class` as a heartbeat's
    ///   section is read, on the collection's one count of divergences in
    ///   a row; a followed one of the other class is
    ///   [`SectionRead::OtherClass`], unread and uncounted. The group is a
    ///   heartbeat applied ([`View::heartbeats`], [`View::owner_time`])
    ///   only when a section was read: one on the other class's key reads
    ///   none.
    pub fn apply_group(
        &mut self,
        class: crate::heartbeat::Class,
        entry: &crate::catalog::Entry,
        group: &crate::heartbeat::Group,
        time: crate::heartbeat::Time,
        at: T,
    ) -> GroupRead {
        if entry.iface != self.layout.iface || !self.follows_any() {
            return GroupRead::NotFollowed;
        }
        if entry.contract != self.layout.fingerprint || !group.tag_is(&self.layout) {
            return GroupRead::Revision;
        }
        let read = match group.read(&self.layout) {
            Ok(s) => s,
            Err(r) => return GroupRead::Refused(r),
        };
        let mut sections = Vec::with_capacity(read.len());
        for (i, section) in read.iter().enumerate() {
            sections.push(if !self.follows[i] {
                SectionRead::NotFollowed
            } else if self.layout.collections[i].class != class {
                SectionRead::OtherClass
            } else {
                self.read_section(i, section.as_ref(), at)
            });
        }
        // v2 §2.5: what counts for a collection is "the groups whose
        // sections were read for its interface, on its own class's key". A
        // group on the other class's key reads no section of the view, so
        // it is no heartbeat applied to it: neither its count nor the
        // owner's time moves (review of #1137).
        if sections
            .iter()
            .any(|s| !matches!(s, SectionRead::NotFollowed | SectionRead::OtherClass))
        {
            self.time = Some(time);
            self.heartbeats += 1;
        }
        GroupRead::Read(sections)
    }

    /// A GET's snapshot vouched for `key`'s live value at `at` (v2 §2.6,
    /// text 0.7; core §7.5's confirmation): kept as a heartbeat's would be,
    /// when it is later than what the view held. A deleted member, or one
    /// the view does not hold, is left as it is.
    pub fn confirm(&mut self, key: &str, at: T) {
        let Some(k) = crate::heartbeat::base_relative(key) else {
            return;
        };
        if let Some(h) = self.members.get_mut(k)
            && !h.deleted
            && h.confirmed.is_none_or(|c| c < at)
        {
            h.confirmed = Some(at);
        }
    }

    /// The last heartbeat that vouched for `key` since its last mutation.
    #[must_use]
    pub fn confirmed(&self, key: &str) -> Option<T> {
        let k = crate::heartbeat::base_relative(key)?;
        self.members.get(k).and_then(|h| h.confirmed)
    }

    /// The collections due a read: two heartbeats in a row diverged there.
    #[must_use]
    pub fn reread_due(&self) -> Vec<usize> {
        (0..self.diverged.len())
            .filter(|i| self.follows[*i] && self.diverged[*i] >= 2)
            .collect()
    }

    /// Whether the last heartbeat came after a gap in its key's seqs: the
    /// interface's own heartbeat key's. A gap on an owner heartbeat key is
    /// [`Views::gap`]'s.
    #[must_use]
    pub fn gap(&self) -> bool {
        self.seq.gap()
    }

    /// Whether it follows the collection at `index`.
    #[must_use]
    pub fn follows(&self, index: usize) -> bool {
        self.follows.get(index).copied().unwrap_or(false)
    }

    /// The classes of the collections it follows, `link` first: the
    /// provider's owner heartbeat keys a subscriber subscribes to beside
    /// its heartbeat key (v2 §2.5, "Both forms").
    #[must_use]
    pub fn classes(&self) -> Vec<crate::heartbeat::Class> {
        crate::heartbeat::Class::ALL
            .into_iter()
            .filter(|c| {
                self.layout
                    .collections
                    .iter()
                    .zip(&self.follows)
                    .any(|(x, f)| *f && x.class == *c)
            })
            .collect()
    }

    /// The owner's time in the last heartbeat applied, or in the last
    /// owner heartbeat a group of which read a section of a followed
    /// collection.
    #[must_use]
    pub fn owner_time(&self) -> Option<crate::heartbeat::Time> {
        self.time
    }

    /// The last heartbeat applied on the interface's own heartbeat key:
    /// its stamp. An owner heartbeat's is its key's ([`Views::last`]).
    #[must_use]
    pub fn last_heartbeat(&self) -> Option<Stamp> {
        self.seq.last()
    }

    /// How many heartbeats it applied, each group among them that read a
    /// section of a followed collection, on its class's key.
    #[must_use]
    pub fn heartbeats(&self) -> u64 {
        self.heartbeats
    }

    /// `key`'s last confirmation at `now` (§2.5): the later of its last
    /// mutation and the last heartbeat that vouched for it, as a [`Last`];
    /// `None` for a member the view does not hold.
    #[must_use]
    pub fn last(&self, key: &str, now: T) -> Option<Last> {
        let k = crate::heartbeat::base_relative(key)?;
        let h = self.members.get(k)?;
        Some(if h.deleted {
            Last::Delete(now.since(h.at))
        } else {
            Last::Put(now.since(h.confirmed.map_or(h.at, |c| c.max(h.at))))
        })
    }

    /// `key` as a subscription's observation at `now` (§2.5), the view
    /// standing in for its deliveries: its last confirmation, how long the
    /// subscription has `listened`, and complete when the subscription
    /// lost nothing (`complete`) and no heartbeat was lost.
    #[must_use]
    pub fn observation(
        &self,
        key: &str,
        now: T,
        listened: Duration,
        complete: bool,
    ) -> Observation {
        Observation::Subscribed {
            last: self.last(key, now),
            listened,
            complete: complete && !self.seq.gap(),
        }
    }
}

/// What a reader reads a group's index through (core §8.6): the catalogs
/// it holds, and the one the owner names in its descriptor, `None` where
/// it names none, which refuses every index (`unknown_catalog`).
#[derive(Debug, Clone, Copy)]
pub struct Catalogs<'a> {
    pub held: &'a [crate::catalog::Catalog],
    pub named: Option<crate::catalog::CatalogId>,
}

/// One owner heartbeat key's state, as a reader holds it.
#[derive(Debug, Clone, Default)]
struct ClassKey {
    seq: Sequence,
    /// The interfaces a group on the key has named within the run: whose
    /// collections of the key's class it covers, to this reader.
    named: std::collections::BTreeSet<crate::grammar::IfaceId>,
    read: u64,
}

/// One provider's views as one reader holds them, an interface each, with
/// a [`Sequence`] per owner heartbeat key in front of them (`freshness.v2`
/// §2.5, text 0.9; #1110's H2a). A heartbeat is still its interface's
/// view's ([`Views::view_mut`], [`View::apply`]); an owner heartbeat is
/// read here ([`Views::apply_owner`]), since its sequence is its key's and
/// its groups are several views'.
///
/// - **Older and lost are per key.** Each class's key has one sequence. A
///   gap on it is one owner heartbeat lost for every collection the key
///   covers: those of the key's class, in each interface a group on the
///   key has named within the run ([`Views::lost`]). It says nothing of
///   the other class's key, nor of an interface confirmed by its own
///   heartbeat.
/// - **Divergences are per collection.** A collection has one count, its
///   view's, which a heartbeat's section and a read group's move alike.
/// - **A reader bound to one interface** holds one view here, and reads
///   the other groups as not followed, by their sizes.
#[derive(Debug, Clone)]
pub struct Views<T> {
    views: BTreeMap<crate::grammar::IfaceId, View<T>>,
    keys: BTreeMap<crate::heartbeat::Class, ClassKey>,
}

impl<T> Default for Views<T> {
    fn default() -> Self {
        Self {
            views: BTreeMap::new(),
            keys: BTreeMap::new(),
        }
    }
}

impl<T: Arrival> Views<T> {
    /// No view, and no owner heartbeat read.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Holds `view` as its interface's, in place of any view held for it.
    pub fn insert(&mut self, view: View<T>) -> Option<View<T>> {
        self.views.insert(view.layout().iface.clone(), view)
    }

    /// The view of an interface.
    #[must_use]
    pub fn view(&self, iface: &crate::grammar::IfaceId) -> Option<&View<T>> {
        self.views.get(iface)
    }

    /// The view of an interface, to hear a mutation, a read's answer or
    /// the interface's own heartbeat with.
    pub fn view_mut(&mut self, iface: &crate::grammar::IfaceId) -> Option<&mut View<T>> {
        self.views.get_mut(iface)
    }

    /// The view of the interface a state key is of, namespace in front or
    /// none.
    #[must_use]
    pub fn view_of(&self, key: &str) -> Option<&View<T>> {
        self.views.get(&iface_of(key)?)
    }

    /// As [`Views::view_of`], to change it.
    pub fn view_of_mut(&mut self, key: &str) -> Option<&mut View<T>> {
        self.views.get_mut(&iface_of(key)?)
    }

    /// Every view, in order of its interface.
    pub fn iter(&self) -> impl Iterator<Item = &View<T>> {
        self.views.values()
    }

    /// The classes of the collections the views follow, `link` first: the
    /// provider's owner heartbeat keys to subscribe to (v2 §2.5, "Both
    /// forms").
    #[must_use]
    pub fn classes(&self) -> Vec<crate::heartbeat::Class> {
        crate::heartbeat::Class::ALL
            .into_iter()
            .filter(|c| self.views.values().any(|v| v.classes().contains(c)))
            .collect()
    }

    /// The horizon of the provider's owner heartbeat key of `class`, as
    /// this reader can tell it (core §8.5): the shortest among the
    /// collections of that class in the revisions it holds a view of,
    /// `None` with none. A reader across a face declares the key's
    /// subscription again after two of them of silence.
    #[must_use]
    pub fn class_horizon(&self, class: crate::heartbeat::Class) -> Option<Duration> {
        self.views
            .values()
            .filter_map(|v| v.layout().class_horizon(class))
            .min()
    }

    /// An owner heartbeat heard at `at` on the key of `class`: CH's tag,
    /// its stamp and its body, read through the catalog its owner names
    /// among those the reader holds (`through`), by v2 §2.5's steps.
    ///
    /// 1. **Refused:** core §7.5 refuses it whole.
    /// 2. **Older:** within one run, its seq is not after the last read
    ///    one's on this key.
    /// 3. **Read:** each group alone, in order: no index
    ///    ([`GroupRead::Refused`]), then as its interface's view reads it
    ///    ([`View::apply_group`]), not followed where no view is held for
    ///    the interface. A group that confirms nothing takes nothing from
    ///    the groups beside it.
    ///
    /// One stopped at step 1 or 2 moves neither the key's sequence nor a
    /// count of divergences, and names no interface.
    pub fn apply_owner(
        &mut self,
        class: crate::heartbeat::Class,
        tag: crate::wire::Tag,
        stamp: Stamp,
        body: &[u8],
        through: Catalogs<'_>,
        at: T,
    ) -> OwnerApplied {
        let hb = match crate::heartbeat::OwnerHeartbeat::parse(tag, body) {
            Ok(hb) => hb,
            Err(r) => return OwnerApplied::Refused(r),
        };
        let key = self.keys.entry(class).or_default();
        let Some(read) = key.seq.read(stamp) else {
            return OwnerApplied::Older;
        };
        if read.run {
            // Another run starts the sequence again, and its covered
            // collections with it.
            key.named.clear();
        }
        key.read += 1;
        let mut groups = Vec::with_capacity(hb.groups.len());
        for g in &hb.groups {
            let entry = match g.entry(through.held, through.named) {
                Ok(e) => e,
                Err(r) => {
                    groups.push(GroupApplied {
                        index: g.index,
                        iface: None,
                        read: GroupRead::Refused(r),
                    });
                    continue;
                }
            };
            // A group names an interface once its index is read, whatever
            // becomes of it after.
            key.named.insert(entry.iface.clone());
            let read = match self.views.get_mut(&entry.iface) {
                Some(v) => v.apply_group(class, entry, g, hb.time, at),
                None => GroupRead::NotFollowed,
            };
            groups.push(GroupApplied {
                index: g.index,
                iface: Some(entry.iface.clone()),
                read,
            });
        }
        OwnerApplied::Read {
            gap: read.gap,
            groups,
        }
    }

    /// Whether the last owner heartbeat read on the key of `class`
    /// followed a gap in that key's seqs; `None` while none was read on
    /// it.
    #[must_use]
    pub fn gap(&self, class: crate::heartbeat::Class) -> Option<bool> {
        let k = self.keys.get(&class)?;
        k.seq.last().map(|_| k.seq.gap())
    }

    /// The last owner heartbeat read on the key of `class`: its stamp.
    #[must_use]
    pub fn last(&self, class: crate::heartbeat::Class) -> Option<Stamp> {
        self.keys.get(&class)?.seq.last()
    }

    /// How many owner heartbeats were read on the key of `class`, whatever
    /// became of their groups.
    #[must_use]
    pub fn owner_heartbeats(&self, class: crate::heartbeat::Class) -> u64 {
        self.keys.get(&class).map_or(0, |k| k.read)
    }

    /// Whether the followed collection at `index` of `iface` is read as a
    /// lost delivery (v1 §2.5 rule 3): its interface's heartbeat key's
    /// last heartbeat followed a gap, or its class's owner heartbeat key's
    /// did and a group on that key has named the interface within the
    /// run. Until one arrives in sequence on that key, or one of another
    /// run does.
    #[must_use]
    pub fn is_lost(&self, iface: &crate::grammar::IfaceId, index: usize) -> bool {
        let Some(v) = self.views.get(iface) else {
            return false;
        };
        if !v.follows(index) {
            return false;
        }
        v.gap()
            || self
                .keys
                .get(&v.layout().collections[index].class)
                .is_some_and(|k| k.seq.gap() && k.named.contains(iface))
    }

    /// Every followed collection read as a lost delivery
    /// ([`Views::is_lost`]), by interface, then in map order.
    #[must_use]
    pub fn lost(&self) -> Vec<(crate::grammar::IfaceId, usize)> {
        self.views
            .iter()
            .flat_map(|(iface, v)| {
                (0..v.layout().collections.len())
                    .filter(|i| self.is_lost(iface, *i))
                    .map(|i| (iface.clone(), i))
            })
            .collect()
    }

    /// `key` as a subscription's observation at `now` (§2.5), as
    /// [`View::observation`], complete only while its collection is read
    /// as no lost delivery on either key that confirms it
    /// ([`Views::is_lost`]). `None` for a key of no view held.
    #[must_use]
    pub fn observation(
        &self,
        key: &str,
        now: T,
        listened: Duration,
        complete: bool,
    ) -> Option<Observation> {
        let v = self.view_of(key)?;
        let lost = crate::heartbeat::base_relative(key)
            .and_then(|k| v.layout().collection_of(k))
            .is_some_and(|i| self.is_lost(&v.layout().iface, i));
        Some(v.observation(key, now, listened, complete && !lost))
    }
}

/// The interface a data key is of, namespace in front or none.
fn iface_of(key: &str) -> Option<crate::grammar::IfaceId> {
    match crate::grammar::parse(crate::heartbeat::base_relative(key)?) {
        Ok(crate::grammar::ZkKey::Data { iface, .. }) => Some(iface),
        _ => None,
    }
}

/// A subscription's last delivery of a member and, where a [`View`]
/// holds it, the last heartbeat that vouched for it: the later is its
/// last confirmation (§2.5). `delivered` is the subscription's own
/// [`Last`]; a delete stays a delete. A member never delivered that a
/// heartbeat confirmed, one a late joiner's read seeded (`freshness.v2`
/// §2.5), is confirmed then.
#[must_use]
pub fn confirmed_last(delivered: Option<Last>, heartbeat: Option<Duration>) -> Option<Last> {
    match (delivered, heartbeat) {
        (Some(Last::Put(a)), Some(h)) => Some(Last::Put(a.min(h))),
        (None, Some(h)) => Some(Last::Put(h)),
        (d, _) => d,
    }
}

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

    fn ann(v: Value) -> BTreeMap<String, Value> {
        BTreeMap::from([(TTL_S.to_owned(), v)])
    }

    #[test]
    fn the_horizon_is_a_whole_number_of_seconds() {
        let h = |v: Value| horizon(Kind::State, &ann(v));
        assert_eq!(h(json!(60)), Horizon::Within(Duration::from_secs(60)));
        assert_eq!(h(json!(60.0)), Horizon::Within(Duration::from_secs(60)));
        assert_eq!(h(json!(-0.0)), Horizon::Never);
        assert_eq!(h(json!(0)), Horizon::Never);
        assert!(matches!(h(json!(1.5)), Horizon::Invalid(_)));
        assert!(matches!(h(json!(-1)), Horizon::Invalid(_)));
        assert!(matches!(h(json!(MAX_TTL_S + 1)), Horizon::Invalid(_)));
        assert_eq!(
            horizon(Kind::Event, &ann(json!("x"))),
            Horizon::Ignored,
            "the kind first"
        );
        assert_eq!(horizon(Kind::State, &BTreeMap::new()), Horizon::Undeclared);
        assert_eq!(
            h(json!(61)).refresh_bound(),
            Some(Duration::from_millis(30_500))
        );
    }

    #[test]
    fn a_trusted_reply_is_judged_in_the_band() {
        let h = Horizon::Within(Duration::from_secs(2));
        let got = |s: f64| Observation::Got {
            reply: Some(Reply::Put {
                stamp_age: Some(StampAge::from_secs_f64(s)),
            }),
            clock: ClockTrust::Trusted {
                delta: DEFAULT_DELTA,
            },
        };
        let v = |s: f64| judge(&h, &got(s)).reason;
        assert_eq!(v(1.5), Reason::WithinHorizon);
        assert_eq!(v(1.6), Reason::NearHorizon);
        assert_eq!(v(2.5), Reason::NearHorizon);
        assert_eq!(v(2.6), Reason::BeyondHorizon);
        assert_eq!(v(-0.5), Reason::WithinHorizon);
        assert_eq!(v(-0.6), Reason::ClockDisagrees);
    }

    #[test]
    fn fresh_wins_then_stale_then_unobservable() {
        let j = |v, r| Judged::new(v, r);
        assert_eq!(
            combine([
                j(Verdict::Stale, Reason::NoDelivery),
                j(Verdict::Fresh, Reason::WithinHorizon)
            ])
            .verdict,
            Verdict::Fresh
        );
        assert_eq!(
            combine([
                j(Verdict::Unobservable, Reason::ClockUntrusted),
                j(Verdict::Stale, Reason::NoDelivery)
            ])
            .reason,
            Reason::NoDelivery
        );
        assert_eq!(combine([]).reason, Reason::NoObservation);
    }

    mod view {
        use super::super::*;
        use crate::contract::load_str;
        use crate::heartbeat::{Digest, Heartbeat, Layout, Members, Section, Time};
        use crate::timing::Mono;
        use crate::wire::{Run, Seq, Tag};

        const HB: &str = r#"
[interface]
name = "hb"
major = 1
minor = 0
uses = ["freshness.v1"]
[resources.link]
kind = "state"
type = { raw = "text/plain" }
annotations = { "freshness.ttl_s" = 2 }
[resources."peer/{peer}"]
kind = "state"
type = { raw = "text/plain" }
params = { peer = "string" }
cardinality = 5
annotations = { "freshness.ttl_s" = 2 }
"#;
        const LINK: &str = "zk2/lab/n1/hb.v1/state/link";
        const A: &str = "zk2/lab/n1/hb.v1/state/peer/a";
        const B: &str = "zk2/lab/n1/hb.v1/state/peer/b";

        fn layout() -> Layout {
            let c = load_str(HB, std::path::Path::new("."), None)
                .contract
                .unwrap();
            Layout::of(&c)
        }
        fn st(run: u16, seq: u32) -> Stamp {
            Stamp {
                run: Run::U16(run),
                seq: Seq::new(seq).unwrap(),
            }
        }
        fn ms(n: u64) -> Mono {
            Mono::after(Duration::from_millis(n))
        }
        /// A heartbeat over (link, peer/*), its sections given.
        fn body(l: &Layout, link: Option<Section>, peers: Option<Section>) -> Vec<u8> {
            Heartbeat {
                time: Time::Unknown,
                sections: vec![link, peers],
            }
            .write(l)
            .unwrap()
        }
        fn view() -> View<Mono> {
            let mut v = View::new(layout());
            assert!(v.follow_resource("state/link"));
            assert!(v.follow_resource("state/peer/{peer}"));
            assert!(!v.follow_resource("state/nothing"));
            v
        }

        #[test]
        fn a_heartbeat_whose_digest_is_the_views_confirms_what_it_vouches_for() {
            let l = layout();
            let mut v = view();
            v.put(LINK, Some(st(1, 1)), ms(0));
            v.put(A, Some(st(1, 2)), ms(0));
            v.put(B, Some(st(1, 3)), ms(0));
            let link = Section {
                digest: Digest::of([(LINK, st(1, 1))]),
                members: Members::One { vouched: true },
            };
            let peers = Section {
                digest: Digest::of([(A, st(1, 2)), (B, st(1, 3))]),
                members: Members::templated(2, [1]),
            };
            let got = v.apply(
                l.tag,
                st(9, 0),
                &body(&l, Some(link), Some(peers)),
                ms(1500),
            );
            assert_eq!(
                got,
                Applied::Read {
                    gap: false,
                    sections: vec![
                        SectionRead::Confirmed(vec![LINK.into()]),
                        SectionRead::Confirmed(vec![B.into()]),
                    ]
                }
            );
            assert_eq!(v.confirmed(B), Some(ms(1500)));
            assert_eq!(v.confirmed(A), None, "not vouched for");
            // At 3 s: the link put at 0 is 3 s old, confirmed 1.5 s ago.
            let h = Horizon::Within(Duration::from_secs(2));
            let j = |k: &str| {
                judge(
                    &h,
                    &v.observation(k, ms(3000), Duration::from_secs(3), true),
                )
            };
            assert_eq!(j(LINK).verdict, Verdict::Fresh);
            assert_eq!(j(B).verdict, Verdict::Fresh);
            assert_eq!(
                j(A).verdict,
                Verdict::Stale,
                "a cleared bit is no confirmation"
            );
            // A namespace in front reads as the base-relative key.
            assert_eq!(v.confirmed(&format!("prod/{LINK}")), Some(ms(1500)));
        }

        #[test]
        fn a_missed_change_diverges_and_two_in_a_row_are_due_a_read() {
            let l = layout();
            let mut v = view();
            v.put(A, Some(st(1, 2)), ms(0));
            // The owner holds a's seq 5 and b: the view missed both.
            let owner = Digest::of([(A, st(1, 5)), (B, st(1, 6))]);
            let sec = || Section {
                digest: owner,
                members: Members::templated(2, [0, 1]),
            };
            for (seq, due) in [(0, false), (1, true)] {
                let got = v.apply(l.tag, st(9, seq), &body(&l, None, Some(sec())), ms(1000));
                assert_eq!(
                    got,
                    Applied::Read {
                        gap: false,
                        sections: vec![SectionRead::Absent, SectionRead::Diverged]
                    }
                );
                assert_eq!(v.reread_due() == vec![1], due);
            }
            assert_eq!(v.confirmed(A), None);
            // The read's answer replaces the view, and the next heartbeat confirms.
            v.replace(1, [(A, Some(st(1, 5))), (B, Some(st(1, 6)))], ms(1100));
            assert!(v.reread_due().is_empty());
            let got = v.apply(l.tag, st(9, 2), &body(&l, None, Some(sec())), ms(1200));
            assert_eq!(
                got,
                Applied::Read {
                    gap: false,
                    sections: vec![
                        SectionRead::Absent,
                        SectionRead::Confirmed(vec![A.into(), B.into()])
                    ]
                }
            );
        }

        #[test]
        fn a_deleted_member_leaves_the_digest_and_a_stale_put_is_not_taken() {
            let mut v = view();
            v.put(A, Some(st(1, 4)), ms(0));
            v.put(A, Some(st(1, 3)), ms(10));
            assert_eq!(v.digest(1), Some(Digest::of([(A, st(1, 4))])));
            v.delete(A, Some(st(1, 5)), ms(20));
            assert_eq!(v.digest(1), Some(Digest::EMPTY));
            assert_eq!(
                v.last(A, ms(30)),
                Some(Last::Delete(Duration::from_millis(10)))
            );
            // Another run's put is taken whatever its seq.
            v.put(A, Some(st(2, 0)), ms(40));
            assert_eq!(v.digest(1), Some(Digest::of([(A, st(2, 0))])));
            // A put with no envelope leaves the collection with no digest.
            v.put(B, None, ms(50));
            assert_eq!(v.digest(1), None);
            // A key of no collection is not held.
            v.put("zk2/lab/n1/hb.v1/state/other", Some(st(1, 1)), ms(60));
            assert_eq!(v.last("zk2/lab/n1/hb.v1/state/other", ms(70)), None);
        }

        #[test]
        fn a_gap_is_a_heartbeat_lost_and_the_tag_and_the_order_guard() {
            let l = layout();
            let mut v = view();
            v.put(LINK, Some(st(1, 1)), ms(0));
            let link = || {
                Some(Section {
                    digest: Digest::of([(LINK, st(1, 1))]),
                    members: Members::One { vouched: true },
                })
            };
            let b = body(&l, link(), None);
            let other = Tag::new((l.tag.get() + 1) % 16).unwrap();
            assert_eq!(v.apply(other, st(9, 0), &b, ms(100)), Applied::Revision);
            assert!(matches!(
                v.apply(l.tag, st(9, 0), &b, ms(100)),
                Applied::Read { gap: false, .. }
            ));
            assert!(matches!(
                v.apply(l.tag, st(9, 3), &b, ms(200)),
                Applied::Read { gap: true, .. }
            ));
            assert!(v.gap());
            let o = v.observation(LINK, ms(5000), Duration::from_secs(5), true);
            assert_eq!(
                judge(&Horizon::Within(Duration::from_secs(2)), &o).reason,
                Reason::Incomplete
            );
            assert_eq!(v.apply(l.tag, st(9, 3), &b, ms(300)), Applied::Older);
            assert_eq!(v.apply(l.tag, st(9, 1), &b, ms(300)), Applied::Older);
            assert!(matches!(
                v.apply(l.tag, st(9, 4), &b, ms(400)),
                Applied::Read { gap: false, .. }
            ));
            assert!(!v.gap());
            // A new run of the key is no gap, and its seq starts anew.
            assert!(matches!(
                v.apply(l.tag, st(10, 0), &b, ms(500)),
                Applied::Read { gap: false, .. }
            ));
            // A body cut short is refused, and counts as no heartbeat.
            assert!(matches!(
                v.apply(l.tag, st(10, 1), &b[..2], ms(600)),
                Applied::Refused(_)
            ));
            assert_eq!(v.heartbeats(), 4);
        }
    }

    /// `freshness.v2` §2.5's owner heartbeat, where `apply.json` leaves a
    /// reading unpinned: what a key covers, and a group's steps one by one.
    mod views {
        use super::super::*;
        use crate::catalog::Catalog;
        use crate::contract::load_str;
        use crate::heartbeat::{
            Class, Digest, Group, GroupRefusal, Layout, Members, OwnerHeartbeat, Section, Time,
        };
        use crate::timing::Mono;
        use crate::wire::{Run, Seq, Tag};

        const MIXED: &str = r#"
[interface]
name = "mixed"
major = 1
minor = 0
uses = ["freshness.v2", "link.v1"]
[resources."peer/{peer}"]
kind = "state"
type = { raw = "text/plain" }
params = { peer = "string" }
cardinality = 8
annotations = { "freshness.ttl_s" = 120 }
[resources.status]
kind = "state"
type = { raw = "text/plain" }
annotations = { "freshness.ttl_s" = 60, "link.exposure" = "link" }
"#;
        const VITAL: &str = r#"
[interface]
name = "vital"
major = 1
minor = 0
uses = ["freshness.v2"]
[resources.status]
kind = "state"
type = { raw = "text/plain" }
annotations = { "freshness.ttl_s" = 60 }
"#;
        const PEER: &str = "zk2/lab/n1/mixed.v1/state/peer/p1";
        const STATUS: &str = "zk2/lab/n1/mixed.v1/state/status";
        const VITALS: &str = "zk2/lab/n1/vital.v1/state/status";

        fn layout(text: &str) -> Layout {
            Layout::of(
                &load_str(text, std::path::Path::new("."), None)
                    .contract
                    .unwrap(),
            )
        }
        fn st(run: u16, seq: u32) -> Stamp {
            Stamp {
                run: Run::U16(run),
                seq: Seq::new(seq).unwrap(),
            }
        }
        fn ms(n: u64) -> Mono {
            Mono::after(Duration::from_millis(n))
        }
        /// mixed.v1 at index 0 and vital.v1 at index 1.
        fn catalog(mixed: &Layout, vital: &Layout) -> Catalog {
            let mut c = Catalog::new(0).unwrap();
            c.push(mixed.iface.clone(), mixed.fingerprint.clone())
                .unwrap();
            c.push(vital.iface.clone(), vital.fingerprint.clone())
                .unwrap();
            c
        }
        fn one(key: &str, stamp: Stamp) -> Option<Section> {
            Some(Section {
                digest: Digest::of([(key, stamp)]),
                members: Members::One { vouched: true },
            })
        }
        /// mixed.v1's group on the `host` key: `peer/p1` vouched for, and
        /// no bit for `status`, a `link` collection.
        fn mixed_host(l: &Layout) -> Group {
            let peers = Section {
                digest: Digest::of([(PEER, st(1, 1))]),
                members: Members::templated(1, [0]),
            };
            Group::of(0, l, &[Some(peers), None]).unwrap()
        }
        fn vital_host(l: &Layout) -> Group {
            Group::of(1, l, &[one(VITALS, st(1, 3))]).unwrap()
        }
        fn body(groups: Vec<Group>) -> Vec<u8> {
            OwnerHeartbeat {
                time: Time::Unknown,
                groups,
            }
            .write()
            .unwrap()
        }
        /// Both views, every collection followed, a member in each.
        fn views(mixed: &Layout, vital: &Layout) -> Views<Mono> {
            let mut vs = Views::new();
            for l in [mixed, vital] {
                let mut v = View::new(l.clone());
                for i in 0..l.collections.len() {
                    assert!(v.follow(i));
                }
                assert!(vs.insert(v).is_none());
            }
            vs.view_of_mut(PEER)
                .unwrap()
                .put(PEER, Some(st(1, 1)), ms(0));
            vs.view_of_mut(STATUS)
                .unwrap()
                .put(STATUS, Some(st(1, 2)), ms(0));
            vs.view_of_mut(VITALS)
                .unwrap()
                .put(VITALS, Some(st(1, 3)), ms(0));
            vs
        }

        #[test]
        fn a_class_is_the_exposure_and_a_key_is_one_classs() {
            let (mixed, vital) = (layout(MIXED), layout(VITAL));
            assert_eq!(
                mixed
                    .collections
                    .iter()
                    .map(|c| c.class)
                    .collect::<Vec<_>>(),
                vec![Class::Host, Class::Link]
            );
            assert_eq!(mixed.classes(), vec![Class::Link, Class::Host]);
            assert_eq!(vital.classes(), vec![Class::Host]);
            assert_eq!(
                mixed.class_horizon(Class::Link),
                Some(Duration::from_secs(60))
            );
            assert_eq!(
                mixed.class_horizon(Class::Host),
                Some(Duration::from_secs(120))
            );
            assert_eq!(vital.class_horizon(Class::Link), None);
            // A subscriber subscribes to the keys of the classes it follows.
            let mut v = View::<Mono>::new(mixed.clone());
            assert!(v.classes().is_empty());
            assert!(v.follow_resource("state/status"));
            assert_eq!(v.classes(), vec![Class::Link]);
            let vs = views(&mixed, &vital);
            assert_eq!(vs.classes(), vec![Class::Link, Class::Host]);
        }

        /// A group on the other class's key reads no section of the view,
        /// so it is no heartbeat applied to it: v2 §2.5 counts "the groups
        /// whose sections were read for its interface, on its own class's
        /// key" (review of #1137). The owner heartbeat itself is read and
        /// counted on its key.
        #[test]
        fn a_group_on_the_other_classs_key_is_no_heartbeat_applied() {
            let (mixed, vital) = (layout(MIXED), layout(VITAL));
            let cat = catalog(&mixed, &vital);
            let through = Catalogs {
                held: std::slice::from_ref(&cat),
                named: Some(cat.id()),
            };
            // A reader of mixed.v1's `status` alone, its `link` collection.
            let mut v = View::new(mixed.clone());
            assert!(v.follow_resource("state/status"));
            v.put(STATUS, Some(st(1, 2)), ms(0));
            let mut vs = Views::new();
            vs.insert(v);
            let known = Time::At { secs: 7, ms: 0 };
            let put = |g: Group| {
                OwnerHeartbeat {
                    time: known,
                    groups: vec![g],
                }
                .write()
                .unwrap()
            };
            // On the `host` key, mixed.v1's group holds `peer` alone.
            let host = vs.apply_owner(
                Class::Host,
                Tag::new(0).unwrap(),
                st(9, 0),
                &put(mixed_host(&mixed)),
                through,
                ms(10),
            );
            let OwnerApplied::Read { groups, .. } = host else {
                panic!("read: {host:?}");
            };
            assert_eq!(
                groups[0].read,
                GroupRead::Read(vec![SectionRead::NotFollowed, SectionRead::OtherClass])
            );
            let view = vs.view(&mixed.iface).unwrap();
            assert_eq!(view.heartbeats(), 0, "no section read, none applied");
            assert_eq!(view.owner_time(), None);
            assert_eq!(vs.owner_heartbeats(Class::Host), 1, "read on its key");
            // On the `link` key, its group reads `status`: one applied.
            let link = Group::of(0, &mixed, &[None, one(STATUS, st(1, 2))]).unwrap();
            let applied = vs.apply_owner(
                Class::Link,
                Tag::new(0).unwrap(),
                st(9, 0),
                &put(link),
                through,
                ms(20),
            );
            let OwnerApplied::Read { groups, .. } = applied else {
                panic!("read: {applied:?}");
            };
            assert_eq!(
                groups[0].read,
                GroupRead::Read(vec![
                    SectionRead::NotFollowed,
                    SectionRead::Confirmed(vec![STATUS.to_owned()])
                ])
            );
            let view = vs.view(&mixed.iface).unwrap();
            assert_eq!(view.heartbeats(), 1);
            assert_eq!(view.owner_time(), Some(known));
            // A map bit of 0 on the collection's own key is a section read
            // (`absent`), so its group is applied.
            let absent = Group::of(0, &mixed, &[None, None]).unwrap();
            vs.apply_owner(
                Class::Link,
                Tag::new(0).unwrap(),
                st(9, 1),
                &put(absent),
                through,
                ms(30),
            );
            assert_eq!(vs.view(&mixed.iface).unwrap().heartbeats(), 2);
        }

        #[test]
        fn a_sequence_is_its_keys_alone() {
            let mut s = Sequence::default();
            let first = s.read(st(9, 5)).unwrap();
            assert!(!first.gap && !first.run);
            assert_eq!(s.read(st(9, 5)), None, "the same seq");
            assert_eq!(s.read(st(9, 4)), None, "an earlier one");
            assert_eq!(s.read(st(9, 5 + (1 << 23))), None, "2^23 ahead, unordered");
            assert_eq!(s.last(), Some(st(9, 5)), "an older one moves nothing");
            assert!(!s.read(st(9, 6)).unwrap().gap);
            assert!(s.read(st(9, 8)).unwrap().gap);
            assert!(s.gap());
            let other = s.read(st(10, 3)).unwrap();
            assert!(other.run && !other.gap, "another run starts it again");
            assert!(!s.gap());
            // The seq wraps in serial order.
            let mut s = Sequence::default();
            s.read(st(9, Seq::MAX.get())).unwrap();
            assert!(!s.read(st(9, 0)).unwrap().gap);
        }

        #[test]
        fn a_gap_loses_what_a_group_on_the_key_named_within_the_run() {
            let (mixed, vital) = (layout(MIXED), layout(VITAL));
            let held = [catalog(&mixed, &vital)];
            let named = Some(held[0].id());
            let mut vs = views(&mixed, &vital);
            let alone = body(vec![mixed_host(&mixed)]);
            let both = body(vec![mixed_host(&mixed), vital_host(&vital)]);
            let through = Catalogs { held: &held, named };
            let host = |vs: &mut Views<Mono>, stamp, body: &[u8], at| match vs.apply_owner(
                Class::Host,
                Tag::NONE,
                stamp,
                body,
                through,
                ms(at),
            ) {
                OwnerApplied::Read { gap, .. } => gap,
                other => panic!("{other:?}"),
            };
            let lost = |vs: &Views<Mono>| -> Vec<(String, usize)> {
                vs.lost()
                    .into_iter()
                    .map(|(i, c)| (i.to_string(), c))
                    .collect()
            };
            // mixed.v1's group alone, then a gap: vital.v1 was never named
            // on the key, so its collection is no lost delivery.
            assert!(!host(&mut vs, st(9, 0), &alone, 100));
            assert!(host(&mut vs, st(9, 2), &alone, 200));
            assert_eq!(lost(&vs), vec![("mixed.v1".to_owned(), 0)]);
            assert!(vs.is_lost(&mixed.iface, 0));
            assert!(!vs.is_lost(&mixed.iface, 1), "a `link` collection");
            assert!(!vs.is_lost(&vital.iface, 0), "not named on the key");
            // The member is read as a lost delivery: incomplete.
            let o = |vs: &Views<Mono>, key| {
                let o = vs
                    .observation(key, ms(250), Duration::from_secs(1), true)
                    .unwrap();
                matches!(o, Observation::Subscribed { complete: true, .. })
            };
            assert!(!o(&vs, PEER));
            assert!(o(&vs, STATUS));
            assert!(o(&vs, VITALS));
            assert_eq!(vs.gap(Class::Host), Some(true));
            assert_eq!(vs.gap(Class::Link), None, "nothing read on the `link` key");
            // One in sequence ends it, and names vital.v1.
            assert!(!host(&mut vs, st(9, 3), &both, 300));
            assert!(lost(&vs).is_empty());
            // The next gap on the key covers both, though the owner
            // heartbeat after it holds mixed.v1's group alone.
            assert!(host(&mut vs, st(9, 5), &alone, 400));
            assert_eq!(
                lost(&vs),
                vec![("mixed.v1".to_owned(), 0), ("vital.v1".to_owned(), 0)]
            );
            // Another run starts the sequence again, and what the key
            // covers with it.
            assert!(!host(&mut vs, st(10, 0), &alone, 500));
            assert!(lost(&vs).is_empty());
            assert!(host(&mut vs, st(10, 2), &alone, 600));
            assert_eq!(lost(&vs), vec![("mixed.v1".to_owned(), 0)]);
            assert_eq!(vs.owner_heartbeats(Class::Host), 6);
            assert_eq!(vs.last(Class::Host), Some(st(10, 2)));
            // A key of no view held has no observation.
            assert!(
                vs.observation(
                    "zk2/lab/n1/other.v1/state/x",
                    ms(700),
                    Duration::from_secs(1),
                    true
                )
                .is_none()
            );
        }

        #[test]
        fn a_group_stops_at_the_first_step_that_answers() {
            let (mixed, vital) = (layout(MIXED), layout(VITAL));
            let cat = catalog(&mixed, &vital);
            let (e_mixed, e_vital) = (cat.entry(0).unwrap(), cat.entry(1).unwrap());
            let mut v = View::<Mono>::new(vital.clone());
            let g = vital_host(&vital);
            // Not followed: the view follows no collection yet, or the
            // index names another interface.
            assert_eq!(
                v.apply_group(Class::Host, e_vital, &g, Time::Unknown, ms(1)),
                GroupRead::NotFollowed
            );
            assert!(v.follow(0));
            v.put(VITALS, Some(st(1, 3)), ms(0));
            assert_eq!(
                v.apply_group(Class::Host, e_mixed, &g, Time::Unknown, ms(1)),
                GroupRead::NotFollowed
            );
            // Another revision: by the catalog's word, or by the tag.
            let elsewhere = crate::catalog::Entry {
                iface: vital.iface.clone(),
                contract: mixed.fingerprint.clone(),
            };
            assert_eq!(
                v.apply_group(Class::Host, &elsewhere, &g, Time::Unknown, ms(1)),
                GroupRead::Revision
            );
            let mut retagged = g.clone();
            retagged.tag = Tag::new((vital.tag.get() + 1) % 16).unwrap();
            assert_eq!(
                v.apply_group(Class::Host, e_vital, &retagged, Time::Unknown, ms(1)),
                GroupRead::Revision
            );
            // Refused: its sections, here cut one bit short. Counted for
            // nothing: the divergence before it and the one after are two
            // in a row.
            let diverged = Group::of(1, &vital, &[one(VITALS, st(1, 4))]).unwrap();
            assert_eq!(
                v.apply_group(Class::Host, e_vital, &diverged, Time::Unknown, ms(2)),
                GroupRead::Read(vec![SectionRead::Diverged])
            );
            let mut short = g.clone();
            short.sections.bits -= 1;
            assert_eq!(
                v.apply_group(Class::Host, e_vital, &short, Time::Unknown, ms(3)),
                GroupRead::Refused(GroupRefusal::Short)
            );
            assert!(v.reread_due().is_empty());
            assert_eq!(
                v.apply_group(Class::Host, e_vital, &diverged, Time::Unknown, ms(4)),
                GroupRead::Read(vec![SectionRead::Diverged])
            );
            assert_eq!(v.reread_due(), vec![0]);
            // Read, and on the other class's key not read at all: the
            // count of divergences stands.
            assert_eq!(
                v.apply_group(Class::Link, e_vital, &g, Time::Unknown, ms(5)),
                GroupRead::Read(vec![SectionRead::OtherClass])
            );
            assert_eq!(v.reread_due(), vec![0]);
            assert_eq!(v.confirmed(VITALS), None);
            assert_eq!(
                v.apply_group(Class::Host, e_vital, &g, Time::Unknown, ms(6)),
                GroupRead::Read(vec![SectionRead::Confirmed(vec![VITALS.to_owned()])])
            );
            assert_eq!(v.confirmed(VITALS), Some(ms(6)));
            assert!(v.reread_due().is_empty());
            // Its own heartbeat key heard nothing through all this.
            assert_eq!(v.last_heartbeat(), None);
            assert!(!v.gap());
        }

        #[test]
        fn an_owner_heartbeat_key_names_its_class() {
            use crate::heartbeat::{covered, owner_class, owner_key};
            let k = owner_key("lab", "n1", Class::Link);
            assert_eq!(k, "zk2/lab/n1/freshness.v2/stream/heartbeats/link");
            let (addr, class) = owner_class(&format!("ns/{k}")).unwrap();
            assert_eq!((addr.to_string().as_str(), class), ("lab/n1", Class::Link));
            assert_eq!(
                owner_class("zk2/lab/n1/freshness.v2/stream/heartbeats/host").map(|x| x.1),
                Some(Class::Host)
            );
            // No other chunk is a class, and neither key reads as the other.
            assert!(owner_class("zk2/lab/n1/freshness.v2/stream/heartbeats/near").is_none());
            assert!(owner_class("zk2/lab/n1/freshness.v2/stream/heartbeat/link.v1").is_none());
            assert!(covered(&k).is_none());
        }
    }

    #[test]
    fn a_measured_offset_trusts_within_the_delta_either_way() {
        let d = DEFAULT_DELTA;
        assert!(matches!(
            ClockTrust::measured(StampAge::ahead(d), d),
            ClockTrust::Trusted { .. }
        ));
        assert_eq!(
            ClockTrust::measured(StampAge::behind(Duration::from_millis(501)), d),
            ClockTrust::Untrusted
        );
    }
}