zenkey-model 0.23.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
//! A collection's snapshot (core §7.5's form 7, 0.97; #977's E1): one
//! `state` or `@state` resource's members, their values and tombstones, in
//! the pages of a GET's reply. An owner answers a state GET with one per
//! collection (core §4.2, #977's E3), and a reader merges its entries per
//! key ([`Page::members`]), holds its pages ([`hear`]), and applies the
//! omission rule over a complete one ([`omit`]), mapping its index with
//! the revision the owner's descriptor names ([`collection_at`]).
//!
//! ```text
//! page        CH · run · asof · body          a GET reply's payload, CH's tag the collection's type's
//! body        time · page · coll · live · tombs
//! time        t32 · ms16: when the owner built the snapshot
//! page        an integer: the page's index × 2, plus 1 when a later page follows
//! coll        an integer: the collection's index
//! live        an integer, their count · that many live entries
//! tombs       an integer, their count · that many tombstones
//! live entry  id · flags · [run] · seq · [conf] · length · record
//! tombstone   id · flags · [run] · seq
//! id          an integer, its length in bytes · that many bytes
//! flags       bit 7 own run · bits 6–5 confirmation · bit 4 run width · bits 3–0 zero
//! ```
//!
//! An integer is unsigned LEB128, at most 5 bytes and at most 2^32 − 1, in
//! its shortest form. The fixed fields are big-endian. An id is empty, or
//! plain chunks (§1.2) joined by `/`, below the reply's key.
//!
//! The envelope is [`crate::wire`]'s: a snapshot is a put's to the parser
//! ([`crate::wire::SampleKind::Put`]), its asof in the seq's place, its body
//! unread there. [`Page::parse`] reads a page's bytes, envelope and body,
//! and [`Page::read`] a body after its envelope; both refuse for the first
//! [`BodyRefusal`] that applies, reading the fields in order, as
//! `spec/conformance/snapshot/bodies.json` pins. [`Page::write`] writes
//! nothing that reading refuses, and every page accepted writes back to its
//! bytes. [`Snapshot::paginate`] cuts a snapshot into pages under a page
//! size, and [`Snapshot::complete`] assembles a complete set of pages.

use thiserror::Error;

use crate::chunk::is_plain_chunk;
use crate::contract::{Contract, Resource};
use crate::grammar::{KindToken, ZkKey, parse};
use crate::template::{Segment, Template};
use crate::wire::{self, Envelope, Form, Header, Run, Seq, Stamp, Tag};

/// The greatest integer the body holds: 2^32 − 1, in at most 5 bytes.
pub const INTEGER_MAX: u32 = u32::MAX;

/// A time, `t32 · ms16`: seconds and milliseconds since the deployment
/// epoch E (core §7.6), or unknown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Time {
    /// t32 all ones with ms16 0: the owner's clock is unknown.
    Unknown,
    /// t32 seconds and ms16 milliseconds since the deployment epoch. A
    /// writer refuses an ms16 above 999, and a t32 all ones, which reads as
    /// unknown with ms16 0 and is unused with any other (`time`).
    Known { s: u32, ms: u16 },
}

impl Time {
    /// The time of an instant `t`, in milliseconds since the Unix epoch,
    /// under the deployment epoch `epoch` in seconds: t32 = ⌊(t − 1000 ×
    /// E) / 1000⌋ and ms16 = (t − 1000 × E) modulo 1000. `None` before the
    /// epoch, and from t32 all ones on, which no known time takes.
    #[must_use]
    pub fn from_unix_ms(t: i128, epoch: i64) -> Option<Time> {
        // Unsigned, so `None` before the epoch.
        let since = u128::try_from(t - i128::from(epoch) * 1000).ok()?;
        let s = u32::try_from(since / 1000)
            .ok()
            .filter(|&s| s != u32::MAX)?;
        let ms = u16::try_from(since % 1000).ok()?;
        Some(Time::Known { s, ms })
    }

    /// The instant, in milliseconds since the Unix epoch, under the
    /// deployment epoch `epoch` in seconds; `None` when unknown.
    #[must_use]
    pub fn unix_ms(self, epoch: i64) -> Option<i128> {
        match self {
            Time::Unknown => None,
            Time::Known { s, ms } => {
                Some(i128::from(epoch) * 1000 + i128::from(s) * 1000 + i128::from(ms))
            }
        }
    }

    /// Its two fields, as a writer writes them, or `time` for one the
    /// reading would refuse or read as another.
    pub(crate) fn fields(self) -> Result<(u32, u16), BodyRefusal> {
        match self {
            Time::Unknown => Ok((u32::MAX, 0)),
            Time::Known { s, ms } if s != u32::MAX && ms <= 999 => Ok((s, ms)),
            Time::Known { .. } => Err(BodyRefusal::Time),
        }
    }

    /// The two fields read: unknown, known, or `time` for an unused ms16
    /// (above 999, or any but 0 with t32 all ones).
    pub(crate) fn of_fields(s: u32, ms: u16) -> Result<Time, BodyRefusal> {
        match (s, ms) {
            (u32::MAX, 0) => Ok(Time::Unknown),
            (u32::MAX, _) => Err(BodyRefusal::Time),
            (_, ms) if ms > 999 => Err(BodyRefusal::Time),
            (s, ms) => Ok(Time::Known { s, ms }),
        }
    }
}

/// When the owner last vouched for a live entry: the flags' bits 6–5.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Confirmation {
    /// 0: the collection has no horizon. A tombstone's is always 0.
    None,
    /// 1: the owner vouches for the member as it builds the snapshot, at
    /// the snapshot's time, as a heartbeat sent then would.
    AtTime,
    /// 2: the owner does not vouch for it now; `conf` follows, its last
    /// confirmation, the later of its last mutation and the last heartbeat
    /// that vouched for it. Unknown when the owner's clock was.
    At(Time),
}

impl Confirmation {
    /// Its code, 0, 1 or 2. 3 is unused.
    #[must_use]
    pub const fn code(self) -> u8 {
        match self {
            Confirmation::None => 0,
            Confirmation::AtTime => 1,
            Confirmation::At(_) => 2,
        }
    }
}

/// A live entry: a member whose last mutation as of asof is a put.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Entry {
    /// Below the reply's key: empty for the key itself, else plain chunks
    /// joined by `/`.
    pub id: String,
    /// Its own run, when its last mutation was under a run other than the
    /// header's; `None` for the header's.
    pub run: Option<Run>,
    /// The put's seq.
    pub seq: Seq,
    pub confirmation: Confirmation,
    /// The put's record, without its envelope; a packed record whole, its
    /// pad included.
    pub record: Vec<u8>,
}

/// A tombstone: a member the owner deleted within the window (S3).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Tombstone {
    /// As an [`Entry`]'s.
    pub id: String,
    /// As an [`Entry`]'s.
    pub run: Option<Run>,
    /// The delete's seq.
    pub seq: Seq,
}

/// One page of a snapshot: a GET reply's payload.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Page {
    /// CH's tag: the collection's type's, as a mutation's is.
    pub tag: Tag,
    /// The owner's run when it built the snapshot.
    pub run: Run,
    /// A seq of that run, in the seq's place: the snapshot reflects every
    /// state mutation of its run at or below it.
    pub asof: Seq,
    /// When the owner built the snapshot; no confirmation.
    pub time: Time,
    /// The page's index, from 0.
    pub index: u32,
    /// Whether a later page of the snapshot follows.
    pub more: bool,
    /// The collection's index among the interface's resources of the reply
    /// key's kind token, in the canonical form's order (§9.5).
    pub coll: u32,
    /// In the byte order of their ids.
    pub live: Vec<Entry>,
    /// In the byte order of their ids, none of them live.
    pub tombs: Vec<Tombstone>,
}

/// A snapshot: a page without its index and more bit, every entry of the
/// collection as of asof.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Snapshot {
    pub tag: Tag,
    pub run: Run,
    pub asof: Seq,
    pub time: Time,
    pub coll: u32,
    pub live: Vec<Entry>,
    pub tombs: Vec<Tombstone>,
}

/// Why a page's body is refused, by its reading or by a writer, which
/// writes nothing the reading refuses (core §7.5, "Reading a snapshot's
/// body"). The variants are in §7.5's order, the first that applies
/// reading the fields in order, and for one field the first in this
/// order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
pub enum BodyRefusal {
    /// The body ends before a byte a field needs, an integer's last byte
    /// included.
    #[error("the body ends before a byte a field needs")]
    Short,
    /// An integer whose fifth byte has its high bit set, one above 2^32 −
    /// 1, or one not in its shortest form.
    #[error("an integer that is not LEB128 in its shortest form, at most 2^32 − 1")]
    Leb128,
    /// A time or a conf whose ms16 is unused: above 999, or any but 0 with
    /// t32 all ones.
    #[error("a time whose ms16 is unused")]
    Time,
    /// An id that is neither empty nor plain chunks joined by `/`.
    #[error("an id that is neither empty nor plain chunks joined by /")]
    Id,
    /// An id not above the one before it in its list, or a tombstone's id
    /// that a live entry of the body has.
    #[error("an id out of order, or both live and a tombstone")]
    Order,
    /// A flags byte with a bit from 3 to 0 set, bit 4 without bit 7,
    /// confirmation 3, or a tombstone's confirmation other than 0.
    #[error("a flags byte this version leaves unused")]
    Flags,
    /// An entry's own run that is the header's, in width and value.
    #[error("an entry's own run is the header's")]
    Run,
    /// A byte after the last tombstone.
    #[error("bytes after the last tombstone")]
    Trailing,
}

impl BodyRefusal {
    /// The token `spec/conformance/snapshot/bodies.json` pins: `short`,
    /// `leb128`, `time`, `id`, `order`, `flags`, `run` or `trailing`.
    #[must_use]
    pub const fn token(self) -> &'static str {
        match self {
            BodyRefusal::Short => "short",
            BodyRefusal::Leb128 => "leb128",
            BodyRefusal::Time => "time",
            BodyRefusal::Id => "id",
            BodyRefusal::Order => "order",
            BodyRefusal::Flags => "flags",
            BodyRefusal::Run => "run",
            BodyRefusal::Trailing => "trailing",
        }
    }
}

/// Why a page's bytes are not read: its envelope refused by §7.5's parse
/// on a put, an envelope of another form, or its body refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum PageRefusal {
    #[error("its envelope is refused: {0}")]
    Envelope(wire::Refusal),
    #[error("its envelope is a {0}, not a snapshot")]
    NotSnapshot(Form),
    #[error("its body is refused: {0}")]
    Body(BodyRefusal),
}

const RUN_FOLLOWS: u8 = 0x80;
const CONFIRMATION_SHIFT: u8 = 5;
const WIDE_RUN: u8 = 0x10;
const UNUSED_FLAGS: u8 = 0x0f;

/// The bytes an integer takes in LEB128's shortest form: 1 to 5.
#[must_use]
pub const fn integer_bytes(v: u32) -> usize {
    match v {
        0..=0x7f => 1,
        0x80..=0x3fff => 2,
        0x4000..=0x1f_ffff => 3,
        0x20_0000..=0x0fff_ffff => 4,
        _ => 5,
    }
}

/// An integer's bytes in LEB128's shortest form, appended to `out`: the
/// one writer of a snapshot's integers and of an owner heartbeat's sizes
/// ([`crate::heartbeat::OwnerHeartbeat`]).
pub(crate) fn write_integer(out: &mut Vec<u8>, mut v: u32) {
    loop {
        let byte = (v & 0x7f) as u8;
        v >>= 7;
        if v == 0 {
            out.push(byte);
            return;
        }
        out.push(byte | 0x80);
    }
}

/// Why an integer does not read ([`read_integer`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IntegerRefusal {
    /// The bytes end before the integer's last byte.
    Short,
    /// Its fifth byte has its high bit set, it is above 2^32 − 1, or it is
    /// not in its shortest form.
    Leb128,
}

/// An integer read a byte at a time from `next`, which gives `None` where
/// the bytes end: unsigned LEB128, stopping at the fifth byte, whose high
/// bit set is `leb128` whatever follows it. The one reader of a snapshot's
/// integers and of an owner heartbeat's sizes, whose bytes fall on no byte
/// boundary ([`crate::heartbeat::OwnerHeartbeat::parse`]).
pub(crate) fn read_integer(mut next: impl FnMut() -> Option<u8>) -> Result<u32, IntegerRefusal> {
    let mut v: u64 = 0;
    for i in 0..5 {
        let b = next().ok_or(IntegerRefusal::Short)?;
        v |= u64::from(b & 0x7f) << (7 * i);
        if b & 0x80 == 0 {
            if b == 0 && i > 0 {
                return Err(IntegerRefusal::Leb128);
            }
            return u32::try_from(v).map_err(|_| IntegerRefusal::Leb128);
        }
    }
    Err(IntegerRefusal::Leb128)
}

/// A length as an integer, `leb128` above 2^32 − 1.
fn length(n: usize) -> Result<u32, BodyRefusal> {
    u32::try_from(n).map_err(|_| BodyRefusal::Leb128)
}

/// A length or a count as an integer for its size alone, 2^32 − 1 above
/// it: LEB128 takes 5 bytes there either way, and a writer refuses such a
/// length ([`length`]) before any size is relied on.
fn saturating(n: usize) -> u32 {
    u32::try_from(n).unwrap_or(u32::MAX)
}

/// Whether an id is empty, or plain chunks joined by `/`.
fn id_valid(id: &[u8]) -> bool {
    id.is_empty() || std::str::from_utf8(id).is_ok_and(|s| s.split('/').all(is_plain_chunk))
}

/// The flags byte of an entry: its own run, its confirmation's code.
fn flags(run: Option<Run>, confirmation: u8) -> u8 {
    let run_bits = match run {
        None => 0,
        Some(r) if r.is_wide() => RUN_FOLLOWS | WIDE_RUN,
        Some(_) => RUN_FOLLOWS,
    };
    run_bits | (confirmation << CONFIRMATION_SHIFT)
}

fn write_run(out: &mut Vec<u8>, run: Run) {
    match run {
        Run::U16(v) => out.extend_from_slice(&v.to_be_bytes()),
        Run::U32(v) => out.extend_from_slice(&v.to_be_bytes()),
    }
}

fn write_seq(out: &mut Vec<u8>, seq: Seq) {
    out.extend_from_slice(&seq.get().to_be_bytes()[1..]);
}

fn write_time(out: &mut Vec<u8>, (s, ms): (u32, u16)) {
    out.extend_from_slice(&s.to_be_bytes());
    out.extend_from_slice(&ms.to_be_bytes());
}

/// A writer's checks on an entry's id, as the reading makes them: `id`,
/// then `order` against `before`, the id before it in its list, and for a
/// tombstone against `live`, the body's live entries in order.
fn check_id(id: &str, before: Option<&str>, live: Option<&[Entry]>) -> Result<(), BodyRefusal> {
    if !id_valid(id.as_bytes()) {
        return Err(BodyRefusal::Id);
    }
    if before.is_some_and(|b| id.as_bytes() <= b.as_bytes()) {
        return Err(BodyRefusal::Order);
    }
    if live.is_some_and(|l| {
        l.binary_search_by(|e| e.id.as_bytes().cmp(id.as_bytes()))
            .is_ok()
    }) {
        return Err(BodyRefusal::Order);
    }
    Ok(())
}

fn check_run(own: Option<Run>, header: Run) -> Result<(), BodyRefusal> {
    if own == Some(header) {
        return Err(BodyRefusal::Run);
    }
    Ok(())
}

impl Entry {
    /// Its bytes in a body: id, flags, its own run, seq, conf, length and
    /// record.
    fn write_to(&self, out: &mut Vec<u8>) -> Result<(), BodyRefusal> {
        write_integer(out, length(self.id.len())?);
        out.extend_from_slice(self.id.as_bytes());
        out.push(flags(self.run, self.confirmation.code()));
        if let Some(r) = self.run {
            write_run(out, r);
        }
        write_seq(out, self.seq);
        if let Confirmation::At(t) = self.confirmation {
            write_time(out, t.fields()?);
        }
        write_integer(out, length(self.record.len())?);
        out.extend_from_slice(&self.record);
        Ok(())
    }

    /// Its bytes in a body, computed without writing it.
    fn size(&self) -> usize {
        integer_bytes(saturating(self.id.len()))
            + self.id.len()
            + 1
            + self.run.map_or(0, Run::width_bytes)
            + 3
            + 6 * usize::from(matches!(self.confirmation, Confirmation::At(_)))
            + integer_bytes(saturating(self.record.len()))
            + self.record.len()
    }
}

impl Tombstone {
    fn write_to(&self, out: &mut Vec<u8>) -> Result<(), BodyRefusal> {
        write_integer(out, length(self.id.len())?);
        out.extend_from_slice(self.id.as_bytes());
        out.push(flags(self.run, 0));
        if let Some(r) = self.run {
            write_run(out, r);
        }
        write_seq(out, self.seq);
        Ok(())
    }

    fn size(&self) -> usize {
        integer_bytes(saturating(self.id.len()))
            + self.id.len()
            + 1
            + self.run.map_or(0, Run::width_bytes)
            + 3
    }
}

/// A body's bytes, read a field at a time.
struct Reader<'a> {
    bytes: &'a [u8],
}

impl<'a> Reader<'a> {
    fn take(&mut self, n: usize) -> Result<&'a [u8], BodyRefusal> {
        if self.bytes.len() < n {
            return Err(BodyRefusal::Short);
        }
        let (head, rest) = self.bytes.split_at(n);
        self.bytes = rest;
        Ok(head)
    }

    fn byte(&mut self) -> Result<u8, BodyRefusal> {
        Ok(self.take(1)?[0])
    }

    /// An integer, by [`read_integer`] over the body's next bytes.
    fn integer(&mut self) -> Result<u32, BodyRefusal> {
        read_integer(|| self.byte().ok()).map_err(|e| match e {
            IntegerRefusal::Short => BodyRefusal::Short,
            IntegerRefusal::Leb128 => BodyRefusal::Leb128,
        })
    }

    fn time(&mut self) -> Result<Time, BodyRefusal> {
        let t = self.take(6)?;
        Time::of_fields(
            u32::from_be_bytes([t[0], t[1], t[2], t[3]]),
            u16::from_be_bytes([t[4], t[5]]),
        )
    }

    fn id(&mut self) -> Result<&'a [u8], BodyRefusal> {
        let n = self.integer()?;
        let id = self.take(n as usize)?;
        if !id_valid(id) {
            return Err(BodyRefusal::Id);
        }
        Ok(id)
    }

    /// An entry's flags, then its own run: `(run, confirmation)`.
    fn flags_and_run(
        &mut self,
        header: Run,
        tombstone: bool,
    ) -> Result<(Option<Run>, u8), BodyRefusal> {
        let f = self.byte()?;
        let confirmation = (f >> CONFIRMATION_SHIFT) & 0x03;
        let follows = f & RUN_FOLLOWS != 0;
        let wide = f & WIDE_RUN != 0;
        if f & UNUSED_FLAGS != 0
            || (wide && !follows)
            || confirmation == 3
            || (tombstone && confirmation != 0)
        {
            return Err(BodyRefusal::Flags);
        }
        let run = if !follows {
            None
        } else if wide {
            let r = self.take(4)?;
            Some(Run::U32(u32::from_be_bytes([r[0], r[1], r[2], r[3]])))
        } else {
            let r = self.take(2)?;
            Some(Run::U16(u16::from_be_bytes([r[0], r[1]])))
        };
        check_run(run, header)?;
        Ok((run, confirmation))
    }

    fn seq(&mut self) -> Result<Seq, BodyRefusal> {
        let s = self.take(3)?;
        Ok(Seq::new(u32::from_be_bytes([0, s[0], s[1], s[2]])).expect("24 bits"))
    }
}

/// An id read as text: [`Reader::id`] has checked it is ASCII.
fn id_text(id: &[u8]) -> String {
    std::str::from_utf8(id)
        .expect("plain chunks are ASCII")
        .to_owned()
}

impl Page {
    /// A page's bytes, CH to its last tombstone: the envelope by §7.5's
    /// parse on a put, which must be a snapshot's, then its body
    /// ([`Page::read`]). The key's kind is not read here:
    /// [`crate::wire::read_put`] refuses a snapshot off a state key.
    ///
    /// # Errors
    ///
    /// The envelope's refusal, a form other than a snapshot, or the
    /// body's first refusal.
    pub fn parse(bytes: &[u8]) -> Result<Page, PageRefusal> {
        let e = Envelope::parse(bytes).map_err(PageRefusal::Envelope)?;
        Page::read(&e)
    }

    /// A snapshot's envelope with its body read: the body's fields in
    /// order, with the header's run, refused for the first that applies
    /// (core §7.5, "Reading a snapshot's body").
    ///
    /// # Errors
    ///
    /// [`PageRefusal::NotSnapshot`] for an envelope of another form, and
    /// [`PageRefusal::Body`] with the first [`BodyRefusal`] that applies.
    pub fn read(envelope: &Envelope<'_>) -> Result<Page, PageRefusal> {
        if envelope.form != Form::Snapshot {
            return Err(PageRefusal::NotSnapshot(envelope.form));
        }
        Page::read_body(envelope.tag, envelope.stamp, envelope.record).map_err(PageRefusal::Body)
    }

    fn read_body(tag: Tag, stamp: Stamp, body: &[u8]) -> Result<Page, BodyRefusal> {
        let header = stamp.run;
        let mut r = Reader { bytes: body };
        let time = r.time()?;
        let page = r.integer()?;
        let coll = r.integer()?;
        let live_count = r.integer()?;
        // Never `with_capacity` from a count: it comes from the wire, up to
        // 2^32 − 1, and only the entries that follow it bound it. The
        // vectors grow with the entries read, so a short body is refused
        // before it holds more than its bytes.
        let mut live: Vec<Entry> = Vec::new();
        for _ in 0..live_count {
            let id = r.id()?;
            if live.last().is_some_and(|b| id <= b.id.as_bytes()) {
                return Err(BodyRefusal::Order);
            }
            let (run, c) = r.flags_and_run(header, false)?;
            let seq = r.seq()?;
            let confirmation = match c {
                0 => Confirmation::None,
                1 => Confirmation::AtTime,
                _ => Confirmation::At(r.time()?),
            };
            let n = r.integer()?;
            let record = r.take(n as usize)?.to_vec();
            live.push(Entry {
                id: id_text(id),
                run,
                seq,
                confirmation,
                record,
            });
        }
        let tomb_count = r.integer()?;
        let mut tombs: Vec<Tombstone> = Vec::new();
        for _ in 0..tomb_count {
            let id = r.id()?;
            if tombs.last().is_some_and(|b| id <= b.id.as_bytes())
                || live.binary_search_by(|e| e.id.as_bytes().cmp(id)).is_ok()
            {
                return Err(BodyRefusal::Order);
            }
            let (run, _) = r.flags_and_run(header, true)?;
            let seq = r.seq()?;
            tombs.push(Tombstone {
                id: id_text(id),
                run,
                seq,
            });
        }
        if !r.bytes.is_empty() {
            return Err(BodyRefusal::Trailing);
        }
        Ok(Page {
            tag,
            run: header,
            asof: stamp.seq,
            time,
            index: page >> 1,
            more: page & 1 == 1,
            coll,
            live,
            tombs,
        })
    }

    /// Its CH: a snapshot, the width the run takes, and its tag.
    #[must_use]
    pub const fn header(&self) -> Header {
        Header {
            form: Form::Snapshot,
            wide: self.run.is_wide(),
            tag: self.tag,
        }
    }

    /// The page's bytes, CH to its last tombstone, or the refusal its
    /// reading would give, the first in reading order: a writer writes no
    /// page the reading refuses (core §7.5).
    ///
    /// # Errors
    ///
    /// `time`, `id`, `order` or `run` for a field the reading would
    /// refuse, and `leb128` for an index, a count or a length above 2^32 −
    /// 1 as an integer.
    pub fn write(&self) -> Result<Vec<u8>, BodyRefusal> {
        let page = self
            .index
            .checked_mul(2)
            .and_then(|p| p.checked_add(u32::from(self.more)))
            .ok_or(BodyRefusal::Leb128)?;
        let mut out = Vec::with_capacity(self.size());
        out.push(self.header().byte());
        Stamp {
            run: self.run,
            seq: self.asof,
        }
        .write_to(&mut out);
        write_time(&mut out, self.time.fields()?);
        write_integer(&mut out, page);
        write_integer(&mut out, self.coll);
        write_integer(&mut out, length(self.live.len())?);
        let mut before: Option<&str> = None;
        for e in &self.live {
            check_id(&e.id, before, None)?;
            check_run(e.run, self.run)?;
            e.write_to(&mut out)?;
            before = Some(&e.id);
        }
        write_integer(&mut out, length(self.tombs.len())?);
        let mut before: Option<&str> = None;
        for t in &self.tombs {
            check_id(&t.id, before, Some(&self.live))?;
            check_run(t.run, self.run)?;
            t.write_to(&mut out)?;
            before = Some(&t.id);
        }
        Ok(out)
    }

    /// Its bytes' count, CH to its last tombstone, as [`Page::write`]
    /// writes them.
    #[must_use]
    pub fn size(&self) -> usize {
        page_size(
            self.run,
            self.index,
            self.coll,
            self.live.len(),
            self.live.iter().map(Entry::size).sum(),
            self.tombs.len(),
            self.tombs.iter().map(Tombstone::size).sum(),
        )
    }
}

/// A page's bytes: CH, the run, asof, the time, the page integer (whose
/// more bit never changes its size), coll, the two counts and the entries.
fn page_size(
    run: Run,
    index: u32,
    coll: u32,
    live: usize,
    live_bytes: usize,
    tombs: usize,
    tomb_bytes: usize,
) -> usize {
    1 + run.width_bytes()
        + 3
        + 6
        + integer_bytes(index.saturating_mul(2))
        + integer_bytes(coll)
        + integer_bytes(saturating(live))
        + live_bytes
        + integer_bytes(saturating(tombs))
        + tomb_bytes
}

/// One of a snapshot's entries, live or a tombstone, as the pages take
/// them: together, in the byte order of their ids.
#[derive(Clone, Copy)]
enum Item<'a> {
    Live(&'a Entry),
    Tomb(&'a Tombstone),
}

impl<'a> Item<'a> {
    fn id(self) -> &'a str {
        match self {
            Item::Live(e) => &e.id,
            Item::Tomb(t) => &t.id,
        }
    }
}

impl Snapshot {
    /// The snapshot as one page, index 0 and the last: what its pages
    /// write, checked whole.
    fn as_page(&self) -> Page {
        Page {
            tag: self.tag,
            run: self.run,
            asof: self.asof,
            time: self.time,
            index: 0,
            more: false,
            coll: self.coll,
            live: self.live.clone(),
            tombs: self.tombs.clone(),
        }
    }

    /// The snapshot cut into pages under a page size of `page_bytes`
    /// (core §7.5, "Pages"): its live entries and tombstones together, in
    /// the byte order of their ids, fill page 0, then page 1. A page takes
    /// the next entry when it holds none yet, or when its bytes with that
    /// entry, CH to its last tombstone, are within the page size. The last
    /// page's more bit is 0, and a snapshot with no entry is one page.
    ///
    /// # Errors
    ///
    /// The refusal [`Page::write`] gives the snapshot as one page: a
    /// writer cuts no snapshot it could not write.
    pub fn paginate(&self, page_bytes: usize) -> Result<Vec<Page>, BodyRefusal> {
        self.as_page().write()?;
        let mut items: Vec<Item<'_>> = self
            .live
            .iter()
            .map(Item::Live)
            .chain(self.tombs.iter().map(Item::Tomb))
            .collect();
        items.sort_by_key(|i| i.id().as_bytes());
        let empty = |index: u32| Page {
            tag: self.tag,
            run: self.run,
            asof: self.asof,
            time: self.time,
            index,
            more: false,
            coll: self.coll,
            live: Vec::new(),
            tombs: Vec::new(),
        };
        let mut pages = vec![empty(0)];
        let (mut live_bytes, mut tomb_bytes) = (0usize, 0usize);
        for item in items {
            let (dl, dt, size) = match item {
                Item::Live(e) => (1, 0, e.size()),
                Item::Tomb(t) => (0, 1, t.size()),
            };
            let page = pages.last().expect("a page");
            let held = page.live.len() + page.tombs.len();
            let with = page_size(
                self.run,
                page.index,
                self.coll,
                page.live.len() + dl,
                live_bytes + dl * size,
                page.tombs.len() + dt,
                tomb_bytes + dt * size,
            );
            if held > 0 && with > page_bytes {
                let index = page.index.checked_add(1).ok_or(BodyRefusal::Leb128)?;
                pages.last_mut().expect("a page").more = true;
                pages.push(empty(index));
                live_bytes = 0;
                tomb_bytes = 0;
            }
            let page = pages.last_mut().expect("a page");
            match item {
                Item::Live(e) => {
                    page.live.push(e.clone());
                    live_bytes += size;
                }
                Item::Tomb(t) => {
                    page.tombs.push(t.clone());
                    tomb_bytes += size;
                }
            }
        }
        Ok(pages)
    }

    /// The snapshot a complete set of pages holds (core §7.5,
    /// "Complete"): one page of each index from 0 to a page whose more bit
    /// is 0, all with one CH, run, asof, time and coll, in any order.
    /// `None` when they are not complete.
    #[must_use]
    pub fn complete(pages: &[Page]) -> Option<Snapshot> {
        let mut sorted: Vec<&Page> = pages.iter().collect();
        sorted.sort_by_key(|p| p.index);
        let first = sorted.first()?;
        let last = sorted.last()?;
        let same = |p: &Page| {
            (p.tag, p.run, p.asof, p.time, p.coll)
                == (first.tag, first.run, first.asof, first.time, first.coll)
        };
        let whole = sorted.iter().enumerate().all(|(i, p)| {
            u32::try_from(i).is_ok_and(|i| p.index == i)
                && p.more == (p.index != last.index)
                && same(p)
        });
        if !whole {
            return None;
        }
        Some(Snapshot {
            tag: first.tag,
            run: first.run,
            asof: first.asof,
            time: first.time,
            coll: first.coll,
            live: sorted.iter().flat_map(|p| p.live.iter().cloned()).collect(),
            tombs: sorted
                .iter()
                .flat_map(|p| p.tombs.iter().cloned())
                .collect(),
        })
    }
}

/// A member's key in a page heard on `key`: `key`, then `/` and the id;
/// `key` itself for the empty id (core §7.5).
#[must_use]
pub fn member_key(key: &str, id: &str) -> String {
    if id.is_empty() {
        key.to_owned()
    } else {
        format!("{key}/{id}")
    }
}

/// One entry of a page as the per-key reply it stands for (core §4.2's
/// "What a profile reads"): on its member's key,
/// with its stamp, a live entry the put of its record and a tombstone the
/// delete. A reader that reads per-key replies reads these the same way:
/// [`Member::payload`] is the bytes the mutation put, and
/// [`Member::attachment`] the delete's.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Member {
    /// The page's key, then `/` and the id ([`member_key`]).
    pub key: String,
    /// Its own run, else the page's, and its seq.
    pub stamp: Stamp,
    /// CH's tag: the page's, the collection's type's, as the mutation's.
    pub tag: Tag,
    /// A live entry's confirmation; a tombstone's is
    /// [`Confirmation::None`].
    pub confirmation: Confirmation,
    /// A live entry's record; `None` for a tombstone.
    pub record: Option<Vec<u8>>,
}

impl Member {
    /// Whether it is a tombstone: a delete within the window (S3).
    #[must_use]
    pub const fn is_tombstone(&self) -> bool {
        self.record.is_none()
    }

    /// A live entry's put, as the owner's per-key reply carries it:
    /// `CH · run · seq · record`, CH a mutation's with the page's tag and
    /// the width its run takes. `None` for a tombstone.
    #[must_use]
    pub fn payload(&self) -> Option<Vec<u8>> {
        let record = self.record.as_deref()?;
        Some(Envelope::mutation(self.tag, self.stamp, record).write())
    }

    /// A tombstone's delete, as the owner's `reply_del` carries it in its
    /// attachment: `CH · run · seq`. `None` for a live entry.
    #[must_use]
    pub fn attachment(&self) -> Option<Vec<u8>> {
        self.is_tombstone()
            .then(|| wire::DeleteStamp { stamp: self.stamp }.write())
    }
}

impl Page {
    /// Its entries as the per-key replies they stand for, live entries and
    /// tombstones together in the byte order of their ids, each on its
    /// member's key below `key`, the key the page was heard on.
    #[must_use]
    pub fn members(&self, key: &str) -> Vec<Member> {
        let stamp = |run: Option<Run>, seq| Stamp {
            run: run.unwrap_or(self.run),
            seq,
        };
        let mut out: Vec<Member> = self
            .live
            .iter()
            .map(|e| Member {
                key: member_key(key, &e.id),
                stamp: stamp(e.run, e.seq),
                tag: self.tag,
                confirmation: e.confirmation,
                record: Some(e.record.clone()),
            })
            .chain(self.tombs.iter().map(|t| Member {
                key: member_key(key, &t.id),
                stamp: stamp(t.run, t.seq),
                tag: self.tag,
                confirmation: Confirmation::None,
                record: None,
            }))
            .collect();
        out.sort_by(|a, b| a.key.as_bytes().cmp(b.key.as_bytes()));
        out
    }
}

/// One snapshot as a reader holds it, from the pages it heard (core §7.5,
/// "Complete"): the pages of one key, CH's tag, run, asof, time and coll,
/// and which indices it holds.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Heard {
    /// The key its pages were heard on: the snapshot key of a collection
    /// read, a member's key of a member read.
    pub key: String,
    pub tag: Tag,
    pub run: Run,
    pub asof: Seq,
    pub time: Time,
    pub coll: u32,
    /// The indices held, each once however often it was heard.
    pub pages: std::collections::BTreeSet<u32>,
    /// The indices held whose more bit is 0.
    pub last: std::collections::BTreeSet<u32>,
}

impl Heard {
    /// The snapshot `page`, heard on `key`, is a page of, holding none of
    /// its pages yet.
    #[must_use]
    pub fn of(key: &str, page: &Page) -> Heard {
        Heard {
            key: key.to_owned(),
            tag: page.tag,
            run: page.run,
            asof: page.asof,
            time: page.time,
            coll: page.coll,
            pages: std::collections::BTreeSet::new(),
            last: std::collections::BTreeSet::new(),
        }
    }

    /// Whether `page`, heard on `key`, is one of its pages: one key, CH's
    /// tag, run (its width included), asof, time and coll.
    #[must_use]
    pub fn holds(&self, key: &str, page: &Page) -> bool {
        self.key == key
            && (self.tag, self.run, self.asof, self.time, self.coll)
                == (page.tag, page.run, page.asof, page.time, page.coll)
    }

    /// Holds `page`, one of its pages; whether it held none of its index
    /// before.
    pub fn add(&mut self, page: &Page) -> bool {
        if !page.more {
            self.last.insert(page.index);
        }
        self.pages.insert(page.index)
    }

    /// Whether it is complete (core §7.5): one page of each index from 0
    /// to a page whose more bit is 0, and no other, so that it holds every
    /// entry the snapshot has.
    #[must_use]
    pub fn complete(&self) -> bool {
        let Some(&last) = self.last.first() else {
            return false;
        };
        self.last.len() == 1
            && self.pages.last() == Some(&last)
            && u64::try_from(self.pages.len()).is_ok_and(|n| n == u64::from(last) + 1)
    }
}

/// Adds `page`, heard on `key`, to the snapshot of `heard` it is a page of,
/// or to a new one at the end: one GET's snapshots, in the order of their
/// first page. Returns that snapshot's place, and whether this page made it
/// complete: complete now, and not before.
pub fn hear(heard: &mut Vec<Heard>, key: &str, page: &Page) -> (usize, bool) {
    let at = match heard.iter().position(|h| h.holds(key, page)) {
        Some(at) => at,
        None => {
            heard.push(Heard::of(key, page));
            heard.len() - 1
        }
    };
    let h = &mut heard[at];
    let was = h.complete();
    h.add(page);
    (at, !was && h.complete())
}

/// The collection's index of `resource`, a `state` or `@state` resource of
/// `contract`: its place, from 0, among the contract's resources of its
/// kind token, in the canonical form's order (core §7.5, §9.5), the order
/// [`Contract::resources`] keeps. `None` for any other kind, and for a
/// resource the contract does not hold.
#[must_use]
pub fn coll_of(contract: &Contract, resource: &Resource) -> Option<u32> {
    if !matches!(resource.token, KindToken::State | KindToken::ExplicitState) {
        return None;
    }
    let at = contract
        .resources
        .iter()
        .filter(|r| r.token == resource.token)
        .position(|r| r.template == resource.template)?;
    u32::try_from(at).ok()
}

/// The resource a snapshot's coll names, heard on a key whose kind token
/// is `kind` (`state` or `@state`): [`coll_of`]'s inverse. `None` when the
/// contract has no such collection, which a reader without the contract
/// cannot tell either (core §7.5, "Why no contract").
#[must_use]
pub fn collection_of(contract: &Contract, kind: KindToken, coll: u32) -> Option<&Resource> {
    if !matches!(kind, KindToken::State | KindToken::ExplicitState) {
        return None;
    }
    contract
        .resources
        .iter()
        .filter(|r| r.token == kind)
        .nth(usize::try_from(coll).ok()?)
}

/// A collection's snapshot key below its kind token (core §4.2,
/// "Answering a state GET"): its template's chunks before its
/// first parameter, the whole template when it has none. `None` for a
/// template whose first chunk is a parameter, which has no snapshot key.
#[must_use]
pub fn snapshot_prefix(template: &Template) -> Option<Vec<&str>> {
    let prefix: Vec<&str> = template
        .segments()
        .iter()
        .map_while(|s| match s {
            Segment::Literal(l) => Some(l.as_str()),
            Segment::Param(_) | Segment::Rest(_) => None,
        })
        .collect();
    (!prefix.is_empty()).then_some(prefix)
}

/// Whether `key` is a member's key of `resource`'s collection: a zk2 data
/// key of the resource's kind token whose resource chunks its template
/// matches, each parameter one chunk. A key with a namespace in front is
/// read from its first `zk2` chunk from which the grammar parses a data
/// key, as [`wire::enveloped_kind`] reads one. The address and interface
/// are not read: the caller asks of keys at or under one page's key.
#[must_use]
pub fn is_member(resource: &Resource, key: &str) -> bool {
    data_of(key).is_some_and(|(kind, chunks)| {
        let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
        kind == resource.token && resource.template.matches(&refs).is_some()
    })
}

/// Whether a resource of `token`, with resolved `annotations`, in a
/// revision whose `uses` lists the profiles `uses` says, is a **per-key
/// resource** (core §4.2, "A per-key resource"): a state §4.3's table
/// lists, read by a profile for the time its replies carry.
///
/// - a state that declares `freshness.ttl_s` above 0, of a revision that
///   does not use `freshness.v2`;
/// - a desired resource, its annotations holding `desired.target_param`,
///   of a revision that does not use `desired.v2` (core 0.112: a
///   `desired.v2` one is answered by snapshot, its version its in-band
///   stamp);
/// - a metric resource of `telemetry.v1` or `telemetry.v2` (a key of its
///   vocabulary), of a revision that uses one;
/// - every state of a revision that uses `redundancy.v1`; a state of one
///   that uses `redundancy.v2` is a collection like any other
///   (`redundancy.v2` §2.6, core 0.119).
///
/// Its owner answers each member a GET reaches with a reply of its own,
/// and one it deleted within the window with a `reply_del` (S2, S3). Every
/// other state is a collection its owner answers by snapshot.
#[must_use]
pub fn per_key_in(
    token: KindToken,
    annotations: &std::collections::BTreeMap<String, serde_json::Value>,
    uses: impl Fn(&str) -> bool,
) -> bool {
    use crate::authoring::Kind;
    if !matches!(token, KindToken::State | KindToken::ExplicitState) {
        return false;
    }
    let horizon = crate::freshness::horizon(Kind::State, annotations)
        .ttl()
        .is_some()
        && !uses(crate::freshness::PROFILE_V2);
    let desired = annotations.contains_key(crate::desired::TARGET_PARAM)
        && !uses(crate::desired::v2::PROFILE);
    let metric = (uses(crate::telemetry::PROFILE) || uses(crate::telemetry::PROFILE_V2))
        && crate::telemetry::VOCABULARY
            .iter()
            .any(|k| annotations.contains_key(&format!("telemetry.{k}")));
    let governed = uses(crate::redundancy::PROFILE);
    horizon || desired || metric || governed
}

/// [`per_key_in`] of `resource`, a resource of `contract`.
#[must_use]
pub fn per_key(contract: &Contract, resource: &Resource) -> bool {
    per_key_in(resource.token, &resource.annotations, |p| {
        contract.uses.iter().any(|u| u.to_string() == p)
    })
}

/// What a state GET's reader refuses a **stray `reply_del`** as
/// ([`stray_reply_del`]; #977's E4): its form, `form`, as a reader of
/// mutations refuses a snapshot's page. An owner answers a member of a
/// collection by snapshot, one it deleted within the window as a
/// tombstone, and sends a `reply_del` only for a per-key resource's member
/// (core S2, S3). So a `reply_del` on a collection's member is no owner's
/// answer: the reader counts it undecodable, and never merges it as a
/// deletion. The text names no reading for one; this is the reference's.
pub const STRAY_REPLY_DEL: wire::Refusal = wire::Refusal::Reserved(Form::Delete);

/// Whether a `reply_del` heard on `key`, a state GET's reply, is a stray
/// one, read with `contract`, the revision of the key's interface the
/// reader holds: `key` is a member's key of a state of `contract`, and no
/// state of `contract` it is a member of is a per-key resource
/// ([`per_key`]). Its reader refuses it as [`STRAY_REPLY_DEL`]. `false`
/// for a per-key resource's member, and for a key of another interface or
/// of no state of `contract`, which `contract` cannot judge. A key with a
/// namespace in front is read as [`is_member`] reads one.
#[must_use]
pub fn stray_reply_del(contract: &Contract, key: &str) -> bool {
    let Some(ZkKey::Data {
        iface,
        kind,
        resource,
        ..
    }) = data_key_of(key)
    else {
        return false;
    };
    if iface != contract.iface {
        return false;
    }
    let refs: Vec<&str> = resource.iter().map(String::as_str).collect();
    let mut of = contract
        .resources
        .iter()
        .filter(|r| r.token == kind && r.template.matches(&refs).is_some())
        .peekable();
    of.peek().is_some() && of.all(|r| !per_key(contract, r))
}

/// A state GET, as its owner answers it (core §4.2, "Answering a state
/// GET"), for the conditional read's rule ([`answers_held`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StateRead {
    /// A member read of one concrete key, on a collection the owner
    /// answers by snapshot: the one GET that can be a conditional read.
    Member,
    /// A member read whose selector is not one concrete key: it holds a
    /// `*`, a `**` or a `$*` chunk.
    Wildcard,
    /// A collection read: a selector that includes the snapshot key
    /// followed by `/**`.
    Collection,
    /// A read of a per-key resource ([`per_key`]), answered with a reply
    /// per key.
    PerKey,
}

impl StateRead {
    /// `member`, `wildcard`, `collection` or `per_key`, as
    /// `spec/conformance/envelope/held.json`'s `answers` spell it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            StateRead::Member => "member",
            StateRead::Wildcard => "wildcard",
            StateRead::Collection => "collection",
            StateRead::PerKey => "per_key",
        }
    }
}

/// An owner's answer to a conditional read (core 0.110 §4.2, "A
/// conditional read"): the held stamp it answers alone, or `None` where it
/// answers whole, as it answers a GET with no payload.
///
/// `Some` exactly when the GET is a member read of one concrete key
/// ([`StateRead::Member`]), its payload carries a held stamp that §7.5's
/// parse accepts ([`wire::read_get`], `encoding` the payload's), and the
/// member's last mutation, `last`, carries exactly that stamp: the same
/// run, in width and value, and the same seq. `last` is the stamp a
/// snapshot would list for the member: its last put's, or its delete's
/// within the window, `None` where the owner holds no member there. The
/// reply's payload is then the held stamp the GET carried
/// ([`wire::HeldStamp::write`]), on the member's key.
///
/// An owner MUST NOT answer a held stamp in any other case: another seq,
/// another run or the same run's value at the other width, no member held,
/// a payload §7.5 refuses (never refused, never left unanswered), and
/// every other kind of GET, whose held stamp is ignored. The run the owner
/// writes under now is not read.
#[must_use]
pub fn answers_held(
    read: StateRead,
    encoding: &str,
    payload: Option<&[u8]>,
    last: Option<wire::Stamp>,
) -> Option<wire::HeldStamp> {
    if read != StateRead::Member {
        return None;
    }
    answers_carried(read, wire::read_get(encoding, payload).ok().flatten(), last)
}

/// [`answers_held`] of a GET whose payload its owner already read
/// ([`wire::read_get`]): `carried` is the held stamp it carries, `None`
/// for no payload and for one §7.5 refuses. An owner that also keeps what
/// each GET carried parses the payload once.
#[must_use]
pub fn answers_carried(
    read: StateRead,
    carried: Option<wire::HeldStamp>,
    last: Option<wire::Stamp>,
) -> Option<wire::HeldStamp> {
    carried.filter(|held| read == StateRead::Member && last == Some(held.stamp))
}

/// The collection read of a GET on `selector`, a key expression over one
/// resource's members (core §4.2, "A collection read"): its snapshot key
/// followed by `/**`, where every parameter from its template's first on
/// is a wildcard, so the GET asks for the collection whole.
/// `None` for a selector that binds a parameter, which reads members, and
/// for a template whose first chunk is a parameter, which has no snapshot
/// key.
#[must_use]
pub fn collection_read(selector: &str, template: &Template) -> Option<String> {
    let prefix = snapshot_prefix(template)?;
    let n = template.segments().len();
    if n == prefix.len() {
        // No parameter: the member's key is the snapshot key, and its
        // member read is answered by snapshot already.
        return None;
    }
    let chunks: Vec<&str> = selector.split('/').collect();
    let tail = chunks.len().checked_sub(n - prefix.len())?;
    let head = tail.checked_sub(prefix.len())?;
    // Past the prefix, each parameter a wildcard and each literal itself.
    let rest = chunks[tail..]
        .iter()
        .zip(&template.segments()[prefix.len()..])
        .all(|(c, g)| match g {
            Segment::Literal(l) => c == l,
            Segment::Param(_) => *c == "*",
            Segment::Rest(_) => *c == "**",
        });
    (chunks[head..tail] == prefix[..] && rest).then(|| format!("{}/**", chunks[..tail].join("/")))
}

/// A zk2 data key's kind token and resource chunks, read from its first
/// `zk2` chunk from which the grammar parses a data key, a namespace in
/// front skipped (as [`is_member`] reads one).
fn data_of(key: &str) -> Option<(KindToken, Vec<String>)> {
    match data_key_of(key)? {
        ZkKey::Data { kind, resource, .. } => Some((kind, resource)),
        _ => None,
    }
}

/// [`data_of`]'s data key whole.
fn data_key_of(key: &str) -> Option<ZkKey> {
    let mut rest = Some(key);
    while let Some(k) = rest {
        if k.starts_with("zk2/")
            && let Ok(d @ ZkKey::Data { .. }) = parse(k)
        {
            return Some(d);
        }
        rest = k.split_once('/').map(|(_, r)| r);
    }
    None
}

/// The collection a snapshot heard on `key` with index `coll` is, read
/// with `contract`, the revision the owner's descriptor names (core §4.2,
/// "The owner's revision maps the index"; #977's E3, F-497): the state
/// resource of the reply key's kind token at `coll`, where `key` is its
/// snapshot key or one of its members' keys. `None` where the revision has
/// no such resource at the index, or has one of which `key` is neither:
/// the reader then applies no omission rule over the snapshot, and its
/// entries still merge on their keys.
#[must_use]
pub fn collection_at<'c>(contract: &'c Contract, key: &str, coll: u32) -> Option<&'c Resource> {
    let (kind, chunks) = data_of(key)?;
    let r = collection_of(contract, kind, coll)?;
    let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
    let at_snapshot_key = snapshot_prefix(&r.template).is_some_and(|p| p == refs);
    (at_snapshot_key || r.template.matches(&refs).is_some()).then_some(r)
}

/// The omission rule over a snapshot a reader holds complete in `pages`,
/// heard on `key`, read with `contract`, the revision the owner's
/// descriptor names (core §4.2; #977's E3): the keys of `held` it drops,
/// [`crate::seed::apply_snapshot`] over the collection
/// [`collection_at`] names. Nothing where the pages are not one complete
/// snapshot, or the index names no collection of `key`.
#[must_use]
pub fn omit<'a>(
    contract: &Contract,
    key: &str,
    pages: &[Page],
    held: impl IntoIterator<Item = crate::seed::HeldMember<'a>>,
) -> Vec<&'a str> {
    let Some(snapshot) = Snapshot::complete(pages) else {
        return Vec::new();
    };
    let Some(r) = collection_at(contract, key, snapshot.coll) else {
        return Vec::new();
    };
    crate::seed::apply_snapshot(&snapshot, key, |k| is_member(r, k), held)
}

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

    #[test]
    fn integers_round_trip_in_their_shortest_form() {
        for v in [
            0,
            1,
            127,
            128,
            16_383,
            16_384,
            0x0fff_ffff,
            0x1000_0000,
            u32::MAX,
        ] {
            let mut out = Vec::new();
            write_integer(&mut out, v);
            assert_eq!(out.len(), integer_bytes(v), "{v}");
            let mut r = Reader { bytes: &out };
            assert_eq!(r.integer(), Ok(v));
            assert!(r.bytes.is_empty());
        }
        let refused = |b: &[u8]| Reader { bytes: b }.integer();
        assert_eq!(refused(&[0x80, 0x00][..]), Err(BodyRefusal::Leb128));
        assert_eq!(
            refused(&[0xff, 0xff, 0xff, 0xff, 0x10][..]),
            Err(BodyRefusal::Leb128)
        );
        assert_eq!(
            refused(&[0x80, 0x80, 0x80, 0x80, 0x80][..]),
            Err(BodyRefusal::Leb128)
        );
        assert_eq!(
            refused(&[0x80, 0x80, 0x80, 0x80][..]),
            Err(BodyRefusal::Short)
        );
    }

    #[test]
    fn a_time_from_the_unix_clock() {
        let epoch = 1_767_225_600;
        let t = i128::from(epoch) * 1000 + 3_600_250;
        assert_eq!(
            Time::from_unix_ms(t, epoch),
            Some(Time::Known { s: 3600, ms: 250 })
        );
        assert_eq!(Time::Known { s: 3600, ms: 250 }.unix_ms(epoch), Some(t));
        assert_eq!(Time::from_unix_ms(t - 3_600_251, epoch), None);
        assert_eq!(Time::Unknown.unix_ms(epoch), None);
    }

    /// A page's entries are the per-key replies they stand for: a live
    /// entry the bytes its mutation put, which §7.5's parse reads back to
    /// its stamp and record, a tombstone a delete's attachment; an entry's
    /// own run beside the header's.
    #[test]
    fn a_pages_entries_are_their_members_replies() {
        let page = Page {
            tag: Tag::new(3).unwrap(),
            run: Run::U16(5),
            asof: Seq::new(9).unwrap(),
            time: Time::Unknown,
            index: 0,
            more: false,
            coll: 1,
            live: vec![
                Entry {
                    id: "a".into(),
                    run: Some(Run::U32(7)),
                    seq: Seq::new(2).unwrap(),
                    confirmation: Confirmation::AtTime,
                    record: b"r".to_vec(),
                },
                Entry {
                    id: "c".into(),
                    run: None,
                    seq: Seq::new(4).unwrap(),
                    confirmation: Confirmation::None,
                    record: Vec::new(),
                },
            ],
            tombs: vec![Tombstone {
                id: "b".into(),
                run: None,
                seq: Seq::new(3).unwrap(),
            }],
        };
        let m = page.members("zk2/h/s/i.v1/state/x");
        let keys: Vec<&str> = m.iter().map(|m| m.key.as_str()).collect();
        assert_eq!(
            keys,
            [
                "zk2/h/s/i.v1/state/x/a",
                "zk2/h/s/i.v1/state/x/b",
                "zk2/h/s/i.v1/state/x/c"
            ]
        );
        let bytes = m[0].payload().unwrap();
        let put = Envelope::parse(&bytes).unwrap();
        assert_eq!(
            (put.form, put.tag, put.record),
            (Form::Mutation, page.tag, &b"r"[..])
        );
        assert_eq!(put.stamp.run, Run::U32(7), "its own run");
        assert!(m[1].is_tombstone() && m[1].payload().is_none());
        let del = wire::DeleteStamp::parse(&m[1].attachment().unwrap()).unwrap();
        assert_eq!(
            del.stamp,
            Stamp {
                run: Run::U16(5),
                seq: Seq::new(3).unwrap()
            }
        );
        assert_eq!(m[2].attachment(), None);
        assert_eq!(member_key("k", ""), "k");
    }

    /// Pages are held by snapshot, and one is complete at one page of each
    /// index to a last, and no other: out of order, twice, a page lost, two
    /// last pages, or two times apart.
    #[test]
    fn a_snapshot_is_complete_at_every_index_to_its_last() {
        let page = |index, more| Page {
            tag: Tag::NONE,
            run: Run::U16(1),
            asof: Seq::new(9).unwrap(),
            time: Time::Known { s: 1, ms: 2 },
            index,
            more,
            coll: 0,
            live: Vec::new(),
            tombs: Vec::new(),
        };
        let mut heard = Vec::new();
        assert_eq!(hear(&mut heard, "k", &page(2, false)), (0, false));
        assert_eq!(hear(&mut heard, "k", &page(0, true)), (0, false));
        assert_eq!(hear(&mut heard, "k", &page(0, true)), (0, false), "twice");
        assert_eq!(
            hear(&mut heard, "k", &page(1, true)),
            (0, true),
            "complete now"
        );
        assert_eq!(
            hear(&mut heard, "k", &page(1, true)),
            (0, false),
            "and not newly"
        );
        assert!(heard[0].complete());
        let mut other = page(0, false);
        other.time = Time::Unknown;
        assert_eq!(
            hear(&mut heard, "k", &other),
            (1, true),
            "another time, another snapshot"
        );
        assert_eq!(
            hear(&mut heard, "j", &page(0, false)),
            (2, true),
            "another key"
        );
        let mut lost = Vec::new();
        hear(&mut lost, "k", &page(0, true));
        hear(&mut lost, "k", &page(2, false));
        assert!(!lost[0].complete(), "page 1 lost");
        let mut two = Vec::new();
        hear(&mut two, "k", &page(0, false));
        hear(&mut two, "k", &page(1, false));
        assert!(!two[0].complete(), "two last pages");
    }

    /// A collection's index is its place among its kind token's resources
    /// in canonical order; its snapshot key the template's chunks before its
    /// first parameter; and its members the keys its template matches.
    #[test]
    fn a_collections_index_snapshot_key_and_members() {
        let l = crate::contract::load_str(
            r#"[interface]
name = "c"
major = 1
minor = 0

[resources."b/{x}"]
kind = "state"
type = { raw = "text/plain" }
params = { x = "string" }
cardinality = 4

[resources.a]
kind = "state"
type = { raw = "text/plain" }

[resources."{y}/z"]
kind = "state"
explicit = true
type = { raw = "text/plain" }
params = { y = "string" }
cardinality = 4

[resources.s]
kind = "stream"
type = { raw = "text/plain" }
"#,
            std::path::Path::new("."),
            None,
        );
        let c = l.contract.unwrap_or_else(|| panic!("{}", l.report));
        let by = |t: &str| {
            c.resources
                .iter()
                .find(|r| r.template.as_str() == t)
                .unwrap()
        };
        assert_eq!(coll_of(&c, by("a")), Some(0));
        assert_eq!(coll_of(&c, by("b/{x}")), Some(1));
        assert_eq!(coll_of(&c, by("{y}/z")), Some(0), "@state counts apart");
        assert_eq!(coll_of(&c, by("s")), None, "a stream is no collection");
        let named = |k, i| collection_of(&c, k, i).map(|r| r.template.as_str());
        assert_eq!(named(KindToken::State, 1), Some("b/{x}"));
        assert_eq!(named(KindToken::ExplicitState, 0), Some("{y}/z"));
        assert_eq!(named(KindToken::State, 2), None);
        assert_eq!(named(KindToken::Stream, 0), None);
        assert_eq!(snapshot_prefix(&by("b/{x}").template), Some(vec!["b"]));
        assert_eq!(snapshot_prefix(&by("a").template), Some(vec!["a"]));
        assert_eq!(snapshot_prefix(&by("{y}/z").template), None);
        assert!(is_member(by("b/{x}"), "zk2/h/s/c.v1/state/b/one"));
        assert!(
            is_member(by("b/{x}"), "prod/zk2/h/s/c.v1/state/b/one"),
            "namespaced"
        );
        assert!(
            !is_member(by("b/{x}"), "zk2/h/s/c.v1/state/b"),
            "the snapshot key"
        );
        assert!(!is_member(by("b/{x}"), "zk2/h/s/c.v1/state/b/one/two"));
        assert!(
            !is_member(by("b/{x}"), "zk2/h/s/c.v1/@state/b/one"),
            "another kind"
        );
        assert!(is_member(by("a"), "zk2/h/s/c.v1/state/a"));
    }

    /// #977's E4: a `reply_del` is an owner's answer only on a per-key
    /// resource's member (core S2, S3): here `fresh`, whose horizon is
    /// `freshness.v1`'s, a state §4.3's table lists. On a member of a
    /// collection answered by snapshot it is stray; on a key the contract
    /// holds no state at, or another interface's, the contract cannot
    /// judge it.
    #[test]
    fn a_reply_del_answers_only_a_per_key_resources_member() {
        let l = crate::contract::load_str(
            r#"[interface]
name = "c"
major = 1
minor = 0
uses = ["freshness.v1"]

[resources."b/{x}"]
kind = "state"
type = { raw = "text/plain" }
params = { x = "string" }
cardinality = 4

[resources.fresh]
kind = "state"
type = { raw = "text/plain" }
annotations = { "freshness.ttl_s" = 60 }

[resources.s]
kind = "stream"
type = { raw = "text/plain" }
"#,
            std::path::Path::new("."),
            None,
        );
        let c = l.contract.unwrap_or_else(|| panic!("{}", l.report));
        let by = |t: &str| {
            c.resources
                .iter()
                .find(|r| r.template.as_str() == t)
                .unwrap()
        };
        assert!(per_key(&c, by("fresh")), "a freshness.v1 horizon");
        assert!(!per_key(&c, by("b/{x}")), "answered by snapshot");
        assert!(!per_key(&c, by("s")), "a stream is no state");
        assert!(stray_reply_del(&c, "zk2/h/s/c.v1/state/b/one"));
        assert!(
            stray_reply_del(&c, "prod/zk2/h/s/c.v1/state/b/one"),
            "namespaced"
        );
        assert!(!stray_reply_del(&c, "zk2/h/s/c.v1/state/fresh"));
        assert!(
            !stray_reply_del(&c, "zk2/h/s/c.v1/state/b"),
            "no member's key"
        );
        assert!(
            !stray_reply_del(&c, "zk2/h/s/d.v1/state/b/one"),
            "another interface"
        );
        assert_eq!(STRAY_REPLY_DEL.token(), "form");
    }

    #[test]
    fn an_empty_snapshot_is_one_sixteen_byte_page() {
        let s = Snapshot {
            tag: Tag::NONE,
            run: Run::U16(1),
            asof: Seq::new(9).unwrap(),
            time: Time::Known { s: 3600, ms: 250 },
            coll: 0,
            live: Vec::new(),
            tombs: Vec::new(),
        };
        let pages = s.paginate(1).unwrap();
        assert_eq!(pages.len(), 1);
        let bytes = pages[0].write().unwrap();
        assert_eq!(bytes.len(), 16);
        assert_eq!(pages[0].size(), 16);
        assert_eq!(Page::parse(&bytes).as_ref(), Ok(&pages[0]));
        assert_eq!(Snapshot::complete(&pages), Some(s));
    }

    #[test]
    fn a_selector_over_every_member_reads_the_collection_whole() {
        let t = crate::template::Template::parse("sdu/endpoint/{endpoint}").unwrap();
        assert_eq!(
            super::collection_read("zk2/h/rf0/modem.v3/state/sdu/endpoint/*", &t).as_deref(),
            Some("zk2/h/rf0/modem.v3/state/sdu/endpoint/**")
        );
        assert_eq!(
            super::collection_read("zk2/h/rf0/modem.v3/state/sdu/endpoint/a", &t),
            None
        );
        let lead = crate::template::Template::parse("{peer}/route").unwrap();
        assert_eq!(
            super::collection_read("zk2/h/s/i.v1/state/*/route", &lead),
            None
        );
        let one = crate::template::Template::parse("oper").unwrap();
        assert_eq!(
            super::collection_read("zk2/h/s/i.v1/state/oper", &one),
            None
        );
        let two = crate::template::Template::parse("a/{x}/b/{y}").unwrap();
        assert_eq!(
            super::collection_read("zk2/h/s/i.v1/state/a/X/b/*", &two),
            None
        );
        assert_eq!(
            super::collection_read("zk2/h/s/i.v1/state/a/*/b/*", &two).as_deref(),
            Some("zk2/h/s/i.v1/state/a/**")
        );
        // Another resource's selector of as many chunks reads nothing whole.
        assert_eq!(
            super::collection_read("zk2/h/s/i.v1/state/plans/*", &t),
            None
        );
    }
}