forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrdt.rs
More file actions
1664 lines (1494 loc) · 52.5 KB
/
Copy pathcrdt.rs
File metadata and controls
1664 lines (1494 loc) · 52.5 KB
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
//! Conflict-free Replicated Data Types (CRDTs) for Nulang.
//!
//! CRDTs enable distributed actors to share mutable state without locks,
//! consensus, or coordination. All changes merge automatically and converge
//! to the same result.
//!
//! This module provides the core [`Crdt`] trait and five concrete
//! implementations:
//!
//! | Type | Operations | Semantics |
//! |---------------|--------------------|-------------------------------------|
//! | [`GCounter`] | increment | Grow-only counter (monotonic) |
//! | [`PNCounter`] | increment, decrement | Counter that can go negative |
//! | [`GSet`] | insert | Grow-only set |
//! | [`ORSet`] | add, remove | Add-wins observed-remove set |
//! | [`AWORSet`] | add, remove | Timestamp-based add-wins OR set |
//!
//! # Mathematical Foundations
//!
//! Every CRDT satisfies three algebraic properties:
//!
//! **Associativity** — `merge(a, merge(b, c)) == merge(merge(a, b), c)`
//! Merging can be grouped arbitrarily; the order of pairwise merges does not
//! matter. This allows tree-structured or pipelined replication topologies.
//!
//! **Commutativity** — `merge(a, b) == merge(b, a)`
//! The merge order is irrelevant. This is the key property that eliminates
//! the need for consensus: replicas can merge in any order and still agree.
//!
//! **Idempotency** — `merge(a, a) == a`
//! Merging a replica with itself is a no-op. This makes retries safe and
//! deduplication unnecessary.
//!
//! Together, these properties form a **join-semilattice** where `merge` is the
//! least-upper-bound (LUB) operator and the CRDT state is ordered by the
//! "happens-before" relation. The LUB of any two states always exists and is
//! unique, guaranteeing convergence.
//!
//! # Delta-state replication
//!
//! Every CRDT additionally provides `delta_since(&self, base) -> Option<Self>`:
//! the minimal state that, when merged into any replica that already contains
//! `base`, produces the same result as merging this full state. Formally, for
//! any replica `r` with `base ⊑ r`:
//!
//! ```text
//! r.merge(self.delta_since(base)) == r.merge(self)
//! ```
//!
//! A delta is itself a valid CRDT state (serialized with the usual
//! `to_bytes`), so receivers merge it through the same code path as a
//! full-state merge. `None` means nothing changed since `base`. Deltas are
//! only meaningful to a peer that already holds `base`; a peer seeing an
//! entry for the first time must receive a full-state snapshot instead
//! (the join fallback, see `CrdtManager::generate_delta_sync_ops`).
use std::collections::{HashMap, HashSet};
// =============================================================================
// Core CRDT Trait
// =============================================================================
/// The core trait for all Conflict-free Replicated Data Types.
///
/// Every CRDT must support:
/// - [`merge`](Crdt::merge): combine two replicas into one (must be associative, commutative, idempotent)
/// - [`value`](Crdt::value): read the current logical value
/// - [`delta_since`](Crdt::delta_since): compute a minimal delta-state relative to a base
/// - [`to_bytes`](Crdt::to_bytes) / [`from_bytes`](Crdt::from_bytes): serialize for network transmission
///
/// # Type Parameters
///
/// - `Value`: The logical (user-facing) type that this CRDT represents.
/// This is often different from the internal replica state. For example,
/// a `PNCounter` internally stores two `GCounter`s but its logical value
/// is `i64`.
pub trait Crdt: Clone {
/// The logical value type that this CRDT represents.
///
/// This is the type returned by [`value`](Crdt::value) and is the
/// user-facing abstraction over the internal replicated state.
type Value;
/// Merge another replica into this one.
///
/// After `self.merge(other)`, `self` contains the combined state
/// of both replicas. This operation must be:
///
/// - **Associative**: `a.merge(b.merge(c)) == a.merge(b).merge(c)`
/// - **Commutative**: `a.merge(b) == b.merge(a)`
/// - **Idempotent**: `a.merge(a) == a`
fn merge(&mut self, other: &Self);
/// Read the current logical value.
fn value(&self) -> Self::Value;
/// Compute the delta-state relative to `base`.
///
/// Returns the minimal state that, when merged into any replica that
/// already contains `base`, produces the same result as merging the full
/// current state. `None` when nothing changed since `base`.
fn delta_since(&self, base: &Self) -> Option<Self>;
/// Serialize this CRDT to bytes for network transmission.
fn to_bytes(&self) -> Vec<u8>;
/// Deserialize a CRDT from bytes.
fn from_bytes(bytes: &[u8]) -> Option<Self>;
}
// =============================================================================
// Serialization Helpers
// =============================================================================
#[inline]
fn push_u64(buf: &mut Vec<u8>, v: u64) {
buf.extend_from_slice(&v.to_be_bytes());
}
#[inline]
fn push_u32(buf: &mut Vec<u8>, v: u32) {
buf.extend_from_slice(&v.to_be_bytes());
}
#[inline]
fn read_u64(bytes: &[u8], pos: usize) -> Option<(u64, usize)> {
let end = pos.checked_add(8)?;
if end > bytes.len() {
return None;
}
let mut arr = [0u8; 8];
arr.copy_from_slice(&bytes[pos..end]);
Some((u64::from_be_bytes(arr), end))
}
#[inline]
fn read_u32(bytes: &[u8], pos: usize) -> Option<(u32, usize)> {
let end = pos.checked_add(4)?;
if end > bytes.len() {
return None;
}
let mut arr = [0u8; 4];
arr.copy_from_slice(&bytes[pos..end]);
Some((u32::from_be_bytes(arr), end))
}
#[inline]
fn push_string(buf: &mut Vec<u8>, s: &str) {
push_u32(buf, s.len() as u32);
buf.extend_from_slice(s.as_bytes());
}
#[inline]
fn read_string(bytes: &[u8], pos: usize) -> Option<(String, usize)> {
let (len, pos) = read_u32(bytes, pos)?;
let len = len as usize;
let end = pos.checked_add(len)?;
if end > bytes.len() {
return None;
}
let s = String::from_utf8(bytes[pos..end].to_vec()).ok()?;
Some((s, end))
}
// =============================================================================
// GCounter
// =============================================================================
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GCounter {
pub counts: HashMap<u64, u64>,
pub node_id: u64,
}
impl GCounter {
pub fn new(node_id: u64) -> Self {
Self {
counts: HashMap::new(),
node_id,
}
}
pub fn increment(&mut self) {
*self.counts.entry(self.node_id).or_insert(0) += 1;
}
pub fn increment_by(&mut self, delta: u64) {
*self.counts.entry(self.node_id).or_insert(0) += delta;
}
pub fn value(&self) -> u64 {
self.counts.values().sum()
}
/// Delta relative to `base`: only the per-node entries that grew since
/// `base`. `None` when no entry changed.
pub fn delta_since(&self, base: &Self) -> Option<Self> {
let mut counts = HashMap::new();
for (node_id, count) in &self.counts {
let base_count = base.counts.get(node_id).copied().unwrap_or(0);
if *count > base_count {
counts.insert(*node_id, *count);
}
}
if counts.is_empty() {
None
} else {
Some(Self {
counts,
node_id: self.node_id,
})
}
}
}
impl Crdt for GCounter {
type Value = u64;
fn merge(&mut self, other: &Self) {
for (node_id, count) in &other.counts {
let entry = self.counts.entry(*node_id).or_insert(0);
*entry = (*entry).max(*count);
}
}
fn value(&self) -> Self::Value {
self.value()
}
fn delta_since(&self, base: &Self) -> Option<Self> {
GCounter::delta_since(self, base)
}
fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
push_u64(&mut buf, self.node_id);
push_u32(&mut buf, self.counts.len() as u32);
for (node_id, count) in &self.counts {
push_u64(&mut buf, *node_id);
push_u64(&mut buf, *count);
}
buf
}
fn from_bytes(bytes: &[u8]) -> Option<Self> {
let (node_id, pos) = read_u64(bytes, 0)?;
let (num_entries, mut pos) = read_u32(bytes, pos)?;
let mut counts = HashMap::new();
for _ in 0..num_entries {
let (nid, p) = read_u64(bytes, pos)?;
let (cnt, p) = read_u64(bytes, p)?;
counts.insert(nid, cnt);
pos = p;
}
Some(Self { counts, node_id })
}
}
// =============================================================================
// PNCounter
// =============================================================================
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PNCounter {
pub increments: GCounter,
pub decrements: GCounter,
}
impl PNCounter {
pub fn new(node_id: u64) -> Self {
Self {
increments: GCounter::new(node_id),
decrements: GCounter::new(node_id),
}
}
pub fn increment(&mut self) {
self.increments.increment();
}
pub fn decrement(&mut self) {
self.decrements.increment();
}
pub fn increment_by(&mut self, delta: u64) {
self.increments.increment_by(delta);
}
pub fn decrement_by(&mut self, delta: u64) {
self.decrements.increment_by(delta);
}
pub fn value(&self) -> i64 {
self.increments.value() as i64 - self.decrements.value() as i64
}
/// Delta relative to `base`: the deltas of both underlying GCounters.
/// `None` when neither side changed.
pub fn delta_since(&self, base: &Self) -> Option<Self> {
match (
self.increments.delta_since(&base.increments),
self.decrements.delta_since(&base.decrements),
) {
(None, None) => None,
(inc, dec) => Some(Self {
increments: inc.unwrap_or_else(|| GCounter::new(self.increments.node_id)),
decrements: dec.unwrap_or_else(|| GCounter::new(self.decrements.node_id)),
}),
}
}
}
impl Crdt for PNCounter {
type Value = i64;
fn merge(&mut self, other: &Self) {
self.increments.merge(&other.increments);
self.decrements.merge(&other.decrements);
}
fn value(&self) -> Self::Value {
self.value()
}
fn delta_since(&self, base: &Self) -> Option<Self> {
PNCounter::delta_since(self, base)
}
fn to_bytes(&self) -> Vec<u8> {
let mut buf = self.increments.to_bytes();
buf.extend_from_slice(&self.decrements.to_bytes());
buf
}
fn from_bytes(bytes: &[u8]) -> Option<Self> {
let (node_id, pos) = read_u64(bytes, 0)?;
let (num_entries, _) = read_u32(bytes, pos)?;
// `num_entries` comes off the wire: validate the split point before
// slicing so a crafted payload cannot panic the scheduler thread.
// The decrement half needs no explicit bound — once `increment_len`
// is in range the second slice is valid, and `GCounter::from_bytes`
// bounds-checks its own contents.
let increment_len = (num_entries as usize).checked_mul(16)?.checked_add(12)?;
if increment_len > bytes.len() {
return None;
}
let inc_bytes = &bytes[0..increment_len];
let dec_bytes = &bytes[increment_len..];
let increments = GCounter::from_bytes(inc_bytes)?;
let decrements = GCounter::from_bytes(dec_bytes)?;
if increments.node_id != node_id || decrements.node_id != node_id {
return None;
}
Some(Self {
increments,
decrements,
})
}
}
// =============================================================================
// GSet
// =============================================================================
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GSet<T: Clone + Eq + std::hash::Hash> {
pub elements: HashSet<T>,
}
impl<T: Clone + Eq + std::hash::Hash> GSet<T> {
pub fn new() -> Self {
Self {
elements: HashSet::new(),
}
}
pub fn insert(&mut self, element: T) -> bool {
self.elements.insert(element)
}
pub fn contains(&self, element: &T) -> bool {
self.elements.contains(element)
}
pub fn len(&self) -> usize {
self.elements.len()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn value(&self) -> &HashSet<T> {
&self.elements
}
/// Delta relative to `base`: the elements added since `base`.
/// `None` when the set did not grow.
pub fn delta_since(&self, base: &Self) -> Option<Self> {
let elements: HashSet<T> = self.elements.difference(&base.elements).cloned().collect();
if elements.is_empty() {
None
} else {
Some(Self { elements })
}
}
}
impl<T: Clone + Eq + std::hash::Hash> Default for GSet<T> {
fn default() -> Self {
Self::new()
}
}
impl Crdt for GSet<String> {
type Value = HashSet<String>;
fn merge(&mut self, other: &Self) {
self.elements.extend(other.elements.iter().cloned());
}
fn value(&self) -> Self::Value {
self.elements.clone()
}
fn delta_since(&self, base: &Self) -> Option<Self> {
GSet::delta_since(self, base)
}
fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
push_u32(&mut buf, self.elements.len() as u32);
for elem in &self.elements {
push_string(&mut buf, elem);
}
buf
}
fn from_bytes(bytes: &[u8]) -> Option<Self> {
let (num_elements, mut pos) = read_u32(bytes, 0)?;
let mut elements = HashSet::new();
for _ in 0..num_elements {
let (s, p) = read_string(bytes, pos)?;
elements.insert(s);
pos = p;
}
Some(Self { elements })
}
}
// =============================================================================
// ORSet
// =============================================================================
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Tag {
pub node_id: u32,
pub counter: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ORSet<T: Clone + Eq + std::hash::Hash> {
pub entries: HashMap<T, HashSet<Tag>>,
/// Tags removed by `remove`, each stamped with the removing node's
/// logical time (a `LamportTime{counter, node_id}` where `counter` comes
/// from the removing node's matrix clock). Subtracted on merge so
/// removals replicate and removed elements never resurrect (same role as
/// `AWORSet::removed`). The stamp is what lets the causal-stability
/// watermark decide when the tombstone may be garbage-collected.
pub removed: HashMap<Tag, LamportTime>,
pub tag_counter: u64,
pub node_id: u64,
/// Per-replica observation matrix used to compute the causal-stability
/// watermark for tombstone GC.
pub matrix: MatrixClock,
}
impl<T: Clone + Eq + std::hash::Hash> ORSet<T> {
pub fn new(node_id: u64) -> Self {
Self {
entries: HashMap::new(),
removed: HashMap::new(),
tag_counter: 0,
node_id,
matrix: MatrixClock::new(node_id),
}
}
fn fresh_tag(&mut self) -> Tag {
let tag = Tag {
node_id: self.node_id as u32,
counter: self.tag_counter as u32,
};
self.tag_counter = self.tag_counter.wrapping_add(1);
tag
}
pub fn add(&mut self, element: T) {
let tag = self.fresh_tag();
self.entries
.entry(element)
.or_insert_with(HashSet::new)
.insert(tag);
}
pub fn remove(&mut self, element: &T) {
// Tombstone the observed tags instead of forgetting them: on merge,
// replicas that still hold these tags will subtract them. The removal
// is a distinct causal event, so every tombstoned tag is stamped with
// one fresh matrix tick — without this the removal would be invisible
// to observation vectors (the tags are reused, not re-created).
if let Some(tags) = self.entries.remove(element) {
let rt = self.matrix.tick_local();
for tag in tags {
self.removed.insert(
tag,
LamportTime {
counter: rt,
node_id: self.node_id,
},
);
}
}
}
pub fn contains(&self, element: &T) -> bool {
self.entries
.get(element)
.map_or(false, |tags| !tags.is_empty())
}
pub fn value(&self) -> HashSet<T> {
self.entries
.iter()
.filter(|(_, tags)| !tags.is_empty())
.map(|(elem, _)| elem.clone())
.collect()
}
pub fn len(&self) -> usize {
self.value().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Delta relative to `base`: for each element, the tags not present in
/// `base`, plus the tombstones not present in `base`. Elements with no
/// new tags are omitted. `None` when neither tags nor tombstones
/// changed. The current `tag_counter` rides along so merging the delta
/// advances the receiver's counter exactly like a full-state merge.
pub fn delta_since(&self, base: &Self) -> Option<Self> {
let mut entries = HashMap::new();
for (element, tags) in &self.entries {
let new_tags: HashSet<Tag> = tags
.iter()
.filter(|t| base.entries.get(element).map_or(true, |bt| !bt.contains(t)))
.copied()
.collect();
if !new_tags.is_empty() {
entries.insert(element.clone(), new_tags);
}
}
let removed: HashMap<Tag, LamportTime> = self
.removed
.iter()
.filter(|(tag, _)| !base.removed.contains_key(tag))
.map(|(tag, rt)| (*tag, *rt))
.collect();
if entries.is_empty() && removed.is_empty() {
None
} else {
Some(Self {
entries,
removed,
tag_counter: self.tag_counter,
node_id: self.node_id,
matrix: self.matrix.clone(),
})
}
}
/// Garbage collect tombstones that are causally stable: a tombstone
/// stamped `(counter: t, node_id: n)` is dropped once every healthy
/// replica has observed logical time `t` from `n` (i.e.
/// `watermark[n] >= t`).
pub fn gc_tombstones(&mut self, watermark: &HashMap<u64, u64>) {
self.removed
.retain(|_, rt| rt.counter > watermark.get(&rt.node_id).copied().unwrap_or(0));
}
}
impl Crdt for ORSet<String> {
type Value = HashSet<String>;
fn merge(&mut self, other: &Self) {
// Tombstones first: a tag removed on either side must not survive.
for tags in self.entries.values_mut() {
tags.retain(|t| !other.removed.contains_key(t));
}
// Merge tombstones, keeping the latest removal stamp per tag.
for (tag, rt) in &other.removed {
match self.removed.get(tag) {
Some(existing) if *rt <= *existing => {}
_ => {
self.removed.insert(*tag, *rt);
}
}
}
for (element, tags) in &other.entries {
let entry = self
.entries
.entry(element.clone())
.or_insert_with(HashSet::new);
for tag in tags {
if !self.removed.contains_key(tag) {
entry.insert(*tag);
}
}
}
self.tag_counter = self.tag_counter.max(other.tag_counter);
self.matrix.merge(&other.matrix);
}
fn value(&self) -> Self::Value {
self.value()
}
fn delta_since(&self, base: &Self) -> Option<Self> {
ORSet::delta_since(self, base)
}
fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
push_u64(&mut buf, self.node_id);
push_u64(&mut buf, self.tag_counter);
push_u32(&mut buf, self.entries.len() as u32);
for (element, tags) in &self.entries {
push_string(&mut buf, element);
push_u32(&mut buf, tags.len() as u32);
for tag in tags {
push_u64(
&mut buf,
((tag.node_id as u64) << 32) | (tag.counter as u64),
);
}
}
push_u32(&mut buf, self.removed.len() as u32);
for (tag, rt) in &self.removed {
push_u64(
&mut buf,
((tag.node_id as u64) << 32) | (tag.counter as u64),
);
push_u64(&mut buf, rt.counter);
push_u64(&mut buf, rt.node_id);
}
self.matrix.to_bytes(&mut buf);
buf
}
fn from_bytes(bytes: &[u8]) -> Option<Self> {
let (node_id, pos) = read_u64(bytes, 0)?;
let (tag_counter, pos) = read_u64(bytes, pos)?;
let (num_elements, mut pos) = read_u32(bytes, pos)?;
let mut entries = HashMap::new();
for _ in 0..num_elements {
let (element, p) = read_string(bytes, pos)?;
let (tag_count, mut p) = read_u32(bytes, p)?;
let mut tags = HashSet::new();
for _ in 0..tag_count {
let (tag_val, p2) = read_u64(bytes, p)?;
tags.insert(Tag {
node_id: (tag_val >> 32) as u32,
counter: tag_val as u32,
});
p = p2;
}
entries.insert(element, tags);
pos = p;
}
let (num_removed, mut pos) = read_u32(bytes, pos)?;
let mut removed = HashMap::new();
for _ in 0..num_removed {
let (tag_val, p) = read_u64(bytes, pos)?;
pos = p;
let (cnt, p) = read_u64(bytes, pos)?;
pos = p;
let (nid, p) = read_u64(bytes, pos)?;
pos = p;
removed.insert(
Tag {
node_id: (tag_val >> 32) as u32,
counter: tag_val as u32,
},
LamportTime {
counter: cnt,
node_id: nid,
},
);
}
let matrix = MatrixClock::from_bytes(bytes, &mut pos)?;
Some(Self {
entries,
removed,
tag_counter,
node_id,
matrix,
})
}
}
// =============================================================================
// LamportTime + LamportClock
// =============================================================================
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LamportTime {
pub counter: u64,
pub node_id: u64,
}
impl LamportTime {
pub fn new(counter: u64, node_id: u64) -> Self {
Self { counter, node_id }
}
pub fn is_greater_than(&self, other: &LamportTime) -> bool {
self.counter > other.counter
|| (self.counter == other.counter && self.node_id > other.node_id)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LamportClock {
pub node_id: u64,
pub counter: u64,
}
impl LamportClock {
pub fn new(node_id: u64) -> Self {
Self {
node_id,
counter: 0,
}
}
pub fn tick(&mut self) -> LamportTime {
self.counter += 1;
LamportTime {
counter: self.counter,
node_id: self.node_id,
}
}
}
// =============================================================================
// MatrixClock — causal-stability watermark for tombstone GC
// =============================================================================
/// A per-CRDT matrix clock used to compute a causal-stability watermark for
/// tombstone garbage collection.
///
/// `matrix[P][N]` is the maximum logical time that node `P` has observed from
/// source node `N`; its own entry `matrix[L][L]` advances on every **local
/// mutation** — adds *and* removes — so removals are causally visible as
/// distinct events (an ORSet removal reuses existing tags, so it must be
/// timestamped or it is invisible to any observation vector).
///
/// The clock travels inside the CRDT state that is synced, so a replica that
/// merges state from `P` both learns what `P` itself observed (the `matrix[P]`
/// row) and absorbs `P`'s observations into its own row.
///
/// A tombstone created by node `N` at logical time `t` is **causally stable**
/// once every healthy replica's row satisfies `matrix[R][N] >= t`; only then
/// may it be dropped without risking element resurrection.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MatrixClock {
pub local_node: u64,
/// peer node -> (source node -> max logical time observed).
pub matrix: HashMap<u64, HashMap<u64, u64>>,
}
impl MatrixClock {
pub fn new(local_node: u64) -> Self {
Self {
local_node,
matrix: HashMap::new(),
}
}
/// Advance the local node's own counter (one tick per local mutation) and
/// return the new value.
pub fn tick_local(&mut self) -> u64 {
let row = self.matrix.entry(self.local_node).or_default();
let e = row.entry(self.local_node).or_insert(0);
*e = e.wrapping_add(1);
*e
}
/// Merge another replica's matrix clock into ours.
pub fn merge(&mut self, other: &Self) {
for (peer, row) in &other.matrix {
{
let local = self.matrix.entry(self.local_node).or_default();
for (src, t) in row {
let e = local.entry(*src).or_insert(0);
*e = (*e).max(*t);
}
}
{
let dest = self.matrix.entry(*peer).or_default();
for (src, t) in row {
let e = dest.entry(*src).or_insert(0);
*e = (*e).max(*t);
}
}
}
}
/// The causal-stability watermark: for each source node `N`, the maximum
/// logical time from `N` that **every** replica in `{local} ∪ healthy`
/// has observed. A healthy replica with no recorded row is treated as
/// having observed nothing (so a fresh/partitioned peer blocks GC), and
/// the local node is always considered.
pub fn watermark(&self, healthy: &[u64]) -> HashMap<u64, u64> {
let mut sources: Vec<u64> = Vec::new();
for row in self.matrix.values() {
for s in row.keys() {
if !sources.contains(s) {
sources.push(*s);
}
}
}
let mut wm = HashMap::new();
for src in sources {
let local_t = self
.matrix
.get(&self.local_node)
.and_then(|r| r.get(&src))
.copied()
.unwrap_or(0);
let mut min = local_t;
for peer in healthy {
let t = self
.matrix
.get(peer)
.and_then(|r| r.get(&src))
.copied()
.unwrap_or(0);
min = min.min(t);
}
wm.insert(src, min);
}
wm
}
/// Re-root this clock to a different local node id.
///
/// Used when a replica is created from an incoming payload (or a persisted
/// snapshot): the parsed clock's `local_node` is the *sender's* id. After
/// re-rooting, the new node absorbs every observation the payload carried
/// into its own row and keeps each peer's row, so its view is attributed
/// to the correct node from then on.
pub fn reroot(&mut self, new_local: u64) {
if self.local_node == new_local {
return;
}
let old = std::mem::replace(self, MatrixClock::new(new_local));
self.merge(&old);
}
/// Drop rows for peers that are no longer healthy (keeps the clock from
/// growing without bound as nodes churn). The local row is always kept.
pub fn prune(&mut self, healthy: &[u64]) {
self.matrix
.retain(|peer, _| *peer == self.local_node || healthy.contains(peer));
}
pub(crate) fn to_bytes(&self, buf: &mut Vec<u8>) {
push_u64(buf, self.local_node);
let mut peers: Vec<u64> = self.matrix.keys().copied().collect();
peers.sort_unstable();
push_u32(buf, peers.len() as u32);
for peer in peers {
let row = &self.matrix[&peer];
push_u64(buf, peer);
let mut srcs: Vec<u64> = row.keys().copied().collect();
srcs.sort_unstable();
push_u32(buf, srcs.len() as u32);
for src in srcs {
push_u64(buf, src);
push_u64(buf, row[&src]);
}
}
}
pub(crate) fn from_bytes(bytes: &[u8], pos: &mut usize) -> Option<Self> {
let (local_node, p) = read_u64(bytes, *pos)?;
*pos = p;
let (num_peers, p) = read_u32(bytes, *pos)?;
*pos = p;
let mut matrix = HashMap::new();
for _ in 0..num_peers {
let (peer, p) = read_u64(bytes, *pos)?;
*pos = p;
let (num_srcs, p) = read_u32(bytes, *pos)?;
*pos = p;
let mut row = HashMap::new();
for _ in 0..num_srcs {
let (src, p) = read_u64(bytes, *pos)?;
*pos = p;
let (t, p) = read_u64(bytes, *pos)?;
*pos = p;
row.insert(src, t);
}
matrix.insert(peer, row);
}
Some(Self { local_node, matrix })
}
}
// =============================================================================
// AWORSet
// =============================================================================
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AWORSet<T: Clone + Eq + std::hash::Hash> {
pub entries: HashMap<T, LamportTime>,
pub removed: HashMap<T, LamportTime>,
pub clock: LamportClock,
/// Per-replica observation matrix used to compute the causal-stability
/// watermark for tombstone GC. Local add/remove timestamps are drawn
/// from it so removals are causally comparable to the watermark.
pub matrix: MatrixClock,
}
impl<T: Clone + Eq + std::hash::Hash> AWORSet<T> {
pub fn new(node_id: u64) -> Self {
Self {
entries: HashMap::new(),
removed: HashMap::new(),
clock: LamportClock::new(node_id),
matrix: MatrixClock::new(node_id),
}
}
pub fn add(&mut self, element: T) {
let ts = self.matrix.tick_local();
self.clock.counter = self.clock.counter.max(ts);
self.entries.insert(
element,
LamportTime {
counter: ts,
node_id: self.clock.node_id,
},
);
}
pub fn remove(&mut self, element: &T) {
let ts = self.matrix.tick_local();
self.clock.counter = self.clock.counter.max(ts);
self.removed.insert(
element.clone(),
LamportTime {
counter: ts,
node_id: self.clock.node_id,
},
);
}
pub fn contains(&self, element: &T) -> bool {
match (self.entries.get(element), self.removed.get(element)) {
(Some(add_ts), Some(rem_ts)) => add_ts.is_greater_than(rem_ts),
(Some(_), None) => true,
(None, _) => false,
}
}
pub fn value(&self) -> HashSet<T> {
self.entries
.keys()
.filter(|e| self.contains(e))
.cloned()
.collect()
}
pub fn len(&self) -> usize {
self.value().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Delta relative to `base`: add/remove timestamps strictly newer than
/// `base`'s for the same element. `None` when nothing changed. The
/// current clock rides along so merging the delta advances the
/// receiver's clock exactly like a full-state merge.
pub fn delta_since(&self, base: &Self) -> Option<Self> {
let mut entries = HashMap::new();
for (element, ts) in &self.entries {
if base.entries.get(element).map_or(true, |bts| ts > bts) {
entries.insert(element.clone(), *ts);
}
}
let mut removed = HashMap::new();
for (element, ts) in &self.removed {
if base.removed.get(element).map_or(true, |bts| ts > bts) {
removed.insert(element.clone(), *ts);