Skip to main content

logicaffeine_data/crdt/causal/
context.rs

1//! Dot Context - Tracks seen events for OR-Set semantics.
2//!
3//! DotContext combines a VClock with a "cloud" of non-contiguous dots.
4
5use super::super::replica::ReplicaId;
6use super::dot::Dot;
7use super::vclock::VClock;
8use serde::{Deserialize, Serialize};
9use std::collections::HashSet;
10
11/// Tracks which events have been seen in the system.
12///
13/// The DotContext maintains a VClock for contiguous sequences and a "cloud"
14/// set for dots that arrive out of order. When gaps are filled, dots are
15/// compacted from the cloud into the clock.
16#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
17pub struct DotContext {
18    /// Contiguous event counters per replica
19    clock: VClock,
20    /// Non-contiguous dots (arrived out of order)
21    cloud: HashSet<Dot>,
22}
23
24impl DotContext {
25    /// Create a new empty context.
26    pub fn new() -> Self {
27        Self::default()
28    }
29
30    /// Generate the next dot for a replica and mark it as seen.
31    pub fn next(&mut self, replica: ReplicaId) -> Dot {
32        let counter = self.clock.increment(replica);
33        Dot::new(replica, counter)
34    }
35
36    /// Check if a dot has been seen (either in clock or cloud).
37    pub fn has_seen(&self, dot: &Dot) -> bool {
38        self.clock.get(dot.replica) >= dot.counter || self.cloud.contains(dot)
39    }
40
41    /// Add a dot to the context.
42    ///
43    /// If the dot is contiguous with the clock, increment the clock.
44    /// Otherwise, add it to the cloud. Then attempt to compact.
45    pub fn add(&mut self, dot: Dot) {
46        if dot.counter == self.clock.get(dot.replica) + 1 {
47            // Contiguous - add to clock
48            self.clock.increment(dot.replica);
49            // Compact: pull any waiting dots from cloud
50            self.compact_replica(dot.replica);
51        } else if dot.counter > self.clock.get(dot.replica) {
52            // Out of order - add to cloud
53            self.cloud.insert(dot);
54        }
55        // If dot.counter <= clock.get(dot.replica), we've already seen it
56    }
57
58    /// Compact the cloud for a specific replica.
59    fn compact_replica(&mut self, replica: ReplicaId) {
60        loop {
61            let next_counter = self.clock.get(replica) + 1;
62            let next_dot = Dot::new(replica, next_counter);
63            if self.cloud.remove(&next_dot) {
64                self.clock.increment(replica);
65            } else {
66                break;
67            }
68        }
69    }
70
71    /// Compact all replicas in the cloud.
72    fn compact(&mut self) {
73        let replicas: Vec<ReplicaId> = self.cloud.iter().map(|d| d.replica).collect();
74        for replica in replicas {
75            self.compact_replica(replica);
76        }
77    }
78
79    /// Merge another context into this one.
80    pub fn merge(&mut self, other: &Self) {
81        self.clock.merge_vclock(&other.clock);
82        for &dot in &other.cloud {
83            if !self.has_seen(&dot) {
84                self.cloud.insert(dot);
85            }
86        }
87        self.compact();
88    }
89
90    /// Get the underlying vector clock.
91    pub fn clock(&self) -> &VClock {
92        &self.clock
93    }
94
95    /// How many distinct events this context has observed — every replica's contiguous counter plus
96    /// the out-of-order dots. An event that has seen another has observed strictly more, so this is a
97    /// Lamport clock over the events the context tracks.
98    pub fn observed(&self) -> u64 {
99        self.clock.total() + self.cloud.len() as u64
100    }
101
102    /// Get the version as a VClock clone (for DeltaCrdt).
103    pub fn version(&self) -> VClock {
104        self.clock.clone()
105    }
106}
107
108#[cfg(test)]
109#[path = "../../../../logicaffeine_tests/unit/logicaffeine_data/crdt/causal/context/tests.rs"]
110mod tests;