forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

dfs.rs416 lines, 11.0 KiBHistoryRawDownload
1use std::collections::HashSet;
2
3use crate::{
4 dag::{Dag, DagNode},
5 id::ID,
6 version::Frontiers,
7};
8
9fn get_all_points<T: DagNode, D: Dag<Node = T>>(graph: &D, points: &mut HashSet<ID>, current: &ID) {
10 points.insert(*current);
11 for to_id in graph.get(*current).unwrap().deps().iter() {
12 get_all_points(graph, points, &to_id);
13 }
14}
15
16pub fn get_end_list<T: DagNode, D: Dag<Node = T>>(graph: &D, start_list: &Frontiers) -> Frontiers {
17 let mut end_set: HashSet<ID> = HashSet::new();
18 for start_id in start_list.iter() {
19 end_dfs(graph, &start_id, &mut end_set);
20 }
21 end_set.into_iter().collect()
22}
23
24fn end_dfs<T: DagNode, D: Dag<Node = T>>(graph: &D, current: &ID, end_set: &mut HashSet<ID>) {
25 let binding = graph.get(*current).unwrap();
26 let deps = binding.deps();
27 if deps.is_empty() {
28 end_set.insert(*current);
29 }
30 for to_id in deps.iter() {
31 end_dfs(graph, &to_id, end_set);
32 }
33}
34
35pub fn calc_critical_version_dfs<T: DagNode, D: Dag<Node = T>>(
36 graph: &D,
37 start_list: &Frontiers,
38 end_list: &Frontiers,
39) -> Vec<ID> {
40 let mut result: Vec<ID> = vec![];
41 let mut points: HashSet<ID> = HashSet::new();
42 let start_list_set: HashSet<ID> = HashSet::from_iter(start_list.iter());
43 let end_list_set: HashSet<ID> = HashSet::from_iter(end_list.iter());
44 for start_id in start_list.iter() {
45 get_all_points(graph, &mut points, &start_id);
46 }
47 for escape in points {
48 let mut flag = false;
49 for start_id in start_list.iter() {
50 if dfs(graph, &start_id, &escape, &end_list_set) {
51 flag = true;
52 break;
53 }
54 }
55 if flag {
56 continue;
57 }
58 if !end_list_set.contains(&escape) && !start_list_set.contains(&escape) {
59 result.push(escape);
60 }
61 }
62 result
63}
64
65fn dfs<T: DagNode, D: Dag<Node = T>>(
66 graph: &D,
67 current: &ID,
68 escape: &ID,
69 end_list_set: &HashSet<ID>,
70) -> bool {
71 if current == escape {
72 return false;
73 }
74 if end_list_set.contains(current) {
75 return true;
76 }
77 for to_id in graph.get(*current).unwrap().deps().iter() {
78 if dfs(graph, &to_id, escape, end_list_set) {
79 return true;
80 }
81 }
82 false
83}
84
85#[cfg(test)]
86mod additional_tests {
87 use std::collections::BTreeMap;
88
89 use loro_common::{HasId, HasIdSpan};
90 use rle::{HasLength, Sliceable};
91
92 use super::*;
93 use crate::{
94 change::Lamport,
95 span::{HasLamport, HasLamportSpan},
96 version::VersionVector,
97 };
98
99 #[derive(Clone, Debug)]
100 struct TestNode {
101 id: ID,
102 lamport: Lamport,
103 deps: Frontiers,
104 }
105
106 impl DagNode for TestNode {
107 fn deps(&self) -> &Frontiers {
108 &self.deps
109 }
110 }
111
112 impl HasId for TestNode {
113 fn id_start(&self) -> ID {
114 self.id
115 }
116 }
117
118 impl HasLamport for TestNode {
119 fn lamport(&self) -> Lamport {
120 self.lamport
121 }
122 }
123
124 impl HasLength for TestNode {
125 fn content_len(&self) -> usize {
126 1
127 }
128 }
129
130 impl Sliceable for TestNode {
131 fn slice(&self, _from: usize, _to: usize) -> Self {
132 self.clone()
133 }
134 }
135
136 #[derive(Debug)]
137 struct TestDag {
138 nodes: BTreeMap<ID, TestNode>,
139 vv: VersionVector,
140 frontier: Frontiers,
141 }
142
143 impl TestDag {
144 fn new(nodes: impl IntoIterator<Item = TestNode>, frontier: Frontiers) -> Self {
145 let mut vv = VersionVector::default();
146 let nodes = nodes
147 .into_iter()
148 .map(|node| {
149 vv.set_end(node.id_end());
150 (node.id_start(), node)
151 })
152 .collect();
153 Self {
154 nodes,
155 vv,
156 frontier,
157 }
158 }
159 }
160
161 impl Dag for TestDag {
162 type Node = TestNode;
163
164 fn get(&self, id: ID) -> Option<Self::Node> {
165 self.nodes.get(&id).cloned()
166 }
167
168 fn frontier(&self) -> &Frontiers {
169 &self.frontier
170 }
171
172 fn vv(&self) -> &VersionVector {
173 &self.vv
174 }
175
176 fn contains(&self, id: ID) -> bool {
177 self.nodes.contains_key(&id)
178 }
179 }
180
181 fn node(peer: u64, counter: i32, lamport: Lamport, deps: Frontiers) -> TestNode {
182 TestNode {
183 id: ID::new(peer, counter),
184 lamport,
185 deps,
186 }
187 }
188
189 #[test]
190 fn end_list_collects_dependency_leaves_from_all_start_frontiers() {
191 let a = node(1, 0, 0, Frontiers::default());
192 let b = node(1, 1, 1, a.id.into());
193 let c = node(2, 0, 2, a.id.into());
194 let d = node(3, 0, 3, Frontiers::from([b.id, c.id]));
195 let e = node(4, 0, 4, c.id.into());
196 let dag = TestDag::new(
197 vec![a.clone(), b.clone(), c.clone(), d.clone(), e.clone()],
198 Frontiers::from([d.id, e.id]),
199 );
200
201 let ends = get_end_list(&dag, &Frontiers::from([d.id, e.id]));
202 assert_eq!(ends, Frontiers::from(a.id));
203 }
204
205 #[test]
206 fn dfs_critical_versions_include_linear_cut_points() {
207 let root = node(1, 0, 0, Frontiers::default());
208 let middle = node(1, 1, 1, root.id.into());
209 let head = node(1, 2, 2, middle.id.into());
210 let dag = TestDag::new(
211 vec![root.clone(), middle.clone(), head.clone()],
212 head.id.into(),
213 );
214
215 let critical = calc_critical_version_dfs(&dag, &head.id.into(), &root.id.into());
216 assert_eq!(critical, vec![middle.id]);
217 }
218
219 #[test]
220 fn dfs_critical_versions_exclude_diamond_branches_with_alternate_paths() {
221 let root = node(1, 0, 0, Frontiers::default());
222 let left = node(2, 0, 1, root.id.into());
223 let right = node(3, 0, 2, root.id.into());
224 let merge = node(4, 0, 3, Frontiers::from([left.id, right.id]));
225 let dag = TestDag::new(
226 vec![root.clone(), left.clone(), right.clone(), merge.clone()],
227 merge.id.into(),
228 );
229
230 let critical = calc_critical_version_dfs(&dag, &merge.id.into(), &root.id.into());
231 assert!(critical.is_empty());
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238 use std::{
239 cmp::Ordering,
240 collections::{HashMap, HashSet},
241 sync::Arc,
242 };
243
244 use crate::{
245 change::Lamport,
246 id::{Counter, PeerID},
247 span::{HasId, HasLamport},
248 };
249 use rle::{HasLength, Sliceable};
250
251 #[derive(Debug, Clone, PartialEq, Eq)]
252 struct TestNode {
253 id: ID,
254 lamport: Lamport,
255 len: usize,
256 deps: Arc<Frontiers>,
257 }
258
259 impl TestNode {
260 fn new(id: ID, lamport: Lamport, deps: Frontiers) -> Self {
261 Self {
262 id,
263 lamport,
264 len: 1,
265 deps: Arc::new(deps),
266 }
267 }
268 }
269
270 impl DagNode for TestNode {
271 fn deps(&self) -> &Frontiers {
272 &self.deps
273 }
274 }
275
276 impl Sliceable for TestNode {
277 fn slice(&self, _from: usize, _to: usize) -> Self {
278 self.clone()
279 }
280 }
281
282 impl HasLamport for TestNode {
283 fn lamport(&self) -> Lamport {
284 self.lamport
285 }
286 }
287
288 impl HasId for TestNode {
289 fn id_start(&self) -> ID {
290 self.id
291 }
292 }
293
294 impl HasLength for TestNode {
295 fn content_len(&self) -> usize {
296 self.len
297 }
298 }
299
300 #[derive(Debug)]
301 struct TestDag {
302 nodes: HashMap<PeerID, Vec<TestNode>>,
303 version_vec: crate::version::VersionVector,
304 }
305
306 impl TestDag {
307 fn new(nodes: Vec<TestNode>) -> Self {
308 let mut map: HashMap<PeerID, Vec<TestNode>> = HashMap::new();
309 let mut vv = crate::version::VersionVector::new();
310 for node in nodes {
311 vv.insert(node.id.peer, node.id.counter + node.len as Counter);
312 map.entry(node.id.peer).or_default().push(node);
313 }
314 for nodes in map.values_mut() {
315 nodes.sort_by(|a, b| match a.id.counter.cmp(&b.id.counter) {
316 Ordering::Equal => a.len.cmp(&b.len),
317 other => other,
318 });
319 }
320 Self {
321 nodes: map,
322 version_vec: vv,
323 }
324 }
325 }
326
327 impl Dag for TestDag {
328 type Node = TestNode;
329
330 fn get(&self, id: ID) -> Option<Self::Node> {
331 let arr = self.nodes.get(&id.peer)?;
332 arr.binary_search_by(|node| {
333 if node.id.counter > id.counter {
334 Ordering::Greater
335 } else if node.id.counter + node.len as i32 <= id.counter {
336 Ordering::Less
337 } else {
338 Ordering::Equal
339 }
340 })
341 .ok()
342 .map(|idx| arr[idx].clone())
343 }
344
345 fn frontier(&self) -> &Frontiers {
346 panic!("frontier is not used in dfs tests")
347 }
348
349 fn vv(&self) -> &crate::version::VersionVector {
350 &self.version_vec
351 }
352
353 fn contains(&self, id: ID) -> bool {
354 self.version_vec.includes_id(id)
355 }
356 }
357
358 fn id(peer: PeerID, counter: Counter) -> ID {
359 ID::new(peer, counter)
360 }
361
362 fn frontier(ids: &[ID]) -> Frontiers {
363 let mut frontier = Frontiers::new();
364 for id in ids {
365 frontier.push(*id);
366 }
367 frontier
368 }
369
370 fn as_set(ids: Vec<ID>) -> HashSet<ID> {
371 ids.into_iter().collect()
372 }
373
374 #[test]
375 fn get_end_list_collects_all_leaf_nodes_reachable_from_start() {
376 let graph = TestDag::new(vec![
377 TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])),
378 TestNode::new(id(2, 0), 7, Frontiers::new()),
379 TestNode::new(id(3, 0), 8, Frontiers::new()),
380 ]);
381
382 let ends = get_end_list(&graph, &frontier(&[id(1, 0)]));
383
384 assert_eq!(ends.len(), 2);
385 assert!(ends.contains(&id(2, 0)));
386 assert!(ends.contains(&id(3, 0)));
387 assert!(!ends.contains(&id(1, 0)));
388 }
389
390 #[test]
391 fn calc_critical_version_dfs_returns_non_start_nodes_when_no_end_is_present() {
392 let graph = TestDag::new(vec![
393 TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])),
394 TestNode::new(id(2, 0), 7, Frontiers::new()),
395 TestNode::new(id(3, 0), 8, Frontiers::new()),
396 ]);
397
398 let result = calc_critical_version_dfs(&graph, &frontier(&[id(1, 0)]), &Frontiers::new());
399
400 assert_eq!(as_set(result), as_set(vec![id(2, 0), id(3, 0)]));
401 }
402
403 #[test]
404 fn calc_critical_version_dfs_skips_candidates_when_an_end_is_on_every_start_path() {
405 let graph = TestDag::new(vec![
406 TestNode::new(id(1, 0), 10, frontier(&[id(2, 0), id(3, 0)])),
407 TestNode::new(id(2, 0), 7, Frontiers::new()),
408 TestNode::new(id(3, 0), 8, Frontiers::new()),
409 ]);
410
411 let result =
412 calc_critical_version_dfs(&graph, &frontier(&[id(1, 0)]), &frontier(&[id(2, 0)]));
413
414 assert!(result.is_empty());
415 }
416}