loro-internal 1.12.0

Loro internal library. Do not use it directly as it's not stable.
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
use std::collections::HashSet;

use crate::{
    dag::{Dag, DagNode},
    id::ID,
    version::Frontiers,
};

fn get_all_points<T: DagNode, D: Dag<Node = T>>(graph: &D, points: &mut HashSet<ID>, current: &ID) {
    points.insert(*current);
    for to_id in graph.get(*current).unwrap().deps().iter() {
        get_all_points(graph, points, &to_id);
    }
}

pub fn get_end_list<T: DagNode, D: Dag<Node = T>>(graph: &D, start_list: &Frontiers) -> Frontiers {
    let mut end_set: HashSet<ID> = HashSet::new();
    for start_id in start_list.iter() {
        end_dfs(graph, &start_id, &mut end_set);
    }
    end_set.into_iter().collect()
}

fn end_dfs<T: DagNode, D: Dag<Node = T>>(graph: &D, current: &ID, end_set: &mut HashSet<ID>) {
    let binding = graph.get(*current).unwrap();
    let deps = binding.deps();
    if deps.is_empty() {
        end_set.insert(*current);
    }
    for to_id in deps.iter() {
        end_dfs(graph, &to_id, end_set);
    }
}

pub fn calc_critical_version_dfs<T: DagNode, D: Dag<Node = T>>(
    graph: &D,
    start_list: &Frontiers,
    end_list: &Frontiers,
) -> Vec<ID> {
    let mut result: Vec<ID> = vec![];
    let mut points: HashSet<ID> = HashSet::new();
    let start_list_set: HashSet<ID> = HashSet::from_iter(start_list.iter());
    let end_list_set: HashSet<ID> = HashSet::from_iter(end_list.iter());
    for start_id in start_list.iter() {
        get_all_points(graph, &mut points, &start_id);
    }
    for escape in points {
        let mut flag = false;
        for start_id in start_list.iter() {
            if dfs(graph, &start_id, &escape, &end_list_set) {
                flag = true;
                break;
            }
        }
        if flag {
            continue;
        }
        if !end_list_set.contains(&escape) && !start_list_set.contains(&escape) {
            result.push(escape);
        }
    }
    result
}

fn dfs<T: DagNode, D: Dag<Node = T>>(
    graph: &D,
    current: &ID,
    escape: &ID,
    end_list_set: &HashSet<ID>,
) -> bool {
    if current == escape {
        return false;
    }
    if end_list_set.contains(current) {
        return true;
    }
    for to_id in graph.get(*current).unwrap().deps().iter() {
        if dfs(graph, &to_id, escape, end_list_set) {
            return true;
        }
    }
    false
}

#[cfg(test)]
mod additional_tests {
    use std::collections::BTreeMap;

    use loro_common::{HasId, HasIdSpan};
    use rle::{HasLength, Sliceable};

    use super::*;
    use crate::{
        change::Lamport,
        span::{HasLamport, HasLamportSpan},
        version::VersionVector,
    };

    #[derive(Clone, Debug)]
    struct TestNode {
        id: ID,
        lamport: Lamport,
        deps: Frontiers,
    }

    impl DagNode for TestNode {
        fn deps(&self) -> &Frontiers {
            &self.deps
        }
    }

    impl HasId for TestNode {
        fn id_start(&self) -> ID {
            self.id
        }
    }

    impl HasLamport for TestNode {
        fn lamport(&self) -> Lamport {
            self.lamport
        }
    }

    impl HasLength for TestNode {
        fn content_len(&self) -> usize {
            1
        }
    }

    impl Sliceable for TestNode {
        fn slice(&self, _from: usize, _to: usize) -> Self {
            self.clone()
        }
    }

    #[derive(Debug)]
    struct TestDag {
        nodes: BTreeMap<ID, TestNode>,
        vv: VersionVector,
        frontier: Frontiers,
    }

    impl TestDag {
        fn new(nodes: impl IntoIterator<Item = TestNode>, frontier: Frontiers) -> Self {
            let mut vv = VersionVector::default();
            let nodes = nodes
                .into_iter()
                .map(|node| {
                    vv.set_end(node.id_end());
                    (node.id_start(), node)
                })
                .collect();
            Self {
                nodes,
                vv,
                frontier,
            }
        }
    }

    impl Dag for TestDag {
        type Node = TestNode;

        fn get(&self, id: ID) -> Option<Self::Node> {
            self.nodes.get(&id).cloned()
        }

        fn frontier(&self) -> &Frontiers {
            &self.frontier
        }

        fn vv(&self) -> &VersionVector {
            &self.vv
        }

        fn contains(&self, id: ID) -> bool {
            self.nodes.contains_key(&id)
        }
    }

    fn node(peer: u64, counter: i32, lamport: Lamport, deps: Frontiers) -> TestNode {
        TestNode {
            id: ID::new(peer, counter),
            lamport,
            deps,
        }
    }

    #[test]
    fn end_list_collects_dependency_leaves_from_all_start_frontiers() {
        let a = node(1, 0, 0, Frontiers::default());
        let b = node(1, 1, 1, a.id.into());
        let c = node(2, 0, 2, a.id.into());
        let d = node(3, 0, 3, Frontiers::from([b.id, c.id]));
        let e = node(4, 0, 4, c.id.into());
        let dag = TestDag::new(
            vec![a.clone(), b.clone(), c.clone(), d.clone(), e.clone()],
            Frontiers::from([d.id, e.id]),
        );

        let ends = get_end_list(&dag, &Frontiers::from([d.id, e.id]));
        assert_eq!(ends, Frontiers::from(a.id));
    }

    #[test]
    fn dfs_critical_versions_include_linear_cut_points() {
        let root = node(1, 0, 0, Frontiers::default());
        let middle = node(1, 1, 1, root.id.into());
        let head = node(1, 2, 2, middle.id.into());
        let dag = TestDag::new(
            vec![root.clone(), middle.clone(), head.clone()],
            head.id.into(),
        );

        let critical = calc_critical_version_dfs(&dag, &head.id.into(), &root.id.into());
        assert_eq!(critical, vec![middle.id]);
    }

    #[test]
    fn dfs_critical_versions_exclude_diamond_branches_with_alternate_paths() {
        let root = node(1, 0, 0, Frontiers::default());
        let left = node(2, 0, 1, root.id.into());
        let right = node(3, 0, 2, root.id.into());
        let merge = node(4, 0, 3, Frontiers::from([left.id, right.id]));
        let dag = TestDag::new(
            vec![root.clone(), left.clone(), right.clone(), merge.clone()],
            merge.id.into(),
        );

        let critical = calc_critical_version_dfs(&dag, &merge.id.into(), &root.id.into());
        assert!(critical.is_empty());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        cmp::Ordering,
        collections::{HashMap, HashSet},
        sync::Arc,
    };

    use crate::{
        change::Lamport,
        id::{Counter, PeerID},
        span::{HasId, HasLamport},
    };
    use rle::{HasLength, Sliceable};

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct TestNode {
        id: ID,
        lamport: Lamport,
        len: usize,
        deps: Arc<Frontiers>,
    }

    impl TestNode {
        fn new(id: ID, lamport: Lamport, deps: Frontiers) -> Self {
            Self {
                id,
                lamport,
                len: 1,
                deps: Arc::new(deps),
            }
        }
    }

    impl DagNode for TestNode {
        fn deps(&self) -> &Frontiers {
            &self.deps
        }
    }

    impl Sliceable for TestNode {
        fn slice(&self, _from: usize, _to: usize) -> Self {
            self.clone()
        }
    }

    impl HasLamport for TestNode {
        fn lamport(&self) -> Lamport {
            self.lamport
        }
    }

    impl HasId for TestNode {
        fn id_start(&self) -> ID {
            self.id
        }
    }

    impl HasLength for TestNode {
        fn content_len(&self) -> usize {
            self.len
        }
    }

    #[derive(Debug)]
    struct TestDag {
        nodes: HashMap<PeerID, Vec<TestNode>>,
        version_vec: crate::version::VersionVector,
    }

    impl TestDag {
        fn new(nodes: Vec<TestNode>) -> Self {
            let mut map: HashMap<PeerID, Vec<TestNode>> = HashMap::new();
            let mut vv = crate::version::VersionVector::new();
            for node in nodes {
                vv.insert(node.id.peer, node.id.counter + node.len as Counter);
                map.entry(node.id.peer).or_default().push(node);
            }
            for nodes in map.values_mut() {
                nodes.sort_by(|a, b| match a.id.counter.cmp(&b.id.counter) {
                    Ordering::Equal => a.len.cmp(&b.len),
                    other => other,
                });
            }
            Self {
                nodes: map,
                version_vec: vv,
            }
        }
    }

    impl Dag for TestDag {
        type Node = TestNode;

        fn get(&self, id: ID) -> Option<Self::Node> {
            let arr = self.nodes.get(&id.peer)?;
            arr.binary_search_by(|node| {
                if node.id.counter > id.counter {
                    Ordering::Greater
                } else if node.id.counter + node.len as i32 <= id.counter {
                    Ordering::Less
                } else {
                    Ordering::Equal
                }
            })
            .ok()
            .map(|idx| arr[idx].clone())
        }

        fn frontier(&self) -> &Frontiers {
            panic!("frontier is not used in dfs tests")
        }

        fn vv(&self) -> &crate::version::VersionVector {
            &self.version_vec
        }

        fn contains(&self, id: ID) -> bool {
            self.version_vec.includes_id(id)
        }
    }

    fn id(peer: PeerID, counter: Counter) -> ID {
        ID::new(peer, counter)
    }

    fn frontier(ids: &[ID]) -> Frontiers {
        let mut frontier = Frontiers::new();
        for id in ids {
            frontier.push(*id);
        }
        frontier
    }

    fn as_set(ids: Vec<ID>) -> HashSet<ID> {
        ids.into_iter().collect()
    }

    #[test]
    fn get_end_list_collects_all_leaf_nodes_reachable_from_start() {
        let graph = TestDag::new(vec![
            TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])),
            TestNode::new(id(2, 0), 7, Frontiers::new()),
            TestNode::new(id(3, 0), 8, Frontiers::new()),
        ]);

        let ends = get_end_list(&graph, &frontier(&[id(1, 0)]));

        assert_eq!(ends.len(), 2);
        assert!(ends.contains(&id(2, 0)));
        assert!(ends.contains(&id(3, 0)));
        assert!(!ends.contains(&id(1, 0)));
    }

    #[test]
    fn calc_critical_version_dfs_returns_non_start_nodes_when_no_end_is_present() {
        let graph = TestDag::new(vec![
            TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])),
            TestNode::new(id(2, 0), 7, Frontiers::new()),
            TestNode::new(id(3, 0), 8, Frontiers::new()),
        ]);

        let result = calc_critical_version_dfs(&graph, &frontier(&[id(1, 0)]), &Frontiers::new());

        assert_eq!(as_set(result), as_set(vec![id(2, 0), id(3, 0)]));
    }

    #[test]
    fn calc_critical_version_dfs_skips_candidates_when_an_end_is_on_every_start_path() {
        let graph = TestDag::new(vec![
            TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])),
            TestNode::new(id(2, 0), 7, Frontiers::new()),
            TestNode::new(id(3, 0), 8, Frontiers::new()),
        ]);

        let result =
            calc_critical_version_dfs(&graph, &frontier(&[id(1, 0)]), &frontier(&[id(2, 0)]));

        assert!(result.is_empty());
    }
}