Debian Codegraph @

core/src/dag_walk_async.rs

raw
1 // Copyright 2026 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! General-purpose async DAG algorithms.
16
17 use std::collections::BTreeSet;
18 use std::collections::BinaryHeap;
19 use std::collections::HashMap;
20 use std::collections::HashSet;
21 use std::hash::Hash;
22 use std::iter;
23 use std::mem;
24
25 use futures::Stream;
26 use futures::future::try_join_all;
27 use futures::stream;
28 use indexmap::IndexMap;
29 use itertools::Itertools as _;
30 use smallvec::SmallVec;
31 use smallvec::smallvec_inline;
32
33 /// Traverses nodes from `start` in depth-first order.
34 ///
35 /// An `Err` is emitted as a node with no neighbors. Caller may decide to
36 /// short-circuit on it.
37 pub fn dfs<T, ID, E, II, NI>(
38 start: II,
39 id_fn: impl Fn(&T) -> ID,
40 mut neighbors_fn: impl FnMut(&T) -> NI,
41 ) -> impl Iterator<Item = Result<T, E>>
42 where
43 ID: Hash + Eq,
44 II: IntoIterator<Item = Result<T, E>>,
45 NI: IntoIterator<Item = Result<T, E>>,
46 {
47 let mut work: Vec<Result<T, E>> = start.into_iter().collect();
48 let mut visited: HashSet<ID> = HashSet::new();
49 iter::from_fn(move || {
50 loop {
51 let c = match work.pop() {
52 Some(Ok(c)) => c,
53 r @ (Some(Err(_)) | None) => return r,
54 };
55 let id = id_fn(&c);
56 if visited.contains(&id) {
57 continue;
58 }
59 for p in neighbors_fn(&c) {
60 work.push(p);
61 }
62 visited.insert(id);
63 return Some(Ok(c));
64 }
65 })
66 }
67
68 /// Builds a list of `Ok` nodes reachable from the `start` where neighbors come
69 /// before the node itself.
70 ///
71 /// If `start` or `neighbors_fn()` yields an `Err`, this function terminates and
72 /// returns the error. If the graph has cycle, `cycle_fn()` is called with one
73 /// of the nodes involved in the cycle.
74 pub async fn topo_order_forward<T, ID, E, II, NI>(
75 start: II,
76 id_fn: impl Fn(&T) -> ID,
77 mut neighbors_fn: impl AsyncFnMut(&T) -> NI,
78 cycle_fn: impl FnOnce(T) -> E,
79 ) -> Result<Vec<T>, E>
80 where
81 ID: Hash + Eq + Clone,
82 II: IntoIterator<Item = Result<T, E>>,
83 NI: IntoIterator<Item = Result<T, E>>,
84 {
85 let mut stack: Vec<(T, bool)> = start.into_iter().map(|r| Ok((r?, false))).try_collect()?;
86 let mut visiting = HashSet::new();
87 let mut emitted = HashSet::new();
88 let mut result = vec![];
89 while let Some((node, neighbors_visited)) = stack.pop() {
90 let id = id_fn(&node);
91 if emitted.contains(&id) {
92 continue;
93 }
94 if !neighbors_visited {
95 if !visiting.insert(id.clone()) {
96 return Err(cycle_fn(node));
97 }
98 let neighbors_iter = neighbors_fn(&node).await.into_iter();
99 stack.reserve(neighbors_iter.size_hint().0 + 1);
100 stack.push((node, true));
101 for neighbor in neighbors_iter {
102 stack.push((neighbor?, false));
103 }
104 } else {
105 visiting.remove(&id);
106 emitted.insert(id);
107 result.push(node);
108 }
109 }
110 Ok(result)
111 }
112
113 /// Builds a list of `Ok` nodes reachable from the `start` where neighbors come
114 /// after the node itself.
115 ///
116 /// If `start` or `neighbors_fn()` yields an `Err`, this function terminates and
117 /// returns the error. If the graph has cycle, `cycle_fn()` is called with one
118 /// of the nodes involved in the cycle.
119 pub async fn topo_order_reverse<T, ID, E, II, NI>(
120 start: II,
121 id_fn: impl Fn(&T) -> ID,
122 neighbors_fn: impl AsyncFnMut(&T) -> NI,
123 cycle_fn: impl FnOnce(T) -> E,
124 ) -> Result<Vec<T>, E>
125 where
126 ID: Hash + Eq + Clone,
127 II: IntoIterator<Item = Result<T, E>>,
128 NI: IntoIterator<Item = Result<T, E>>,
129 {
130 let mut result = topo_order_forward(start, id_fn, neighbors_fn, cycle_fn).await?;
131 result.reverse();
132 Ok(result)
133 }
134
135 /// Like `topo_order_reverse()`, but can iterate linear DAG lazily.
136 ///
137 /// The DAG is supposed to be (mostly) topologically ordered by `T: Ord`.
138 /// For example, topological order of chronological data should respect
139 /// timestamp (except a few outliers caused by clock skew.)
140 ///
141 /// Use `topo_order_reverse()` if the DAG is heavily branched. This can
142 /// only process linear part lazily.
143 ///
144 /// The returned iterator short-circuits at an `Err`. Pending non-linear nodes
145 /// before the `Err` will be discarded. If the graph has cycle, `cycle_fn()` is
146 /// called with one of the nodes involved in the cycle.
147 pub fn topo_order_reverse_lazy<T, ID, E, II, NI>(
148 start: II,
149 id_fn: impl Fn(&T) -> ID,
150 neighbors_fn: impl AsyncFnMut(&T) -> NI,
151 cycle_fn: impl FnMut(T) -> E,
152 ) -> impl Stream<Item = Result<T, E>>
153 where
154 T: Ord,
155 ID: Hash + Eq + Clone,
156 II: IntoIterator<Item = Result<T, E>>,
157 NI: IntoIterator<Item = Result<T, E>>,
158 {
159 let mut inner = TopoOrderReverseLazyInner::empty();
160 inner.extend(start);
161 stream::unfold(
162 (inner, id_fn, neighbors_fn, cycle_fn),
163 |(mut inner, id_fn, mut neighbors_fn, mut cycle_fn)| async move {
164 inner
165 .next(&id_fn, &mut neighbors_fn, &mut cycle_fn)
166 .await
167 .map(|result| (result, (inner, id_fn, neighbors_fn, cycle_fn)))
168 },
169 )
170 }
171
172 #[derive(Clone, Debug)]
173 struct TopoOrderReverseLazyInner<T, ID, E> {
174 start: Vec<T>,
175 result: Vec<Result<T, E>>,
176 emitted: HashSet<ID>,
177 }
178
179 impl<T: Ord, ID: Hash + Eq + Clone, E> TopoOrderReverseLazyInner<T, ID, E> {
180 fn empty() -> Self {
181 Self {
182 start: Vec::new(),
183 result: Vec::new(),
184 emitted: HashSet::new(),
185 }
186 }
187
188 fn extend(&mut self, iter: impl IntoIterator<Item = Result<T, E>>) {
189 let iter = iter.into_iter();
190 self.start.reserve(iter.size_hint().0);
191 for res in iter {
192 if let Ok(node) = res {
193 self.start.push(node);
194 } else {
195 // Emit the error and terminate
196 self.start.clear();
197 self.result.insert(0, res);
198 return;
199 }
200 }
201 }
202
203 async fn next<NI: IntoIterator<Item = Result<T, E>>>(
204 &mut self,
205 id_fn: impl Fn(&T) -> ID,
206 mut neighbors_fn: impl AsyncFnMut(&T) -> NI,
207 mut cycle_fn: impl FnMut(T) -> E,
208 ) -> Option<Result<T, E>> {
209 if let Some(res) = self.result.pop() {
210 return Some(res);
211 }
212
213 // Fast path for linear DAG
214 if self.start.len() <= 1 {
215 let node = self.start.pop()?;
216 self.extend(neighbors_fn(&node).await);
217 if self.emitted.insert(id_fn(&node)) {
218 return Some(Ok(node));
219 } else {
220 return Some(Err(cycle_fn(node)));
221 }
222 }
223
224 // Extract graph nodes based on T's order, and sort them by using ids
225 // (because we wouldn't want to clone T itself)
226 let start_ids = self.start.iter().map(&id_fn).collect_vec();
227 match look_ahead_sub_graph(mem::take(&mut self.start), &id_fn, &mut neighbors_fn).await {
228 Ok((mut node_map, neighbor_ids_map, remainder)) => {
229 self.start = remainder;
230 let sorted_ids = match topo_order_forward(
231 start_ids.iter().map(Ok),
232 |id| *id,
233 async |id| neighbor_ids_map[id].iter().map(Ok),
234 |id| cycle_fn(node_map.remove(id).unwrap()),
235 )
236 .await
237 {
238 Ok(ids) => ids,
239 Err(err) => return Some(Err(err)),
240 };
241 self.result.reserve(sorted_ids.len());
242 for id in sorted_ids {
243 let (id, node) = node_map.remove_entry(id).unwrap();
244 if self.emitted.insert(id) {
245 self.result.push(Ok(node));
246 } else {
247 self.result.push(Err(cycle_fn(node)));
248 }
249 }
250 self.result.pop()
251 }
252 Err(err) => Some(Err(err)),
253 }
254 }
255 }
256
257 /// Splits DAG at the first single fork point, and builds a list of nodes
258 /// reachable from the `start` where neighbors come after the node itself.
259 ///
260 /// This is a building block for lazy DAG iterators similar to
261 /// [`topo_order_reverse_lazy()`]. The `start` list will be updated to
262 /// include the next nodes to visit.
263 ///
264 /// If the split chunk of the graph has cycle, `cycle_fn()` is called with one
265 /// of the nodes involved in the cycle.
266 pub async fn topo_order_reverse_chunked<T, ID, E, NI>(
267 start: &mut Vec<T>,
268 id_fn: impl Fn(&T) -> ID,
269 mut neighbors_fn: impl AsyncFnMut(&T) -> NI,
270 mut cycle_fn: impl FnMut(T) -> E,
271 ) -> Result<SmallVec<[T; 1]>, E>
272 where
273 T: Ord,
274 ID: Hash + Eq + Clone,
275 NI: IntoIterator<Item = Result<T, E>>,
276 {
277 // Fast path for linear DAG
278 if start.len() <= 1 {
279 let Some(node) = start.pop() else {
280 return Ok(SmallVec::new());
281 };
282 let neighbors_iter = neighbors_fn(&node).await.into_iter();
283 start.reserve(neighbors_iter.size_hint().0);
284 for neighbor in neighbors_iter {
285 start.push(neighbor?);
286 }
287 return Ok(smallvec_inline![node]);
288 }
289
290 // Extract graph nodes based on T's order, and sort them by using ids
291 // (because we wouldn't want to clone T itself)
292 let start_ids = start.iter().map(&id_fn).collect_vec();
293 let (mut node_map, neighbor_ids_map, remainder) =
294 look_ahead_sub_graph(mem::take(start), &id_fn, &mut neighbors_fn).await?;
295 *start = remainder;
296 let sorted_ids = topo_order_forward(
297 start_ids.iter().map(Ok),
298 |id| *id,
299 async |id| neighbor_ids_map[id].iter().map(Ok),
300 |id| cycle_fn(node_map.remove(id).unwrap()),
301 )
302 .await?;
303 let sorted_nodes = sorted_ids
304 .iter()
305 .rev()
306 .map(|&id| node_map.remove(id).unwrap())
307 .collect();
308 Ok(sorted_nodes)
309 }
310
311 /// Splits DAG at single fork point, and extracts branchy part as sub graph.
312 ///
313 /// ```text
314 /// o | C
315 /// | o B
316 /// |/ <---- split here (A->B or A->C would create cycle)
317 /// o A
318 /// ```
319 ///
320 /// If a branch reached to root (empty neighbors), the graph can't be split
321 /// anymore because the other branch may be connected to a descendant of
322 /// the rooted branch.
323 ///
324 /// ```text
325 /// o | C
326 /// | o B
327 /// | <---- can't split here (there may be edge A->B)
328 /// o A
329 /// ```
330 ///
331 /// We assume the graph is (mostly) topologically ordered by `T: Ord`.
332 async fn look_ahead_sub_graph<T, ID, E, NI>(
333 start: Vec<T>,
334 id_fn: impl Fn(&T) -> ID,
335 mut neighbors_fn: impl AsyncFnMut(&T) -> NI,
336 ) -> Result<(HashMap<ID, T>, HashMap<ID, Vec<ID>>, Vec<T>), E>
337 where
338 T: Ord,
339 ID: Hash + Eq + Clone,
340 NI: IntoIterator<Item = Result<T, E>>,
341 {
342 let mut queue: BinaryHeap<T> = start.into();
343 // Build separate node/neighbors maps since lifetime is different at caller
344 let mut node_map: HashMap<ID, T> = HashMap::new();
345 let mut neighbor_ids_map: HashMap<ID, Vec<ID>> = HashMap::new();
346 let mut has_reached_root = false;
347 while queue.len() > 1 || node_map.is_empty() || has_reached_root {
348 let Some(node) = queue.pop() else {
349 break;
350 };
351 let node_id = id_fn(&node);
352 if node_map.contains_key(&node_id) {
353 continue;
354 }
355
356 let mut neighbor_ids = Vec::new();
357 let mut neighbors_iter = neighbors_fn(&node).await.into_iter().peekable();
358 has_reached_root |= neighbors_iter.peek().is_none();
359 for neighbor in neighbors_iter {
360 let neighbor = neighbor?;
361 neighbor_ids.push(id_fn(&neighbor));
362 queue.push(neighbor);
363 }
364 node_map.insert(node_id.clone(), node);
365 neighbor_ids_map.insert(node_id, neighbor_ids);
366 }
367
368 assert!(queue.len() <= 1, "order of remainder shouldn't matter");
369 let remainder = queue.into_vec();
370
371 // Omit unvisited neighbors
372 if let Some(unvisited_id) = remainder.first().map(&id_fn) {
373 for neighbor_ids in neighbor_ids_map.values_mut() {
374 neighbor_ids.retain(|id| *id != unvisited_id);
375 }
376 }
377
378 Ok((node_map, neighbor_ids_map, remainder))
379 }
380
381 /// Builds a list of `Ok` nodes reachable from the `start` where neighbors come
382 /// after the node itself.
383 ///
384 /// Unlike `topo_order_reverse()`, nodes are sorted in reverse `T: Ord` order
385 /// so long as they can respect the topological requirement.
386 ///
387 /// If `start` or `neighbors_fn()` yields an `Err`, this function terminates and
388 /// returns the error. If the graph has cycle, `cycle_fn()` is called with one
389 /// of the nodes involved in the cycle.
390 pub async fn topo_order_reverse_ord<T, ID, E, II, NI>(
391 start: II,
392 id_fn: impl Fn(&T) -> ID,
393 mut neighbors_fn: impl AsyncFnMut(&T) -> NI,
394 cycle_fn: impl FnOnce(T) -> E,
395 ) -> Result<Vec<T>, E>
396 where
397 T: Ord,
398 ID: Hash + Eq + Clone,
399 II: IntoIterator<Item = Result<T, E>>,
400 NI: IntoIterator<Item = Result<T, E>>,
401 {
402 struct InnerNode<T> {
403 node: Option<T>,
404 indegree: usize,
405 }
406
407 // DFS to accumulate incoming edges
408 let mut stack: Vec<T> = start.into_iter().try_collect()?;
409 let mut head_node_map: HashMap<ID, T> = HashMap::new();
410 let mut inner_node_map: HashMap<ID, InnerNode<T>> = HashMap::new();
411 let mut neighbor_ids_map: HashMap<ID, Vec<ID>> = HashMap::new();
412 while let Some(node) = stack.pop() {
413 let node_id = id_fn(&node);
414 if neighbor_ids_map.contains_key(&node_id) {
415 continue; // Already visited
416 }
417
418 let neighbors_iter = neighbors_fn(&node).await.into_iter();
419 let pos = stack.len();
420 stack.reserve(neighbors_iter.size_hint().0);
421 for neighbor in neighbors_iter {
422 stack.push(neighbor?);
423 }
424 let neighbor_ids = stack[pos..].iter().map(&id_fn).collect_vec();
425 if let Some(inner) = inner_node_map.get_mut(&node_id) {
426 inner.node = Some(node);
427 } else {
428 head_node_map.insert(node_id.clone(), node);
429 }
430
431 for neighbor_id in &neighbor_ids {
432 if let Some(inner) = inner_node_map.get_mut(neighbor_id) {
433 inner.indegree += 1;
434 } else {
435 let inner = InnerNode {
436 node: head_node_map.remove(neighbor_id),
437 indegree: 1,
438 };
439 inner_node_map.insert(neighbor_id.clone(), inner);
440 }
441 }
442 neighbor_ids_map.insert(node_id, neighbor_ids);
443 }
444
445 debug_assert!(
446 head_node_map
447 .keys()
448 .all(|id| !inner_node_map.contains_key(id))
449 );
450 debug_assert!(inner_node_map.values().all(|inner| inner.node.is_some()));
451 debug_assert!(inner_node_map.values().all(|inner| inner.indegree > 0));
452
453 // Using Kahn's algorithm
454 let mut queue: BinaryHeap<T> = head_node_map.into_values().collect();
455 let mut result = Vec::new();
456 while let Some(node) = queue.pop() {
457 let node_id = id_fn(&node);
458 result.push(node);
459 for neighbor_id in neighbor_ids_map.remove(&node_id).unwrap() {
460 let inner = inner_node_map.get_mut(&neighbor_id).unwrap();
461 inner.indegree -= 1;
462 if inner.indegree == 0 {
463 queue.push(inner.node.take().unwrap());
464 inner_node_map.remove(&neighbor_id);
465 }
466 }
467 }
468
469 if let Some(inner) = inner_node_map.into_values().next() {
470 Err(cycle_fn(inner.node.unwrap()))
471 } else {
472 Ok(result)
473 }
474 }
475
476 /// Finds `Ok` nodes in the start set that are not reachable from other nodes in
477 /// the start set.
478 ///
479 /// If `start` or `neighbors_fn()` yields an `Err`, this function terminates and
480 /// returns the error.
481 pub async fn heads<T, ID, E, II, NI>(
482 start: II,
483 id_fn: impl Fn(&T) -> ID,
484 neighbors_fn: impl AsyncFn(&T) -> Result<NI, E>,
485 ) -> Result<HashSet<T>, E>
486 where
487 T: Hash + Eq + Clone,
488 ID: Hash + Eq,
489 II: IntoIterator<Item = T>,
490 NI: IntoIterator<Item = T>,
491 {
492 let mut heads: HashSet<T> = start.into_iter().collect();
493 // Do a BFS until we have only one item left in the frontier. That frontier must
494 // have originated from one of the heads, and since there can't be cycles,
495 // it won't be able to eliminate any other heads.
496 let mut frontier: Vec<T> = heads.iter().cloned().collect();
497 let mut visited: HashSet<ID> = heads.iter().map(&id_fn).collect();
498 let mut root_reached = false;
499 while frontier.len() > 1 || (!frontier.is_empty() && root_reached) {
500 let neighbors_lists = try_join_all(frontier.iter().map(|node| neighbors_fn(node))).await?;
501 let mut new_frontier = vec![];
502 for neighbors in neighbors_lists {
503 let length_before = new_frontier.len();
504 new_frontier.extend(neighbors);
505 root_reached |= new_frontier.len() == length_before;
506 }
507 frontier = new_frontier;
508 for node in &frontier {
509 heads.remove(node);
510 }
511 frontier.retain(|node| visited.insert(id_fn(node)));
512 }
513 Ok(heads)
514 }
515
516 /// Finds the closest common `Ok` neighbors among the `set1` and `set2`. Uses
517 /// `T`'s `Ord` implementation as a heuristic for determining which neighbor to
518 /// visit next. The neighbor that compares greater will be visited first.
519 ///
520 /// If the traverse reached to an `Err`, this function terminates and returns
521 /// the error.
522 pub async fn closest_common_nodes<T, ID, E, II1, II2, NI>(
523 set1: II1,
524 set2: II2,
525 id_fn: impl Fn(&T) -> ID,
526 neighbors_fn: impl AsyncFn(&T) -> Result<NI, E>,
527 ) -> Result<Vec<T>, E>
528 where
529 T: Ord,
530 ID: Hash + Eq,
531 II1: IntoIterator<Item = T>,
532 II2: IntoIterator<Item = T>,
533 NI: IntoIterator<Item = T>,
534 {
535 type Reachability = u8;
536 const LEFT: Reachability = 1;
537 const RIGHT: Reachability = 2;
538 const BOTH: Reachability = LEFT | RIGHT;
539 const NON_CLOSEST: Reachability = 4;
540
541 let mut reachable: HashMap<ID, Reachability> = HashMap::new();
542 let mut work: BTreeSet<T> = BTreeSet::new();
543
544 let mark_reachable = |reachable: &mut HashMap<ID, Reachability>, id: ID, side: Reachability| {
545 reachable
546 .entry(id)
547 .and_modify(|existing_side| {
548 *existing_side |= side;
549 })
550 .or_insert(side);
551 };
552
553 for node in set1 {
554 reachable.insert(id_fn(&node), LEFT);
555 work.insert(node);
556 }
557 for node in set2 {
558 mark_reachable(&mut reachable, id_fn(&node), RIGHT);
559 work.insert(node);
560 }
561
562 // Nodes reachable from both sets, keyed by their ids.
563 let mut candidates = IndexMap::new();
564 let mut root_reached = false;
565 while let Some(node) = work.pop_last() {
566 let id = id_fn(&node);
567 let side = *reachable.get(&id).unwrap();
568 let neighbors = neighbors_fn(&node).await;
569 if side & BOTH == BOTH {
570 if candidates.insert(id, node).is_some() {
571 continue;
572 }
573 if work.is_empty() && !root_reached {
574 break;
575 }
576 // We continue walking ancestors of this node in order to possibly
577 // terminate the walk from the other set early when we reach one of
578 // these non-closest common ancestors.
579 }
580 let mut is_root = true;
581 for neighbor in neighbors? {
582 is_root = false;
583 let neighbor_id = id_fn(&neighbor);
584 if side & BOTH == BOTH {
585 mark_reachable(&mut reachable, neighbor_id, BOTH | NON_CLOSEST);
586 } else {
587 mark_reachable(&mut reachable, neighbor_id, side);
588 }
589 work.insert(neighbor);
590 }
591 root_reached |= is_root;
592 }
593
594 let closest = candidates
595 .into_iter()
596 .filter_map(|(id, node)| {
597 (*reachable.get(&id).unwrap() & NON_CLOSEST != NON_CLOSEST).then_some(node)
598 })
599 .collect();
600 Ok(closest)
601 }
602
603 #[cfg(test)]
604 mod tests {
605 use std::pin::pin;
606
607 use assert_matches::assert_matches;
608 use futures::StreamExt as _;
609 use futures::TryStreamExt as _;
610 use maplit::hashmap;
611 use maplit::hashset;
612 use pollster::FutureExt as _;
613
614 use super::*;
615
616 fn to_ok_iter(
617 iter: impl IntoIterator<Item = char>,
618 ) -> impl Iterator<Item = Result<char, char>> {
619 iter.into_iter().map(Ok)
620 }
621
622 #[test]
623 fn test_dfs() {
624 let neighbors = hashmap! {
625 'A' => vec![],
626 'B' => vec![Ok('A'), Err('X')],
627 'C' => vec![Ok('B')],
628 };
629 let id_fn = |node: &char| *node;
630 let neighbors_fn = |node: &char| neighbors[node].clone();
631
632 // Self and neighbor nodes shouldn't be lost at the error.
633 let nodes = dfs([Ok('C')], id_fn, neighbors_fn).collect_vec();
634 assert_eq!(nodes, [Ok('C'), Ok('B'), Err('X'), Ok('A')]);
635 }
636
637 #[test]
638 fn test_topo_order_reverse_linear() {
639 // This graph:
640 // o C
641 // o B
642 // o A
643
644 let neighbors = hashmap! {
645 'A' => vec![],
646 'B' => vec!['A'],
647 'C' => vec!['B'],
648 };
649 let id_fn = |node: &char| *node;
650 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
651 let cycle_fn = |id| id;
652
653 let common = topo_order_reverse(vec![Ok('C')], id_fn, neighbors_fn, cycle_fn)
654 .block_on()
655 .unwrap();
656 assert_eq!(common, vec!['C', 'B', 'A']);
657 let common = topo_order_reverse(vec![Ok('C'), Ok('B')], id_fn, neighbors_fn, cycle_fn)
658 .block_on()
659 .unwrap();
660 assert_eq!(common, vec!['C', 'B', 'A']);
661 let common = topo_order_reverse(vec![Ok('B'), Ok('C')], id_fn, neighbors_fn, cycle_fn)
662 .block_on()
663 .unwrap();
664 assert_eq!(common, vec!['C', 'B', 'A']);
665
666 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('C')], id_fn, neighbors_fn, cycle_fn)
667 .try_collect()
668 .block_on()
669 .unwrap();
670 assert_eq!(common, vec!['C', 'B', 'A']);
671 let common: Vec<_> =
672 topo_order_reverse_lazy(vec![Ok('C'), Ok('B')], id_fn, neighbors_fn, cycle_fn)
673 .try_collect()
674 .block_on()
675 .unwrap();
676 assert_eq!(common, vec!['C', 'B', 'A']);
677 let common: Vec<_> =
678 topo_order_reverse_lazy(vec![Ok('B'), Ok('C')], id_fn, neighbors_fn, cycle_fn)
679 .try_collect()
680 .block_on()
681 .unwrap();
682 assert_eq!(common, vec!['C', 'B', 'A']);
683
684 let common = topo_order_reverse_ord(vec![Ok('C')], id_fn, neighbors_fn, cycle_fn)
685 .block_on()
686 .unwrap();
687 assert_eq!(common, vec!['C', 'B', 'A']);
688 let common = topo_order_reverse_ord(vec![Ok('C'), Ok('B')], id_fn, neighbors_fn, cycle_fn)
689 .block_on()
690 .unwrap();
691 assert_eq!(common, vec!['C', 'B', 'A']);
692 let common = topo_order_reverse_ord(vec![Ok('B'), Ok('C')], id_fn, neighbors_fn, cycle_fn)
693 .block_on()
694 .unwrap();
695 assert_eq!(common, vec!['C', 'B', 'A']);
696 }
697
698 #[test]
699 fn test_topo_order_reverse_merge() {
700 // This graph:
701 // o F
702 // |\
703 // o | E
704 // | o D
705 // | o C
706 // | o B
707 // |/
708 // o A
709
710 let neighbors = hashmap! {
711 'A' => vec![],
712 'B' => vec!['A'],
713 'C' => vec!['B'],
714 'D' => vec!['C'],
715 'E' => vec!['A'],
716 'F' => vec!['E', 'D'],
717 };
718 let id_fn = |node: &char| *node;
719 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
720 let cycle_fn = |id| id;
721
722 let common = topo_order_reverse(vec![Ok('F')], id_fn, neighbors_fn, cycle_fn)
723 .block_on()
724 .unwrap();
725 assert_eq!(common, vec!['F', 'E', 'D', 'C', 'B', 'A']);
726 let common = topo_order_reverse(
727 vec![Ok('F'), Ok('E'), Ok('C')],
728 id_fn,
729 neighbors_fn,
730 cycle_fn,
731 )
732 .block_on()
733 .unwrap();
734 assert_eq!(common, vec!['F', 'D', 'E', 'C', 'B', 'A']);
735 let common = topo_order_reverse(
736 vec![Ok('F'), Ok('D'), Ok('E')],
737 id_fn,
738 neighbors_fn,
739 cycle_fn,
740 )
741 .block_on()
742 .unwrap();
743 assert_eq!(common, vec!['F', 'D', 'C', 'B', 'E', 'A']);
744
745 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('F')], id_fn, neighbors_fn, cycle_fn)
746 .try_collect()
747 .block_on()
748 .unwrap();
749 assert_eq!(common, vec!['F', 'E', 'D', 'C', 'B', 'A']);
750 let common: Vec<_> = topo_order_reverse_lazy(
751 vec![Ok('F'), Ok('E'), Ok('C')],
752 id_fn,
753 neighbors_fn,
754 cycle_fn,
755 )
756 .try_collect()
757 .block_on()
758 .unwrap();
759 assert_eq!(common, vec!['F', 'D', 'E', 'C', 'B', 'A']);
760 let common: Vec<_> = topo_order_reverse_lazy(
761 vec![Ok('F'), Ok('D'), Ok('E')],
762 id_fn,
763 neighbors_fn,
764 cycle_fn,
765 )
766 .try_collect()
767 .block_on()
768 .unwrap();
769 assert_eq!(common, vec!['F', 'D', 'C', 'B', 'E', 'A']);
770
771 let common = topo_order_reverse_ord(vec![Ok('F')], id_fn, neighbors_fn, cycle_fn)
772 .block_on()
773 .unwrap();
774 assert_eq!(common, vec!['F', 'E', 'D', 'C', 'B', 'A']);
775 let common = topo_order_reverse_ord(
776 vec![Ok('F'), Ok('E'), Ok('C')],
777 id_fn,
778 neighbors_fn,
779 cycle_fn,
780 )
781 .block_on()
782 .unwrap();
783 assert_eq!(common, vec!['F', 'E', 'D', 'C', 'B', 'A']);
784 let common = topo_order_reverse_ord(
785 vec![Ok('F'), Ok('D'), Ok('E')],
786 id_fn,
787 neighbors_fn,
788 cycle_fn,
789 )
790 .block_on()
791 .unwrap();
792 assert_eq!(common, vec!['F', 'E', 'D', 'C', 'B', 'A']);
793 }
794
795 #[test]
796 fn test_topo_order_reverse_nested_merges() {
797 // This graph:
798 // o I
799 // |\
800 // | o H
801 // | |\
802 // | | o G
803 // | o | F
804 // | | o E
805 // o |/ D
806 // | o C
807 // o | B
808 // |/
809 // o A
810
811 let neighbors = hashmap! {
812 'A' => vec![],
813 'B' => vec!['A'],
814 'C' => vec!['A'],
815 'D' => vec!['B'],
816 'E' => vec!['C'],
817 'F' => vec!['C'],
818 'G' => vec!['E'],
819 'H' => vec!['F', 'G'],
820 'I' => vec!['D', 'H'],
821 };
822 let id_fn = |node: &char| *node;
823 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
824 let cycle_fn = |id| id;
825
826 let common = topo_order_reverse(vec![Ok('I')], id_fn, neighbors_fn, cycle_fn)
827 .block_on()
828 .unwrap();
829 assert_eq!(common, vec!['I', 'D', 'B', 'H', 'F', 'G', 'E', 'C', 'A']);
830
831 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('I')], id_fn, neighbors_fn, cycle_fn)
832 .try_collect()
833 .block_on()
834 .unwrap();
835 assert_eq!(common, vec!['I', 'D', 'B', 'H', 'F', 'G', 'E', 'C', 'A']);
836
837 let common = topo_order_reverse_ord(vec![Ok('I')], id_fn, neighbors_fn, cycle_fn)
838 .block_on()
839 .unwrap();
840 assert_eq!(common, vec!['I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']);
841 }
842
843 #[test]
844 fn test_topo_order_reverse_nested_merges_bad_order() {
845 // This graph:
846 // o I
847 // |\
848 // | |\
849 // | | |\
850 // | | | o h (h > I)
851 // | | |/|
852 // | | o | G
853 // | |/| o f
854 // | o |/ e (e > I, G)
855 // |/| o D
856 // o |/ C
857 // | o b (b > D)
858 // |/
859 // o A
860
861 let neighbors = hashmap! {
862 'A' => vec![],
863 'b' => vec!['A'],
864 'C' => vec!['A'],
865 'D' => vec!['b'],
866 'e' => vec!['C', 'b'],
867 'f' => vec!['D'],
868 'G' => vec!['e', 'D'],
869 'h' => vec!['G', 'f'],
870 'I' => vec!['C', 'e', 'G', 'h'],
871 };
872 let id_fn = |node: &char| *node;
873 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
874 let cycle_fn = |id| id;
875
876 let common = topo_order_reverse(vec![Ok('I')], id_fn, neighbors_fn, cycle_fn)
877 .block_on()
878 .unwrap();
879 assert_eq!(common, vec!['I', 'h', 'G', 'e', 'C', 'f', 'D', 'b', 'A']);
880
881 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('I')], id_fn, neighbors_fn, cycle_fn)
882 .try_collect()
883 .block_on()
884 .unwrap();
885 assert_eq!(common, vec!['I', 'h', 'G', 'e', 'C', 'f', 'D', 'b', 'A']);
886
887 let common = topo_order_reverse_ord(vec![Ok('I')], id_fn, neighbors_fn, cycle_fn)
888 .block_on()
889 .unwrap();
890 assert_eq!(common, vec!['I', 'h', 'f', 'G', 'e', 'D', 'b', 'C', 'A']);
891 }
892
893 #[test]
894 fn test_topo_order_reverse_merge_bad_fork_order_at_root() {
895 // This graph:
896 // o E
897 // |\
898 // o | D
899 // | o C
900 // | o B
901 // |/
902 // o a (a > D, B)
903
904 let neighbors = hashmap! {
905 'a' => vec![],
906 'B' => vec!['a'],
907 'C' => vec!['B'],
908 'D' => vec!['a'],
909 'E' => vec!['D', 'C'],
910 };
911 let id_fn = |node: &char| *node;
912 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
913 let cycle_fn = |id| id;
914
915 let common = topo_order_reverse(vec![Ok('E')], id_fn, neighbors_fn, cycle_fn)
916 .block_on()
917 .unwrap();
918 assert_eq!(common, vec!['E', 'D', 'C', 'B', 'a']);
919
920 // The root node 'a' is visited before 'C'. If the graph were split there,
921 // the branch 'C->B->a' would be orphaned.
922 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('E')], id_fn, neighbors_fn, cycle_fn)
923 .try_collect()
924 .block_on()
925 .unwrap();
926 assert_eq!(common, vec!['E', 'D', 'C', 'B', 'a']);
927
928 let common = topo_order_reverse_ord(vec![Ok('E')], id_fn, neighbors_fn, cycle_fn)
929 .block_on()
930 .unwrap();
931 assert_eq!(common, vec!['E', 'D', 'C', 'B', 'a']);
932 }
933
934 #[test]
935 fn test_topo_order_reverse_merge_and_linear() {
936 // This graph:
937 // o G
938 // |\
939 // | o F
940 // o | E
941 // | o D
942 // |/
943 // o C
944 // o B
945 // o A
946
947 let neighbors = hashmap! {
948 'A' => vec![],
949 'B' => vec!['A'],
950 'C' => vec!['B'],
951 'D' => vec!['C'],
952 'E' => vec!['C'],
953 'F' => vec!['D'],
954 'G' => vec!['E', 'F'],
955 };
956 let id_fn = |node: &char| *node;
957 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
958 let cycle_fn = |id| id;
959
960 let common = topo_order_reverse(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
961 .block_on()
962 .unwrap();
963 assert_eq!(common, vec!['G', 'E', 'F', 'D', 'C', 'B', 'A']);
964
965 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
966 .try_collect()
967 .block_on()
968 .unwrap();
969 assert_eq!(common, vec!['G', 'E', 'F', 'D', 'C', 'B', 'A']);
970
971 let common = topo_order_reverse_ord(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
972 .block_on()
973 .unwrap();
974 assert_eq!(common, vec!['G', 'F', 'E', 'D', 'C', 'B', 'A']);
975
976 // Iterator can be lazy for linear chunks.
977 let mut inner_iter = TopoOrderReverseLazyInner::empty();
978 inner_iter.extend([Ok('G')]);
979 assert_eq!(
980 inner_iter.next(id_fn, neighbors_fn, cycle_fn).block_on(),
981 Some(Ok('G'))
982 );
983 assert!(!inner_iter.start.is_empty());
984 assert!(inner_iter.result.is_empty());
985 assert_eq!(
986 iter::from_fn(|| inner_iter.next(id_fn, neighbors_fn, cycle_fn).block_on())
987 .take(4)
988 .collect_vec(),
989 ['E', 'F', 'D', 'C'].map(Ok),
990 );
991 assert!(!inner_iter.start.is_empty());
992 assert!(inner_iter.result.is_empty());
993
994 // Run each step of lazy iterator by using low-level function.
995 let mut start = vec!['G'];
996 let next = |start: &mut Vec<char>| {
997 topo_order_reverse_chunked(start, id_fn, neighbors_fn, cycle_fn)
998 .block_on()
999 .unwrap()
1000 };
1001 assert_eq!(next(&mut start), ['G'].into());
1002 assert_eq!(start, ['E', 'F']);
1003 assert_eq!(next(&mut start), ['E', 'F', 'D', 'C'].into());
1004 assert_eq!(start, ['B']);
1005 assert_eq!(next(&mut start), ['B'].into());
1006 assert_eq!(start, ['A']);
1007 assert_eq!(next(&mut start), ['A'].into());
1008 assert!(start.is_empty());
1009 assert!(next(&mut start).is_empty());
1010 assert!(start.is_empty());
1011 }
1012
1013 #[test]
1014 fn test_topo_order_reverse_merge_and_linear_bad_fork_order() {
1015 // This graph:
1016 // o G
1017 // |\
1018 // o | F
1019 // o | E
1020 // | o D
1021 // |/
1022 // o c (c > E, D)
1023 // o B
1024 // o A
1025
1026 let neighbors = hashmap! {
1027 'A' => vec![],
1028 'B' => vec!['A'],
1029 'c' => vec!['B'],
1030 'D' => vec!['c'],
1031 'E' => vec!['c'],
1032 'F' => vec!['E'],
1033 'G' => vec!['F', 'D'],
1034 };
1035 let id_fn = |node: &char| *node;
1036 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
1037 let cycle_fn = |id| id;
1038
1039 let common = topo_order_reverse(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
1040 .block_on()
1041 .unwrap();
1042 assert_eq!(common, vec!['G', 'F', 'E', 'D', 'c', 'B', 'A']);
1043
1044 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
1045 .try_collect()
1046 .block_on()
1047 .unwrap();
1048 assert_eq!(common, vec!['G', 'F', 'E', 'D', 'c', 'B', 'A']);
1049
1050 let common = topo_order_reverse_ord(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
1051 .block_on()
1052 .unwrap();
1053 assert_eq!(common, vec!['G', 'F', 'E', 'D', 'c', 'B', 'A']);
1054
1055 // Iterator can be lazy for linear chunks. The node 'c' is visited before 'D',
1056 // but it will be processed lazily.
1057 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
1058 let mut inner_iter = TopoOrderReverseLazyInner::empty();
1059 inner_iter.extend([Ok('G')]);
1060 assert_eq!(
1061 inner_iter.next(id_fn, neighbors_fn, cycle_fn).block_on(),
1062 Some(Ok('G'))
1063 );
1064 assert!(!inner_iter.start.is_empty());
1065 assert!(inner_iter.result.is_empty());
1066 assert_eq!(
1067 iter::from_fn(|| inner_iter.next(id_fn, neighbors_fn, cycle_fn).block_on())
1068 .take(4)
1069 .collect_vec(),
1070 ['F', 'E', 'D', 'c'].map(Ok),
1071 );
1072 assert!(!inner_iter.start.is_empty());
1073 assert!(inner_iter.result.is_empty());
1074
1075 // Run each step of lazy iterator by using low-level function.
1076 let mut start = vec!['G'];
1077 let next = |start: &mut Vec<char>| {
1078 topo_order_reverse_chunked(start, id_fn, neighbors_fn, cycle_fn)
1079 .block_on()
1080 .unwrap()
1081 };
1082 assert_eq!(next(&mut start), ['G'].into());
1083 assert_eq!(start, ['F', 'D']);
1084 assert_eq!(next(&mut start), ['F', 'E', 'D', 'c'].into());
1085 assert_eq!(start, ['B']);
1086 assert_eq!(next(&mut start), ['B'].into());
1087 assert_eq!(start, ['A']);
1088 assert_eq!(next(&mut start), ['A'].into());
1089 assert!(start.is_empty());
1090 assert!(next(&mut start).is_empty());
1091 assert!(start.is_empty());
1092 }
1093
1094 #[test]
1095 fn test_topo_order_reverse_merge_and_linear_bad_merge_order() {
1096 // This graph:
1097 // o G
1098 // |\
1099 // o | f (f > G)
1100 // o | e
1101 // | o d (d > G)
1102 // |/
1103 // o C
1104 // o B
1105 // o A
1106
1107 let neighbors = hashmap! {
1108 'A' => vec![],
1109 'B' => vec!['A'],
1110 'C' => vec!['B'],
1111 'd' => vec!['C'],
1112 'e' => vec!['C'],
1113 'f' => vec!['e'],
1114 'G' => vec!['f', 'd'],
1115 };
1116 let id_fn = |node: &char| *node;
1117 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
1118 let cycle_fn = |id| id;
1119
1120 let common = topo_order_reverse(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
1121 .block_on()
1122 .unwrap();
1123 assert_eq!(common, vec!['G', 'f', 'e', 'd', 'C', 'B', 'A']);
1124
1125 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
1126 .try_collect()
1127 .block_on()
1128 .unwrap();
1129 assert_eq!(common, vec!['G', 'f', 'e', 'd', 'C', 'B', 'A']);
1130
1131 let common = topo_order_reverse_ord(vec![Ok('G')], id_fn, neighbors_fn, cycle_fn)
1132 .block_on()
1133 .unwrap();
1134 assert_eq!(common, vec!['G', 'f', 'e', 'd', 'C', 'B', 'A']);
1135
1136 // Iterator can be lazy for linear chunks.
1137 let mut inner_iter = TopoOrderReverseLazyInner::empty();
1138 inner_iter.extend([Ok('G')]);
1139 assert_eq!(
1140 inner_iter.next(id_fn, neighbors_fn, cycle_fn).block_on(),
1141 Some(Ok('G'))
1142 );
1143 assert!(!inner_iter.start.is_empty());
1144 assert!(inner_iter.result.is_empty());
1145 assert_eq!(
1146 iter::from_fn(|| inner_iter.next(id_fn, neighbors_fn, cycle_fn).block_on())
1147 .take(4)
1148 .collect_vec(),
1149 ['f', 'e', 'd', 'C'].map(Ok),
1150 );
1151 assert!(!inner_iter.start.is_empty());
1152 assert!(inner_iter.result.is_empty());
1153
1154 // Run each step of lazy iterator by using low-level function.
1155 let mut start = vec!['G'];
1156 let next = |start: &mut Vec<char>| {
1157 topo_order_reverse_chunked(start, id_fn, neighbors_fn, cycle_fn)
1158 .block_on()
1159 .unwrap()
1160 };
1161 assert_eq!(next(&mut start), ['G'].into());
1162 assert_eq!(start, ['f', 'd']);
1163 assert_eq!(next(&mut start), ['f', 'e', 'd', 'C'].into());
1164 assert_eq!(start, ['B']);
1165 assert_eq!(next(&mut start), ['B'].into());
1166 assert_eq!(start, ['A']);
1167 assert_eq!(next(&mut start), ['A'].into());
1168 assert!(start.is_empty());
1169 assert!(next(&mut start).is_empty());
1170 assert!(start.is_empty());
1171 }
1172
1173 #[test]
1174 fn test_topo_order_reverse_multiple_heads() {
1175 // This graph:
1176 // o F
1177 // |\
1178 // o | E
1179 // | o D
1180 // | | o C
1181 // | | |
1182 // | | o B
1183 // | |/
1184 // |/
1185 // o A
1186
1187 let neighbors = hashmap! {
1188 'A' => vec![],
1189 'B' => vec!['A'],
1190 'C' => vec!['B'],
1191 'D' => vec!['A'],
1192 'E' => vec!['A'],
1193 'F' => vec!['E', 'D'],
1194 };
1195 let id_fn = |node: &char| *node;
1196 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
1197 let cycle_fn = |id| id;
1198
1199 let common = topo_order_reverse(vec![Ok('F'), Ok('C')], id_fn, neighbors_fn, cycle_fn)
1200 .block_on()
1201 .unwrap();
1202 assert_eq!(common, vec!['F', 'E', 'D', 'C', 'B', 'A']);
1203
1204 let common: Vec<_> =
1205 topo_order_reverse_lazy(vec![Ok('F'), Ok('C')], id_fn, neighbors_fn, cycle_fn)
1206 .try_collect()
1207 .block_on()
1208 .unwrap();
1209 assert_eq!(common, vec!['F', 'E', 'D', 'C', 'B', 'A']);
1210
1211 let common = topo_order_reverse_ord(vec![Ok('F'), Ok('C')], id_fn, neighbors_fn, cycle_fn)
1212 .block_on()
1213 .unwrap();
1214 assert_eq!(common, vec!['F', 'E', 'D', 'C', 'B', 'A']);
1215 }
1216
1217 #[test]
1218 fn test_topo_order_reverse_multiple_roots() {
1219 // This graph:
1220 // o D
1221 // | \
1222 // o | C
1223 // o B
1224 // o A
1225
1226 let neighbors = hashmap! {
1227 'A' => vec![],
1228 'B' => vec!['A'],
1229 'C' => vec![],
1230 'D' => vec!['C', 'B'],
1231 };
1232 let id_fn = |node: &char| *node;
1233 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
1234 let cycle_fn = |id| id;
1235
1236 let common = topo_order_reverse(vec![Ok('D')], id_fn, neighbors_fn, cycle_fn)
1237 .block_on()
1238 .unwrap();
1239 assert_eq!(common, vec!['D', 'C', 'B', 'A']);
1240
1241 let common: Vec<_> = topo_order_reverse_lazy(vec![Ok('D')], id_fn, neighbors_fn, cycle_fn)
1242 .try_collect()
1243 .block_on()
1244 .unwrap();
1245 assert_eq!(common, vec!['D', 'C', 'B', 'A']);
1246
1247 let common = topo_order_reverse_ord(vec![Ok('D')], id_fn, neighbors_fn, cycle_fn)
1248 .block_on()
1249 .unwrap();
1250 assert_eq!(common, vec!['D', 'C', 'B', 'A']);
1251 }
1252
1253 #[test]
1254 fn test_topo_order_reverse_cycle_linear() {
1255 // This graph:
1256 // o C
1257 // o B
1258 // o A (to C)
1259
1260 let neighbors = hashmap! {
1261 'A' => vec!['C'],
1262 'B' => vec!['A'],
1263 'C' => vec!['B'],
1264 };
1265 let id_fn = |node: &char| *node;
1266 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
1267 let cycle_fn = |id| id;
1268
1269 let result = topo_order_reverse(vec![Ok('C')], id_fn, neighbors_fn, cycle_fn).block_on();
1270 assert_matches!(result, Err('C' | 'B' | 'A'));
1271
1272 let result: Vec<_> = topo_order_reverse_lazy(vec![Ok('C')], id_fn, neighbors_fn, cycle_fn)
1273 .take(4)
1274 .collect()
1275 .block_on();
1276 assert_matches!(
1277 result[..],
1278 [Ok('C'), Ok('B'), Ok('A'), Err('C' | 'B' | 'A')]
1279 );
1280
1281 let result =
1282 topo_order_reverse_ord(vec![Ok('C')], id_fn, neighbors_fn, cycle_fn).block_on();
1283 assert_matches!(result, Err('C' | 'B' | 'A'));
1284 }
1285
1286 #[test]
1287 fn test_topo_order_reverse_cycle_to_branchy_sub_graph() {
1288 // This graph:
1289 // o D
1290 // |\
1291 // | o C
1292 // |/
1293 // o B
1294 // o A (to C)
1295
1296 let neighbors = hashmap! {
1297 'A' => vec!['C'],
1298 'B' => vec!['A'],
1299 'C' => vec!['B'],
1300 'D' => vec!['B', 'C'],
1301 };
1302 let id_fn = |node: &char| *node;
1303 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
1304 let cycle_fn = |id| id;
1305
1306 let result = topo_order_reverse(vec![Ok('D')], id_fn, neighbors_fn, cycle_fn).block_on();
1307 assert_matches!(result, Err('C' | 'B' | 'A'));
1308
1309 let result: Vec<_> = topo_order_reverse_lazy(vec![Ok('D')], id_fn, neighbors_fn, cycle_fn)
1310 .take(5)
1311 .collect()
1312 .block_on();
1313 assert_matches!(
1314 result[..],
1315 [Ok('D'), Ok('C'), Ok('B'), Ok('A'), Err('C' | 'B' | 'A')]
1316 );
1317
1318 let result =
1319 topo_order_reverse_ord(vec![Ok('D')], id_fn, neighbors_fn, cycle_fn).block_on();
1320 assert_matches!(result, Err('C' | 'B' | 'A'));
1321 }
1322
1323 #[test]
1324 fn test_topo_order_reverse_lazy_cycle_within_branchy_sub_graph() {
1325 // This graph:
1326 // o D
1327 // |\
1328 // | o C
1329 // |/
1330 // o B (to C)
1331 // o A
1332
1333 let neighbors = hashmap! {
1334 'A' => vec![],
1335 'B' => vec!['A', 'C'],
1336 'C' => vec!['B'],
1337 'D' => vec!['B', 'C'],
1338 };
1339 let id_fn = |node: &char| *node;
1340 let neighbors_fn = async |node: &char| to_ok_iter(neighbors[node].iter().copied());
1341 let cycle_fn = |id| id;
1342
1343 let mut stream = pin!(topo_order_reverse_lazy(
1344 [Ok('D')],
1345 id_fn,
1346 neighbors_fn,
1347 cycle_fn
1348 ));
1349 stream.next().block_on().unwrap().unwrap(); // Skip first item (D).
1350 let result = stream.next().block_on().unwrap();
1351 assert_matches!(result, Err('C' | 'B'));
1352
1353 // Try again with low-level function
1354 let mut start = vec!['D'];
1355 topo_order_reverse_chunked(&mut start, id_fn, neighbors_fn, cycle_fn)
1356 .block_on()
1357 .unwrap();
1358 assert_matches!(
1359 topo_order_reverse_chunked(&mut start, id_fn, neighbors_fn, cycle_fn).block_on(),
1360 Err('C' | 'B')
1361 );
1362 }
1363
1364 #[test]
1365 fn test_topo_order() {
1366 let neighbors = hashmap! {
1367 'A' => vec![Err('Y')],
1368 'B' => vec![Ok('A'), Err('X')],
1369 'C' => vec![Ok('B')],
1370 };
1371 let id_fn = |node: &char| *node;
1372 let neighbors_fn = async |node: &char| neighbors[node].clone();
1373 let cycle_fn = |id| id;
1374
1375 // Terminates at Err('X') no matter if the sorting order is forward or
1376 // reverse. The visiting order matters.
1377 let result = topo_order_forward([Ok('C')], id_fn, neighbors_fn, cycle_fn).block_on();
1378 assert_eq!(result, Err('X'));
1379 let result = topo_order_reverse([Ok('C')], id_fn, neighbors_fn, cycle_fn).block_on();
1380 assert_eq!(result, Err('X'));
1381 let nodes: Vec<_> = topo_order_reverse_lazy([Ok('C')], id_fn, neighbors_fn, cycle_fn)
1382 .collect()
1383 .block_on();
1384 assert_eq!(nodes, [Ok('C'), Ok('B'), Err('X')]);
1385 let result = topo_order_reverse_ord([Ok('C')], id_fn, neighbors_fn, cycle_fn).block_on();
1386 assert_eq!(result, Err('X'));
1387 }
1388
1389 #[test]
1390 fn test_closest_common_nodes_tricky() {
1391 // Test this case where A is the shortest distance away, but we still want the
1392 // result to be B because A is an ancestor of B. In other words, we want
1393 // to minimize the longest distance.
1394 //
1395 // E H
1396 // |\ /|
1397 // | D G |
1398 // | C F |
1399 // \ \ / /
1400 // \ B /
1401 // \|/
1402 // A
1403
1404 let neighbors = hashmap! {
1405 'A' => vec![],
1406 'B' => vec!['A'],
1407 'C' => vec!['B'],
1408 'D' => vec!['C'],
1409 'E' => vec!['A','D'],
1410 'F' => vec!['B'],
1411 'G' => vec!['F'],
1412 'H' => vec!['A', 'G'],
1413 };
1414 let id_fn = |node: &char| *node;
1415 let neighbors_fn = async |node: &char| Ok::<_, char>(neighbors[node].clone());
1416
1417 let common = closest_common_nodes(vec!['E'], vec!['H'], id_fn, neighbors_fn).block_on();
1418 assert_eq!(common, Ok(vec!['B']));
1419 }
1420
1421 #[test]
1422 fn test_closest_common_nodes_tricky_ancestor() {
1423 // Find the clostest common ancestor between B and F. It should be B because
1424 // it's even an ancestor of F, but we used to find A because the path to it
1425 // from F is shorter (via E).
1426 //
1427 // F
1428 // |\
1429 // D |
1430 // | |
1431 // C E
1432 // | |
1433 // B |
1434 // |/
1435 // A
1436
1437 let neighbors = hashmap! {
1438 'A' => vec![],
1439 'B' => vec!['A'],
1440 'C' => vec!['B'],
1441 'D' => vec!['C'],
1442 'E' => vec!['A'],
1443 'F' => vec!['D', 'E'],
1444 };
1445 let id_fn = |node: &char| *node;
1446 let neighbors_fn = async |node: &char| Ok::<_, char>(neighbors[node].clone());
1447
1448 let common = closest_common_nodes(vec!['B'], vec!['F'], id_fn, neighbors_fn).block_on();
1449 assert_eq!(common, Ok(vec!['B']));
1450 }
1451
1452 #[test]
1453 fn test_closest_common_nodes_tricky_ancestor_with_bad_heuristic() {
1454 // Find the clostest common ancestor between D and A. It should be D because
1455 // it's even an ancestor of A.
1456 //
1457 // A
1458 // |\
1459 // B |
1460 // | |
1461 // C E
1462 // | |
1463 // D |
1464 // |/
1465 // F
1466
1467 let neighbors = hashmap! {
1468 'F' => vec![],
1469 'E' => vec!['F'],
1470 'D' => vec!['F'],
1471 'C' => vec!['D'],
1472 'B' => vec!['C'],
1473 'A' => vec!['B', 'E'],
1474 };
1475 let id_fn = |node: &char| *node;
1476 let neighbors_fn = async |node: &char| Ok::<_, char>(neighbors[node].clone());
1477
1478 let common = closest_common_nodes(vec!['D'], vec!['A'], id_fn, neighbors_fn).block_on();
1479 assert_eq!(common, Ok(vec!['D']));
1480 }
1481
1482 #[test]
1483 fn test_closest_common_nodes_criss_cross() {
1484 // The closest common ancestors between D and E should be both B and C.
1485 //
1486 // D E
1487 // |X|
1488 // B C
1489 // |/
1490 // A
1491
1492 let neighbors = hashmap! {
1493 'A' => vec![],
1494 'B' => vec!['A'],
1495 'C' => vec!['A'],
1496 'D' => vec!['B', 'C'],
1497 'E' => vec!['B', 'C'],
1498 };
1499 let id_fn = |node: &char| *node;
1500 let neighbors_fn = async |node: &char| Ok::<_, char>(neighbors[node].clone());
1501
1502 let common = closest_common_nodes(vec!['D'], vec!['E'], id_fn, neighbors_fn).block_on();
1503 assert_eq!(common, Ok(vec!['C', 'B']));
1504 }
1505
1506 #[test]
1507 fn test_closest_common_nodes_many_paths() {
1508 // One side has very many possible paths due to repeated forking and merging. We
1509 // must not walk the exponential number of paths between A and MN when finding
1510 // common ancestors between MN and B.
1511 //
1512 // MN
1513 // |\
1514 // LN RN
1515 // |/
1516 // ...
1517 // M1
1518 // |\
1519 // L1 R1
1520 // |/
1521 // | B
1522 // |/
1523 // A
1524
1525 let mut neighbors = hashmap! {
1526 "A".to_string() => vec![],
1527 "B".to_string() => vec!["A".to_string()],
1528 };
1529 let mut merge = "A".to_string();
1530 for i in 1..50 {
1531 neighbors.insert(format!("L{i}"), vec![merge.clone()]);
1532 neighbors.insert(format!("R{i}"), vec![merge.clone()]);
1533 merge = format!("M{i}");
1534 neighbors.insert(merge.clone(), vec![format!("L{i}"), format!("R{i}")]);
1535 }
1536 let id_fn = |node: &String| node.clone();
1537 let neighbors_fn = async |node: &String| Ok::<_, String>(neighbors[node].clone());
1538
1539 let common = closest_common_nodes(vec![merge], vec!["B".to_string()], id_fn, neighbors_fn)
1540 .block_on();
1541 assert_eq!(common, Ok(vec!["A".to_string()]));
1542 }
1543 #[test]
1544 fn test_closest_common_nodes() {
1545 let neighbors = hashmap! {
1546 'A' => Err('Y'),
1547 'B' => Ok(vec!['A']),
1548 'C' => Ok(vec!['A']),
1549 'D' => Err('X'),
1550 };
1551 let id_fn = |node: &char| *node;
1552 let neighbors_fn = async |node: &char| neighbors[node].clone();
1553
1554 let result = closest_common_nodes(['B'], ['C'], id_fn, neighbors_fn).block_on();
1555 assert_eq!(result, Ok(vec!['A']));
1556 let result = closest_common_nodes(['C'], ['D'], id_fn, neighbors_fn).block_on();
1557 assert_eq!(result, Err('X'));
1558 }
1559
1560 #[test]
1561 fn test_closest_common_nodes_simple_with_bad_heuristic() {
1562 // We still find the right common ancestor between C and A when given a bad
1563 // heuristic.
1564 //
1565 // C A
1566 // |/
1567 // B
1568 // |
1569 // D
1570
1571 let neighbors = hashmap! {
1572 'D' => vec![],
1573 'B' => vec!['D'],
1574 'C' => vec!['B'],
1575 'A' => vec!['B'],
1576 };
1577 let id_fn = |node: &char| *node;
1578 let neighbors_fn = async |node: &char| Ok::<_, char>(neighbors[node].clone());
1579
1580 let common = closest_common_nodes(vec!['C'], vec!['A'], id_fn, neighbors_fn).block_on();
1581 assert_eq!(common, Ok(vec!['B']));
1582 }
1583
1584 #[test]
1585 fn test_closest_common_nodes_ancestor_with_bad_heuristic() {
1586 // We still find the right common ancestor between A and B when given a bad
1587 // heuristic.
1588 //
1589 // A
1590 // |
1591 // C
1592 // |
1593 // B
1594 // |
1595 // D
1596
1597 let neighbors = hashmap! {
1598 'D' => vec![],
1599 'B' => vec!['D'],
1600 'C' => vec!['B'],
1601 'A' => vec!['C'],
1602 };
1603 let id_fn = |node: &char| *node;
1604 let neighbors_fn = async |node: &char| Ok::<_, char>(neighbors[node].clone());
1605
1606 let common = closest_common_nodes(vec!['A'], vec!['B'], id_fn, neighbors_fn).block_on();
1607 assert_eq!(common, Ok(vec!['B']));
1608 }
1609
1610 #[test]
1611 fn test_heads_mixed() {
1612 // Test the uppercase letters are in the start set
1613 //
1614 // D F
1615 // |/|
1616 // C e
1617 // |/
1618 // b
1619 // |
1620 // A
1621
1622 let neighbors = hashmap! {
1623 'A' => vec![],
1624 'b' => vec!['A'],
1625 'C' => vec!['b'],
1626 'D' => vec!['C'],
1627 'e' => vec!['b'],
1628 'F' => vec!['C', 'e'],
1629 };
1630 let id_fn = |node: &char| *node;
1631 let neighbors_fn = async |node: &char| Ok::<_, char>(neighbors[node].clone());
1632
1633 let actual = heads(vec!['A', 'C', 'D', 'F'], id_fn, neighbors_fn).block_on();
1634 assert_eq!(actual, Ok(hashset!['D', 'F']));
1635
1636 // Check with a different order in the start set
1637 let actual = heads(vec!['F', 'D', 'C', 'A'], id_fn, neighbors_fn).block_on();
1638 assert_eq!(actual, Ok(hashset!['D', 'F']));
1639 }
1640
1641 #[test]
1642 fn test_heads() {
1643 let neighbors = hashmap! {
1644 'A' => Ok(vec![]),
1645 'B' => Err('X'),
1646 'C' => Ok(vec!['B']),
1647 };
1648 let id_fn = |node: &char| *node;
1649 let neighbors_fn = async |node: &char| neighbors[node].clone();
1650
1651 let result = heads(['C'], id_fn, neighbors_fn).block_on();
1652 assert_eq!(result, Ok(hashset! {'C'}));
1653 let result = heads(['B'], id_fn, neighbors_fn).block_on();
1654 assert_eq!(result, Ok(hashset! {'B'}));
1655 let result = heads(['A'], id_fn, neighbors_fn).block_on();
1656 assert_eq!(result, Ok(hashset! {'A'}));
1657 let result = heads(['C', 'B'], id_fn, neighbors_fn).block_on();
1658 assert_eq!(result, Err('X'));
1659 let result = heads(['C', 'A'], id_fn, neighbors_fn).block_on();
1660 assert_eq!(result, Err('X'));
1661 }
1662 }