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
//! `telemetry.v1`: what a metric is, and how a reader reads one
//! (`spec/profiles/telemetry/v1.md`, #819).
//!
//! The profile's session-free half: the declaration read from a resolved
//! resource (§2.2, §2.4), one sample's conformance and the member's kind and
//! unit (§2.5, §2.6), and the continuity and rate of a pair of samples
//! (§2.9–§2.11).
//!
//! ```text
//! declaration(kind, annotations, type, attachment) ─▶ declared │ invalid [reasons] │ ignored │ not this profile's
//! check(declaration, payload)                      ─▶ conforms │ does_not [reasons] │ unobservable │ not_asked, + kind, unit, reading
//! pair(earlier, later, presence)                   ─▶ same_epoch │ reset │ decreased │ unobservable │ not_asked, + epoch, rate
//! ```
//!
//! There is no I/O and no clock here. A reader decodes a payload into a
//! [`Datum`] (JSON's data model, or CBOR's with its byte strings and its
//! non-finite floats), measures what it saw of presence and when each
//! sample arrived, and hands them over as values. The owner's in-band
//! epoch is the runtime's.
//!
//! [`decode`] reads a sample's bytes as §2.6 reads them (text 0.2): strict
//! JSON, and CBOR with its bignums, into a [`Datum`] whose integers are
//! exact. [`wire`] is the standard schema's types as an owner puts them:
//! the Point, its tagged value and the histogram, with serde (#819, TB).
//! [`stamp_ns`] is a state sample's stamp in nanoseconds, as zenoh reads it
//! (§2.11, 0.2).
//!
//! `telemetry.v2` (`spec/profiles/telemetry/v2.md`, #983 T1) restates these
//! rules by reference and binds a frame's fields to series ([`frames`]). A
//! counter carries its width ([`Measure::Counter`]), so [`pair`] reads a
//! narrow one in a serial window (v2 §2.20), and a frame's sample carries
//! its record's time ([`RecordTime`]), so a rate names its basis
//! ([`TimeBasis`], v2 §2.21). A v1 sample is a 64-bit counter with no
//! record time, and reads as before.

use std::collections::BTreeMap;
use std::fmt;

use serde_json::Value;

use crate::authoring::Kind;
use crate::contract::{Body, Contract, Resource};
use crate::schema::{Artifact, ArtifactData, TypeId};

pub mod decode;
pub mod frames;
pub mod wire;

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

/// `telemetry.v2`'s id (#983 T1): v1's rules by reference, and a frame
/// resource's fields bound to series by `telemetry.series` (v2 §2.16).
pub const PROFILE_V2: &str = "telemetry.v2";

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

/// `telemetry.kind` (§4).
pub const KIND: &str = "telemetry.kind";
/// `telemetry.unit` (§4).
pub const UNIT: &str = "telemetry.unit";
/// `telemetry.buckets` (§4).
pub const BUCKETS: &str = "telemetry.buckets";
/// `telemetry.semantic` (§4).
pub const SEMANTIC: &str = "telemetry.semantic";

/// `telemetry.series` (v2 §4): a frame resource's fields, each bound to a
/// series.
pub const SERIES: &str = "telemetry.series";

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

/// `telemetry.v2`'s vocabulary (v2 §4): v1's four keys and `series`, which
/// W105 reads for a contract that uses `telemetry.v2`.
pub const VOCABULARY_V2: &[&str] = &["kind", "unit", "buckets", "semantic", "series"];

/// Whether `c` uses `telemetry.v2` (v2 §1): its frame resources' fields
/// are series by their `telemetry.series`, and every other resource reads
/// as `telemetry.v1` reads it.
#[must_use]
pub fn uses_v2(c: &Contract) -> bool {
    c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
}

/// A v1 counter's width: every count from 0 to 2^64 − 1 (§2.7).
pub const FULL_WIDTH: u32 = 64;

/// The standard schema's stem (§3): `telemetry.v1.json`.
pub const SCHEMA_STEM: &str = "telemetry.v1";
/// The Point's type name (§2.3).
pub const POINT: &str = "telemetry.v1.Point";
/// The tagged value's type name (§2.3).
pub const VALUE: &str = "telemetry.v1.Value";
/// The histogram's type name (§2.3, §2.8).
pub const HISTOGRAM: &str = "telemetry.v1.Histogram";
/// The in-band epoch's type name (§2.3, §2.9).
pub const EPOCH: &str = "telemetry.v1.Epoch";

/// The standard schema's artifact ids the profile publishes (§3), oldest
/// first: ZenSight's file before the profile, then text 0.1's. A type of
/// one of these artifacts is the profile's (§2.3).
pub const PUBLISHED: &[&str] = &[
    "sha256:3d6276dd302873ca5938013a44d460267971123fd25500f189e30be718f9dc1e",
    "sha256:715ce537b2150beb3863f0e5cd356281357f7ec56d93625ee64e14f0045629e9",
];

/// The longest unit and the longest in-band epoch, in characters (§2.2,
/// §2.6).
pub const MAX_UNIT: usize = 64;
pub const MAX_EPOCH: usize = 64;

/// Whether `id` is one of the standard schema's published artifact ids.
#[must_use]
pub fn is_published(id: &str) -> bool {
    PUBLISHED.contains(&id)
}

/// A metric's kind (§2.2), one spelling on the annotation and on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MetricKind {
    Counter,
    Gauge,
    Histogram,
    Text,
    Boolean,
    Binary,
}

impl MetricKind {
    pub const ALL: [Self; 6] = [
        Self::Counter,
        Self::Gauge,
        Self::Histogram,
        Self::Text,
        Self::Boolean,
        Self::Binary,
    ];

    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Counter => "counter",
            Self::Gauge => "gauge",
            Self::Histogram => "histogram",
            Self::Text => "text",
            Self::Boolean => "boolean",
            Self::Binary => "binary",
        }
    }

    /// The kind spelled `s`, compared byte for byte.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|k| k.as_str() == s)
    }

    /// Counters and histograms have an epoch, a continuity and, for a
    /// counter, a rate (§2.7–§2.11).
    #[must_use]
    pub fn is_cumulative(self) -> bool {
        matches!(self, Self::Counter | Self::Histogram)
    }
}

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

/// A presentation hint (§2.2), never a finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Semantic {
    Temperature,
    Power,
    Bytes,
    Duration,
    Ratio,
    Count,
    Identity,
    State,
}

impl Semantic {
    pub const ALL: [Self; 8] = [
        Self::Temperature,
        Self::Power,
        Self::Bytes,
        Self::Duration,
        Self::Ratio,
        Self::Count,
        Self::Identity,
        Self::State,
    ];

    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Temperature => "temperature",
            Self::Power => "power",
            Self::Bytes => "bytes",
            Self::Duration => "duration",
            Self::Ratio => "ratio",
            Self::Count => "count",
            Self::Identity => "identity",
            Self::State => "state",
        }
    }

    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|k| k.as_str() == s)
    }
}

/// A unit (§2.2): 1 to 64 characters, each printable ASCII from 0x21 to
/// 0x7E. Never parsed or converted.
#[must_use]
pub fn is_unit(s: &str) -> bool {
    (1..=MAX_UNIT).contains(&s.len()) && s.bytes().all(|b| (0x21..=0x7e).contains(&b))
}

/// An in-band epoch (§2.6, §2.9): a string of 1 to 64 characters, counted
/// as Unicode code points, as JSON Schema's `minLength`/`maxLength` count.
#[must_use]
pub fn is_epoch(s: &str) -> bool {
    (1..=MAX_EPOCH).contains(&s.chars().count())
}

// ---------------------------------------------------------------------------
// The declaration (§2.2, §2.4)
// ---------------------------------------------------------------------------

/// A resource's type, as a reader of the declaration sees it (§2.4).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TypeView<'a> {
    /// A JSON Schema type: its name, its artifact's id, and its root
    /// schema, `$ref`s followed (core §9.8), when the reader resolved it.
    Json {
        name: &'a str,
        schema: &'a str,
        root: Option<&'a Value>,
    },
    /// A raw type, of any media type.
    Raw,
    /// A protobuf message.
    Protobuf,
    /// A packed record (core §7.6), which this profile's reader does not
    /// read yet: it carries no metric kind.
    Packed,
}

impl TypeView<'_> {
    /// Whether this is the profile's type `name`, by its artifact's id
    /// (§2.3).
    #[must_use]
    pub fn is_profiles(&self, type_name: &str) -> bool {
        matches!(self, Self::Json { name, schema, .. } if *name == type_name && is_published(schema))
    }
}

/// What a declaration's samples are (§2.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Carrier {
    /// The profile's Point, which says its own kind.
    Point,
    /// A bare value of the declared kind.
    Bare,
}

impl Carrier {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Point => "point",
            Self::Bare => "bare",
        }
    }
}

/// Where a member's in-band epoch rides (§2.4, §2.9).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EpochIn {
    /// The Point's `epoch`.
    Point,
    /// The sample's attachment, typed `telemetry.v1.Epoch`.
    Attachment,
}

impl EpochIn {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Point => "point",
            Self::Attachment => "attachment",
        }
    }
}

/// A valid declaration (§2.2).
#[derive(Debug, Clone, PartialEq)]
pub struct Declared {
    pub carrier: Carrier,
    /// The declared kind; `None` for a Point that says its own.
    pub kind: Option<MetricKind>,
    pub unit: Option<String>,
    /// The bounds, as doubles (§2.2), exactly when the kind is `histogram`.
    pub buckets: Option<Vec<f64>>,
    pub semantic: Option<Semantic>,
    /// Where an in-band epoch rides, if anywhere.
    pub epoch: Option<EpochIn>,
}

/// Why a declaration is invalid (§2.2), in the order a reader checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Invalid {
    KindValue,
    UnitValue,
    BucketsValue,
    SemanticValue,
    KindMissing,
    BucketsWithoutHistogram,
    HistogramWithoutBuckets,
    NotACarrier,
}

impl Invalid {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::KindValue => "kind_value",
            Self::UnitValue => "unit_value",
            Self::BucketsValue => "buckets_value",
            Self::SemanticValue => "semantic_value",
            Self::KindMissing => "kind_missing",
            Self::BucketsWithoutHistogram => "buckets_without_histogram",
            Self::HistogramWithoutBuckets => "histogram_without_buckets",
            Self::NotACarrier => "not_a_carrier",
        }
    }

    /// The reason in words, for a linter's or a tool's message.
    #[must_use]
    pub fn says(self) -> &'static str {
        match self {
            Self::KindValue => "telemetry.kind is not one of the six kinds",
            Self::UnitValue => {
                "telemetry.unit is not 1 to 64 printable ASCII characters (0x21 to 0x7E)"
            }
            Self::BucketsValue => {
                "telemetry.buckets is not a non-empty array of finite numbers, strictly ascending"
            }
            Self::SemanticValue => "telemetry.semantic is not one of the eight semantics",
            Self::KindMissing => "no telemetry.kind, and the type is not the profile's Point",
            Self::BucketsWithoutHistogram => {
                "telemetry.buckets on a resource whose declared kind is not histogram"
            }
            Self::HistogramWithoutBuckets => "a histogram without telemetry.buckets",
            Self::NotACarrier => "the type cannot carry the declared kind",
        }
    }
}

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

/// What a reader reads of a resolved resource (§2.2, §2.4).
#[derive(Debug, Clone, PartialEq)]
pub enum Declaration {
    Declared(Declared),
    /// The reasons, in §2.2's order.
    Invalid(Vec<Invalid>),
    /// An event or an operation that writes a key of the vocabulary: it
    /// means nothing there (§2.1, §2.2).
    Ignored,
    /// Not a metric resource: no key of the vocabulary, and not the Point,
    /// or an event or an operation that writes none.
    NotThisProfiles,
}

impl Declaration {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Declared(_) => "declared",
            Self::Invalid(_) => "invalid",
            Self::Ignored => "ignored",
            Self::NotThisProfiles => "not_this_profiles",
        }
    }

    #[must_use]
    pub fn declared(&self) -> Option<&Declared> {
        match self {
            Self::Declared(d) => Some(d),
            _ => None,
        }
    }
}

/// One key's value, as §2.2 reads it.
enum Read<T> {
    Absent,
    Valid(T),
    Wrong,
}

impl<T> Read<T> {
    fn of(v: Option<&Value>, f: impl FnOnce(&Value) -> Option<T>) -> Self {
        match v {
            None => Self::Absent,
            Some(v) => f(v).map_or(Self::Wrong, Self::Valid),
        }
    }
    fn is_wrong(&self) -> bool {
        matches!(self, Self::Wrong)
    }
    fn valid(&self) -> Option<&T> {
        match self {
            Self::Valid(t) => Some(t),
            _ => None,
        }
    }
}

/// `telemetry.buckets`' value (§2.2): a non-empty array of finite numbers,
/// strictly ascending as doubles.
fn read_buckets(v: &Value) -> Option<Vec<f64>> {
    let a = v.as_array()?;
    let b: Vec<f64> = a.iter().map(Value::as_f64).collect::<Option<_>>()?;
    (!b.is_empty() && b.iter().all(|x| x.is_finite()) && ascending(&b)).then_some(b)
}

fn ascending(b: &[f64]) -> bool {
    b.windows(2).all(|w| w[0] < w[1])
}

/// A root schema's `type` as a set of names (core §7.3); empty when it has
/// none, or one that is not a name or a list of names.
fn type_names(root: &Value) -> Vec<&str> {
    let mut v: Vec<&str> = match root.get("type") {
        Some(Value::String(s)) => vec![s.as_str()],
        Some(Value::Array(a)) => {
            let names: Option<Vec<&str>> = a.iter().map(Value::as_str).collect();
            names.unwrap_or_default()
        }
        _ => Vec::new(),
    };
    v.sort_unstable();
    v.dedup();
    v
}

/// Whether a type carries `kind` (§2.4).
#[must_use]
pub fn carries(ty: &TypeView<'_>, kind: MetricKind) -> bool {
    if ty.is_profiles(POINT) {
        return true;
    }
    if ty.is_profiles(HISTOGRAM) {
        return kind == MetricKind::Histogram;
    }
    match ty {
        TypeView::Raw => kind == MetricKind::Binary,
        TypeView::Protobuf | TypeView::Packed | TypeView::Json { root: None, .. } => false,
        TypeView::Json {
            root: Some(root), ..
        } => {
            let t = type_names(root);
            match kind {
                MetricKind::Counter => t == ["integer"],
                MetricKind::Gauge => {
                    !t.is_empty() && t.iter().all(|n| matches!(*n, "integer" | "number"))
                }
                MetricKind::Boolean => t == ["boolean"],
                MetricKind::Text => t == ["string"],
                MetricKind::Histogram | MetricKind::Binary => false,
            }
        }
    }
}

/// Reads the declaration of a resource of `kind` from its resolved
/// annotations (core §9.3), its type and its attachment's type (§2.2,
/// §2.4). `ty` is `None` for an operation, which has no payload type.
#[must_use]
pub fn declaration(
    kind: Kind,
    annotations: &BTreeMap<String, Value>,
    ty: Option<&TypeView<'_>>,
    attachment: Option<&TypeView<'_>>,
) -> Declaration {
    let any_key = [KIND, UNIT, BUCKETS, SEMANTIC]
        .iter()
        .any(|k| annotations.contains_key(*k));
    if matches!(kind, Kind::Event | Kind::Operation) {
        return if any_key {
            Declaration::Ignored
        } else {
            Declaration::NotThisProfiles
        };
    }
    let point = ty.is_some_and(|t| t.is_profiles(POINT));
    if !any_key && !point {
        return Declaration::NotThisProfiles;
    }
    let k = Read::of(annotations.get(KIND), |v| {
        v.as_str().and_then(MetricKind::parse)
    });
    let u = Read::of(annotations.get(UNIT), |v| {
        v.as_str().filter(|s| is_unit(s)).map(str::to_owned)
    });
    let b = Read::of(annotations.get(BUCKETS), read_buckets);
    let s = Read::of(annotations.get(SEMANTIC), |v| {
        v.as_str().and_then(Semantic::parse)
    });
    let mut why = Vec::new();
    for (wrong, r) in [
        (k.is_wrong(), Invalid::KindValue),
        (u.is_wrong(), Invalid::UnitValue),
        (b.is_wrong(), Invalid::BucketsValue),
        (s.is_wrong(), Invalid::SemanticValue),
    ] {
        if wrong {
            why.push(r);
        }
    }
    if matches!(k, Read::Absent) && !point {
        why.push(Invalid::KindMissing);
    }
    let histogram = matches!(k, Read::Valid(MetricKind::Histogram));
    if matches!(b, Read::Valid(_)) && !k.is_wrong() && !histogram {
        why.push(Invalid::BucketsWithoutHistogram);
    }
    if histogram && matches!(b, Read::Absent) {
        why.push(Invalid::HistogramWithoutBuckets);
    }
    if let Some(declared) = k.valid()
        && !ty.is_some_and(|t| carries(t, *declared))
    {
        why.push(Invalid::NotACarrier);
    }
    if !why.is_empty() {
        return Declaration::Invalid(why);
    }
    let kind = k.valid().copied();
    let epoch = if point {
        Some(EpochIn::Point)
    } else if kind.is_some_and(MetricKind::is_cumulative)
        && attachment.is_some_and(|a| a.is_profiles(EPOCH))
    {
        Some(EpochIn::Attachment)
    } else {
        None
    };
    Declaration::Declared(Declared {
        carrier: if point { Carrier::Point } else { Carrier::Bare },
        kind,
        unit: u.valid().cloned(),
        buckets: b.valid().cloned(),
        semantic: s.valid().copied(),
        epoch,
    })
}

/// [`declaration`] of a resource of a contract: its type's root schema
/// resolved from the contract's artifacts ([`root_schema`]).
#[must_use]
pub fn declaration_of(c: &Contract, r: &Resource) -> Declaration {
    let Body::Data(d) = &r.body else {
        return declaration(r.kind, &r.annotations, None, None);
    };
    let root = match &d.type_ {
        TypeId::JsonSchema { name, schema } => root_schema(&c.artifacts, schema, name),
        _ => None,
    };
    let ty = view(&d.type_, root.as_ref());
    let attachment = d.attachment.as_ref().map(|a| view(a, None));
    declaration(r.kind, &r.annotations, Some(&ty), attachment.as_ref())
}

fn view<'a>(t: &'a TypeId, root: Option<&'a Value>) -> TypeView<'a> {
    match t {
        TypeId::JsonSchema { name, schema } => TypeView::Json { name, schema, root },
        TypeId::Raw { .. } => TypeView::Raw,
        TypeId::Protobuf { .. } => TypeView::Protobuf,
        TypeId::Packed { .. } => TypeView::Packed,
    }
}

/// The root schema of the JSON Schema type `name` in the artifact `schema`
/// (§2.4): `$defs/<name>`, its `$ref`s followed across the artifacts by
/// stem, as core §9.8 follows them, a keyword beside a `$ref` added to its
/// target and an outer one taking the place of the target's own. `None`
/// when a `$ref` resolves to nothing, or the chain runs past 64 steps.
#[must_use]
pub fn root_schema(
    artifacts: &BTreeMap<String, Artifact>,
    schema: &str,
    name: &str,
) -> Option<Value> {
    fn json(a: &Artifact) -> Option<&Value> {
        match &a.data {
            ArtifactData::Json(v) => Some(v),
            ArtifactData::Protobuf(_) => None,
        }
    }
    let mut doc = json(artifacts.get(schema)?)?;
    let mut s = doc.get("$defs")?.get(name)?.clone();
    for _ in 0..64 {
        let Some(Value::String(r)) = s.get("$ref").cloned() else {
            return Some(s);
        };
        let (file, pointer) = r.split_once('#').unwrap_or((r.as_str(), ""));
        if !file.is_empty() {
            let base = file.rsplit('/').next().unwrap_or(file);
            let stem = base.strip_suffix(".json").unwrap_or(base);
            doc = artifacts
                .values()
                .filter(|a| a.kind == crate::schema::SchemaKind::JsonSchema && a.name == stem)
                .find_map(json)?;
        }
        let target = if pointer.is_empty() {
            doc
        } else {
            doc.pointer(pointer)?
        };
        let mut merged = target.as_object()?.clone();
        for (k, v) in s.as_object()? {
            if k != "$ref" && k != "$defs" {
                merged.insert(k.clone(), v.clone());
            }
        }
        if target.get("$ref").is_none() {
            merged.remove("$ref");
        } else {
            merged.insert("$ref".to_owned(), target["$ref"].clone());
        }
        s = Value::Object(merged);
    }
    None
}

// ---------------------------------------------------------------------------
// A decoded value (§2.6)
// ---------------------------------------------------------------------------

/// A sample's decoded data item (§2.6): JSON's data model, plus what CBOR
/// adds, byte strings and non-finite floats. Integers are exact.
#[derive(Debug, Clone, PartialEq)]
pub enum Datum {
    Null,
    Bool(bool),
    /// An integer: JSON text with no fraction and no exponent, CBOR's major
    /// types 0 and 1, or a bignum (tags 2 and 3, 0.2).
    Int(i128),
    /// An integer beyond i128 (0.2): JSON text within the double's finite
    /// range, or a CBOR bignum of any length, held as its nearest double
    /// (infinite past the double's range). No range of §2.6 admits one:
    /// as an integer it reads beyond every bound, as a number it is that
    /// double.
    BigInt(f64),
    /// A float: JSON text with a fraction or an exponent, a CBOR float.
    Float(f64),
    Text(String),
    Bytes(Vec<u8>),
    Array(Vec<Datum>),
    Map(BTreeMap<String, Datum>),
}

impl Datum {
    /// A JSON value as a datum: an integer JSON number exactly, any other
    /// as its double. `serde_json` holds no integer beyond 64 bits, and
    /// keeps the last of two duplicate members: a sample's bytes are read by
    /// [`Datum::from_json_bytes`], strict JSON (§2.6, 0.2).
    #[must_use]
    pub fn from_json(v: &Value) -> Self {
        match v {
            Value::Null => Self::Null,
            Value::Bool(b) => Self::Bool(*b),
            Value::Number(n) => {
                if let Some(u) = n.as_u64() {
                    Self::Int(i128::from(u))
                } else if let Some(i) = n.as_i64() {
                    Self::Int(i128::from(i))
                } else {
                    Self::Float(n.as_f64().unwrap_or(f64::NAN))
                }
            }
            Value::String(s) => Self::Text(s.clone()),
            Value::Array(a) => Self::Array(a.iter().map(Self::from_json).collect()),
            Value::Object(m) => Self::Map(
                m.iter()
                    .map(|(k, v)| (k.clone(), Self::from_json(v)))
                    .collect(),
            ),
        }
    }

    /// A CBOR data item as a datum, keeping byte strings and non-finite
    /// floats (§2.6); a tag reads as its content. `None` for a map key that
    /// is not text, or a value with no datum.
    #[must_use]
    pub fn from_cbor(v: &ciborium::Value) -> Option<Self> {
        use ciborium::Value as C;
        Some(match v {
            C::Null => Self::Null,
            C::Bool(b) => Self::Bool(*b),
            C::Integer(i) => Self::Int((*i).into()),
            C::Float(f) => Self::Float(*f),
            C::Text(s) => Self::Text(s.clone()),
            C::Bytes(b) => Self::Bytes(b.clone()),
            C::Array(a) => Self::Array(a.iter().map(Self::from_cbor).collect::<Option<_>>()?),
            C::Map(m) => {
                let mut out = BTreeMap::new();
                for (k, v) in m {
                    let C::Text(k) = k else { return None };
                    out.insert(k.clone(), Self::from_cbor(v)?);
                }
                Self::Map(out)
            }
            C::Tag(t @ (2 | 3), inner) if matches!(**inner, C::Bytes(_)) => {
                let C::Bytes(m) = &**inner else {
                    return None;
                };
                decode::bignum_of(*t == 3, m)
            }
            C::Tag(_, inner) => Self::from_cbor(inner)?,
            _ => return None,
        })
    }

    /// One JSON text, as strict JSON reads it (§2.6, 0.2; [`decode::json`]):
    /// `None` when the bytes are not one, the sample `undecodable`.
    #[must_use]
    pub fn from_json_bytes(bytes: &[u8]) -> Option<Self> {
        decode::json(bytes)
    }

    /// One CBOR data item and nothing after it, its bignums integers (§2.6,
    /// 0.2; [`decode::cbor`]): `None` when the bytes are not one.
    #[must_use]
    pub fn from_cbor_bytes(bytes: &[u8]) -> Option<Self> {
        decode::cbor(bytes)
    }

    /// A sample's bytes as `encoding` carries them: JSON unless CBOR.
    #[must_use]
    pub fn decode(bytes: &[u8], encoding: Option<crate::authoring::Encoding>) -> Option<Self> {
        match encoding {
            Some(crate::authoring::Encoding::Cbor) => decode::cbor(bytes),
            _ => decode::json(bytes),
        }
    }

    /// An attachment's bytes as the datum a reader checks (§2.6 check 2,
    /// 0.2): decoded as `encoding` carries it, or, when they do not decode,
    /// the bytes themselves, which are no string, so an Epoch attachment
    /// that does not decode is an epoch present and not a string:
    /// `epoch_invalid`, the sample still read. Zero bytes are such an
    /// attachment.
    #[must_use]
    pub fn attachment(bytes: &[u8], encoding: Option<crate::authoring::Encoding>) -> Self {
        Self::decode(bytes, encoding).unwrap_or_else(|| Self::Bytes(bytes.to_vec()))
    }

    fn get(&self, k: &str) -> Option<&Self> {
        match self {
            Self::Map(m) => m.get(k),
            _ => None,
        }
    }

    /// A number, as a double (an integer to its nearest).
    fn number(&self) -> Option<f64> {
        match self {
            Self::Int(i) => Some(*i as f64),
            Self::Float(f) | Self::BigInt(f) => Some(*f),
            _ => None,
        }
    }

    /// An integer, as JSON Schema's `integer` reads one: an integer, or an
    /// integral finite float, the integer it equals. `None` for any other
    /// value. An integral float beyond ±2^127 saturates to `i128`'s bound,
    /// which is beyond every range §2.6 asks of an integer, as its value is.
    fn integer(&self) -> Option<i128> {
        match self {
            Self::Int(i) => Some(*i),
            // `as` saturates a float to the integer's bound.
            Self::Float(f) if f.is_finite() && f.fract() == 0.0 => Some(*f as i128),
            // Beyond i128: past every bound, on its side.
            Self::BigInt(f) => Some(if *f < 0.0 { i128::MIN } else { i128::MAX }),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// A sample's conformance (§2.5, §2.6)
// ---------------------------------------------------------------------------

/// A sample's payload, as the reader received it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Payload<'a> {
    /// The decoded data item, and the decoded attachment, if any.
    Decoded {
        value: &'a Datum,
        attachment: Option<&'a Datum>,
    },
    /// Bytes the core could not decode (§2.6).
    Undecodable,
}

/// Why a sample does not conform (§2.6), in the order a reader checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Problem {
    NotAPoint,
    EpochInvalid,
    UnitInvalid,
    TagDisagrees,
    UnitDisagrees,
    WrongType,
    OutOfRange,
    NotFinite,
    BoundsInvalid,
    BoundsDiffer,
    CountsLength,
    CountSum,
}

impl Problem {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NotAPoint => "not_a_point",
            Self::EpochInvalid => "epoch_invalid",
            Self::UnitInvalid => "unit_invalid",
            Self::TagDisagrees => "tag_disagrees",
            Self::UnitDisagrees => "unit_disagrees",
            Self::WrongType => "wrong_type",
            Self::OutOfRange => "out_of_range",
            Self::NotFinite => "not_finite",
            Self::BoundsInvalid => "bounds_invalid",
            Self::BoundsDiffer => "bounds_differ",
            Self::CountsLength => "counts_length",
            Self::CountSum => "count_sum",
        }
    }

    /// The reason in words, for a tool's message.
    #[must_use]
    pub fn says(self) -> &'static str {
        match self {
            Self::NotAPoint => "the payload is not a telemetry.v1.Point",
            Self::EpochInvalid => "the in-band epoch is not a string of 1 to 64 characters",
            Self::UnitInvalid => "the Point's unit is not a unit",
            Self::TagDisagrees => "the Point's tag differs from the declared kind",
            Self::UnitDisagrees => "the Point's unit differs from the declared unit",
            Self::WrongType => "the value is not of the type its kind needs",
            Self::OutOfRange => "a count outside 0 to 2^64-1",
            Self::NotFinite => "a number that is NaN or infinite",
            Self::BoundsInvalid => "the histogram's bounds are empty or not strictly ascending",
            Self::BoundsDiffer => "the histogram's bounds differ from the declared buckets",
            Self::CountsLength => "counts is not one longer than buckets",
            Self::CountSum => "count is not the sum of counts",
        }
    }
}

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

/// Why a question about a sample was put and could not be answered, or
/// was not asked (§2.6, §5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Unasked {
    /// Unobservable: the declaration is invalid (§2.2).
    DeclarationInvalid,
    /// Unobservable: the core could not decode the sample.
    Undecodable,
    /// Not asked: not a metric resource.
    NotThisProfiles,
    /// Not asked: an event or an operation.
    Ignored,
}

impl Unasked {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::DeclarationInvalid => "declaration_invalid",
            Self::Undecodable => "undecodable",
            Self::NotThisProfiles => "not_this_profiles",
            Self::Ignored => "ignored",
        }
    }
}

/// The answer to "does this sample conform?" (§2.6). `DoesNot` is the
/// finding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Conformance {
    Conforms,
    /// The reasons, in §2.6's order.
    DoesNot(Vec<Problem>),
    Unobservable(Unasked),
    NotAsked(Unasked),
}

impl Conformance {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Conforms => "conforms",
            Self::DoesNot(_) => "does_not",
            Self::Unobservable(_) => "unobservable",
            Self::NotAsked(_) => "not_asked",
        }
    }
}

/// Where a member's kind or unit came from (§2.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
    /// The resource's annotation.
    Declared,
    /// The Point: its tag, or its `unit`.
    Point,
}

impl Source {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Declared => "declared",
            Self::Point => "point",
        }
    }
}

/// A histogram's value (§2.8).
#[derive(Debug, Clone, PartialEq)]
pub struct Histogram {
    pub bounds: Vec<f64>,
    pub counts: Vec<u64>,
    pub count: u64,
    pub sum: f64,
}

/// A conforming sample's value, by its kind.
#[derive(Debug, Clone, PartialEq)]
pub enum Measure {
    /// A count modulo 2^`width`: a v1 counter's width is 64
    /// ([`FULL_WIDTH`]), a frame's counter field's its declared width, from
    /// 1 to 64 (core §7.6, v2 §2.20).
    Counter {
        value: u64,
        width: u32,
    },
    Gauge(f64),
    Histogram(Histogram),
    Text(String),
    Boolean(bool),
    Binary(Vec<u8>),
}

impl Measure {
    /// A 64-bit counter, as every v1 carrier holds one (§2.7).
    #[must_use]
    pub const fn counter(value: u64) -> Self {
        Self::Counter {
            value,
            width: FULL_WIDTH,
        }
    }

    #[must_use]
    pub fn kind(&self) -> MetricKind {
        match self {
            Self::Counter { .. } => MetricKind::Counter,
            Self::Gauge(_) => MetricKind::Gauge,
            Self::Histogram(_) => MetricKind::Histogram,
            Self::Text(_) => MetricKind::Text,
            Self::Boolean(_) => MetricKind::Boolean,
            Self::Binary(_) => MetricKind::Binary,
        }
    }
}

/// What a conforming sample says: its value, its measurement time (a
/// Point's `timestamp`) and its in-band epoch.
#[derive(Debug, Clone, PartialEq)]
pub struct Reading {
    pub value: Measure,
    pub timestamp_ms: Option<i64>,
    pub epoch: Option<String>,
}

/// One sample, read (§2.5, §2.6).
#[derive(Debug, Clone, PartialEq)]
pub struct Checked {
    pub conformance: Conformance,
    /// The member's kind as this sample gives it, or `None`: unobservable
    /// or not this profile's (§2.5).
    pub kind: Option<(MetricKind, Source)>,
    /// The member's unit as this sample gives it, or `None`: unknown,
    /// never dimensionless (§2.5).
    pub unit: Option<(String, Source)>,
    /// The sample's value, when it conforms.
    pub reading: Option<Reading>,
}

/// A Point, its shape checked (§2.6, check 1).
struct PointView<'a> {
    timestamp: i64,
    tag: MetricKind,
    value: &'a Datum,
    unit: Option<&'a str>,
    epoch: Option<&'a Datum>,
}

fn point_view(d: &Datum) -> Option<PointView<'_>> {
    let Datum::Map(_) = d else { return None };
    let timestamp = i64::try_from(d.get("timestamp")?.integer()?).ok()?;
    let v = d.get("value")?;
    let Datum::Map(_) = v else { return None };
    let Some(Datum::Text(tag)) = v.get("type") else {
        return None;
    };
    let tag = MetricKind::parse(tag)?;
    let value = v.get("value")?;
    match d.get("labels") {
        None => {}
        Some(Datum::Map(m)) if m.values().all(|l| matches!(l, Datum::Text(_))) => {}
        Some(_) => return None,
    }
    let unit = match d.get("unit") {
        None => None,
        Some(Datum::Text(u)) => Some(u.as_str()),
        Some(_) => return None,
    };
    Some(PointView {
        timestamp,
        tag,
        value,
        unit,
        epoch: d.get("epoch"),
    })
}

/// A count (§2.6, check 7): `Ok` in 0 to 2^64−1, `Err` out of range.
fn count(i: i128) -> Result<u64, ()> {
    u64::try_from(i).map_err(|_| ())
}

/// The value checks (§2.6, checks 6 to 12) of `v` as a `kind`, a Point's
/// value or a bare one, against the declared bounds of a histogram.
fn check_value(
    kind: MetricKind,
    v: &Datum,
    point: bool,
    declared: Option<&[f64]>,
    out: &mut Vec<Problem>,
) -> Option<Measure> {
    match kind {
        MetricKind::Counter => {
            let Some(i) = v.integer() else {
                out.push(Problem::WrongType);
                return None;
            };
            match count(i) {
                Ok(n) => Some(Measure::counter(n)),
                Err(()) => {
                    out.push(Problem::OutOfRange);
                    None
                }
            }
        }
        MetricKind::Gauge => {
            let Some(f) = v.number() else {
                out.push(Problem::WrongType);
                return None;
            };
            if f.is_finite() {
                Some(Measure::Gauge(f))
            } else {
                out.push(Problem::NotFinite);
                None
            }
        }
        MetricKind::Boolean => match v {
            Datum::Bool(b) => Some(Measure::Boolean(*b)),
            _ => {
                out.push(Problem::WrongType);
                None
            }
        },
        MetricKind::Text => match v {
            Datum::Text(s) => Some(Measure::Text(s.clone())),
            _ => {
                out.push(Problem::WrongType);
                None
            }
        },
        MetricKind::Binary => {
            let bytes = match (point, v) {
                (false, Datum::Bytes(b)) => Some(b.clone()),
                (true, Datum::Array(a)) => a
                    .iter()
                    .map(|x| x.integer().and_then(|i| u8::try_from(i).ok()))
                    .collect(),
                _ => None,
            };
            if bytes.is_none() {
                out.push(Problem::WrongType);
            }
            bytes.map(Measure::Binary)
        }
        MetricKind::Histogram => check_histogram(v, declared, out),
    }
}

fn check_histogram(v: &Datum, declared: Option<&[f64]>, out: &mut Vec<Problem>) -> Option<Measure> {
    let shape = (|| {
        let Some(Datum::Array(b)) = v.get("buckets") else {
            return None;
        };
        let Some(Datum::Array(c)) = v.get("counts") else {
            return None;
        };
        let bounds: Vec<f64> = b.iter().map(Datum::number).collect::<Option<_>>()?;
        let counts: Vec<i128> = c.iter().map(Datum::integer).collect::<Option<_>>()?;
        let count = v.get("count")?.integer()?;
        let sum = v.get("sum")?.number()?;
        Some((bounds, counts, count, sum))
    })();
    let Some((bounds, counts, total, sum)) = shape else {
        out.push(Problem::WrongType);
        return None;
    };
    let before = out.len();
    let in_range: Option<(Vec<u64>, u64)> = (|| {
        let c: Vec<u64> = counts
            .iter()
            .map(|i| count(*i).ok())
            .collect::<Option<_>>()?;
        Some((c, count(total).ok()?))
    })();
    if in_range.is_none() {
        out.push(Problem::OutOfRange);
    }
    let finite = bounds.iter().all(|b| b.is_finite());
    if !finite || !sum.is_finite() {
        out.push(Problem::NotFinite);
    }
    let valid_bounds = finite && !bounds.is_empty() && ascending(&bounds);
    if finite && !valid_bounds {
        out.push(Problem::BoundsInvalid);
    }
    if valid_bounds
        && let Some(d) = declared
        && (d.len() != bounds.len() || d.iter().zip(&bounds).any(|(a, b)| a != b))
    {
        out.push(Problem::BoundsDiffer);
    }
    if counts.len() != bounds.len() + 1 {
        out.push(Problem::CountsLength);
    }
    if let Some((c, n)) = &in_range
        && c.iter().map(|x| u128::from(*x)).sum::<u128>() != u128::from(*n)
    {
        out.push(Problem::CountSum);
    }
    if out.len() > before {
        return None;
    }
    let (counts, count) = in_range?;
    Some(Measure::Histogram(Histogram {
        bounds,
        counts,
        count,
        sum,
    }))
}

/// Reads one sample of a member whose resource's declaration is `decl`
/// (§2.5, §2.6): its conformance, the member's kind and unit as the sample
/// gives them, and its value when it conforms.
#[must_use]
pub fn check(decl: &Declaration, payload: &Payload<'_>) -> Checked {
    let none = |c| Checked {
        conformance: c,
        kind: None,
        unit: None,
        reading: None,
    };
    let d = match decl {
        Declaration::NotThisProfiles => {
            return none(Conformance::NotAsked(Unasked::NotThisProfiles));
        }
        Declaration::Ignored => return none(Conformance::NotAsked(Unasked::Ignored)),
        Declaration::Invalid(_) => {
            return none(Conformance::Unobservable(Unasked::DeclarationInvalid));
        }
        Declaration::Declared(d) => d,
    };
    let mut out = Checked {
        conformance: Conformance::Conforms,
        kind: d.kind.map(|k| (k, Source::Declared)),
        unit: d.unit.clone().map(|u| (u, Source::Declared)),
        reading: None,
    };
    let Payload::Decoded { value, attachment } = *payload else {
        out.conformance = Conformance::Unobservable(Unasked::Undecodable);
        return out;
    };
    let mut problems = Vec::new();
    let epoch_of = |e: &Datum, problems: &mut Vec<Problem>| match e {
        Datum::Text(s) if is_epoch(s) => Some(s.clone()),
        _ => {
            problems.push(Problem::EpochInvalid);
            None
        }
    };
    let (measure, timestamp_ms, epoch, point) = match d.carrier {
        Carrier::Point => {
            let Some(p) = point_view(value) else {
                out.conformance = Conformance::DoesNot(vec![Problem::NotAPoint]);
                return out;
            };
            let epoch = p.epoch.and_then(|e| epoch_of(e, &mut problems));
            let unit = p.unit.filter(|u| is_unit(u));
            if p.unit.is_some() && unit.is_none() {
                problems.push(Problem::UnitInvalid);
            }
            if d.kind.is_some_and(|k| k != p.tag) {
                problems.push(Problem::TagDisagrees);
            }
            if let (Some(du), Some(u)) = (&d.unit, unit)
                && du != u
            {
                problems.push(Problem::UnitDisagrees);
            }
            let m = check_value(p.tag, p.value, true, d.buckets.as_deref(), &mut problems);
            (m, Some(p.timestamp), epoch, Some((p.tag, unit)))
        }
        Carrier::Bare => {
            let kind = d.kind.expect("a valid bare declaration declares its kind");
            let epoch = match (d.epoch, attachment) {
                (Some(EpochIn::Attachment), Some(a)) => epoch_of(a, &mut problems),
                _ => None,
            };
            let m = check_value(kind, value, false, d.buckets.as_deref(), &mut problems);
            (m, None, epoch, None)
        }
    };
    if !problems.is_empty() {
        problems.sort_unstable();
        problems.dedup();
        out.conformance = Conformance::DoesNot(problems);
        return out;
    }
    if let Some((tag, unit)) = point {
        out.kind.get_or_insert((tag, Source::Point));
        if out.unit.is_none() {
            out.unit = unit.map(|u| (u.to_owned(), Source::Point));
        }
    }
    out.reading = measure.map(|value| Reading {
        value,
        timestamp_ms,
        epoch,
    });
    out
}

// ---------------------------------------------------------------------------
// A pair: its continuity and its rate (§2.9–§2.11)
// ---------------------------------------------------------------------------

/// One sample of a pair, as the reader holds it (§2.10, §2.11).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sampled<'a> {
    /// The conforming sample's value; its kind is the sample's.
    pub value: &'a Measure,
    /// Its in-band epoch (§2.9), if it carries one.
    pub epoch: Option<&'a str>,
    /// The Point's `timestamp`, for a Point.
    pub timestamp_ms: Option<i64>,
    /// The owner's stamp, in nanoseconds since the Unix epoch, for state:
    /// [`stamp_ns`] of its NTP64 value (0.2).
    pub stamp_ns: Option<i128>,
    /// When the reader received it, in nanoseconds on its monotonic clock.
    pub arrival_ns: i128,
    /// A frame's sample: its record's time (v2 §2.21). `None` for every v1
    /// carrier, whose time base is §2.11's list.
    pub record: Option<RecordTime>,
}

/// A frame record's time, as a frame's sample carries it (v2 §2.21, core
/// §7.7): what [`crate::frame::RecordRead`] reads, and which frame of the
/// key the record came in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecordTime {
    /// Which frame of its key it came in, as its reader counts them: two
    /// records with one number came in one frame, and are timed by their
    /// offsets from its record 0.
    pub frame: u64,
    pub when: crate::frame::When,
    /// After record 0: its measured offset, or `step_ms` × its index when
    /// scheduled. 0 for record 0.
    pub after_ms: u64,
    /// Its instant in milliseconds from the deployment epoch, `None` when
    /// its frame's time is unknown.
    pub at_ms: Option<u64>,
}

impl RecordTime {
    /// How far its time may lie from the instant it gives: a scheduled
    /// record's `jitter_ms`, else 0.
    #[must_use]
    pub const fn jitter_ms(&self) -> u64 {
        match self.when {
            crate::frame::When::Scheduled { jitter_ms } => jitter_ms as u64,
            _ => 0,
        }
    }

    const fn scheduled(&self) -> bool {
        matches!(self.when, crate::frame::When::Scheduled { .. })
    }
}

/// What a frame's rate is timed by (v2 §2.21). A v1 rate names none.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeBasis {
    /// Both records' times measured on the owner's clocks.
    Measured,
    /// At least one record's time scheduled: the elapsed time is exact to
    /// within `jitter_ms` either way, the sum of the scheduled records'
    /// `jitter_ms`. Never a measured rate.
    Scheduled { jitter_ms: u64 },
    /// The reader's arrivals: a record's time was unknown.
    Arrival,
}

impl TimeBasis {
    /// The fixture's token.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Measured => "measured",
            Self::Scheduled { .. } => "scheduled",
            Self::Arrival => "arrival",
        }
    }
}

/// What the reader observed of the owning service's instance tokens, or of
/// a member's tokens for a template that declares `epoch` (§2.9).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Presence<'a> {
    /// One instance (or member epoch) alone, without a loss on the presence
    /// view, from before the earlier arrival to after the later one's.
    pub alone_throughout: bool,
    /// The only instance present at the earlier arrival; `None` when there
    /// was none, several, or the reader cannot tell.
    pub earlier: Option<&'a str>,
    /// The only instance present at the later arrival, likewise.
    pub later: Option<&'a str>,
}

/// How an epoch was established (§2.9).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Via {
    InBand,
    Presence,
}

impl Via {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::InBand => "in_band",
            Self::Presence => "presence",
        }
    }
}

/// The epoch evidence for a pair (§2.9).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Epochs {
    Same(Via),
    Different(Via),
    Unobservable,
}

/// §2.9: in-band when both carry an epoch, else presence, else
/// unobservable.
#[must_use]
pub fn epochs(
    earlier: Option<&str>,
    later: Option<&str>,
    presence: Option<&Presence<'_>>,
) -> Epochs {
    if let (Some(a), Some(b)) = (earlier, later) {
        return if a == b {
            Epochs::Same(Via::InBand)
        } else {
            Epochs::Different(Via::InBand)
        };
    }
    match presence {
        Some(p) if p.alone_throughout => Epochs::Same(Via::Presence),
        Some(Presence {
            earlier: Some(a),
            later: Some(b),
            ..
        }) if a != b => Epochs::Different(Via::Presence),
        _ => Epochs::Unobservable,
    }
}

/// The answer to a pair's continuity (§2.10). `Decreased` is the finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Continuity {
    SameEpoch,
    Reset,
    Decreased,
    /// The two samples cannot be compared (`incomparable`: their kinds,
    /// their widths, or a histogram's bounds or length differ), or a narrow
    /// counter's change within one epoch lies outside its serial window
    /// (`wrap_or_decrease`, v2 §2.20). [`Pair::unobservable`] says which.
    Unobservable,
    /// Neither sample is a counter or a histogram (`kind`).
    NotAsked,
}

impl Continuity {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::SameEpoch => "same_epoch",
            Self::Reset => "reset",
            Self::Decreased => "decreased",
            Self::Unobservable => "unobservable",
            Self::NotAsked => "not_asked",
        }
    }
}

/// Whether a pair's epoch was established, and how, or assumed (§2.10).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Basis {
    Established(Via),
    Assumed,
}

/// Why a pair has no rate (§2.11).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoRate {
    /// Not asked: the pair is not of two counters, an incomparable pair
    /// included, since two counters are always comparable (0.2, F-146).
    Kind,
    Reset,
    Decreased,
    /// The elapsed time is 0 or less.
    Elapsed,
    /// A narrow counter's change within one epoch lies outside its serial
    /// window: a wrap or a decrease, which the two values cannot tell apart
    /// (v2 §2.20).
    WrapOrDecrease,
}

impl NoRate {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Kind => "kind",
            Self::Reset => "reset",
            Self::Decreased => "decreased",
            Self::Elapsed => "elapsed",
            Self::WrapOrDecrease => "wrap_or_decrease",
        }
    }
}

/// A counter's rate over a pair (§2.11).
#[derive(Debug, Clone, PartialEq)]
pub struct Rate {
    /// Per second, by §2.11's formula.
    pub per_s: f64,
    /// The counter's unit followed by `/s`; `None` when it is unknown.
    pub unit: Option<String>,
    /// The elapsed time the rate is over, in nanoseconds, above 0.
    pub elapsed_ns: i128,
    /// A frame's rate's time basis (v2 §2.21); `None` for a v1 pair, timed
    /// by §2.11's list.
    pub basis: Option<TimeBasis>,
}

/// A pair, judged (§2.10, §2.11).
#[derive(Debug, Clone, PartialEq)]
pub struct Pair {
    pub continuity: Continuity,
    /// `None` when the epoch was not asked of the pair.
    pub basis: Option<Basis>,
    pub rate: Result<Rate, NoRate>,
}

impl Pair {
    /// Why an unobservable pair is: `incomparable` (§2.10), or
    /// `wrap_or_decrease` (v2 §2.20). `None` for any other continuity.
    #[must_use]
    pub fn unobservable(&self) -> Option<&'static str> {
        match (self.continuity, &self.rate) {
            (Continuity::Unobservable, Err(NoRate::WrapOrDecrease)) => Some("wrap_or_decrease"),
            (Continuity::Unobservable, _) => Some("incomparable"),
            _ => None,
        }
    }
}

/// How a later value moved from an earlier one of one member (§2.10, v2
/// §2.20).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Change {
    /// No decrease: a counter's increase by this much (0 for a histogram).
    Up(u64),
    /// A decrease (§2.10).
    Down,
    /// A narrow counter's change outside its serial window (v2 §2.20).
    Outside,
}

/// How `later` moved from `earlier` (§2.10); `None` when the two cannot be
/// compared: their kinds, a counter's widths, or a histogram's bounds or
/// length differ. A counter of width w below 64 is read in a serial window
/// (v2 §2.20): the increase d = (b − a) mod 2^w when d < 2^(w−1), else
/// outside it. At width 64, b below a is a decrease.
fn change(earlier: &Measure, later: &Measure) -> Option<Change> {
    match (earlier, later) {
        (
            Measure::Counter { value: a, width: w },
            Measure::Counter {
                value: b,
                width: wb,
            },
        ) => {
            if w != wb || *w == 0 || *w > FULL_WIDTH {
                return None;
            }
            if *w == FULL_WIDTH {
                return Some(if b < a {
                    Change::Down
                } else {
                    Change::Up(b - a)
                });
            }
            let mask = (1u64 << w) - 1;
            let d = b.wrapping_sub(*a) & mask;
            Some(if d < 1u64 << (w - 1) {
                Change::Up(d)
            } else {
                Change::Outside
            })
        }
        (Measure::Histogram(a), Measure::Histogram(b)) => {
            let same_bounds = a.bounds.len() == b.bounds.len()
                && a.bounds.iter().zip(&b.bounds).all(|(x, y)| x == y);
            if !same_bounds || a.counts.len() != b.counts.len() {
                return None;
            }
            let down = b.count < a.count || a.counts.iter().zip(&b.counts).any(|(x, y)| y < x);
            Some(if down { Change::Down } else { Change::Up(0) })
        }
        _ => None,
    }
}

/// The elapsed time between two samples, in nanoseconds, and what it is
/// timed by: two frame records by their times (v2 §2.21), else the first
/// time base of §2.11's list both have. [`pair`] times a rate by it; a
/// reader shows it for a pair with no rate too.
#[must_use]
pub fn elapsed(a: &Sampled<'_>, b: &Sampled<'_>) -> (i128, Option<TimeBasis>) {
    const MS: i128 = 1_000_000;
    if let (Some(x), Some(y)) = (&a.record, &b.record) {
        let timed = if x.scheduled() || y.scheduled() {
            TimeBasis::Scheduled {
                jitter_ms: x.jitter_ms() + y.jitter_ms(),
            }
        } else {
            TimeBasis::Measured
        };
        if x.frame == y.frame {
            let e = i128::from(y.after_ms) - i128::from(x.after_ms);
            return (e * MS, Some(timed));
        }
        if let (Some(p), Some(q)) = (x.at_ms, y.at_ms) {
            return ((i128::from(q) - i128::from(p)) * MS, Some(timed));
        }
        return (b.arrival_ns - a.arrival_ns, Some(TimeBasis::Arrival));
    }
    let e = if let (Some(x), Some(y)) = (a.timestamp_ms, b.timestamp_ms) {
        (i128::from(y) - i128::from(x)) * MS
    } else if let (Some(x), Some(y)) = (a.stamp_ns, b.stamp_ns) {
        y - x
    } else {
        b.arrival_ns - a.arrival_ns
    };
    (e, None)
}

/// A state sample's stamp in nanoseconds (§2.11, 0.2, F-142), from its raw
/// NTP64 value: the seconds (the high 32 bits) times 10^9, plus the 32-bit
/// fraction times 10^9 divided by 2^32, rounded up. uhlc's
/// `NTP64::as_nanos`, which zenoh reads a stamp's time with; a pair's
/// elapsed time is the later stamp's nanoseconds less the earlier's, each
/// converted alone.
#[must_use]
pub fn stamp_ns(ntp64: u64) -> i128 {
    let secs = i128::from(ntp64 >> 32);
    // Below 2^32 times 10^9, so below 2^62: no overflow in a u64.
    let frac = ntp64 & 0xffff_ffff;
    let sub = (frac * 1_000_000_000).div_ceil(1 << 32);
    secs * 1_000_000_000 + i128::from(sub)
}

/// §2.11's rate: `double(d) / (double(e) / 1e9)`, rounding to nearest.
#[must_use]
pub fn rate_per_s(d: u64, elapsed_ns: i128) -> f64 {
    d as f64 / (elapsed_ns as f64 / 1e9)
}

/// Judges a pair of conforming samples of one member, in arrival order
/// (§2.9–§2.11). `unit` is the counter's unit (§2.5), for the rate's. A
/// counter narrower than 64 bits is read in its serial window, and two
/// frame records are timed by their records (`telemetry.v2` §2.20,
/// §2.21).
#[must_use]
pub fn pair(
    earlier: &Sampled<'_>,
    later: &Sampled<'_>,
    unit: Option<&str>,
    presence: Option<&Presence<'_>>,
) -> Pair {
    let (ka, kb) = (earlier.value.kind(), later.value.kind());
    if !ka.is_cumulative() && !kb.is_cumulative() {
        return Pair {
            continuity: Continuity::NotAsked,
            basis: None,
            rate: Err(NoRate::Kind),
        };
    }
    let counters = ka == MetricKind::Counter && kb == MetricKind::Counter;
    let no_rate = |why: NoRate| -> Result<Rate, NoRate> {
        if counters {
            Err(why)
        } else {
            Err(NoRate::Kind)
        }
    };
    let Some(moved) = (ka == kb)
        .then(|| change(earlier.value, later.value))
        .flatten()
    else {
        // Incomparable (§2.10): two kinds, two counter widths (v2 §2.20),
        // or two histograms' bounds; no rate is asked of it (§2.11).
        return Pair {
            continuity: Continuity::Unobservable,
            basis: None,
            rate: Err(NoRate::Kind),
        };
    };
    let (continuity, basis) = match (epochs(earlier.epoch, later.epoch, presence), moved) {
        (Epochs::Same(via), Change::Down) => (Continuity::Decreased, Basis::Established(via)),
        (Epochs::Same(via), Change::Up(_)) => (Continuity::SameEpoch, Basis::Established(via)),
        (Epochs::Same(via), Change::Outside) => {
            // A wrap or a decrease within one epoch: the values cannot say
            // which (v2 §2.20).
            return Pair {
                continuity: Continuity::Unobservable,
                basis: Some(Basis::Established(via)),
                rate: Err(NoRate::WrapOrDecrease),
            };
        }
        (Epochs::Different(via), _) => (Continuity::Reset, Basis::Established(via)),
        (Epochs::Unobservable, Change::Down | Change::Outside) => {
            (Continuity::Reset, Basis::Assumed)
        }
        (Epochs::Unobservable, Change::Up(_)) => (Continuity::SameEpoch, Basis::Assumed),
    };
    let rate = match (continuity, moved) {
        (Continuity::Reset, _) => no_rate(NoRate::Reset),
        (Continuity::Decreased, _) => no_rate(NoRate::Decreased),
        (Continuity::SameEpoch, Change::Up(d)) if counters => {
            let (e, timed) = elapsed(earlier, later);
            if e <= 0 {
                Err(NoRate::Elapsed)
            } else {
                Ok(Rate {
                    per_s: rate_per_s(d, e),
                    unit: unit.map(|u| format!("{u}/s")),
                    elapsed_ns: e,
                    basis: timed,
                })
            }
        }
        _ => Err(NoRate::Kind),
    };
    Pair {
        continuity,
        basis: Some(basis),
        rate,
    }
}

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

    fn ann(pairs: &[(&str, Value)]) -> BTreeMap<String, Value> {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_owned(), v.clone()))
            .collect()
    }

    fn point() -> TypeView<'static> {
        TypeView::Json {
            name: POINT,
            schema: PUBLISHED[0],
            root: None,
        }
    }

    #[test]
    fn a_kind_on_a_counter_type_is_declared() {
        let root = json!({"type": "integer", "minimum": 0});
        let ty = TypeView::Json {
            name: "Counter",
            schema: "sha256:00",
            root: Some(&root),
        };
        let d = declaration(
            Kind::Stream,
            &ann(&[(KIND, json!("counter")), (UNIT, json!("By"))]),
            Some(&ty),
            None,
        );
        let Declaration::Declared(d) = d else {
            panic!("{d:?}")
        };
        assert_eq!(d.kind, Some(MetricKind::Counter));
        assert_eq!(d.unit.as_deref(), Some("By"));
        assert_eq!(d.carrier, Carrier::Bare);
    }

    #[test]
    fn a_point_needs_no_kind_and_is_known_by_its_id() {
        let d = declaration(Kind::Stream, &BTreeMap::new(), Some(&point()), None);
        assert_eq!(d.declared().map(|d| d.carrier), Some(Carrier::Point));
        let other = TypeView::Json {
            name: POINT,
            schema: "sha256:00",
            root: None,
        };
        assert_eq!(
            declaration(Kind::Stream, &BTreeMap::new(), Some(&other), None),
            Declaration::NotThisProfiles
        );
    }

    #[test]
    fn a_counter_is_read_exactly() {
        let d = declaration(
            Kind::Stream,
            &ann(&[(KIND, json!("counter"))]),
            Some(&TypeView::Json {
                name: "C",
                schema: "x",
                root: Some(&json!({"type": "integer"})),
            }),
            None,
        );
        let at = |v: Value| {
            let datum = Datum::from_json(&v);
            check(
                &d,
                &Payload::Decoded {
                    value: &datum,
                    attachment: None,
                },
            )
            .conformance
        };
        assert_eq!(at(json!(u64::MAX)), Conformance::Conforms);
        assert_eq!(
            at(json!(18_446_744_073_709_551_616.0)),
            Conformance::DoesNot(vec![Problem::OutOfRange])
        );
        assert_eq!(at(json!(5.0)), Conformance::Conforms);
        assert_eq!(
            at(json!(5.5)),
            Conformance::DoesNot(vec![Problem::WrongType])
        );
    }

    #[test]
    fn a_decrease_is_a_reset_unless_one_epoch_is_established() {
        let (a, b) = (Measure::counter(10), Measure::counter(3));
        let s = |v, e| Sampled {
            value: v,
            epoch: e,
            timestamp_ms: None,
            stamp_ns: None,
            arrival_ns: 0,
            record: None,
        };
        let p = pair(&s(&a, None), &s(&b, None), None, None);
        assert_eq!(
            (p.continuity, p.basis),
            (Continuity::Reset, Some(Basis::Assumed))
        );
        let p = pair(&s(&a, Some("e")), &s(&b, Some("e")), None, None);
        assert_eq!(p.continuity, Continuity::Decreased);
        assert_eq!(p.rate, Err(NoRate::Decreased));
    }

    #[test]
    fn the_rate_is_the_formula() {
        let (a, b) = (Measure::counter(0), Measure::counter(1_000));
        let s = |v, t| Sampled {
            value: v,
            epoch: None,
            timestamp_ms: Some(t),
            stamp_ns: None,
            arrival_ns: 0,
            record: None,
        };
        let p = pair(&s(&a, 0), &s(&b, 2_000), Some("By"), None);
        assert_eq!(
            p.rate,
            Ok(Rate {
                per_s: 500.0,
                unit: Some("By/s".into()),
                elapsed_ns: 2_000_000_000,
                basis: None,
            })
        );
    }

    #[test]
    fn a_root_follows_its_refs_across_files_with_outer_keywords_winning() {
        let art = |name: &str, doc: Value| Artifact {
            kind: crate::schema::SchemaKind::JsonSchema,
            name: name.to_owned(),
            data: ArtifactData::Json(doc),
        };
        let a = art(
            "a",
            json!({"$defs": {
                "Count": {"$ref": "#/$defs/Inner", "description": "outer"},
                "Inner": {"$ref": "b.json#/$defs/Base", "minimum": 1},
                "Loop": {"$ref": "#/$defs/Loop"},
            }}),
        );
        let b = art(
            "b",
            json!({"$defs": {"Base": {"type": "integer", "minimum": 0}}}),
        );
        let arts = BTreeMap::from([("sha256:a".to_owned(), a), ("sha256:b".to_owned(), b)]);
        assert_eq!(
            root_schema(&arts, "sha256:a", "Count"),
            Some(json!({"type": "integer", "minimum": 1, "description": "outer"}))
        );
        assert_eq!(root_schema(&arts, "sha256:a", "Loop"), None, "a loop ends");
        assert_eq!(root_schema(&arts, "sha256:a", "Missing"), None);
    }

    #[test]
    fn units_and_epochs_have_their_lengths() {
        assert!(is_unit("dBm") && is_unit("bit/s") && !is_unit("") && !is_unit("m s"));
        assert!(!is_unit(&"x".repeat(65)) && is_unit(&"x".repeat(64)));
        assert!(is_epoch(&"é".repeat(64)) && !is_epoch(&"é".repeat(65)) && !is_epoch(""));
    }
}