bones-core 0.24.4

Core data structures, CRDT event model, and projection engine for bones
Documentation
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
//! Last-Writer-Wins (LWW) Register CRDT.
//!
//! LWW Register is the CRDT for scalar fields: title, description, kind,
//! size, urgency, parent. The merge uses a deterministic 4-step tie-breaking
//! chain that guarantees bit-identical convergence across all replicas.
//!
//! # Tie-Breaking Chain
//!
//! Given two `LwwRegister<T>` values `a` and `b`:
//!
//! 1. **ITC causal dominance**: If `a.stamp.leq(&b.stamp)` and they are
//!    not concurrent, the causally later one wins.
//! 2. **Wall-clock timestamp**: If concurrent, higher `wall_ts` wins.
//! 3. **Agent ID**: If wall clocks are equal, lexicographically greater
//!    `agent_id` wins.
//! 4. **Event hash**: If agent IDs are equal (same agent, concurrent writes),
//!    lexicographically greater `event_hash` wins. This step guarantees
//!    uniqueness — no ties are possible.

use serde::{Deserialize, Serialize};
use std::fmt;

use crate::clock::itc::Stamp;
use crate::crdt::trace::{MergeTrace, TieBreakStep, merge_tracing_enabled};
use tracing::debug;

// ---------------------------------------------------------------------------
// LwwRegister
// ---------------------------------------------------------------------------

/// A Last-Writer-Wins register holding a value of type `T`.
///
/// Each write records the value along with metadata used for deterministic
/// merge: an ITC stamp for causal ordering, a wall-clock timestamp, the
/// writing agent's ID, and the event hash.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LwwRegister<T> {
    /// The current value of the register.
    pub value: T,
    /// ITC stamp for causal ordering.
    pub stamp: Stamp,
    /// Wall-clock timestamp in microseconds since Unix epoch.
    pub wall_ts: u64,
    /// Agent identifier (e.g., "alice", "bot-1").
    pub agent_id: String,
    /// BLAKE3 hash of the event that wrote this value.
    pub event_hash: String,
}

impl<T> LwwRegister<T> {
    /// Create a new LWW register with the given value and metadata.
    pub const fn new(
        value: T,
        stamp: Stamp,
        wall_ts: u64,
        agent_id: String,
        event_hash: String,
    ) -> Self {
        Self {
            value,
            stamp,
            wall_ts,
            agent_id,
            event_hash,
        }
    }
}

impl<T: Clone> LwwRegister<T> {
    /// Merge another register into this one, keeping the "winning" value.
    ///
    /// The 4-step tie-breaking chain:
    /// 1. ITC causal dominance (non-concurrent: later wins)
    /// 2. Wall-clock timestamp (concurrent: higher wins)
    /// 3. Agent ID (lexicographic: greater wins)
    /// 4. Event hash (lexicographic: greater wins — guaranteed unique)
    ///
    /// After merge, `self` contains the winning value.
    pub fn merge(&mut self, other: &Self) {
        if self.wins_over(other) {
            // Keep self
        } else {
            self.value = other.value.clone();
            self.stamp = other.stamp.clone();
            self.wall_ts = other.wall_ts;
            self.agent_id.clone_from(&other.agent_id);
            self.event_hash.clone_from(&other.event_hash);
        }
    }

    /// Merge and optionally emit structured decision trace.
    ///
    /// If tracing is disabled via environment toggles, returns a no-op trace
    /// payload and preserves the normal low-overhead merge path.
    pub fn merge_with_trace(&mut self, other: &Self, field: &str) -> MergeTrace
    where
        T: fmt::Display,
    {
        let (self_wins, step) = self.compare(other);

        let trace = if merge_tracing_enabled() {
            let winner = if self_wins {
                self.value.to_string()
            } else {
                other.value.to_string()
            };

            let trace = MergeTrace {
                field: field.to_string(),
                values: (self.value.to_string(), other.value.to_string()),
                winner,
                step,
                correlation_id: format!("{}..{}", self.event_hash, other.event_hash),
                enabled: true,
            };

            debug!(
                target: "bones_core::crdt::merge_trace",
                field = trace.field,
                winner = trace.winner,
                step = ?trace.step,
                correlation_id = trace.correlation_id,
                "LWW merge decision"
            );

            trace
        } else {
            MergeTrace::disabled()
        };

        if !self_wins {
            self.value = other.value.clone();
            self.stamp = other.stamp.clone();
            self.wall_ts = other.wall_ts;
            self.agent_id.clone_from(&other.agent_id);
            self.event_hash.clone_from(&other.event_hash);
        }

        trace
    }

    /// Returns `true` if `self` wins over `other` in the tie-breaking chain.
    fn wins_over(&self, other: &Self) -> bool {
        self.compare(other).0
    }

    fn compare(&self, other: &Self) -> (bool, TieBreakStep) {
        // Step 1: ITC causal dominance
        let self_leq_other = self.stamp.leq(&other.stamp);
        let other_leq_self = other.stamp.leq(&self.stamp);

        match (self_leq_other, other_leq_self) {
            (true, false) => {
                // other causally dominates self → other wins
                return (false, TieBreakStep::ItcCausal);
            }
            (false, true) => {
                // self causally dominates other → self wins
                return (true, TieBreakStep::ItcCausal);
            }
            (true, true) | (false, false) => {
                // Either equal (both leq each other) or concurrent.
                // Fall through to tie-breaking to ensure convergence.
            }
        }

        // Step 2: Wall-clock timestamp (higher wins)
        match self.wall_ts.cmp(&other.wall_ts) {
            std::cmp::Ordering::Greater => return (true, TieBreakStep::WallTimestamp),
            std::cmp::Ordering::Less => return (false, TieBreakStep::WallTimestamp),
            std::cmp::Ordering::Equal => {}
        }

        // Step 3: Agent ID (lexicographically greater wins)
        match self.agent_id.cmp(&other.agent_id) {
            std::cmp::Ordering::Greater => return (true, TieBreakStep::AgentId),
            std::cmp::Ordering::Less => return (false, TieBreakStep::AgentId),
            std::cmp::Ordering::Equal => {}
        }

        // Step 4: Event hash (lexicographically greater wins — guaranteed unique)
        (self.event_hash >= other.event_hash, TieBreakStep::EventHash)
    }
}

impl<T: fmt::Display> fmt::Display for LwwRegister<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.value)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::clock::itc::Stamp;

    /// Helper: create a stamp with a specific event counter (seed identity).
    fn make_stamp(counter: u64) -> Stamp {
        let mut s = Stamp::seed();
        for _ in 0..counter {
            s.event();
        }
        s
    }

    /// Helper: create a stamp from a fork (anonymous identity, specific event).
    fn make_forked_stamps(counter_a: u64, counter_b: u64) -> (Stamp, Stamp) {
        let seed = Stamp::seed();
        let (mut a, mut b) = seed.fork();
        for _ in 0..counter_a {
            a.event();
        }
        for _ in 0..counter_b {
            b.event();
        }
        (a, b)
    }

    fn reg(
        value: &str,
        stamp: Stamp,
        wall_ts: u64,
        agent: &str,
        hash: &str,
    ) -> LwwRegister<String> {
        LwwRegister::new(
            value.to_string(),
            stamp,
            wall_ts,
            agent.to_string(),
            hash.to_string(),
        )
    }

    // === Step 1: ITC causal dominance ===

    #[test]
    fn causal_later_wins() {
        let s1 = make_stamp(1);
        let s2 = make_stamp(2);
        // s1 is causally before s2 (same lineage, s2 has more events)
        assert!(s1.leq(&s2));
        assert!(!s2.leq(&s1));

        let mut a = reg("old", s1, 100, "alice", "aaa");
        let b = reg("new", s2, 100, "alice", "aaa");
        a.merge(&b);
        assert_eq!(a.value, "new");
    }

    #[test]
    fn causal_earlier_loses() {
        let s1 = make_stamp(1);
        let s2 = make_stamp(2);

        let mut a = reg("new", s2, 100, "alice", "aaa");
        let b = reg("old", s1, 100, "alice", "aaa");
        a.merge(&b);
        assert_eq!(a.value, "new"); // a (later) wins
    }

    // === Step 2: Concurrent, wall_ts tie-break ===

    #[test]
    fn concurrent_higher_wall_ts_wins() {
        let (sa, sb) = make_forked_stamps(1, 1);
        // sa and sb are concurrent (forked, both have events)
        assert!(sa.concurrent(&sb));

        let mut a = reg("alice-val", sa, 200, "alice", "aaa");
        let b = reg("bob-val", sb, 300, "bob", "bbb");
        a.merge(&b);
        assert_eq!(a.value, "bob-val"); // higher wall_ts wins
    }

    #[test]
    fn concurrent_lower_wall_ts_loses() {
        let (sa, sb) = make_forked_stamps(1, 1);

        let mut a = reg("alice-val", sa, 300, "alice", "aaa");
        let b = reg("bob-val", sb, 200, "bob", "bbb");
        a.merge(&b);
        assert_eq!(a.value, "alice-val"); // a has higher wall_ts
    }

    // === Step 3: Concurrent, same wall_ts, agent_id tie-break ===

    #[test]
    fn concurrent_same_ts_higher_agent_wins() {
        let (sa, sb) = make_forked_stamps(1, 1);

        let mut a = reg("alice-val", sa, 100, "alice", "aaa");
        let b = reg("bob-val", sb, 100, "bob", "bbb");
        a.merge(&b);
        assert_eq!(a.value, "bob-val"); // "bob" > "alice" lexicographically
    }

    #[test]
    fn concurrent_same_ts_lower_agent_loses() {
        let (sa, sb) = make_forked_stamps(1, 1);

        let mut a = reg("bob-val", sa, 100, "bob", "bbb");
        let b = reg("alice-val", sb, 100, "alice", "aaa");
        a.merge(&b);
        assert_eq!(a.value, "bob-val"); // "bob" > "alice"
    }

    // === Step 4: Concurrent, same ts, same agent, event_hash tie-break ===

    #[test]
    fn concurrent_same_agent_higher_hash_wins() {
        let (sa, sb) = make_forked_stamps(1, 1);

        let mut a = reg("val-a", sa, 100, "alice", "hash-aaa");
        let b = reg("val-b", sb, 100, "alice", "hash-zzz");
        a.merge(&b);
        assert_eq!(a.value, "val-b"); // "hash-zzz" > "hash-aaa"
    }

    #[test]
    fn concurrent_same_agent_lower_hash_loses() {
        let (sa, sb) = make_forked_stamps(1, 1);

        let mut a = reg("val-a", sa, 100, "alice", "hash-zzz");
        let b = reg("val-b", sb, 100, "alice", "hash-aaa");
        a.merge(&b);
        assert_eq!(a.value, "val-a"); // "hash-zzz" > "hash-aaa"
    }

    // === Semilattice properties ===

    #[test]
    fn semilattice_commutative() {
        let (sa, sb) = make_forked_stamps(1, 1);

        let a = reg("val-a", sa.clone(), 100, "alice", "hash-a");
        let b = reg("val-b", sb.clone(), 200, "bob", "hash-b");

        let mut ab = a.clone();
        ab.merge(&b);

        let mut ba = b.clone();
        ba.merge(&a);

        assert_eq!(ab, ba);
    }

    #[test]
    fn semilattice_associative() {
        let seed = Stamp::seed();
        let (left, right) = seed.fork();
        let (mut sa, sb) = left.fork();
        let (mut sc, _) = right.fork();
        sa.event();
        // sb stays as is (concurrent with sa)
        sc.event();

        let a = reg("val-a", sa, 100, "alice", "hash-a");
        let b = reg("val-b", sb, 200, "bob", "hash-b");
        let c = reg("val-c", sc, 150, "carol", "hash-c");

        // (a merge b) merge c
        let mut left_merge = a.clone();
        left_merge.merge(&b);
        left_merge.merge(&c);

        // a merge (b merge c)
        let mut bc = b.clone();
        bc.merge(&c);
        let mut right_merge = a.clone();
        right_merge.merge(&bc);

        assert_eq!(left_merge, right_merge);
    }

    #[test]
    fn semilattice_idempotent_self_merge() {
        let s = make_stamp(3);
        let a = reg("value", s, 500, "agent", "hash-123");
        let mut m = a.clone();
        m.merge(&a);
        assert_eq!(m, a);
    }

    // === Edge cases ===

    #[test]
    fn equal_stamps_are_idempotent() {
        // Two registers with identical stamps (both leq each other)
        let s = make_stamp(2);
        let a = reg("same", s.clone(), 100, "agent", "hash");
        let mut m = a.clone();
        m.merge(&a);
        assert_eq!(m, a);
    }

    #[test]
    fn identical_timestamps_different_agents() {
        let (sa, sb) = make_forked_stamps(1, 1);

        let a = reg("alice-val", sa.clone(), 999, "alice", "hash-same");
        let b = reg("bob-val", sb.clone(), 999, "bob", "hash-same");

        let mut ab = a.clone();
        ab.merge(&b);
        assert_eq!(ab.value, "bob-val"); // "bob" > "alice"

        let mut ba = b.clone();
        ba.merge(&a);
        assert_eq!(ba.value, "bob-val");

        assert_eq!(ab, ba); // commutative
    }

    #[test]
    fn same_agent_concurrent_writes() {
        // Same agent can have concurrent writes if forked
        let (sa, sb) = make_forked_stamps(1, 1);

        let a = reg("write-1", sa, 100, "alice", "hash-111");
        let b = reg("write-2", sb, 100, "alice", "hash-222");

        let mut ab = a.clone();
        ab.merge(&b);

        let mut ba = b.clone();
        ba.merge(&a);

        assert_eq!(ab, ba); // commutative
        assert_eq!(ab.value, "write-2"); // "hash-222" > "hash-111"
    }

    #[test]
    fn display_shows_value() {
        let s = make_stamp(1);
        let r = reg("Hello, World!", s, 0, "agent", "hash");
        assert_eq!(r.to_string(), "Hello, World!");
    }

    #[test]
    fn serde_roundtrip() {
        let s = make_stamp(2);
        let r = reg("test-value", s, 42, "agent-1", "blake3:abc");
        let json = serde_json::to_string(&r).unwrap();
        let deserialized: LwwRegister<String> = serde_json::from_str(&json).unwrap();
        assert_eq!(r, deserialized);
    }

    #[test]
    fn numeric_value_type() {
        let s = make_stamp(1);
        let mut a = LwwRegister::new(42u64, s.clone(), 100, "alice".to_string(), "h1".to_string());
        let s2 = make_stamp(2);
        let b = LwwRegister::new(99u64, s2, 200, "bob".to_string(), "h2".to_string());
        a.merge(&b);
        assert_eq!(a.value, 99);
    }

    #[test]
    fn merge_with_trace_disabled_by_default_has_no_payload() {
        let s1 = make_stamp(1);
        let s2 = make_stamp(2);

        let mut a = reg("old", s1, 100, "alice", "aaa");
        let b = reg("new", s2, 100, "alice", "bbb");

        let trace = a.merge_with_trace(&b, "title");
        assert_eq!(a.value, "new");
        assert!(!trace.enabled);
        assert_eq!(trace.step, TieBreakStep::Equal);
        assert!(trace.field.is_empty());
    }

    #[test]
    fn merge_with_trace_reports_decisive_step_when_enabled() {
        if !merge_tracing_enabled() {
            return;
        }

        let (sa, sb) = make_forked_stamps(1, 1);
        let mut a = reg("alice-val", sa, 100, "alice", "aaa");
        let b = reg("bob-val", sb, 200, "bob", "bbb");

        let trace = a.merge_with_trace(&b, "title");
        assert!(trace.enabled);
        assert_eq!(trace.field, "title");
        assert_eq!(trace.winner, "bob-val");
        assert_eq!(trace.step, TieBreakStep::WallTimestamp);
        assert!(!trace.correlation_id.is_empty());
    }

    #[test]
    fn merge_chain_converges() {
        // Multiple agents writing concurrently, all merge in different orders
        let seed = Stamp::seed();
        let (left, right) = seed.fork();
        let (mut s1, mut s2) = left.fork();
        let (mut s3, _) = right.fork();
        s1.event();
        s2.event();
        s3.event();

        let r1 = reg("v1", s1, 100, "alice", "h1");
        let r2 = reg("v2", s2, 200, "bob", "h2");
        let r3 = reg("v3", s3, 200, "carol", "h3");

        // Order 1: r1, r2, r3
        let mut m1 = r1.clone();
        m1.merge(&r2);
        m1.merge(&r3);

        // Order 2: r3, r1, r2
        let mut m2 = r3.clone();
        m2.merge(&r1);
        m2.merge(&r2);

        // Order 3: r2, r3, r1
        let mut m3 = r2.clone();
        m3.merge(&r3);
        m3.merge(&r1);

        assert_eq!(m1, m2);
        assert_eq!(m2, m3);
    }
}