File: orswot.rs

package info (click to toggle)
rust-crdts 7.3.2%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 516 kB
  • sloc: makefile: 2; sh: 1
file content (373 lines) | stat: -rw-r--r-- 12,110 bytes parent folder | download
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
use crdts::orswot::Op;
use crdts::{CmRDT, CvRDT, Dot, Map, Orswot, VClock};
use std::collections::HashSet;
use std::iter::once;

type Member = u8;

/// When two orswots have identical clocks, but different elements,
/// any non-common elements will be dropped.  This highlights the
/// proper usage of orswots: don't use the same witness from different
/// copies of the orswot, or elements will be deleted upon merge.
#[test]
fn weird_highlight_1() {
    let mut a = Orswot::new();
    let mut b = Orswot::new();
    a.apply(a.add(1, a.read().derive_add_ctx("A")));
    b.apply(b.add(2, b.read().derive_add_ctx("A")));

    a.merge(b);
    assert!(a.read().val.is_empty());
}

///
#[test]
fn adds_dont_destroy_causality() {
    let mut a = Orswot::new();
    let mut b = a.clone();
    let mut c = a.clone();

    c.apply(c.add("element", c.read().derive_add_ctx("A")));
    c.apply(c.add("element", c.read().derive_add_ctx("B")));

    let c_element_ctx = c.contains(&"element");

    // If we want to remove this entry, the remove context
    // should descend from vclock { 1->1, 2->1 }
    assert_eq!(
        c_element_ctx.rm_clock,
        vec![Dot::new("A", 1), Dot::new("B", 1)]
            .into_iter()
            .collect()
    );

    a.apply(a.add("element", a.read().derive_add_ctx("C")));
    b.apply(c.rm("element", c_element_ctx.derive_rm_ctx()));
    a.apply(a.add("element", a.read().derive_add_ctx("A")));

    a.merge(b);
    assert_eq!(a.read().val, vec!["element"].into_iter().collect());
}

// a bug found with rust quickcheck where identical entries
// with different associated clocks were removed rather
// than merged.
#[test]
fn merge_clocks_of_identical_entries() {
    let mut a = Orswot::new();
    let mut b = a.clone();
    // add element 1 with witnesses 3 and 7
    a.apply(a.add(1, a.read().derive_add_ctx("A")));
    b.apply(a.add(1, b.read().derive_add_ctx("B")));
    a.merge(b);

    assert_eq!(a.read().val, vec![1].into_iter().collect());

    let mut final_clock = VClock::new();
    final_clock.apply(final_clock.inc("A"));
    final_clock.apply(final_clock.inc("B"));
    assert!(a.contains(&1).val);
    assert_eq!(a.contains(&1).rm_clock, final_clock);
}

// port from riak_dt
#[test]
fn test_disjoint_merge() {
    let mut a = Orswot::new();
    let mut b = a.clone();

    a.apply(a.add(0, a.read().derive_add_ctx("A")));
    assert_eq!(a.read().val, vec![0].into_iter().collect());

    b.apply(b.add(1, b.read().derive_add_ctx("B")));
    assert_eq!(b.read().val, vec![1].into_iter().collect());

    let mut c = a.clone();
    c.merge(b);
    assert_eq!(c.read().val, vec![0, 1].into_iter().collect());

    a.apply(a.rm(0, a.contains(&0).derive_rm_ctx()));

    let mut d = a.clone();
    d.merge(c);
    assert_eq!(d.read().val, vec![1].into_iter().collect());
}

// port from riak_dt
// A bug EQC found where dropping the dots in merge was not enough if
// you then store the value with an empty clock (derp).
#[test]
fn test_no_dots_left_test() {
    let mut a = Orswot::new();
    let mut b = Orswot::new();

    a.apply(a.add(0, a.read().derive_add_ctx("A")));
    b.apply(b.add(0, b.read().derive_add_ctx("B")));
    let c = a.clone();
    a.apply(a.rm(0, a.contains(&0).derive_rm_ctx()));

    // replicate B to A, now A has B's 'Z'
    a.merge(b.clone());
    assert_eq!(a.read().val, vec![0].into_iter().collect());

    let mut expected_clock = VClock::new();
    expected_clock.apply(expected_clock.inc("A"));
    expected_clock.apply(expected_clock.inc("B"));
    assert_eq!(a.read().add_clock, expected_clock);

    b.apply(b.rm(0, b.contains(&0).derive_rm_ctx()));
    assert!(b.read().val.is_empty());

    // Replicate C to B, now B has A's old 'Z'
    b.merge(c.clone());
    assert_eq!(b.read().val, vec![0].into_iter().collect());

    // Merge everything, without the fix You end up with 'Z' present,
    // with no dots
    b.merge(a);
    b.merge(c);
    assert!(b.read().val.is_empty());
}

// port from riak_dt
// A test I thought up
// - existing replica of ['A'] at a and b,
// - add ['B'] at b, but not communicated to any other nodes, context returned to client
// - b goes down forever
// - remove ['A'] at a, using the context the client got from b
// - will that remove happen?
//   case for shouldn't: the context at b will always be bigger than that at a
//   case for should: we have the information in dots that may allow us to realise it can be removed
//     without us caring.
//
// as the code stands, 'A' *is* removed, which is almost certainly correct. This behaviour should
// always happen, but may not. (ie, the test needs expanding)
#[test]
fn test_dead_node_update() {
    let mut a = Orswot::new();
    let a_op = a.add(0, a.read().derive_add_ctx("A"));
    assert_eq!(
        a_op,
        Op::Add {
            dot: Dot::new("A", 1),
            members: once(0).collect(),
        }
    );

    a.apply(a_op);
    assert_eq!(a.contains(&0).rm_clock, VClock::from(Dot::new("A", 1)));

    let mut b = a.clone();
    b.apply(b.add(1, b.read().derive_add_ctx("B")));
    let bctx = b.read();
    assert_eq!(
        bctx.add_clock,
        vec![Dot::new("A", 1), Dot::new("B", 1)]
            .into_iter()
            .collect()
    );

    a.apply(a.rm(0, bctx.derive_rm_ctx()));
    assert_eq!(a.read().val, HashSet::new());
}

#[test]
fn test_reset_remove_semantics() {
    let mut m1: Map<u8, Orswot<Member, &str>, &str> = Map::new();

    m1.apply(
        m1.update(101, m1.get(&101).derive_add_ctx("A"), |set, ctx| {
            set.add(1, ctx)
        }),
    );

    let mut m2 = m1.clone();

    m1.apply(m1.rm(101, m1.get(&101).derive_rm_ctx()));
    m2.apply(
        m2.update(101, m2.get(&101).derive_add_ctx("B"), |set, ctx| {
            set.add(2, ctx)
        }),
    );

    assert_eq!(m1.get(&101).val, None);
    assert_eq!(
        m2.get(&101).val.unwrap().read().val,
        vec![1, 2].into_iter().collect()
    );

    m1.merge(m2.clone());
    m2.merge(m1.clone());

    assert_eq!(m1, m2);
    assert_eq!(
        m1.get(&101).val.unwrap().read().val,
        vec![2].into_iter().collect()
    );
}

#[cfg(feature = "quickcheck")]
mod prop_tests {
    use super::*;
    use crdts::{ctx::ReadCtx, DotRange, ResetRemove};
    use quickcheck_macros::quickcheck;

    type Actor = u8;
    const ACTOR_MAX: u8 = 11;

    #[quickcheck]
    fn prop_validate_op(ops: Vec<Op<Member, Actor>>, op: Op<Member, Actor>) -> bool {
        let mut orswot = Orswot::new();
        for op in ops.clone() {
            if orswot.validate_op(&op).is_ok() {
                orswot.apply(op)
            }
        }

        match op.clone() {
            Op::Add { dot, members } => {
                let expected_dot = orswot.clock().inc(dot.actor);
                if dot < expected_dot {
                    assert_eq!(orswot.validate_op(&op), Ok(()));
                    let orswot_clone = orswot.clone();
                    orswot.apply(op);
                    assert_eq!(orswot, orswot_clone);
                } else if dot == expected_dot {
                    assert_eq!(orswot.validate_op(&op), Ok(()));
                    orswot.apply(op);
                    for member in members {
                        let removed = ops.iter().any(|op| {
                            if let Op::Rm { clock, members } = op {
                                members.contains(&member) && clock.dot(dot.actor) >= dot
                            } else {
                                false
                            }
                        });

                        assert!(removed || orswot.contains(&member).val);
                    }
                } else {
                    assert_eq!(
                        orswot.validate_op(&op),
                        Err(DotRange {
                            actor: dot.actor,
                            counter_range: expected_dot.counter..dot.counter,
                        })
                    );
                }
            }
            Op::Rm { .. } => assert_eq!(orswot.validate_op(&op), Ok(())),
        }

        true
    }

    #[quickcheck]
    fn prop_validate_merge(ops_1: Vec<Op<Member, Actor>>, ops_2: Vec<Op<Member, Actor>>) -> bool {
        let mut orswot_1 = Orswot::new();
        let mut orswot_2 = Orswot::new();

        for op in ops_1.clone() {
            if orswot_1.validate_op(&op).is_ok() {
                orswot_1.apply(op)
            }
        }

        for op in ops_2.clone() {
            if orswot_2.validate_op(&op).is_ok() {
                orswot_2.apply(op)
            }
        }

        if orswot_1.validate_merge(&orswot_2).is_ok() {
            assert_eq!(orswot_2.validate_merge(&orswot_1), Ok(()));
        }

        if orswot_2.validate_merge(&orswot_1).is_ok() {
            assert_eq!(orswot_1.validate_merge(&orswot_2), Ok(()));
        }

        if orswot_1.validate_merge(&orswot_2).is_ok() {
            let mut merged = orswot_1.clone();
            merged.merge(orswot_2.clone());
            let merged_members = merged.read().val;

            for ReadCtx { val, rm_clock, .. } in orswot_1.iter() {
                if !merged_members.contains(val) {
                    let mut val_clock = rm_clock.clone();
                    for op in ops_2.iter() {
                        match op {
                            Op::Rm { clock, .. } => val_clock.reset_remove(clock),
                            Op::Add { members, dot } => {
                                if members.is_empty() {
                                    val_clock.reset_remove(&VClock::from(*dot));
                                }
                            }
                        }
                    }
                    assert_eq!(val_clock, VClock::new());
                }
            }

            for ReadCtx { val, rm_clock, .. } in orswot_2.iter() {
                if !merged_members.contains(val) {
                    let mut val_clock = rm_clock.clone();
                    for op in ops_1.iter() {
                        match op {
                            Op::Rm { clock, .. } => val_clock.reset_remove(clock),
                            Op::Add { members, dot } => {
                                if members.is_empty() {
                                    val_clock.reset_remove(&VClock::from(*dot));
                                }
                            }
                        }
                    }
                    assert_eq!(val_clock, VClock::new());
                }
            }
        }

        true
    }

    #[quickcheck]
    fn prop_merge_converges(ops: Vec<Op<Member, Actor>>) -> bool {
        // Different interleavings of ops applied to different
        // orswots should all converge when merged. Apply the
        // ops to increasing numbers of witnessing orswots,
        // then merge them together and make sure they have
        // all converged.
        let mut result = None;
        for i in 2..ACTOR_MAX {
            let mut witnesses: Vec<Orswot<Member, Actor>> = (0..i).map(|_| Orswot::new()).collect();
            for op in ops.iter() {
                let actor_opt = match op {
                    Op::Add { dot, .. } => Some(dot.actor),
                    Op::Rm { clock, .. } => clock.iter().next().map(|d| *d.actor), // any actor will do for Rm
                };

                if let Some(actor) = actor_opt {
                    let witness = &mut witnesses[(actor % i) as usize];
                    witness.apply(op.clone());
                }
            }

            let mut merged = Orswot::new();
            for witness in witnesses {
                merged.merge(witness);
            }

            if let Some(ref prev_res) = result {
                if prev_res != &merged {
                    println!("opvec: {:?}", ops);
                    println!("result: {:?}", result);
                    println!("merged: {:?}", merged);
                    return false;
                };
            } else {
                result = Some(merged);
            }
        }
        true
    }
}