kanidmd_lib/repl/
ruv.rs

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
use crate::be::dbrepl::DbReplMeta;
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::ops::Bound::*;
use std::sync::Arc;
use std::time::Duration;

use concread::bptree::{BptreeMap, BptreeMapReadSnapshot, BptreeMapReadTxn, BptreeMapWriteTxn};

use idlset::v2::IDLBitRange;

use crate::prelude::*;
use crate::repl::cid::Cid;
use crate::repl::proto::{ReplAnchoredCidRange, ReplCidRange};
use std::fmt;

#[derive(Default)]
pub struct ReplicationUpdateVector {
    // This sorts by time. We store the set of entry id's that are affected in an operation.
    // Due to how replication state works, it is possibly that id's in these sets *may* not
    // exist anymore, so these bit ranges likely need intersection with allids before use.
    data: BptreeMap<Cid, IDLBitRange>,
    // This sorts by Server ID. It's used for the RUV to build ranges for you ... guessed it
    // range queries. These are used to build the set of differences that need to be sent in
    // a replication operation.
    //
    // we need a way to invert the cid, but without duplication? Maybe an invert cid type?
    // This way it still orders things in the right order by time stamp just searches by cid
    // first.
    ranged: BptreeMap<Uuid, BTreeSet<Duration>>,
}

/// The status of replication after investigating the RUV states.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum RangeDiffStatus {
    /// Ok - can proceed with replication, supplying the following
    /// ranges of changes to the consumer.
    Ok(BTreeMap<Uuid, ReplCidRange>),
    /// Refresh - The consumer is lagging and is missing a set of changes
    /// that are required to proceed. The consumer *MUST* be refreshed
    /// immediately.
    Refresh {
        lag_range: BTreeMap<Uuid, ReplCidRange>,
    },
    /// Unwilling - The consumer is advanced beyond our state, and supplying
    /// changes to them may introduce inconsistency in replication. This
    /// server should be investigated immediately.
    Unwilling {
        adv_range: BTreeMap<Uuid, ReplCidRange>,
    },
    /// Critical - The consumer is lagging and missing changes, but also is
    /// in possession of changes advancing it beyond our current state. This
    /// is a critical fault in replication and the topology must be
    /// investigated immediately.
    Critical {
        lag_range: BTreeMap<Uuid, ReplCidRange>,
        adv_range: BTreeMap<Uuid, ReplCidRange>,
    },
    /// No RUV Overlap - The consumer has likely desynchronised and no longer has
    /// common overlap with it's RUV to ours. This can indicate it has trimmed
    /// content we may have, or may have become part of a split brain situation.
    /// For replication to proceed, there must be *at least* one common overlapping
    /// point in the RUV.
    NoRUVOverlap,
}

impl ReplicationUpdateVector {
    pub fn write(&self) -> ReplicationUpdateVectorWriteTransaction<'_> {
        ReplicationUpdateVectorWriteTransaction {
            // Need to take the write first, then the read to guarantee ordering.
            added: Some(BTreeSet::default()),
            data: self.data.write(),
            data_pre: self.data.read(),
            ranged: self.ranged.write(),
        }
    }

    pub fn read(&self) -> ReplicationUpdateVectorReadTransaction<'_> {
        ReplicationUpdateVectorReadTransaction {
            data: self.data.read(),
            ranged: self.ranged.read(),
        }
    }

    pub(crate) fn range_diff(
        consumer_range: &BTreeMap<Uuid, ReplCidRange>,
        supplier_range: &BTreeMap<Uuid, ReplCidRange>,
    ) -> RangeDiffStatus {
        // We need to build a new set of ranges that express the difference between
        // these two states.
        let mut diff_range = BTreeMap::default();
        let mut lag_range = BTreeMap::default();
        let mut adv_range = BTreeMap::default();

        let mut consumer_lagging = false;
        let mut supplier_lagging = false;
        let mut valid_content_overlap = false;

        // We need to look at each uuid in the *supplier* and assert if they are present
        // on the *consumer*.
        //
        // If there are s_uuids with the same max, we don't add it to the
        // diff

        for (supplier_s_uuid, supplier_cid_range) in supplier_range.iter() {
            match consumer_range.get(supplier_s_uuid) {
                Some(consumer_cid_range) => {
                    // We have the same server uuid in our RUV's so some content overlap
                    // must exist (or has existed);
                    valid_content_overlap = true;

                    // The two windows just have to overlap. If they over lap
                    // meaning that consumer max > supplier min, then if supplier
                    // max > consumer max, then the range between consumer max
                    // and supplier max must be supplied.
                    //
                    //   [ consumer min ... consumer max ]
                    //      <-- [ supplier min .. supplier max ] -->
                    //
                    // In other words if we have:
                    //
                    //   [ consumer min ... consumer max ]
                    //                                      [ supplier min ... supplier max ]
                    //                                     ^
                    //                                     \-- no overlap of the range windows!
                    //
                    // then because there has been too much lag between consumer and
                    // the supplier then there is a risk of changes being dropped or
                    // missing. In the future we could alter this to force the resend
                    // of zero -> supplier max, but I think thought is needed to
                    // ensure no corruption in this case.
                    if consumer_cid_range.ts_max < supplier_cid_range.ts_min {
                        //
                        //   [ consumer min ... consumer max ]
                        //                                      [ supplier min ... supplier max ]
                        //                                     ^
                        //                                     \-- no overlap of the range windows!
                        //
                        consumer_lagging = true;
                        lag_range.insert(
                            *supplier_s_uuid,
                            ReplCidRange {
                                ts_min: supplier_cid_range.ts_min,
                                ts_max: consumer_cid_range.ts_max,
                            },
                        );
                    } else if supplier_cid_range.ts_max < consumer_cid_range.ts_min {
                        //
                        //                                      [ consumer min ... consumer max ]
                        //   [ supplier min ... supplier max ]
                        //                                     ^
                        //                                     \-- no overlap of the range windows!
                        //
                        // This means we can't supply because we are missing changes that the consumer
                        // has. *we* are lagging.
                        supplier_lagging = true;
                        adv_range.insert(
                            *supplier_s_uuid,
                            ReplCidRange {
                                ts_min: supplier_cid_range.ts_max,
                                ts_max: consumer_cid_range.ts_min,
                            },
                        );
                    } else if consumer_cid_range.ts_max < supplier_cid_range.ts_max {
                        //
                        //                                         /-- consumer needs these changes
                        //                                         v
                        //   [ consumer min ... consumer max ] -->                   ]
                        //                           [ supplier min ... supplier max ]
                        //                              ^
                        //                              \-- overlap of the range windows
                        //
                        // We require the changes from consumer max -> supplier max.
                        diff_range.insert(
                            *supplier_s_uuid,
                            ReplCidRange {
                                ts_min: consumer_cid_range.ts_max,
                                ts_max: supplier_cid_range.ts_max,
                            },
                        );
                    }
                    //
                    //                                       /-- The consumer has changes we don't have.
                    //                                       |   So we don't need to supply
                    //                                       v
                    //                             [ consumer min ... consumer max ]
                    //   [ supplier min ... supplier max ]
                    //                              ^
                    //                              \-- overlap of the range windows
                    //
                    //  OR
                    //
                    //   [ consumer min ... consumer max ]
                    //   [ supplier min ... supplier max ]
                    //                              ^
                    //                              \-- the windows max is identical
                    //                                  no actions needed
                    //
                    // In this case there is no action required since consumer_cid_range.ts_max
                    // must be greater than or equal to supplier max.
                }
                None => {
                    // The consumer does not have any content from this
                    // server. Select from Zero -> max of the supplier.
                    diff_range.insert(
                        *supplier_s_uuid,
                        ReplCidRange {
                            ts_min: Duration::ZERO,
                            ts_max: supplier_cid_range.ts_max,
                        },
                    );
                }
            }
        }

        if !valid_content_overlap {
            return RangeDiffStatus::NoRUVOverlap;
        }

        match (consumer_lagging, supplier_lagging) {
            (false, false) => RangeDiffStatus::Ok(diff_range),
            (true, false) => RangeDiffStatus::Refresh { lag_range },
            (false, true) => RangeDiffStatus::Unwilling { adv_range },
            (true, true) => RangeDiffStatus::Critical {
                lag_range,
                adv_range,
            },
        }
    }
}

pub struct ReplicationUpdateVectorWriteTransaction<'a> {
    added: Option<BTreeSet<Cid>>,
    data: BptreeMapWriteTxn<'a, Cid, IDLBitRange>,
    data_pre: BptreeMapReadTxn<'a, Cid, IDLBitRange>,
    ranged: BptreeMapWriteTxn<'a, Uuid, BTreeSet<Duration>>,
}

impl fmt::Debug for ReplicationUpdateVectorWriteTransaction<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "RUV DATA DUMP")?;
        self.data
            .iter()
            .try_for_each(|(cid, idl)| writeln!(f, "* [{cid} {idl:?}]"))?;
        writeln!(f, "RUV RANGE DUMP")?;
        self.ranged
            .iter()
            .flat_map(|(s_uuid, ts_set)| ts_set.iter().map(|ts| Cid::new(*s_uuid, *ts)))
            .try_for_each(|cid| writeln!(f, "[{cid}]"))
    }
}

pub struct ReplicationUpdateVectorReadTransaction<'a> {
    data: BptreeMapReadTxn<'a, Cid, IDLBitRange>,
    ranged: BptreeMapReadTxn<'a, Uuid, BTreeSet<Duration>>,
}

impl fmt::Debug for ReplicationUpdateVectorReadTransaction<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "RUV DATA DUMP")?;
        self.data
            .iter()
            .try_for_each(|(cid, idl)| writeln!(f, "* [{cid} {idl:?}]"))?;
        writeln!(f, "RUV RANGE DUMP")?;
        self.ranged
            .iter()
            .try_for_each(|(s_uuid, ts)| writeln!(f, "* [{s_uuid} {ts:?}]"))
    }
}

pub trait ReplicationUpdateVectorTransaction {
    fn ruv_snapshot(&self) -> BptreeMapReadSnapshot<'_, Cid, IDLBitRange>;

    fn range_snapshot(&self) -> BptreeMapReadSnapshot<'_, Uuid, BTreeSet<Duration>>;

    fn to_db_backup_ruv(&self) -> DbReplMeta {
        DbReplMeta::V1 {
            ruv: self.ruv_snapshot().keys().map(|cid| cid.into()).collect(),
        }
    }

    /// Return a filtered view of our RUV ranges. This acts similar to "trim" where any s_uuid
    /// where the max cid is less than trim_cid will be excluded from the view.
    fn filter_ruv_range(
        &self,
        trim_cid: &Cid,
    ) -> Result<BTreeMap<Uuid, ReplCidRange>, OperationError> {
        self.range_snapshot()
            .iter()
            .filter_map(|(s_uuid, range)| match (range.first(), range.last()) {
                (Some(first), Some(last)) => {
                    if last < &trim_cid.ts {
                        None
                    } else {
                        Some(Ok((
                            *s_uuid,
                            ReplCidRange {
                                ts_min: *first,
                                ts_max: *last,
                            },
                        )))
                    }
                }
                _ => {
                    error!(
                        "invalid state for server uuid {:?}, no ranges present",
                        s_uuid
                    );
                    Some(Err(OperationError::InvalidState))
                }
            })
            .collect::<Result<BTreeMap<_, _>, _>>()
    }

    /// Return the complete set of RUV ranges present on this replica
    fn current_ruv_range(&self) -> Result<BTreeMap<Uuid, ReplCidRange>, OperationError> {
        self.range_snapshot()
            .iter()
            .map(|(s_uuid, range)| match (range.first(), range.last()) {
                (Some(first), Some(last)) => Ok((
                    *s_uuid,
                    ReplCidRange {
                        ts_min: *first,
                        ts_max: *last,
                    },
                )),
                _ => {
                    error!(
                        "invalid state for server uuid {:?}, no ranges present",
                        s_uuid
                    );
                    Err(OperationError::InvalidState)
                }
            })
            .collect::<Result<BTreeMap<_, _>, _>>()
    }

    fn range_to_idl(&self, ctx_ranges: &BTreeMap<Uuid, ReplCidRange>) -> IDLBitRange {
        let mut idl = IDLBitRange::new();
        // Force the set to be compressed, saves on seeks during inserts.
        idl.compress();
        let range = self.range_snapshot();
        let ruv = self.ruv_snapshot();

        // The range we have has a collection of s_uuid containing low -> high ranges.
        // We need to convert this to absolute ranges of all the idlbitranges that
        // relate to the entries we have.

        for (s_uuid, ctx_range) in ctx_ranges {
            // For each server and range low to high, iterate over
            // the list of CID's in the main RUV.

            let Some(ruv_range) = range.get(s_uuid) else {
                // This is valid because if we clean up a server range on
                // this node, but the other server isn't aware yet, so we
                // just no-op this. The changes we have will still be
                // correctly found and sent.
                debug!(?s_uuid, "range not found in ruv.");
                continue;
            };

            // Get from the min to the max. Unbounded and
            // Included(ctx_range.ts_max) are the same in
            // this context.
            for ts in ruv_range.range((Excluded(ctx_range.ts_min), Unbounded)) {
                let cid = Cid {
                    ts: *ts,
                    s_uuid: *s_uuid,
                };

                if let Some(ruv_idl) = ruv.get(&cid) {
                    ruv_idl.into_iter().for_each(|id| idl.insert_id(id))
                }
                // If the cid isn't found, it may have been trimmed, but that's okay. A cid in
                // a range can be trimmed if all entries of that cid have since tombstoned so
                // no longer need to be applied in change ranges.
            }
        }

        idl
    }

    fn verify(
        &self,
        entries: &[Arc<EntrySealedCommitted>],
        results: &mut Vec<Result<(), ConsistencyError>>,
    ) {
        // Okay rebuild the RUV in parallel.
        let mut check_ruv: BTreeMap<Cid, IDLBitRange> = BTreeMap::default();
        for entry in entries {
            // The DB id we need.
            let eid = entry.get_id();
            let ecstate = entry.get_changestate();
            // We don't need the details of the change - only the cid of the
            // change that this entry was involved in.
            for cid in ecstate.cid_iter() {
                // Add to the main ruv data.
                if let Some(idl) = check_ruv.get_mut(cid) {
                    // We can't guarantee id order, so we have to do this properly.
                    idl.insert_id(eid);
                } else {
                    let mut idl = IDLBitRange::new();
                    idl.insert_id(eid);
                    check_ruv.insert(cid.clone(), idl);
                }
            }
        }

        trace!(?check_ruv);
        // Get the current state
        let snapshot_ruv = self.ruv_snapshot();

        // Now compare. We want to do this checking for each CID in each, and then asserting
        // the content is the same.

        let mut check_iter = check_ruv.iter();
        let mut snap_iter = snapshot_ruv.iter();

        let mut check_next = check_iter.next();
        let mut snap_next = snap_iter.next();

        while let (Some((ck, cv)), Some((sk, sv))) = (&check_next, &snap_next) {
            match ck.cmp(sk) {
                Ordering::Equal => {
                    // Counter intuitive, but here we check that the check set is a *subset*
                    // of the ruv snapshot. This is because when we have an entry that is
                    // tombstoned, all it's CID interactions are "lost" and it's cid becomes
                    // that of when it was tombstoned. So the "rebuilt" ruv will miss that
                    // entry.
                    //
                    // In the future the RUV concept may be ditched entirely anyway, thoughts needed.
                    let intersect = *cv & *sv;
                    if *cv == &intersect {
                        trace!("{:?} is consistent!", ck);
                    } else {
                        error!("{:?} is NOT consistent! IDL's differ", ck);
                        debug_assert!(false);
                        results.push(Err(ConsistencyError::RuvInconsistent(ck.to_string())));
                    }
                    check_next = check_iter.next();
                    snap_next = snap_iter.next();
                }
                // Because we are zipping between these two sets, we only need to compare when
                // the CID's are equal. Otherwise we need the other iter to "catch up"
                Ordering::Less => {
                    check_next = check_iter.next();
                }
                Ordering::Greater => {
                    snap_next = snap_iter.next();
                }
            }
        }

        while let Some((ck, _cv)) = &check_next {
            debug!("{:?} may not be consistent! CID missing from RUV", ck);
            // debug_assert!(false);
            // results.push(Err(ConsistencyError::RuvInconsistent(ck.to_string())));
            check_next = check_iter.next();
        }

        while let Some((sk, _sv)) = &snap_next {
            debug!(
                "{:?} may not be consistent! CID should not exist in RUV",
                sk
            );
            // debug_assert!(false);
            // results.push(Err(ConsistencyError::RuvInconsistent(sk.to_string())));
            snap_next = snap_iter.next();
        }

        // Assert that the content of the ranged set matches the data set and has the
        // correct set of values.
        let snapshot_range = self.range_snapshot();

        for cid in snapshot_ruv.keys() {
            if let Some(server_range) = snapshot_range.get(&cid.s_uuid) {
                if !server_range.contains(&cid.ts) {
                    warn!(
                        "{:?} is NOT consistent! server range is missing cid in index",
                        cid
                    );
                    debug_assert!(false);
                    results.push(Err(ConsistencyError::RuvInconsistent(
                        cid.s_uuid.to_string(),
                    )));
                }
            } else {
                warn!(
                    "{:?} is NOT consistent! server range is not present",
                    cid.s_uuid
                );
                debug_assert!(false);
                results.push(Err(ConsistencyError::RuvInconsistent(
                    cid.s_uuid.to_string(),
                )));
            }
        }

        // Done!
    }

    fn get_anchored_ranges(
        &self,
        ranges: BTreeMap<Uuid, ReplCidRange>,
    ) -> Result<BTreeMap<Uuid, ReplAnchoredCidRange>, OperationError> {
        let self_range_snapshot = self.range_snapshot();

        ranges
            .into_iter()
            .map(|(s_uuid, ReplCidRange { ts_min, ts_max })| {
                let ts_range = self_range_snapshot.get(&s_uuid).ok_or_else(|| {
                    error!(
                        ?s_uuid,
                        "expected cid range for server in ruv, was not present"
                    );
                    OperationError::InvalidState
                })?;

                // If these are equal and excluded, btreeset panics
                let anchors = if ts_max > ts_min {
                    // We exclude the ends because these are already in the ts_min/max
                    ts_range
                        .range((Excluded(ts_min), Excluded(ts_max)))
                        .copied()
                        .collect::<Vec<_>>()
                } else {
                    Vec::with_capacity(0)
                };

                Ok((
                    s_uuid,
                    ReplAnchoredCidRange {
                        ts_min,
                        anchors,
                        ts_max,
                    },
                ))
            })
            .collect()
    }
}

impl ReplicationUpdateVectorTransaction for ReplicationUpdateVectorWriteTransaction<'_> {
    fn ruv_snapshot(&self) -> BptreeMapReadSnapshot<'_, Cid, IDLBitRange> {
        self.data.to_snapshot()
    }

    fn range_snapshot(&self) -> BptreeMapReadSnapshot<'_, Uuid, BTreeSet<Duration>> {
        self.ranged.to_snapshot()
    }
}

impl ReplicationUpdateVectorTransaction for ReplicationUpdateVectorReadTransaction<'_> {
    fn ruv_snapshot(&self) -> BptreeMapReadSnapshot<'_, Cid, IDLBitRange> {
        self.data.to_snapshot()
    }

    fn range_snapshot(&self) -> BptreeMapReadSnapshot<'_, Uuid, BTreeSet<Duration>> {
        self.ranged.to_snapshot()
    }
}

impl ReplicationUpdateVectorWriteTransaction<'_> {
    pub fn clear(&mut self) {
        self.added = None;
        self.data.clear();
        self.ranged.clear();
    }

    pub(crate) fn incremental_preflight_validate_ruv(
        &self,
        ctx_ranges: &BTreeMap<Uuid, ReplAnchoredCidRange>,
        txn_cid: &Cid,
    ) -> Result<(), OperationError> {
        // Check that the incoming ranges, for our servers id, do not exceed
        // our servers max state. This can occur if we restore from a backup
        // where the replication state is older than what our partners have,
        // meaning that the context may have diverged in a way we can't then
        // resolve.

        if let Some(our_cid_range_max) = self
            .ranged
            .get(&txn_cid.s_uuid)
            .and_then(|range| range.last().copied())
        {
            if let Some(incoming_cid_range) = ctx_ranges.get(&txn_cid.s_uuid) {
                if incoming_cid_range.ts_max > our_cid_range_max {
                    error!("The incoming data contains changes matching this server's UUID, and those changes are newer than the local version. This can occur if the server was restored from a backup which was taken before sending out changes. Replication is unable to proceed as data corruption may occur. You must refresh this consumer immediately to continue.");
                    return Err(OperationError::ReplServerUuidSplitDataState);
                }
            }
        }

        let warn_time = txn_cid.ts + REPL_SUPPLIER_ADVANCE_WINDOW;
        for (s_uuid, incoming_cid_range) in ctx_ranges.iter() {
            if incoming_cid_range.ts_max > warn_time {
                // TODO: This would be a great place for fault management to pick up this warning
                warn!(
                    "Incoming changes from {:?} are further than {} seconds in the future.",
                    s_uuid,
                    REPL_SUPPLIER_ADVANCE_WINDOW.as_secs()
                );
            }
        }

        Ok(())
    }

    pub(crate) fn refresh_validate_ruv(
        &self,
        ctx_ranges: &BTreeMap<Uuid, ReplAnchoredCidRange>,
    ) -> Result<(), OperationError> {
        // Assert that the ruv that currently exists, is a valid data set of
        // the supplied consumer range - especially check that when a uuid exists in
        // our ruv, that it's maximum matches the ctx ruv.
        //
        // Since the ctx range comes from the supplier, when we rebuild due to the
        // state machine then some values may not exist since they were replaced
        // or updated. It's also possible that the imported range maximums *may not*
        // exist especially in three way replication scenarios where S1:A was the S1
        // maximum but is replaced by S2:B. This would make S1:A still it's valid
        // maximum but no entry reflects that in it's change state.
        let mut valid = true;

        for (ctx_server_uuid, ctx_server_range) in ctx_ranges.iter() {
            match self.ranged.get(ctx_server_uuid) {
                Some(server_range) => {
                    let ctx_ts = &ctx_server_range.ts_max;
                    match server_range.last() {
                        Some(s_ts) if s_ts <= ctx_ts => {
                            // Ok - our entries reflect maximum or earlier.
                            trace!(?ctx_server_uuid, ?ctx_ts, ?s_ts, "valid");
                        }
                        Some(s_ts) => {
                            valid = false;
                            warn!(?ctx_server_uuid, ?ctx_ts, ?s_ts, "inconsistent s_uuid in ruv, consumer ruv is advanced past supplier");
                        }
                        None => {
                            valid = false;
                            warn!(
                                ?ctx_server_uuid,
                                ?ctx_ts,
                                "inconsistent server range in ruv, no maximum ts found for s_uuid"
                            );
                        }
                    }
                }
                None => {
                    // valid = false;
                    trace!(
                        ?ctx_server_uuid,
                        "s_uuid absent from ranged ruv, possible that changes have been expired"
                    );
                }
            }
        }

        if valid {
            Ok(())
        } else {
            Err(OperationError::ReplInvalidRUVState)
        }
    }

    #[instrument(level = "trace", name = "ruv::refresh_update_ruv", skip_all)]
    pub(crate) fn refresh_update_ruv(
        &mut self,
        ctx_ranges: &BTreeMap<Uuid, ReplAnchoredCidRange>,
    ) -> Result<(), OperationError> {
        // Previously this would just add in the ranges, and then the actual entries
        // from the changestate would populate the data/ranges. Now we add empty idls
        // to each of these so that they are db persisted allowing ruv reload.
        for (ctx_s_uuid, ctx_range) in ctx_ranges.iter() {
            let cid_iter = std::iter::once(&ctx_range.ts_min)
                .chain(ctx_range.anchors.iter())
                .chain(std::iter::once(&ctx_range.ts_max))
                .map(|ts| Cid::new(*ctx_s_uuid, *ts));

            for cid in cid_iter {
                self.insert_change(&cid, IDLBitRange::default())?;
            }
        }

        Ok(())
    }

    /// Restore the ruv from a DB backup. It's important to note here that
    /// we don't actually need to restore and of the IDL's in the process. we only
    /// needs the CID's of the changes/points in time. This is because when the
    /// db entries are restored, their changesets will re-populate the data that we
    /// need in the RUV at these points. The reason we need these ranges without IDL
    /// is so that trim and replication works properly.
    #[instrument(level = "debug", name = "ruv::restore", skip_all)]
    pub(crate) fn restore<I>(&mut self, iter: I) -> Result<(), OperationError>
    where
        I: IntoIterator<Item = Cid>,
    {
        let mut rebuild_ruv: BTreeMap<Cid, IDLBitRange> = BTreeMap::new();
        let mut rebuild_range: BTreeMap<Uuid, BTreeSet<Duration>> = BTreeMap::default();

        for cid in iter {
            if !rebuild_ruv.contains_key(&cid) {
                let idl = IDLBitRange::new();
                rebuild_ruv.insert(cid.clone(), idl);
            }

            if let Some(server_range) = rebuild_range.get_mut(&cid.s_uuid) {
                server_range.insert(cid.ts);
            } else {
                let mut ts_range = BTreeSet::default();
                ts_range.insert(cid.ts);
                rebuild_range.insert(cid.s_uuid, ts_range);
            }
        }

        self.data.extend(rebuild_ruv);
        self.ranged.extend(rebuild_range);

        Ok(())
    }

    #[instrument(level = "debug", name = "ruv::rebuild", skip_all)]
    pub fn rebuild(&mut self, entries: &[Arc<EntrySealedCommitted>]) -> Result<(), OperationError> {
        // Entries and their internal changestates are the "source of truth" for all changes
        // that have ever occurred and are stored on this server. So we use them to rebuild our RUV
        // here!
        //
        // We only update RUV items where an anchor exists.

        // let mut rebuild_ruv: BTreeMap<Cid, IDLBitRange> = BTreeMap::new();
        // let mut rebuild_range: BTreeMap<Uuid, BTreeSet<Duration>> = BTreeMap::default();

        for entry in entries {
            // The DB id we need.
            let eid = entry.get_id();
            let ecstate = entry.get_changestate();
            // We don't need the details of the change - only the cid of the
            // change that this entry was involved in.
            for cid in ecstate.cid_iter() {
                // if let Some(idl) = rebuild_ruv.get_mut(cid) {
                if let Some(idl) = self.data.get_mut(cid) {
                    // We can't guarantee id order, so we have to do this properly.
                    idl.insert_id(eid);
                    /*
                    } else {
                        let mut idl = IDLBitRange::new();
                        idl.insert_id(eid);
                        rebuild_ruv.insert(cid.clone(), idl);
                    */
                }

                /*
                if let Some(server_range) = rebuild_range.get_mut(&cid.s_uuid) {
                    server_range.insert(cid.ts);
                } else {
                    let mut ts_range = BTreeSet::default();
                    ts_range.insert(cid.ts);
                    rebuild_range.insert(cid.s_uuid, ts_range);
                }
                */
            }
        }

        // Finally, we need to do a cleanup/compact of the IDL's if possible.
        self.data.range_mut(..).for_each(|(_k, idl)| {
            idl.maybe_compress();
        });

        // self.data.extend(rebuild_ruv);

        // Warning - you can't extend here because this is keyed by UUID. You need
        // to go through each key and then merge the sets.

        /*
        rebuild_range.into_iter().for_each(|(s_uuid, ts_set)| {
            if let Some(ex_ts_set) = self.ranged.get_mut(&s_uuid) {
                ex_ts_set.extend(ts_set)
            } else {
                self.ranged.insert(s_uuid, ts_set);
            }
        });
        */

        Ok(())
    }

    pub fn insert_change(&mut self, cid: &Cid, idl: IDLBitRange) -> Result<(), OperationError> {
        // Remember, in a transaction the changes can be updated multiple times.
        if let Some(ex_idl) = self.data.get_mut(cid) {
            // This ensures both sets have all the available ids.
            let idl = ex_idl as &_ | &idl;
            *ex_idl = idl;
        } else {
            self.data.insert(cid.clone(), idl);
        }

        if let Some(server_range) = self.ranged.get_mut(&cid.s_uuid) {
            server_range.insert(cid.ts);
        } else {
            let mut range = BTreeSet::default();
            range.insert(cid.ts);
            self.ranged.insert(cid.s_uuid, range);
        }

        if let Some(added) = &mut self.added {
            added.insert(cid.clone());
        }

        Ok(())
    }

    pub fn update_entry_changestate(
        &mut self,
        entry: &EntrySealedCommitted,
    ) -> Result<(), OperationError> {
        let eid = entry.get_id();
        let ecstate = entry.get_changestate();

        trace!("Updating ruv state from entry {}", eid);
        trace!(?ecstate);

        for cid in ecstate.cid_iter() {
            if let Some(idl) = self.data.get_mut(cid) {
                // We can't guarantee id order, so we have to do this properly.
                idl.insert_id(eid);
            } else {
                let mut idl = IDLBitRange::new();
                idl.insert_id(eid);
                self.data.insert(cid.clone(), idl);
            }

            if let Some(server_range) = self.ranged.get_mut(&cid.s_uuid) {
                server_range.insert(cid.ts);
            } else {
                let mut ts_range = BTreeSet::default();
                ts_range.insert(cid.ts);
                self.ranged.insert(cid.s_uuid, ts_range);
            }
        }

        Ok(())
    }

    pub fn ruv_idls(&self) -> IDLBitRange {
        let mut idl = IDLBitRange::new();
        self.data.iter().for_each(|(_cid, ex_idl)| {
            idl = ex_idl as &_ | &idl;
        });
        idl
    }

    /*
        How to handle changelog trimming? If we trim a server out from the RUV as a whole, we
        need to be sure we don't oversupply changes the consumer already has. How can we do
        this cleanly? Or do we just deal with it because our own local trim will occur soon after?

        The situation would be

        A:   1    ->    3
        B:   1    ->    3

        Assuming A trims first:

        A:
        B:   1    ->    3

        Then on A <- B, B would try to supply 1->3 to A assuming it is not present. However,
        the trim would occur soon after on B causing:

        A:
        B:

        And then the supply would stop. So either A needs to retain the max/min in it's range
        to allow the comparison here to continue even if it's ruv is cleaned. Or, we need to
        have a delayed trim on the range that is 2x the normal trim range to give a buffer?

        Mostly longer ruv/cid ranges aren't an issue for us, so could we just make these ranges
        really large?

        NOTE: For now we do NOT trim out max CID's of any s_uuid so that we don't have to confront
        this edge case yet.

        // == RESOLVED: Previously this was a problem as the CID ranges of any node may not be a
        // complete view of all CID's that existed on any other node. Now with anchors in replication
        // this changes and we have not only a complete view of all CID's that were created, but
        // tombstone purge always create an empty anchor so the RUV always advances. This way we
        // have a stronger assurance about which servers are live and which are not.
    */

    // Problem Cases

    /*
       What about generations? There is a "live" generation which can be replicated and a
       former generation of ranges that previously existed. To replicate:
           // The consumer must have content within the current live range.
           consumer.live_max < supplier.live_max
           consumer.live_max >= supplier.live_min
           // The consumer must have all content that was formerly known.
           consumer.live_min >= supplier.former_max
           // I don't think we care what


        // == RESOLVED: Anchors give us the generations that existed previously without us
        // needing to worry about this.
    */

    pub fn trim_up_to(&mut self, cid: &Cid) -> Result<IDLBitRange, OperationError> {
        trace!(trim_up_to_cid = ?cid);
        let mut idl = IDLBitRange::new();
        let mut remove_suuid = Vec::with_capacity(0);

        // Here we can use the for_each here to be trimming the
        // range set since that is not ordered by time, we need
        // to do fragmented searches over this no matter what we
        // try to do.

        for (cid, ex_idl) in self.data.range((Unbounded, Excluded(cid))) {
            trace!(?cid, "examining for RUV removal");
            idl = ex_idl as &_ | &idl;

            // Remove the reverse version of the cid from the ranged index.
            match self.ranged.get_mut(&cid.s_uuid) {
                Some(server_range) => {
                    // Remove returns a bool if the element WAS present.
                    if !server_range.remove(&cid.ts) {
                        error!("Impossible State - The RUV is corrupted due to missing sid:ts pair in ranged index");
                        error!(ruv = ?self);
                        error!(?cid);
                        return Err(OperationError::InvalidState);
                    }

                    if server_range.is_empty() {
                        remove_suuid.push(cid.s_uuid);
                        warn!(s_uuid = ?cid.s_uuid, "disconnected server detected - this will be removed!");
                    } else {
                        trace!(?server_range, "retaining server");
                    }
                }
                None => {
                    error!("Impossible State - The RUV is corrupted due to missing sid in ranged index");
                    error!(ruv = ?self);
                    error!(?cid);
                    return Err(OperationError::InvalidState);
                }
            }
        }

        // We can now remove old server id's because we have a reliable liveness check in the
        // method of anchors being transmissed during replication. If a server is offline for
        // an extended period, it will not have created any anchors, and it will eventually become
        // empty in the data range. This allow it to be trimmed out.
        for s_uuid in remove_suuid {
            let x = self.ranged.remove(&s_uuid);
            assert!(x.map(|y| y.is_empty()).unwrap_or(false))
        }

        // Trim all cid's up to this value, and return the range of IDs
        // that are affected.
        self.data.split_off_lt(cid);

        Ok(idl)
    }

    pub fn added(&self) -> Box<dyn Iterator<Item = Cid> + '_> {
        if let Some(added) = self.added.as_ref() {
            // return what was added this txn. We previously would iterate
            // from data_pre.max() with data, but if an anchor was added that
            // pre-dated data_pre.max() it wouldn't be committed to the db ruv
            // (even though it was in the in memory ruv).
            Box::new(added.iter().map(|cid| {
                debug!(added_cid = ?cid);
                cid.clone()
            }))
        } else {
            // We have been cleared during this txn, so everything in data is
            // added.
            Box::new(self.data.iter().map(|(cid, _)| {
                debug!(added_cid = ?cid);
                cid.clone()
            }))
        }
    }

    pub fn removed(&self) -> impl Iterator<Item = Cid> + '_ {
        let prev_bound = if self.added.is_none() {
            // We have been cleared during this txn, so everything in pre is
            // removed.
            Unbounded
        } else if let Some((min, _)) = self.data.first_key_value() {
            Excluded(min.clone())
        } else {
            // If empty, assume everything is removed.
            Unbounded
        };

        // iterate through our previous data to find what has been removed given
        // the ranges determined above.
        self.data_pre
            .range((Unbounded, prev_bound))
            .map(|(cid, _)| {
                debug!(removed_cid = ?cid);
                cid.clone()
            })
    }

    pub fn commit(self) {
        self.data.commit();
        self.ranged.commit();
    }
}

#[cfg(test)]
mod tests {
    use super::RangeDiffStatus;
    use super::ReplCidRange;
    use super::ReplicationUpdateVector;
    use std::collections::BTreeMap;
    use std::time::Duration;

    const UUID_A: uuid::Uuid = uuid::uuid!("13b530b0-efdd-4934-8fb7-9c35c8aab79e");
    const UUID_B: uuid::Uuid = uuid::uuid!("16327cf8-6a34-4a17-982c-b2eaa6d02d00");
    const UUID_C: uuid::Uuid = uuid::uuid!("2ed717e3-15be-41e6-b966-10a1f6d7ea1c");

    #[test]
    fn test_ruv_range_diff_1() {
        let ctx_a = BTreeMap::default();
        let ctx_b = BTreeMap::default();

        let result = ReplicationUpdateVector::range_diff(&ctx_a, &ctx_b);
        let expect = RangeDiffStatus::NoRUVOverlap;
        assert_eq!(result, expect);

        // Test the inverse.
        let result = ReplicationUpdateVector::range_diff(&ctx_b, &ctx_a);
        let expect = RangeDiffStatus::NoRUVOverlap;
        assert_eq!(result, expect);
    }

    #[test]
    fn test_ruv_range_diff_2() {
        let ctx_a = btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(1),
                ts_max: Duration::from_secs(3),
            }
        ));
        let ctx_b = BTreeMap::default();

        let result = ReplicationUpdateVector::range_diff(&ctx_a, &ctx_b);
        let expect = RangeDiffStatus::NoRUVOverlap;
        assert_eq!(result, expect);

        let result = ReplicationUpdateVector::range_diff(&ctx_b, &ctx_a);
        let expect = RangeDiffStatus::NoRUVOverlap;
        assert_eq!(result, expect);
    }

    #[test]
    fn test_ruv_range_diff_3() {
        let ctx_a = btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(1),
                ts_max: Duration::from_secs(3),
            }
        ));
        let ctx_b = btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(1),
                ts_max: Duration::from_secs(3),
            }
        ));

        let result = ReplicationUpdateVector::range_diff(&ctx_a, &ctx_b);
        let expect = RangeDiffStatus::Ok(BTreeMap::default());
        assert_eq!(result, expect);

        let result = ReplicationUpdateVector::range_diff(&ctx_b, &ctx_a);
        let expect = RangeDiffStatus::Ok(BTreeMap::default());
        assert_eq!(result, expect);
    }

    #[test]
    fn test_ruv_range_diff_4() {
        let ctx_a = btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(1),
                ts_max: Duration::from_secs(3),
            }
        ));
        let ctx_b = btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(1),
                ts_max: Duration::from_secs(4),
            }
        ));

        let result = ReplicationUpdateVector::range_diff(&ctx_a, &ctx_b);
        let expect = RangeDiffStatus::Ok(btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(3),
                ts_max: Duration::from_secs(4),
            }
        )));
        assert_eq!(result, expect);

        let result = ReplicationUpdateVector::range_diff(&ctx_b, &ctx_a);
        let expect = RangeDiffStatus::Ok(BTreeMap::default());
        assert_eq!(result, expect);
    }

    #[test]
    fn test_ruv_range_diff_5() {
        let ctx_a = btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(5),
                ts_max: Duration::from_secs(7),
            }
        ));
        let ctx_b = btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(1),
                ts_max: Duration::from_secs(4),
            }
        ));

        let result = ReplicationUpdateVector::range_diff(&ctx_a, &ctx_b);
        let expect = RangeDiffStatus::Unwilling {
            adv_range: btreemap!((
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(4),
                    ts_max: Duration::from_secs(5),
                }
            )),
        };
        assert_eq!(result, expect);

        let result = ReplicationUpdateVector::range_diff(&ctx_b, &ctx_a);
        let expect = RangeDiffStatus::Refresh {
            lag_range: btreemap!((
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(5),
                    ts_max: Duration::from_secs(4),
                }
            )),
        };
        assert_eq!(result, expect);
    }

    #[test]
    fn test_ruv_range_diff_6() {
        let ctx_a = btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(1),
                ts_max: Duration::from_secs(4),
            }
        ));
        let ctx_b = btreemap!(
            (
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(1),
                    ts_max: Duration::from_secs(3),
                }
            ),
            (
                UUID_B,
                ReplCidRange {
                    ts_min: Duration::from_secs(2),
                    ts_max: Duration::from_secs(4),
                }
            )
        );

        let result = ReplicationUpdateVector::range_diff(&ctx_a, &ctx_b);
        let expect = RangeDiffStatus::Ok(btreemap!((
            UUID_B,
            ReplCidRange {
                ts_min: Duration::ZERO,
                ts_max: Duration::from_secs(4),
            }
        )));
        assert_eq!(result, expect);

        let result = ReplicationUpdateVector::range_diff(&ctx_b, &ctx_a);
        let expect = RangeDiffStatus::Ok(btreemap!((
            UUID_A,
            ReplCidRange {
                ts_min: Duration::from_secs(3),
                ts_max: Duration::from_secs(4),
            }
        )));
        assert_eq!(result, expect);
    }

    #[test]
    fn test_ruv_range_diff_7() {
        let ctx_a = btreemap!(
            (
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(1),
                    ts_max: Duration::from_secs(4),
                }
            ),
            (
                UUID_C,
                ReplCidRange {
                    ts_min: Duration::from_secs(2),
                    ts_max: Duration::from_secs(5),
                }
            )
        );
        let ctx_b = btreemap!(
            (
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(1),
                    ts_max: Duration::from_secs(3),
                }
            ),
            (
                UUID_B,
                ReplCidRange {
                    ts_min: Duration::from_secs(2),
                    ts_max: Duration::from_secs(4),
                }
            ),
            (
                UUID_C,
                ReplCidRange {
                    ts_min: Duration::from_secs(3),
                    ts_max: Duration::from_secs(4),
                }
            )
        );

        let result = ReplicationUpdateVector::range_diff(&ctx_a, &ctx_b);
        let expect = RangeDiffStatus::Ok(btreemap!((
            UUID_B,
            ReplCidRange {
                ts_min: Duration::ZERO,
                ts_max: Duration::from_secs(4),
            }
        )));
        assert_eq!(result, expect);

        let result = ReplicationUpdateVector::range_diff(&ctx_b, &ctx_a);
        let expect = RangeDiffStatus::Ok(btreemap!(
            (
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(3),
                    ts_max: Duration::from_secs(4),
                }
            ),
            (
                UUID_C,
                ReplCidRange {
                    ts_min: Duration::from_secs(4),
                    ts_max: Duration::from_secs(5),
                }
            )
        ));
        assert_eq!(result, expect);
    }

    #[test]
    fn test_ruv_range_diff_8() {
        let ctx_a = btreemap!(
            (
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(4),
                    ts_max: Duration::from_secs(6),
                }
            ),
            (
                UUID_B,
                ReplCidRange {
                    ts_min: Duration::from_secs(1),
                    ts_max: Duration::from_secs(2),
                }
            )
        );
        let ctx_b = btreemap!(
            (
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(1),
                    ts_max: Duration::from_secs(2),
                }
            ),
            (
                UUID_B,
                ReplCidRange {
                    ts_min: Duration::from_secs(4),
                    ts_max: Duration::from_secs(6),
                }
            )
        );

        let result = ReplicationUpdateVector::range_diff(&ctx_a, &ctx_b);
        let expect = RangeDiffStatus::Critical {
            adv_range: btreemap!((
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(2),
                    ts_max: Duration::from_secs(4),
                }
            )),
            lag_range: btreemap!((
                UUID_B,
                ReplCidRange {
                    ts_min: Duration::from_secs(4),
                    ts_max: Duration::from_secs(2),
                }
            )),
        };
        assert_eq!(result, expect);

        let result = ReplicationUpdateVector::range_diff(&ctx_b, &ctx_a);
        let expect = RangeDiffStatus::Critical {
            adv_range: btreemap!((
                UUID_B,
                ReplCidRange {
                    ts_min: Duration::from_secs(2),
                    ts_max: Duration::from_secs(4),
                }
            )),
            lag_range: btreemap!((
                UUID_A,
                ReplCidRange {
                    ts_min: Duration::from_secs(4),
                    ts_max: Duration::from_secs(2),
                }
            )),
        };
        assert_eq!(result, expect);
    }
}