Skip to main content

capsule_core/metadata/crdt/
lww.rs

1//! Last-writer-wins register with a bounded *superseded* log (SSoT: [Metadata —
2//! Surfacing Concurrent Edits]).
3//!
4//! Single-value collaborative fields (caption, rating) are LWW registers keyed by a signed
5//! timestamp with the writing `device_id` as the lexicographic tiebreaker. A plain LWW
6//! loses one side of a tied edit silently; Capsule instead keeps the winner authoritative
7//! **and** preserves displaced values in a `superseded` log (capped, oldest evicted), so a
8//! buggy client clobbering another device's edit becomes an explicit, recoverable surface.
9//!
10//! [Metadata — Surfacing Concurrent Edits]: https://docs/design/metadata/#surfacing-concurrent-edits
11
12use serde::{Deserialize, Serialize};
13use uuid::Uuid;
14
15/// Default cap on the superseded log (see Metadata: `superseded_captions ≤ 16`).
16pub const SUPERSEDED_CAP: usize = 16;
17
18/// A timestamped, device-attributed value.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Stamped<T> {
21    /// The value.
22    pub value: T,
23    /// RFC3339 write time.
24    pub ts: String,
25    /// Writing device id (the tiebreaker).
26    pub by: Uuid,
27}
28
29/// An LWW register that also retains displaced values, newest-superseded first.
30#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
31pub struct Lww<T: Clone + PartialEq> {
32    /// The current authoritative value, if any.
33    pub current: Option<Stamped<T>>,
34    /// Displaced values (most recently superseded first), capped at [`SUPERSEDED_CAP`].
35    pub superseded: Vec<Stamped<T>>,
36}
37
38/// Order two candidates: later timestamp wins; ties break on the larger device id.
39/// `None` if a timestamp is unparseable (caller treats as a structural reject upstream).
40fn beats(a: &Stamped<impl Clone>, b: &Stamped<impl Clone>) -> Option<bool> {
41    let ta = a.ts.parse::<jiff::Timestamp>().ok()?;
42    let tb = b.ts.parse::<jiff::Timestamp>().ok()?;
43    Some((ta, a.by) > (tb, b.by))
44}
45
46impl<T: Clone + PartialEq> Lww<T> {
47    /// An empty register.
48    pub fn new() -> Self {
49        Self {
50            current: None,
51            superseded: Vec::new(),
52        }
53    }
54
55    /// Apply a write. The higher `(ts, device_id)` becomes current; the loser is recorded
56    /// in `superseded` (capped). Returns `false` if a timestamp was unparseable (no change).
57    pub fn set(&mut self, value: T, ts: impl Into<String>, by: Uuid) -> bool {
58        let incoming = Stamped {
59            value,
60            ts: ts.into(),
61            by,
62        };
63        match &self.current {
64            None => {
65                self.current = Some(incoming);
66                true
67            }
68            Some(cur) => match beats(&incoming, cur) {
69                None => false,
70                Some(true) => {
71                    let loser = self
72                        .current
73                        .replace(incoming)
74                        .expect("current is Some in this match arm");
75                    self.push_superseded(loser);
76                    true
77                }
78                Some(false) => {
79                    // Incoming loses (or equals) — keep it as a superseded alternative if
80                    // it is genuinely a different value, not a duplicate of current.
81                    if Some(&incoming.value) != self.current.as_ref().map(|c| &c.value) {
82                        self.push_superseded(incoming);
83                    }
84                    true
85                }
86            },
87        }
88    }
89
90    fn push_superseded(&mut self, s: Stamped<T>) {
91        self.superseded.insert(0, s);
92        self.superseded.truncate(SUPERSEDED_CAP);
93    }
94
95    /// Merge another replica's register: apply its current and all superseded entries.
96    pub fn merge(&mut self, other: &Self) {
97        if let Some(c) = &other.current {
98            self.set(c.value.clone(), c.ts.clone(), c.by);
99        }
100        for s in &other.superseded {
101            self.set(s.value.clone(), s.ts.clone(), s.by);
102        }
103    }
104
105    /// The current value, if any.
106    pub fn get(&self) -> Option<&T> {
107        self.current.as_ref().map(|s| &s.value)
108    }
109}
110
111#[cfg(test)]
112mod tests;