Skip to main content

weirdnet_sync/
merge.rs

1//! Last-writer-wins registers, OR-sets, edit-vs-delete, tombstone GC and a folder-cycle check.
2use crate::hlc::Hlc;
3use serde::{Deserialize, Serialize};
4use std::collections::{HashMap, HashSet};
5use std::hash::Hash;
6
7/// Tombstones may be dropped after 90 days, and only once every known peer cursor is past that delete.
8pub const TOMBSTONE_GC_MS: u64 = 90 * 24 * 60 * 60 * 1000;
9/// Losing versions of a conflict may be kept this long for the application's UI.
10pub const CONFLICT_KEEP_MS: u64 = 30 * 24 * 60 * 60 * 1000;
11
12/// Outcome of a last-writer-wins comparison by total HLC order.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Lww {
15    KeepLocal,
16    TakeRemote,
17    Equal,
18}
19
20/// Higher HLC (physical, counter, node id) wins. Equal clocks are [`Lww::Equal`].
21pub fn lww(local: &Hlc, remote: &Hlc) -> Lww {
22    match local.cmp_total(remote) {
23        std::cmp::Ordering::Greater => Lww::KeepLocal,
24        std::cmp::Ordering::Less => Lww::TakeRemote,
25        std::cmp::Ordering::Equal => Lww::Equal,
26    }
27}
28
29/// Concurrent edit vs delete: the edit wins. A delete whose HLC is strictly later than
30/// the edit wins (the tombstone stands). "Strictly later" is causal: `(physical, counter)`
31/// only, so a tie on those two is concurrent even if the node ids differ.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum EditOrDelete {
34    KeepEdit,
35    TakeDelete,
36}
37
38pub fn edit_vs_delete(edit: &Hlc, delete: &Hlc) -> EditOrDelete {
39    if delete.strictly_later_than(edit) { EditOrDelete::TakeDelete } else { EditOrDelete::KeepEdit }
40}
41
42/// True when this tombstone may be dropped: it is at least 90 days old *and* every known
43/// peer has already applied the delete (otherwise a late catch-up would resurrect the row).
44pub fn can_gc_tombstone(deleted: &Hlc, now_ms: u64, every_peer_cursor_past_delete: bool) -> bool {
45    every_peer_cursor_past_delete && now_ms.saturating_sub(deleted.physical_ms) >= TOMBSTONE_GC_MS
46}
47
48/// An observed-remove set. Concurrent adds of different elements keep both. A remove is a
49/// per-element tombstone and LWW against adds of that element (concurrent add vs remove:
50/// the add wins; a strictly later remove wins).
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct OrSet<T: Eq + Hash> {
53    adds: HashMap<T, Vec<Hlc>>,
54    tombs: HashMap<T, Hlc>,
55}
56
57impl<T: Eq + Hash + Clone> Default for OrSet<T> {
58    fn default() -> Self {
59        Self { adds: HashMap::new(), tombs: HashMap::new() }
60    }
61}
62
63impl<T: Eq + Hash + Clone> OrSet<T> {
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    pub fn add(&mut self, elem: T, hlc: Hlc) {
69        self.adds.entry(elem).or_default().push(hlc);
70    }
71
72    pub fn remove(&mut self, elem: T, hlc: Hlc) {
73        match self.tombs.get(&elem) {
74            Some(prev) if lww(prev, &hlc) != Lww::TakeRemote => {}
75            _ => {
76                self.tombs.insert(elem, hlc);
77            }
78        }
79    }
80
81    fn present(&self, elem: &T) -> bool {
82        let Some(adds) = self.adds.get(elem) else { return false };
83        let tomb = self.tombs.get(elem);
84        adds.iter().any(|a| match tomb {
85            None => true,
86            Some(d) => edit_vs_delete(a, d) == EditOrDelete::KeepEdit,
87        })
88    }
89
90    pub fn contains(&self, elem: &T) -> bool {
91        self.present(elem)
92    }
93
94    pub fn iter(&self) -> impl Iterator<Item = &T> {
95        self.adds.keys().filter(move |e| self.present(e))
96    }
97
98    pub fn values(&self) -> HashSet<T> {
99        self.iter().cloned().collect()
100    }
101
102    /// Merge another replica's add and remove sets into this one.
103    pub fn merge(&mut self, other: &Self) {
104        for (e, clocks) in &other.adds {
105            let slot = self.adds.entry(e.clone()).or_default();
106            for c in clocks {
107                if !slot.contains(c) {
108                    slot.push(c.clone());
109                }
110            }
111        }
112        for (e, h) in &other.tombs {
113            self.remove(e.clone(), h.clone());
114        }
115    }
116}
117
118/// If assigning `child`'s parent to `new_parent` would cycle, the application should move
119/// the later-HLC folder to the root instead.
120pub fn folder_cycle<I, F>(child: &I, new_parent: Option<&I>, mut parent_of: F) -> bool
121where
122    I: Eq + Hash + Clone,
123    F: FnMut(&I) -> Option<I>,
124{
125    let Some(start) = new_parent else { return false };
126    let mut seen = HashSet::new();
127    let mut cur = start.clone();
128    loop {
129        if &cur == child {
130            return true;
131        }
132        if !seen.insert(cur.clone()) {
133            return true;
134        }
135        match parent_of(&cur) {
136            Some(p) => cur = p,
137            None => return false,
138        }
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use crate::hlc::NodeId;
146
147    fn n(s: &str) -> NodeId {
148        NodeId::new(s)
149    }
150    fn h(ms: u64, c: u32, node: &str) -> Hlc {
151        Hlc::new(ms, c, n(node))
152    }
153
154    #[test]
155    fn lww_takes_the_later_clock() {
156        let a = h(10, 0, "a");
157        let b = h(20, 0, "b");
158        assert_eq!(lww(&a, &b), Lww::TakeRemote);
159        assert_eq!(lww(&b, &a), Lww::KeepLocal);
160        assert_eq!(lww(&a, &a), Lww::Equal);
161        // Independent fields: a rename and a move at different clocks both survive
162        // because the caller LWWs each field separately.
163        let title = lww(&h(10, 0, "a"), &h(11, 0, "b"));
164        let parent = lww(&h(12, 0, "a"), &h(11, 0, "b"));
165        assert_eq!(title, Lww::TakeRemote);
166        assert_eq!(parent, Lww::KeepLocal);
167    }
168
169    #[test]
170    fn concurrent_edit_beats_delete_later_delete_wins() {
171        let edit = h(100, 1, "a");
172        let concurrent = h(100, 1, "b");
173        let later = h(100, 2, "b");
174        assert_eq!(edit_vs_delete(&edit, &concurrent), EditOrDelete::KeepEdit);
175        assert_eq!(edit_vs_delete(&edit, &later), EditOrDelete::TakeDelete);
176        assert_eq!(edit_vs_delete(&later, &edit), EditOrDelete::KeepEdit);
177    }
178
179    #[test]
180    fn or_set_keeps_concurrent_adds_and_lww_a_tag_remove() {
181        let mut a = OrSet::new();
182        let mut b = OrSet::new();
183        a.add("work", h(10, 0, "a"));
184        b.add("home", h(10, 0, "b"));
185        a.merge(&b);
186        assert_eq!(a.values(), HashSet::from(["work", "home"]));
187
188        a.remove("work", h(10, 0, "c")); // concurrent with the add: add wins
189        assert!(a.contains(&"work"));
190        a.remove("work", h(11, 0, "c"));
191        assert!(!a.contains(&"work"));
192        assert!(a.contains(&"home"));
193    }
194
195    #[test]
196    fn tombstone_gc_waits_for_age_and_cursors() {
197        let t = h(1000, 0, "a");
198        assert!(!can_gc_tombstone(&t, 1000 + TOMBSTONE_GC_MS - 1, true));
199        assert!(!can_gc_tombstone(&t, 1000 + TOMBSTONE_GC_MS, false));
200        assert!(can_gc_tombstone(&t, 1000 + TOMBSTONE_GC_MS, true));
201        assert_eq!(CONFLICT_KEEP_MS, 30 * 24 * 60 * 60 * 1000);
202    }
203
204    #[test]
205    fn folder_cycle_is_detected_and_a_root_move_is_not() {
206        let parents = HashMap::from([("b", "a"), ("c", "b")]);
207        let parent_of = |id: &&str| parents.get(*id).copied();
208        assert!(folder_cycle(&"a", Some(&"c"), parent_of));
209        assert!(!folder_cycle(&"a", Some(&"d"), parent_of));
210        assert!(!folder_cycle(&"a", None, parent_of));
211    }
212}