beekem 0.9.0

BeeKEM: a concurrent variant of TreeKEM for Continuous Group Key Agreement
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
//! CGKA operations and their causal graph.

use crate::{
    collections::{Map, Set},
    content_addressed_map::CaMap,
    encrypted::EncryptedSecret,
    error::CgkaError,
    id::{MemberId, TreeId},
    pcs_key::PcsKey,
    predecessors::Predecessors,
    transact::{Fork, Merge},
    tree::PathChange,
};
use alloc::{
    boxed::Box,
    collections::{BTreeSet, BinaryHeap},
    sync::Arc,
    vec::Vec,
};
use core::{
    hash::{Hash, Hasher},
    mem,
    ops::Deref,
};
use keyhive_codec::{
    error::DecodeError,
    prefixed::{decode_bytes, decode_list, encode_bytes, encode_list},
    traits::{decode_exact, Decode, Encode, StreamDecode},
};
use keyhive_crypto::{
    digest::Digest,
    share_key::ShareKey,
    signable::{Kind, Kinded},
    verified::Verified,
};
use nonempty::NonEmpty;

/// The identity of a membership citation cited by a [`CgkaOperation`].
///
/// BeeKEM treats it as opaque. Used by [`crate::cgka::ImplicitRemovesProtocol`].
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct CitationId(pub [u8; 32]);

/// The digest's 32 bytes.
impl Encode for CitationId {
    fn encode_into(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.0);
    }
}

impl Decode for CitationId {
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        decode_exact(bytes)
    }
}

impl StreamDecode for CitationId {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        let (digest, rest) = <[u8; 32]>::decode_next(bytes)?;
        Ok((CitationId(digest), rest))
    }
}

/// An ordered [`NonEmpty`] of [`CgkaOperation`]s that a replay applies
/// together.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct CgkaBatch(NonEmpty<Arc<Verified<CgkaOperation>>>);

impl From<NonEmpty<Arc<Verified<CgkaOperation>>>> for CgkaBatch {
    fn from(item: NonEmpty<Arc<Verified<CgkaOperation>>>) -> Self {
        CgkaBatch(item)
    }
}

impl Deref for CgkaBatch {
    type Target = NonEmpty<Arc<Verified<CgkaOperation>>>;

    fn deref(&self) -> &NonEmpty<Arc<Verified<CgkaOperation>>> {
        &self.0
    }
}

impl IntoIterator for CgkaBatch {
    type Item = Arc<Verified<CgkaOperation>>;
    type IntoIter = <NonEmpty<Arc<Verified<CgkaOperation>>> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

/// A root secret wrapped by an [`Invitation`].
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct InvitationSecret {
    /// The update operation that produced the secret in
    /// [`InvitationSecret::encrypted_root_secret`].
    pub update_op_hash: Digest<CgkaOperation>,

    /// The root secret, encrypted to the `pk` of the [`CgkaChange::Add`]
    /// wrapping this invitation.
    pub encrypted_root_secret: EncryptedSecret<PcsKey>,
}

/// `update_op_hash ‖ encrypted_root_secret`.
impl Encode for InvitationSecret {
    fn encode_into(&self, out: &mut Vec<u8>) {
        self.update_op_hash.encode_into(out);
        self.encrypted_root_secret.encode_into(out);
    }
}

impl Decode for InvitationSecret {
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        decode_exact(bytes)
    }
}

impl StreamDecode for InvitationSecret {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        let (update_op_hash, rest) = Digest::decode_next(bytes)?;
        let (encrypted_root_secret, rest) = EncryptedSecret::decode_next(rest)?;
        Ok((
            InvitationSecret {
                update_op_hash,
                encrypted_root_secret,
            },
            rest,
        ))
    }
}

/// When a member is added, it can't derive a root secret from the tree until the next
/// update. An invitation provides it the root secrets the inviter could reach at the
/// point it was added.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct Invitation {
    /// The inviter's share key corresponding to the secret key it used to encrypt
    /// each secret via Diffie-Hellman.
    pub inviter_pk: ShareKey,

    /// The root secrets the inviter could derive when it built this invitation,
    /// for this add's nearest update ancestors and for every chainable update
    /// whose root secret it had not yet decrypted from a later update.
    pub ancestor_secrets: Vec<InvitationSecret>,
}

/// `inviter_pk ‖ count:bijou32 ‖ ancestor_secrets`, in order.
impl Encode for Invitation {
    fn encode_into(&self, out: &mut Vec<u8>) {
        self.inviter_pk.encode_into(out);
        encode_list(&self.ancestor_secrets, out);
    }
}

impl Decode for Invitation {
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        decode_exact(bytes)
    }
}

impl StreamDecode for Invitation {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        let (inviter_pk, rest) = ShareKey::decode_next(bytes)?;
        let (ancestor_secrets, rest) = decode_list(rest)?;
        Ok((
            Invitation {
                inviter_pk,
                ancestor_secrets,
            },
            rest,
        ))
    }
}

/// An earlier update's root secret, wrapped by a later update.
///
/// A member added after an update cannot derive that update's root secret from the
/// tree, so each update encrypts earlier root secrets under a key derived from its
/// own. A member who can derive a later update's secret can then work back to the
/// earlier ones.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct PredecessorSecret {
    /// The update operation that produced the secret in
    /// [`PredecessorSecret::encrypted_root_secret`].
    pub update_op_hash: Digest<CgkaOperation>,

    /// The root secret, encrypted under a key derived from the root secret of the
    /// update that contains this entry.
    pub encrypted_root_secret: Vec<u8>,
}

/// `update_op_hash ‖ len:bijou32 ‖ encrypted_root_secret`.
impl Encode for PredecessorSecret {
    fn encode_into(&self, out: &mut Vec<u8>) {
        self.update_op_hash.encode_into(out);
        encode_bytes(&self.encrypted_root_secret, out);
    }
}

impl Decode for PredecessorSecret {
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        decode_exact(bytes)
    }
}

impl StreamDecode for PredecessorSecret {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        let (update_op_hash, rest) = Digest::decode_next(bytes)?;
        let (encrypted_root_secret, rest) = decode_bytes(rest)?;
        Ok((
            PredecessorSecret {
                update_op_hash,
                encrypted_root_secret: encrypted_root_secret.to_vec(),
            },
            rest,
        ))
    }
}

/// A member optionally listed in a [`CgkaChange::Remove`].
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct RemovedMember {
    /// The member removed.
    pub id: MemberId,
    /// The leaf the member occupied when the remove was created.
    pub leaf_idx: u32,
}

/// `id || leaf_idx:bijou32`, in order.
impl Encode for RemovedMember {
    fn encode_into(&self, out: &mut Vec<u8>) {
        self.id.encode_into(out);
        self.leaf_idx.encode_into(out);
    }
}

impl Decode for RemovedMember {
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        decode_exact(bytes)
    }
}

impl StreamDecode for RemovedMember {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        let (id, rest) = MemberId::decode_next(bytes)?;
        let (leaf_idx, rest) = u32::decode_next(rest)?;
        Ok((RemovedMember { id, leaf_idx }, rest))
    }
}

/// A change to a tree, with the tree it applies to and its causal
/// predecessors.
///
/// Who made it is not a field: it is the signer, in the signed envelope. For
/// an update, the leaf it rotates is the signer's.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct CgkaOperation {
    pub doc_id: TreeId,

    /// The zero or more immediate causal predecessors of this operation.
    pub predecessors: Predecessors,

    pub change: CgkaChange,
}

/// What a [`CgkaOperation`] changes.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub enum CgkaChange {
    Add {
        added_id: MemberId,
        pk: ShareKey,
        /// Root secrets from before this add, encrypted to `pk`, so the new member
        /// can read content written before it could derive anything from the tree.
        /// `None` when the adder had no root secrets to wrap, or no key pair of
        /// its own to wrap them with.
        invitation: Option<Box<Invitation>>,
        /// Evidence that the added member published `pk`, such as its signed
        /// prekey operation. BeeKEM does not read it. `None` when the
        /// authorization in use does not require it.
        key_proof: Option<Vec<u8>>,
        /// The membership citations for this add. An operation's citation set
        /// is everything its causal ancestors cited plus these.
        citations: BTreeSet<CitationId>,
    },
    Remove {
        /// The membership citations for this remove, as for an add.
        citations: BTreeSet<CitationId>,
        /// The members this operation removes from the tree. The set may be
        /// empty depending on whether the client specifies the members to remove
        /// or infers them from the citations.
        removed: BTreeSet<RemovedMember>,
    },
    Update {
        new_path: Box<PathChange>,
        /// The root secrets this update's author could derive for its nearest
        /// update ancestors and for every chainable update whose root secret it
        /// had not yet decrypted from a later update, each encrypted under a key
        /// derived from this update's root secret.
        predecessor_secrets: Vec<PredecessorSecret>,
    },
}

/// Signed as a `KH` frame of kind `C`, and identified by the digest of that
/// frame without its signature: who signed it and what it changes.
impl Kinded for CgkaOperation {
    const KIND: Kind = Kind::CGKA_OPERATION;
    const VERSION: u8 = 1;
}

/// An update cites nothing.
static NO_CITATIONS: BTreeSet<CitationId> = BTreeSet::new();

impl CgkaOperation {
    /// The zero or more immediate causal predecessors of this operation.
    pub fn predecessors(&self) -> &Predecessors {
        &self.predecessors
    }

    /// The membership citations for this operation. Empty for an update.
    pub fn citations(&self) -> &BTreeSet<CitationId> {
        match &self.change {
            CgkaChange::Add { citations, .. } | CgkaChange::Remove { citations, .. } => citations,
            CgkaChange::Update { .. } => &NO_CITATIONS,
        }
    }

    /// Whether this is an add or a remove.
    pub(crate) fn is_membership_change(&self) -> bool {
        !self.is_update()
    }

    /// Whether this is an update.
    pub fn is_update(&self) -> bool {
        matches!(self.change, CgkaChange::Update { .. })
    }

    /// Document/tree id.
    pub fn doc_id(&self) -> &TreeId {
        &self.doc_id
    }
}

/// `doc_id ‖ predecessors ‖ change`, the predecessors as a count and then
/// ascending.
impl Encode for CgkaOperation {
    fn encode_into(&self, out: &mut Vec<u8>) {
        self.doc_id.encode_into(out);
        self.predecessors.encode_into(out);
        self.change.encode_into(out);
    }
}

impl Decode for CgkaOperation {
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        decode_exact(bytes)
    }
}

impl StreamDecode for CgkaOperation {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        let (doc_id, rest) = TreeId::decode_next(bytes)?;
        let (predecessors, rest) = Predecessors::decode_next(rest)?;
        let (change, rest) = CgkaChange::decode_next(rest)?;
        Ok((
            CgkaOperation {
                doc_id,
                predecessors,
                change,
            },
            rest,
        ))
    }
}

/// A tag, `0` add, `1` remove or `2` update, then the variant's fields in
/// order. Sets are a count and then ascending; an `Option` is tag `0`, or tag
/// `1` and the value; `key_proof` is length-prefixed.
impl Encode for CgkaChange {
    fn encode_into(&self, out: &mut Vec<u8>) {
        match self {
            CgkaChange::Add {
                added_id,
                pk,
                invitation,
                key_proof,
                citations,
            } => {
                out.push(0);
                added_id.encode_into(out);
                pk.encode_into(out);
                match invitation {
                    None => out.push(0),
                    Some(invitation) => {
                        out.push(1);
                        invitation.encode_into(out);
                    }
                }
                match key_proof {
                    None => out.push(0),
                    Some(key_proof) => {
                        out.push(1);
                        encode_bytes(key_proof, out);
                    }
                }
                citations.encode_into(out);
            }
            CgkaChange::Remove { citations, removed } => {
                out.push(1);
                citations.encode_into(out);
                removed.encode_into(out);
            }
            CgkaChange::Update {
                new_path,
                predecessor_secrets,
            } => {
                out.push(2);
                new_path.encode_into(out);
                encode_list(predecessor_secrets, out);
            }
        }
    }
}

impl Decode for CgkaChange {
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        decode_exact(bytes)
    }
}

impl StreamDecode for CgkaChange {
    fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        match bytes.split_first() {
            None => Err(DecodeError::UnexpectedEnd),
            Some((0, rest)) => {
                let (added_id, rest) = MemberId::decode_next(rest)?;
                let (pk, rest) = ShareKey::decode_next(rest)?;
                let (invitation, rest) = Option::<Invitation>::decode_next(rest)?;
                let (key_proof, rest) = match rest.split_first() {
                    None => return Err(DecodeError::UnexpectedEnd),
                    Some((0, rest)) => (None, rest),
                    Some((1, rest)) => {
                        let (key_proof, rest) = decode_bytes(rest)?;
                        (Some(key_proof.to_vec()), rest)
                    }
                    Some((&tag, _)) => return Err(DecodeError::InvalidTag(tag)),
                };
                let (citations, rest) = BTreeSet::decode_next(rest)?;
                Ok((
                    CgkaChange::Add {
                        added_id,
                        pk,
                        invitation: invitation.map(Box::new),
                        key_proof,
                        citations,
                    },
                    rest,
                ))
            }
            Some((1, rest)) => {
                let (citations, rest) = BTreeSet::decode_next(rest)?;
                let (removed, rest) = BTreeSet::decode_next(rest)?;
                Ok((CgkaChange::Remove { citations, removed }, rest))
            }
            Some((2, rest)) => {
                let (new_path, rest) = PathChange::decode_next(rest)?;
                let (predecessor_secrets, rest) = decode_list(rest)?;
                Ok((
                    CgkaChange::Update {
                        new_path: Box::new(new_path),
                        predecessor_secrets,
                    },
                    rest,
                ))
            }
            Some((&tag, _)) => Err(DecodeError::InvalidTag(tag)),
        }
    }
}

/// Causal graph of [`CgkaOperation`]s.
///
/// Hashed by hand, with collection keys sorted, so the hash does not depend
/// on iteration order.
#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub struct CgkaOperationGraph {
    pub cgka_ops: CaMap<CgkaOperation>,

    pub cgka_op_heads: Set<Digest<CgkaOperation>>,

    /// The length of the longest chain of predecessors before each operation.
    /// An operation with no predecessors has depth 0.
    depths: Map<Digest<CgkaOperation>, u64>,

    /// The operations that have each operation as a predecessor.
    children: Map<Digest<CgkaOperation>, Set<Digest<CgkaOperation>>>,

    /// The latest update on each branch. These are updates that no later update
    /// has as a nearest update ancestor yet. Every other update is chainable,
    /// meaning a later update could have wrapped its root secret.
    latest_updates: Set<Digest<CgkaOperation>>,

    /// Every citation cited by an operation in the graph.
    citations: BTreeSet<CitationId>,
}

impl Hash for CgkaOperationGraph {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.cgka_ops.hash(state);

        // Hash heads deterministically
        self.cgka_op_heads
            .iter()
            .collect::<BTreeSet<_>>()
            .hash(state);

        // `depths`, `children`, `latest_updates` and `citations` are derived
        // from the operations hashed above.
    }
}

impl Fork for CgkaOperationGraph {
    type Forked = Self;

    fn fork(&self) -> Self::Forked {
        self.clone()
    }
}

impl Merge for CgkaOperationGraph {
    fn merge(&mut self, fork: Self::Forked) {
        // An update is still the latest on its branch if the other side lacks
        // it or also records it as latest.
        self.latest_updates.retain(|update| {
            !fork.cgka_ops.contains_key(update) || fork.latest_updates.contains(update)
        });
        self.latest_updates.extend(
            fork.latest_updates
                .iter()
                .filter(|update| !self.cgka_ops.contains_key(update))
                .copied(),
        );
        self.cgka_ops.merge(fork.cgka_ops);
        self.cgka_op_heads.extend(fork.cgka_op_heads);
        let ops = &self.cgka_ops;
        self.cgka_op_heads.retain(|head| {
            !ops.values()
                .any(|op| op.payload().predecessors.contains(head))
        });
        self.depths.extend(fork.depths);
        for (parent, children) in fork.children {
            self.children.entry(parent).or_default().extend(children);
        }
        self.citations.extend(fork.citations);
    }
}

impl CgkaOperationGraph {
    pub fn new() -> Self {
        Self {
            cgka_ops: CaMap::new(),
            cgka_op_heads: Set::new(),
            depths: Map::new(),
            children: Map::new(),
            latest_updates: Set::new(),
            citations: BTreeSet::new(),
        }
    }

    /// Every citation cited by an operation in the graph.
    pub fn citations(&self) -> &BTreeSet<CitationId> {
        &self.citations
    }

    pub fn contains_op_hash(&self, op_hash: &Digest<CgkaOperation>) -> bool {
        self.cgka_ops.contains_key(op_hash)
    }

    /// Whether `op_hash` is an update that some later update has as a nearest
    /// update ancestor.
    pub(crate) fn is_chainable(&self, op_hash: &Digest<CgkaOperation>) -> bool {
        self.cgka_ops
            .get(op_hash)
            .is_some_and(|op| op.payload().is_update())
            && !self.latest_updates.contains(op_hash)
    }

    /// The share key at the root of the update `op_hash`'s path.
    ///
    /// Returns `None` if we do not have the operation, it is not an update, or
    /// its path is empty.
    pub(crate) fn update_root_share_key(
        &self,
        op_hash: &Digest<CgkaOperation>,
    ) -> Option<ShareKey> {
        let CgkaChange::Update { new_path, .. } = &self.cgka_ops.get(op_hash)?.payload().change
        else {
            return None;
        };
        let (_, root_node) = new_path.path.last()?;
        Some(root_node.pk)
    }

    /// Whether every one of `op_hashes` is in the graph.
    pub fn contains_all<'a>(
        &self,
        op_hashes: impl IntoIterator<Item = &'a Digest<CgkaOperation>>,
    ) -> bool {
        op_hashes
            .into_iter()
            .all(|hash| self.cgka_ops.contains_key(hash))
    }

    /// Whether the causal graph has a single head.
    pub fn has_single_head(&self) -> bool {
        self.cgka_op_heads.len() == 1
    }

    /// Check that `op` can be added to the graph.
    ///
    /// Returns [`CgkaError::InvalidOperation`] if `op` has no
    /// predecessors and is not an add, and [`CgkaError::OutOfOrderOperation`] if
    /// one of its predecessors is not in the graph.
    pub(crate) fn check_can_add(&self, op: &CgkaOperation) -> Result<(), CgkaError> {
        let predecessors = op.predecessors();
        if predecessors.is_empty() && !matches!(op.change, CgkaChange::Add { .. }) {
            return Err(CgkaError::InvalidOperation);
        }
        if !self.contains_all(predecessors) {
            return Err(CgkaError::OutOfOrderOperation);
        }
        Ok(())
    }

    /// Add an operation to the graph, returning the updates it made chainable
    /// for the first time.
    ///
    /// Does nothing if the operation is already in the graph. Returns an
    /// error if it cannot be added or a predecessor has no recorded depth.
    pub fn add_op(
        &mut self,
        op: &Verified<CgkaOperation>,
    ) -> Result<Set<Digest<CgkaOperation>>, CgkaError> {
        let op_hash = op.digest();
        if self.cgka_ops.contains_key(&op_hash) {
            return Ok(Set::new());
        }
        self.check_can_add(op.payload())?;
        let op_predecessors = &op.payload().predecessors;
        let mut depth = 0;
        for pred in op_predecessors {
            depth = depth.max(self.depth(pred)? + 1);
        }
        self.cgka_ops.insert(op.clone().into());
        for pred in op_predecessors {
            self.cgka_op_heads.remove(pred);
            self.children.entry(*pred).or_default().insert(op_hash);
        }
        self.cgka_op_heads.insert(op_hash);
        self.depths.insert(op_hash, depth);
        self.citations
            .extend(op.payload().citations().iter().copied());
        if !op.payload().is_update() {
            return Ok(Set::new());
        }
        let newly_chainable = self
            .nearest_update_ancestors(op.payload().predecessors())
            .into_iter()
            .filter(|update| self.latest_updates.remove(update))
            .collect();
        self.latest_updates.insert(op_hash);
        Ok(newly_chainable)
    }

    /// Whether a replay would put an operation with `predecessors` in the same
    /// batch as an operation for which `matches` is true. `predecessors` must
    /// all be in the graph and must not be empty. An operation without
    /// predecessors is an add, which a caller checks for itself.
    ///
    /// Returns [`CgkaError::OperationNotFound`] if an operation it reaches is not
    /// in the graph, and [`CgkaError::DepthNotFound`] if one has no recorded depth.
    pub(crate) fn batch_has(
        &self,
        predecessors: &Predecessors,
        matches: impl Fn(&Digest<CgkaOperation>, &CgkaOperation) -> bool,
    ) -> Result<bool, CgkaError> {
        if predecessors.contains_heads_of(self) {
            // Every operation in the graph is a head or an ancestor of one. A
            // successor of every head is deeper than all of them and would be
            // in its own batch.
            return Ok(false);
        }
        let mut seen = Set::new();
        let mut frontier = BinaryHeap::new();
        for hash in predecessors.iter().chain(&self.cgka_op_heads) {
            if seen.insert(*hash) {
                frontier.push((self.depth(hash)?, *hash));
            }
        }
        while let Some((_, hash)) = frontier.pop() {
            // If there's only one operation left, it must be from the
            // preceding boundary batch and not the batch we're exploring.
            if frontier.is_empty() {
                break;
            }
            let op = self
                .cgka_ops
                .get(&hash)
                .ok_or(CgkaError::OperationNotFound)?;
            if matches(&hash, op.payload()) {
                return Ok(true);
            }
            for pred in &op.payload().predecessors {
                if seen.insert(*pred) {
                    frontier.push((self.depth(pred)?, *pred));
                }
            }
        }
        Ok(false)
    }

    /// The nearest [`CgkaChange::Update`] operations at or before the provided
    /// heads, skipping operations of other kinds.
    pub(crate) fn nearest_update_ancestors<'a>(
        &self,
        heads: impl IntoIterator<Item = &'a Digest<CgkaOperation>>,
    ) -> Set<Digest<CgkaOperation>> {
        let mut updates = Set::new();
        let mut seen = Set::new();
        let mut frontier = Vec::from_iter(heads.into_iter().copied());
        while let Some(op_hash) = frontier.pop() {
            if !seen.insert(op_hash) {
                continue;
            }
            let Some(op) = self.cgka_ops.get(&op_hash) else {
                continue;
            };
            if op.payload().is_update() {
                updates.insert(op_hash);
                continue;
            }
            if let Some(predecessors) = self.predecessors_for(&op_hash) {
                frontier.extend(predecessors.iter().copied());
            }
        }
        updates
    }

    /// Whether a [`CgkaChange::Add`] of `member` is in the
    /// causal past of `op_hash`, counting `op_hash` itself.
    pub(crate) fn has_add_before(&self, member: MemberId, op_hash: Digest<CgkaOperation>) -> bool {
        let mut seen = Set::new();
        let mut frontier = Vec::from_iter([op_hash]);
        while let Some(current) = frontier.pop() {
            if !seen.insert(current) {
                continue;
            }
            let Some(op) = self.cgka_ops.get(&current) else {
                continue;
            };
            if matches!(
                op.payload().change,
                CgkaChange::Add { added_id, .. }
                    if added_id == member
            ) {
                return true;
            }
            frontier.extend(op.payload().predecessors.iter().copied());
        }
        false
    }

    pub fn predecessors_for(&self, op_hash: &Digest<CgkaOperation>) -> Option<&Predecessors> {
        self.cgka_ops
            .get(op_hash)
            .map(|op| &op.payload().predecessors)
    }

    /// Sort all operations in the graph into batches.
    pub fn batches(&self) -> Result<NonEmpty<CgkaBatch>, CgkaError> {
        self.batches_for_heads(&self.cgka_op_heads)
    }

    /// Sort `heads` and all their ancestors into batches.
    ///
    /// Operations are ordered by depth (and by digest if depth is equal). This
    /// is a causal order since an operation is always deeper than each of its
    /// predecessors.
    ///
    /// A batch is formed in two cases:
    /// 1. Boundary (singleton) batch: a single operation `x` is the only operation at
    ///    its depth, every shallower operation is its ancestor, and none of those
    ///    ancestors has a descendant deeper than `x` through a chain that excludes `x`.
    /// 2. Concurrency batch: all operations between consecutive boundary batches, before
    ///    the first, or after the last (or all operations, if there is no boundary batch).
    ///
    /// A batch contains every operation concurrent with any operation in it (though
    /// two operations in one batch may be causally ordered).
    ///
    /// Returns [`CgkaError::OperationNotFound`] if one of `heads` or their
    /// ancestors is not in the graph. Returns [`CgkaError::NotInitialized`]
    /// if `heads` is empty.
    pub fn batches_for_heads(
        &self,
        heads: &Set<Digest<CgkaOperation>>,
    ) -> Result<NonEmpty<CgkaBatch>, CgkaError> {
        let mut deepest_child: Map<Digest<CgkaOperation>, u64> = Map::new();
        let mut seen = heads.clone();
        let mut frontier = Vec::from_iter(heads.iter().copied());
        let mut ordered = Vec::with_capacity(heads.len());
        // Traverse back from heads, recording each operation's depth and the depth
        // of its deepest child.
        while let Some(op_hash) = frontier.pop() {
            let depth = self.depth(&op_hash)?;
            ordered.push((depth, op_hash));
            let preds = self
                .predecessors_for(&op_hash)
                .ok_or(CgkaError::OperationNotFound)?;
            for pred in preds {
                let deepest = deepest_child.entry(*pred).or_insert(depth);
                *deepest = (*deepest).max(depth);
                if seen.insert(*pred) {
                    frontier.push(*pred);
                }
            }
        }
        ordered.sort_unstable();

        let mut batches: Vec<CgkaBatch> = Vec::new();
        let mut batch = Vec::new();
        // The shallowest depth at which the next boundary batch could occur. This is the
        // greatest depth of any child of an operation in a shallower layer.
        let mut earliest_next_boundary = 0;
        // A layer is all the operations at one depth. They are concurrent with each
        // other since an operation is deeper than each of its ancestors.
        for layer in ordered.chunk_by(|a, b| a.0 == b.0) {
            let depth = layer[0].0;
            // A chain of operations that starts no deeper than a putative boundary operation
            // `x`, doesn't include `x`, and can't be extended further either
            //   1. ends at a shallower depth than `x` (its last operation is a head, which we
            //      treat as having a child of depth `u64::MAX`),
            //   2. includes an operation at the same depth as `x`, or
            //   3. contains an operation whose child skips past `x`.
            // In any of these cases, `x` is not a boundary operation. In case 2,
            // `layer.len() > 1`. In cases 1 and 3, `earliest_next_boundary > depth`.
            let is_boundary = layer.len() == 1 && earliest_next_boundary <= depth;
            if is_boundary {
                batches.extend(NonEmpty::from_vec(mem::take(&mut batch)).map(Into::into));
            }
            for (_, op_hash) in layer {
                batch.push(
                    self.cgka_ops
                        .get(op_hash)
                        .ok_or(CgkaError::OperationNotFound)?
                        .clone(),
                );
                let deepest = match deepest_child.get(op_hash) {
                    Some(depth) => *depth,
                    // This must be a head (it has no children among the sorted operations),
                    // which means every deeper operation is concurrent with it and can't be
                    // a boundary.
                    None => u64::MAX,
                };
                earliest_next_boundary = earliest_next_boundary.max(deepest);
            }
            if is_boundary {
                batches.extend(NonEmpty::from_vec(mem::take(&mut batch)).map(Into::into));
            }
        }
        batches.extend(NonEmpty::from_vec(batch).map(Into::into));

        NonEmpty::from_vec(batches).ok_or(CgkaError::NotInitialized)
    }

    /// The operations that list `op_hash` as a predecessor.
    pub(crate) fn children_of(
        &self,
        op_hash: &Digest<CgkaOperation>,
    ) -> impl Iterator<Item = &Digest<CgkaOperation>> {
        self.children.get(op_hash).into_iter().flatten()
    }

    /// The length of the longest chain of predecessors before `op_hash`. An
    /// operation with no predecessors has depth 0. Returns
    /// [`CgkaError::OperationNotFound`] if it is not in the graph and
    /// [`CgkaError::DepthNotFound`] if it has no recorded depth.
    pub(crate) fn depth(&self, op_hash: &Digest<CgkaOperation>) -> Result<u64, CgkaError> {
        match self.depths.get(op_hash) {
            Some(depth) => Ok(*depth),
            None if self.cgka_ops.contains_key(op_hash) => Err(CgkaError::DepthNotFound),
            None => Err(CgkaError::OperationNotFound),
        }
    }
}

#[cfg(test)]
mod causal_graph_tests {
    use super::*;
    use alloc::{collections::BTreeMap, vec};
    use future_form::Local;
    use keyhive_crypto::{
        share_key::ShareSecretKey, signer::memory::MemorySigner, verified::Verified,
    };

    fn member_id() -> MemberId {
        member_id_from(&mut rand::thread_rng())
    }

    fn member_id_from<R: rand::CryptoRng + rand::RngCore>(rng: &mut R) -> MemberId {
        MemberId::from(&MemorySigner::generate(rng).0)
    }

    async fn signed_add(
        signer: &MemorySigner,
        doc_id: TreeId,
        predecessors: &[&Verified<CgkaOperation>],
    ) -> Verified<CgkaOperation> {
        signed_add_from(&mut rand::thread_rng(), signer, doc_id, predecessors).await
    }

    /// An add of a new member, with its member and key drawn from `rng`.
    async fn signed_add_from<R: rand::CryptoRng + rand::RngCore>(
        rng: &mut R,
        signer: &MemorySigner,
        doc_id: TreeId,
        predecessors: &[&Verified<CgkaOperation>],
    ) -> Verified<CgkaOperation> {
        let added_id = member_id_from(rng);
        signed_add_of(rng, signer, doc_id, added_id, predecessors).await
    }

    async fn signed_add_of<R: rand::CryptoRng + rand::RngCore>(
        rng: &mut R,
        signer: &MemorySigner,
        doc_id: TreeId,
        added_id: MemberId,
        predecessors: &[&Verified<CgkaOperation>],
    ) -> Verified<CgkaOperation> {
        let op = CgkaOperation {
            doc_id,
            predecessors: predecessors.iter().map(|op| op.digest()).collect(),
            change: CgkaChange::Add {
                added_id,
                pk: ShareSecretKey::generate(rng).share_key(),
                invitation: None,
                key_proof: None,
                citations: BTreeSet::new(),
            },
        };
        Verified::sign::<Local, _>(&op, signer)
            .await
            .expect("signing succeeds")
    }

    fn hash_of(graph: &CgkaOperationGraph) -> u64 {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        graph.hash(&mut hasher);
        hasher.finish()
    }

    #[tokio::test]
    async fn merging_a_fork_keeps_the_operations_it_added() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut trunk = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        trunk.add_op(&root).expect("a root has no predecessors");

        let mut forked = trunk.fork();
        let on_fork = signed_add(&signer, doc_id, &[&root]).await;
        let on_fork_hash = on_fork.digest();
        forked
            .add_op(&on_fork)
            .expect("the predecessor is in the graph");

        trunk.merge(forked);

        assert!(
            trunk.contains_op_hash(&on_fork_hash),
            "an operation added on the fork is missing after the merge"
        );
        assert_eq!(
            trunk.predecessors_for(&on_fork_hash),
            Some(&Predecessors::from([root.digest()])),
            "the merged operation lost its predecessors"
        );
        assert_eq!(
            trunk.cgka_op_heads,
            Set::from_iter([on_fork_hash]),
            "the merged operation should be the only head"
        );
        trunk
            .add_op(&signed_add(&signer, doc_id, &[&on_fork]).await)
            .expect("the merged operation's depth is in the graph");
    }

    #[tokio::test]
    async fn a_root_nothing_depends_on_shares_the_first_batch() {
        // root  lone_root
        //  |
        // after_root
        let ops: &[(&str, &[&str])] =
            &[("root", &[]), ("after_root", &["root"]), ("lone_root", &[])];
        assert_eq!(
            batches_of(ops).await,
            vec![BTreeSet::from(["root", "after_root", "lone_root"])]
        );
    }

    #[tokio::test]
    async fn graphs_holding_different_operations_hash_differently() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut one = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        one.add_op(&root).expect("a root has no predecessors");
        let mut two = one.fork();

        assert_eq!(hash_of(&one), hash_of(&two), "equal graphs should agree");

        two.add_op(&signed_add(&signer, doc_id, &[&root]).await)
            .expect("the predecessor is in the graph");

        assert_ne!(
            hash_of(&one),
            hash_of(&two),
            "a graph with an extra operation hashed the same as one without it"
        );
    }

    /// Builds a graph from `(name, predecessors)` pairs listed in causal
    /// order and returns its batches as sets of names.
    async fn batches_of(ops: &[(&'static str, &[&str])]) -> Vec<BTreeSet<&'static str>> {
        batches_up_to(ops, None).await
    }

    /// As [`batches_of`], but sorting only `head` and its ancestors when
    /// `head` is given.
    async fn batches_up_to(
        ops: &[(&'static str, &[&str])],
        head: Option<&str>,
    ) -> Vec<BTreeSet<&'static str>> {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let mut signed = BTreeMap::new();
        for (name, preds) in ops {
            let preds: Vec<_> = preds.iter().map(|pred| &signed[pred]).collect();
            let op = signed_add(&signer, doc_id, &preds).await;
            graph.add_op(&op).expect("predecessors are listed first");
            signed.insert(*name, op);
        }
        let heads = match head {
            Some(head) => Set::from_iter([signed[head].digest()]),
            None => graph.cgka_op_heads.clone(),
        };
        let names: BTreeMap<_, _> = signed
            .into_iter()
            .map(|(name, op)| (op.digest(), name))
            .collect();
        graph
            .batches_for_heads(&heads)
            .expect("the graph sorts")
            .iter()
            .map(|batch| batch.iter().map(|op| names[&op.digest()]).collect())
            .collect()
    }

    /// 24 random adds, and a graph of them in which the first 12 are shared
    /// and each later one is added to the graph, a fork, or both, if that
    /// side has its predecessors. The fork is then merged back, so both sides
    /// add children to the same operations. An operation whose predecessors
    /// neither side has is left out.
    async fn merged_random_graph(
        rng: &mut rand::rngs::StdRng,
    ) -> (Vec<Verified<CgkaOperation>>, CgkaOperationGraph) {
        use rand::{seq::IteratorRandom, Rng};
        let signer = MemorySigner::generate(rng);
        let doc_id = TreeId::from(&signer.0);
        let mut ops: Vec<Verified<CgkaOperation>> = Vec::new();
        for _ in 0..24 {
            let count = rng.gen_range(1..=3).min(ops.len());
            let preds: Vec<_> = ops.iter().choose_multiple(rng, count);
            let op = signed_add_from(rng, &signer, doc_id, &preds).await;
            ops.push(op);
        }
        let mut graph = CgkaOperationGraph::new();
        for op in &ops[..12] {
            graph.add_op(op).expect("predecessors come first");
        }
        let mut fork = graph.fork();
        for op in &ops[12..] {
            let preds = op.payload().predecessors();
            let to_graph = rng.gen_bool(0.5) && graph.contains_all(preds);
            let to_fork = (!to_graph || rng.gen_bool(0.5)) && fork.contains_all(preds);
            if to_graph {
                graph.add_op(op).expect("its predecessors are in the graph");
            }
            if to_fork {
                fork.add_op(op).expect("its predecessors are in the fork");
            }
        }
        graph.merge(fork);
        (ops, graph)
    }

    #[test]
    fn a_merged_graph_equals_one_built_in_order() {
        crate::test_utils::for_each_seed(|mut rng| async move {
            let (ops, graph) = merged_random_graph(&mut rng).await;
            let mut in_order = CgkaOperationGraph::new();
            for op in ops.iter().filter(|op| graph.contains_op_hash(&op.digest())) {
                in_order.add_op(op).expect("predecessors come first");
            }
            assert_eq!(
                graph, in_order,
                "the merged graph differs from one built in order"
            );
        });
    }

    #[test]
    fn a_search_finds_exactly_the_targets_in_the_causal_past() {
        use rand::{seq::IteratorRandom, Rng};
        crate::test_utils::for_each_seed(|mut rng| async move {
            let (_, graph) = merged_random_graph(&mut rng).await;
            let all: BTreeSet<_> = graph.cgka_ops.keys().copied().collect();
            for i in 0..8 {
                let preds: Predecessors = if i == 0 {
                    Predecessors::heads_of(&graph)
                } else {
                    let count = rng.gen_range(1..=3);
                    all.iter()
                        .copied()
                        .choose_multiple(&mut rng, count)
                        .into_iter()
                        .collect()
                };
                let count = rng.gen_range(1..=6);
                let targets: BTreeSet<_> = all
                    .iter()
                    .copied()
                    .choose_multiple(&mut rng, count)
                    .into_iter()
                    .collect();
                let past = crate::test_utils::causal_past(&graph, &preds);
                assert_eq!(
                    preds
                        .filter_in_causal_past(targets.clone(), &graph)
                        .expect("every op is in the graph"),
                    targets
                        .intersection(&past)
                        .copied()
                        .collect::<BTreeSet<_>>(),
                    "predecessors {preds:?}, targets {targets:?}"
                );
            }
        });
    }

    #[tokio::test]
    async fn each_operation_in_a_chain_is_its_own_batch() {
        // a
        // |
        // b
        // |
        // c
        assert_eq!(
            batches_of(&[("a", &[]), ("b", &["a"]), ("c", &["b"])]).await,
            vec![
                BTreeSet::from(["a"]),
                BTreeSet::from(["b"]),
                BTreeSet::from(["c"])
            ]
        );
    }

    #[tokio::test]
    async fn concurrent_branches_share_a_batch_until_they_rejoin() {
        //   a
        //  / \
        // b   c
        //  \ /
        //   d
        let ops: &[(&str, &[&str])] =
            &[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])];
        assert_eq!(
            batches_of(ops).await,
            vec![
                BTreeSet::from(["a"]),
                BTreeSet::from(["b", "c"]),
                BTreeSet::from(["d"])
            ]
        );
    }

    #[tokio::test]
    async fn a_shorter_concurrent_branch_shares_a_batch_with_the_longer_one() {
        //   a
        //  / \
        // b   |
        // |   e
        // c   |
        //  \ /
        //   d
        let ops: &[(&str, &[&str])] = &[
            ("a", &[]),
            ("b", &["a"]),
            ("e", &["a"]),
            ("c", &["b"]),
            ("d", &["c", "e"]),
        ];
        assert_eq!(
            batches_of(ops).await,
            vec![
                BTreeSet::from(["a"]),
                BTreeSet::from(["b", "e", "c"]),
                BTreeSet::from(["d"])
            ]
        );
    }

    #[tokio::test]
    async fn an_unmerged_branch_keeps_later_operations_in_its_batch() {
        //       root
        //      /    \
        //   update  remove
        //     |
        // later_update
        let ops: &[(&str, &[&str])] = &[
            ("root", &[]),
            ("update", &["root"]),
            ("remove", &["root"]),
            ("later_update", &["update"]),
        ];
        assert_eq!(
            batches_of(ops).await,
            vec![
                BTreeSet::from(["root"]),
                BTreeSet::from(["update", "remove", "later_update"])
            ]
        );
    }

    #[tokio::test]
    async fn a_single_head_is_alone_in_the_last_batch_of_its_past() {
        //     a
        //    / \
        //   b   c
        //  / \ /
        // s  target
        let ops: &[(&str, &[&str])] = &[
            ("a", &[]),
            ("b", &["a"]),
            ("c", &["a"]),
            ("target", &["b", "c"]),
            ("s", &["b"]),
        ];
        assert_eq!(
            batches_up_to(ops, Some("target")).await,
            vec![
                BTreeSet::from(["a"]),
                BTreeSet::from(["b", "c"]),
                BTreeSet::from(["target"])
            ]
        );
    }

    #[tokio::test]
    async fn adding_an_op_again_leaves_the_graph_unchanged() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        let child = signed_add(&signer, doc_id, &[&root]).await;
        let grandchild = signed_add(&signer, doc_id, &[&child]).await;
        for op in [&root, &child, &grandchild] {
            graph.add_op(op).expect("predecessors are added first");
        }
        let before = graph.clone();

        graph
            .add_op(&child)
            .expect("re-adding an operation succeeds");

        assert_eq!(graph, before, "re-adding an operation changed the graph");
    }

    #[tokio::test]
    async fn adding_an_op_before_its_predecessor_leaves_the_graph_unchanged() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        graph.add_op(&root).expect("a root has no predecessors");
        let unknown = signed_add(&signer, doc_id, &[]).await;
        let before = graph.clone();

        let result = graph.add_op(&signed_add(&signer, doc_id, &[&root, &unknown]).await);

        assert!(
            matches!(result, Err(CgkaError::OutOfOrderOperation)),
            "an operation with a predecessor missing from the graph was accepted"
        );
        assert!(
            result.is_err_and(|e| e.is_missing_dependency()),
            "an operation whose predecessor may still arrive would not be retried"
        );
        assert_eq!(graph, before, "a rejected operation changed the graph");
    }

    fn is_membership_change(_: &Digest<CgkaOperation>, op: &CgkaOperation) -> bool {
        op.is_membership_change()
    }

    async fn signed_update(
        signer: &MemorySigner,
        doc_id: TreeId,
        predecessors: &[&Verified<CgkaOperation>],
    ) -> Verified<CgkaOperation> {
        let new_path =
            arbitrary::Arbitrary::arbitrary(&mut arbitrary::Unstructured::new(&[0; 4096]))
                .expect("4096 bytes are enough for a path");
        let op = CgkaOperation {
            doc_id,
            predecessors: predecessors.iter().map(|op| op.digest()).collect(),
            change: CgkaChange::Update {
                new_path,
                predecessor_secrets: Vec::new(),
            },
        };
        Verified::sign::<Local, _>(&op, signer)
            .await
            .expect("signing succeeds")
    }

    #[tokio::test]
    async fn a_second_root_puts_later_operations_in_its_batch() {
        // first_add
        //    |       second_add
        //  update
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let first_add = signed_add(&signer, doc_id, &[]).await;
        let update = signed_update(&signer, doc_id, &[&first_add]).await;
        let second_add = signed_add(&signer, doc_id, &[]).await;
        for op in [&first_add, &update, &second_add] {
            graph.add_op(op).expect("predecessors are added first");
        }

        assert!(
            graph
                .batch_has(&Predecessors::from([update.digest()]), is_membership_change)
                .expect("a valid graph"),
            "an operation after the update was not put in a batch with the second root"
        );
    }

    #[tokio::test]
    async fn a_missing_depth_is_an_error() {
        //       root
        //      /    \
        // update  other_update
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        let update = signed_update(&signer, doc_id, &[&root]).await;
        let other_signer = MemorySigner::generate(&mut rand::thread_rng());
        let other_update = signed_update(&other_signer, doc_id, &[&root]).await;
        for op in [&root, &update, &other_update] {
            graph.add_op(op).expect("predecessors are added first");
        }

        graph.depths.clear();
        assert!(
            matches!(
                graph.batch_has(&Predecessors::from([update.digest()]), is_membership_change),
                Err(CgkaError::DepthNotFound)
            ),
            "a graph missing a depth was not reported"
        );
    }

    #[tokio::test]
    async fn a_head_missing_from_the_graph_is_an_error() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let graph = CgkaOperationGraph::new();
        let unknown = signed_add(&signer, doc_id, &[]).await;

        assert!(
            matches!(
                graph.batches_for_heads(&Set::from_iter([unknown.digest()])),
                Err(CgkaError::OperationNotFound)
            ),
            "a head missing from the graph was not reported as missing"
        );
    }

    #[tokio::test]
    async fn an_operation_after_every_head_starts_a_new_batch() {
        // first_root  second_root
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let first_root = signed_add(&signer, doc_id, &[]).await;
        let second_root = signed_add(&signer, doc_id, &[]).await;
        for op in [&first_root, &second_root] {
            graph.add_op(op).expect("a root has no predecessors");
        }

        assert!(
            !graph
                .batch_has(&Predecessors::heads_of(&graph), is_membership_change)
                .expect("a valid graph"),
            "an operation after every head was put in a batch with an add"
        );
    }

    #[tokio::test]
    async fn adding_a_root_that_is_not_an_add_leaves_the_graph_unchanged() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        graph
            .add_op(&signed_add(&signer, doc_id, &[]).await)
            .expect("a root add is accepted");
        let before = graph.clone();

        let result = graph.add_op(&signed_update(&signer, doc_id, &[]).await);

        assert!(
            matches!(result, Err(CgkaError::InvalidOperation)),
            "a root that is not an add was accepted"
        );
        assert!(
            result.is_err_and(|e| !e.is_missing_dependency()),
            "a root that is not an add would be retried"
        );
        assert_eq!(graph, before, "a rejected operation changed the graph");
    }

    #[tokio::test]
    async fn an_update_is_chainable_once_a_later_update_follows_it() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        let u1 = signed_update(&signer, doc_id, &[&root]).await;
        let u2 = signed_update(&signer, doc_id, &[&u1]).await;
        for op in [&root, &u1, &u2] {
            graph.add_op(op).expect("predecessors are added first");
        }

        // Only u1 has a later update to wrap it. u2 has none yet, and the root is
        // not an update.
        let chainable = [&root, &u1, &u2].map(|op| graph.is_chainable(&op.digest()));
        assert_eq!(chainable, [false, true, false]);
    }

    #[tokio::test]
    async fn only_the_first_update_back_from_a_head_is_returned() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        let earlier = signed_update(&signer, doc_id, &[&root]).await;
        let later = signed_update(&signer, doc_id, &[&earlier]).await;
        let add = signed_add(&signer, doc_id, &[&later]).await;
        let later_add = signed_add(&signer, doc_id, &[&add]).await;
        for op in [&root, &earlier, &later, &add, &later_add] {
            graph.add_op(op).expect("predecessors are added first");
        }

        assert_eq!(
            graph.nearest_update_ancestors(&[later_add.digest()]),
            Set::from_iter([later.digest()]),
            "the traversal should skip the adds and stop at the first update"
        );
    }

    #[tokio::test]
    async fn a_head_that_is_an_update_is_its_own_nearest_update() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        let update = signed_update(&signer, doc_id, &[&root]).await;
        for op in [&root, &update] {
            graph.add_op(op).expect("predecessors are added first");
        }

        let update_hash = Set::from_iter([update.digest()]);
        assert_eq!(graph.nearest_update_ancestors(&update_hash), update_hash);
    }

    #[tokio::test]
    async fn a_head_with_no_update_in_its_past_has_no_nearest_update() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        let add = signed_add(&signer, doc_id, &[&root]).await;
        for op in [&root, &add] {
            graph.add_op(op).expect("predecessors are added first");
        }

        assert_eq!(graph.nearest_update_ancestors(&[add.digest()]), Set::new());
    }

    #[tokio::test]
    async fn a_members_secret_is_rebuildable_only_from_its_add_onwards() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let mut rng = rand::thread_rng();
        let founder = member_id();
        let joiner = member_id();
        let root = signed_add_of(&mut rng, &signer, doc_id, founder, &[]).await;
        let before = signed_update(&signer, doc_id, &[&root]).await;
        let join = signed_add_of(&mut rng, &signer, doc_id, joiner, &[&before]).await;
        let after = signed_update(&signer, doc_id, &[&join]).await;
        for op in [&root, &before, &join, &after] {
            graph.add_op(op).expect("predecessors are added first");
        }

        let all = [&root, &before, &join, &after].map(|op| op.digest());
        let rebuildable = |member| all.map(|op_hash| graph.has_add_before(member, op_hash));
        assert_eq!(
            rebuildable(joiner),
            [false, false, true, true],
            "the operations before the joiner was added have no leaf for it to start from"
        );
        assert_eq!(
            rebuildable(founder),
            [true; 4],
            "the founder's add precedes every operation"
        );
    }

    #[tokio::test]
    async fn each_head_contributes_its_own_nearest_update() {
        let signer = MemorySigner::generate(&mut rand::thread_rng());
        let doc_id = TreeId::from(&signer.0);
        let mut graph = CgkaOperationGraph::new();
        let root = signed_add(&signer, doc_id, &[]).await;
        graph.add_op(&root).expect("a root add has no predecessors");

        // Two concurrent branches, each an update followed by an add.
        let mut expected = Set::new();
        let mut heads = Set::new();
        for _ in 0..2 {
            let update = signed_update(&signer, doc_id, &[&root]).await;
            let add = signed_add(&signer, doc_id, &[&update]).await;
            for op in [&update, &add] {
                graph.add_op(op).expect("predecessors are added first");
            }
            expected.insert(update.digest());
            heads.insert(add.digest());
        }

        assert_eq!(graph.nearest_update_ancestors(&heads), expected);
    }
}