forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

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