Debian Codegraph @

crates/graph/src/graph.rs

raw symbols SCIP
1 //! Incremental graph queries backed by a [`ParentsProvider`].
2 //!
3 //! Ported incrementally from `vcsgraph/graph.py`. Phase 1 covers the trivial
4 //! methods that don't need a BFS searcher: parent/child map queries,
5 //! topological ordering (delegated to [`crate::tsort::TopoSorter`]), and the
6 //! left-hand ancestry walks.
7
8 use crate::bfs::BfsState;
9 use crate::parents_provider::{DictParentsProvider, ParentsProvider};
10 use crate::tsort::TopoSorter;
11 use crate::{Error, ParentMap, Parents};
12 use rustc_hash::{FxHashMap, FxHashSet};
13 use std::collections::{BTreeMap, HashMap};
14 use std::hash::Hash;
15
16 /// A revision graph backed by an arbitrary [`ParentsProvider`].
17 ///
18 /// Unlike [`crate::KnownGraph`] this type does not own the full ancestry —
19 /// queries are dispatched to the provider on demand.
20 pub struct Graph<K, P>
21 where
22 K: Hash + Eq + Clone,
23 P: ParentsProvider<K>,
24 {
25 provider: P,
26 _marker: std::marker::PhantomData<K>,
27 }
28
29 /// An error returned from one of `Graph`'s traversal methods.
30 #[derive(Debug, Clone, PartialEq, Eq)]
31 pub enum GraphError<K> {
32 /// A revision reachable via the ancestry walk turned out to be a ghost,
33 /// so we cannot compute a revno for it.
34 GhostRevision { target: K, ghost: K },
35 /// A revision was not known to the provider at all.
36 RevisionNotPresent(K),
37 /// A cycle was detected during a topological walk.
38 Cycle(Vec<K>),
39 }
40
41 impl<K: std::fmt::Display> std::fmt::Display for GraphError<K> {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 match self {
44 GraphError::GhostRevision { target, ghost } => write!(
45 f,
46 "ghost revision {ghost} reached while finding revno for {target}"
47 ),
48 GraphError::RevisionNotPresent(key) => {
49 write!(f, "revision {key} not present in graph")
50 }
51 GraphError::Cycle(nodes) => {
52 write!(f, "cycle detected: ")?;
53 for (i, n) in nodes.iter().enumerate() {
54 if i > 0 {
55 write!(f, " -> ")?;
56 }
57 write!(f, "{n}")?;
58 }
59 Ok(())
60 }
61 }
62 }
63 }
64
65 impl<K: std::fmt::Debug + std::fmt::Display> std::error::Error for GraphError<K> {}
66
67 impl<K, P> Graph<K, P>
68 where
69 K: Hash + Eq + Clone,
70 P: ParentsProvider<K>,
71 {
72 /// Construct a new `Graph` backed by `provider`.
73 pub fn new(provider: P) -> Self {
74 Graph {
75 provider,
76 _marker: std::marker::PhantomData,
77 }
78 }
79
80 /// Borrow the underlying parents provider.
81 pub fn parents_provider(&self) -> &P {
82 &self.provider
83 }
84
85 /// Return a parent map for `keys`. Missing keys are omitted; ghosts are
86 /// reported as [`Parents::Ghost`].
87 pub fn get_parent_map<I>(&self, keys: I) -> ParentMap<K>
88 where
89 I: IntoIterator<Item = K>,
90 {
91 // ParentsProvider takes a std HashSet; collect directly into one
92 // rather than going via FxHashSet and copying.
93 let set: std::collections::HashSet<K> = keys.into_iter().collect();
94 self.provider.get_parent_map(&set)
95 }
96
97 /// Return a mapping from parent → children for the requested keys.
98 ///
99 /// This is the inversion of [`get_parent_map`](Self::get_parent_map);
100 /// only the supplied `keys` are considered as potential children. Ghosts
101 /// are skipped. The children lists are sorted (by insertion order driven
102 /// by the BTreeMap iteration) to match Python's `sorted()` behavior.
103 pub fn get_child_map<I>(&self, keys: I) -> BTreeMap<K, Vec<K>>
104 where
105 K: Ord,
106 I: IntoIterator<Item = K>,
107 {
108 let parent_map = self.get_parent_map(keys);
109 // Walk children in sorted order so parent→children lists mirror the
110 // Python implementation's sorted() iteration.
111 let mut sorted: BTreeMap<K, Parents<K>> = BTreeMap::new();
112 for (k, v) in parent_map {
113 sorted.insert(k, v);
114 }
115 let mut result: BTreeMap<K, Vec<K>> = BTreeMap::new();
116 for (child, parents) in sorted {
117 if let Parents::Known(ps) = parents {
118 for parent in ps {
119 result.entry(parent).or_default().push(child.clone());
120 }
121 }
122 }
123 result
124 }
125
126 /// Iterate over the ancestry of `revision_ids` in topological order.
127 ///
128 /// This delegates to [`TopoSorter`]. The topological order only ensures
129 /// that parents come before children within the ancestry that is
130 /// reachable from the input revisions.
131 pub fn iter_topo_order<I>(&self, revisions: I) -> Result<Vec<K>, Error<K>>
132 where
133 K: std::fmt::Debug,
134 I: IntoIterator<Item = K>,
135 {
136 let pm = self.get_parent_map(revisions);
137 let iter = pm.into_iter().filter_map(|(k, parents)| match parents {
138 Parents::Known(ps) => Some((k, ps)),
139 Parents::Ghost => None,
140 });
141 TopoSorter::new(iter).sorted()
142 }
143
144 /// Walk the left-hand ancestry of `start_key`, stopping when a key in
145 /// `stop_keys` is encountered. Yields `start_key` first, then its
146 /// left-most parent, and so on.
147 ///
148 /// Errors with [`GraphError::RevisionNotPresent`] if a key in the walk is
149 /// missing from the provider.
150 pub fn iter_lefthand_ancestry<S>(
151 &self,
152 start_key: K,
153 stop_keys: S,
154 ) -> Result<Vec<K>, GraphError<K>>
155 where
156 S: IntoIterator<Item = K>,
157 {
158 let stop_keys: FxHashSet<K> = stop_keys.into_iter().collect();
159 let mut result = Vec::new();
160 let mut next_key = start_key;
161 loop {
162 if stop_keys.contains(&next_key) {
163 return Ok(result);
164 }
165 let pm = self.get_parent_map(std::iter::once(next_key.clone()));
166 let parents = match pm.get(&next_key) {
167 Some(Parents::Known(ps)) => ps.clone(),
168 Some(Parents::Ghost) => {
169 return Err(GraphError::RevisionNotPresent(next_key));
170 }
171 None => return Err(GraphError::RevisionNotPresent(next_key)),
172 };
173 result.push(next_key.clone());
174 if parents.is_empty() {
175 return Ok(result);
176 }
177 next_key = parents.into_iter().next().unwrap();
178 }
179 }
180
181 /// Iterate over the ancestry reachable from `revision_ids`, yielding
182 /// `(key, parents)` pairs in a BFS order. Ghosts are yielded with
183 /// `Parents::Ghost`.
184 pub fn iter_ancestry<I>(&self, revision_ids: I) -> Vec<(K, Parents<K>)>
185 where
186 I: IntoIterator<Item = K>,
187 {
188 let mut pending: FxHashSet<K> = revision_ids.into_iter().collect();
189 let mut processed: FxHashSet<K> = FxHashSet::default();
190 let mut out: Vec<(K, Parents<K>)> = Vec::new();
191
192 while !pending.is_empty() {
193 processed.extend(pending.iter().cloned());
194 let next_map = self.get_parent_map(pending.iter().cloned());
195 let mut next_pending: FxHashSet<K> = FxHashSet::default();
196 let mut seen_in_map: FxHashSet<K> = FxHashSet::default();
197
198 for (k, parents) in next_map.iter() {
199 seen_in_map.insert(k.clone());
200 if let Parents::Known(ps) = parents {
201 for p in ps {
202 if !processed.contains(p) {
203 next_pending.insert(p.clone());
204 }
205 }
206 }
207 out.push((k.clone(), parents.clone()));
208 }
209 // Keys in `pending` that the provider didn't return are ghosts.
210 for ghost in pending.difference(&seen_in_map) {
211 out.push((ghost.clone(), Parents::Ghost));
212 }
213 pending = next_pending;
214 }
215 out
216 }
217
218 /// Find the left-hand distance from `target_revision_id` to the origin.
219 ///
220 /// `known_distances` is an iterable of `(revision_id, distance)` pairs
221 /// that seed the search. The origin sentinel (any key equal to `null`,
222 /// supplied by the caller) should be included with distance 0.
223 ///
224 /// This mirrors Python's `find_distance_to_null`, which hard-codes the
225 /// sentinel `NULL_REVISION = b"null:"`. Keeping the sentinel Python-side
226 /// lets the Rust core stay string-typed without baking in bytes.
227 pub fn find_distance_to_null(
228 &self,
229 target_revision_id: K,
230 known_distances: impl IntoIterator<Item = (K, i64)>,
231 null: K,
232 ) -> Result<i64, GraphError<K>> {
233 let mut known_revnos: FxHashMap<K, i64> = known_distances.into_iter().collect();
234 let mut cur_tip = target_revision_id.clone();
235 let mut num_steps: i64 = 0;
236 known_revnos.insert(null.clone(), 0);
237
238 let mut searching_known_tips: Vec<K> = known_revnos.keys().cloned().collect();
239 let mut unknown_searched: FxHashMap<K, i64> = FxHashMap::default();
240
241 while !known_revnos.contains_key(&cur_tip) {
242 unknown_searched.insert(cur_tip.clone(), num_steps);
243 num_steps += 1;
244
245 let mut to_search: FxHashSet<K> = searching_known_tips.iter().cloned().collect();
246 to_search.insert(cur_tip.clone());
247 let parent_map = self.get_parent_map(to_search);
248
249 let parents = match parent_map.get(&cur_tip) {
250 Some(Parents::Known(ps)) if !ps.is_empty() => ps,
251 _ => {
252 return Err(GraphError::GhostRevision {
253 target: target_revision_id,
254 ghost: cur_tip,
255 });
256 }
257 };
258 let next_tip = parents[0].clone();
259
260 let mut next_known_tips: Vec<K> = Vec::new();
261 for revision_id in &searching_known_tips {
262 let parents = match parent_map.get(revision_id) {
263 Some(Parents::Known(ps)) if !ps.is_empty() => ps,
264 _ => continue,
265 };
266 let next = parents[0].clone();
267 let next_revno = known_revnos[revision_id] - 1;
268 if let Some(unknown_steps) = unknown_searched.get(&next) {
269 return Ok(next_revno + unknown_steps);
270 }
271 if known_revnos.contains_key(&next) {
272 continue;
273 }
274 known_revnos.insert(next.clone(), next_revno);
275 next_known_tips.push(next);
276 }
277 searching_known_tips = next_known_tips;
278 cur_tip = next_tip;
279 }
280
281 Ok(known_revnos[&cur_tip] + num_steps)
282 }
283
284 /// Find left-hand distances for every key in `keys`.
285 ///
286 /// Ghosts are reported as distance `-1`, matching the Python contract.
287 pub fn find_lefthand_distances(
288 &self,
289 keys: impl IntoIterator<Item = K>,
290 null: K,
291 ) -> FxHashMap<K, i64> {
292 let mut result: FxHashMap<K, i64> = FxHashMap::default();
293 let mut known: Vec<(K, i64)> = Vec::new();
294 let mut ghosts: Vec<K> = Vec::new();
295 for key in keys {
296 match self.find_distance_to_null(key.clone(), known.iter().cloned(), null.clone()) {
297 Ok(d) => {
298 known.push((key.clone(), d));
299 result.insert(key, d);
300 }
301 Err(GraphError::GhostRevision { .. }) => ghosts.push(key),
302 Err(_) => {
303 // Other errors are unreachable from find_distance_to_null
304 // in practice. Match Python by skipping.
305 }
306 }
307 }
308 for ghost in ghosts {
309 result.insert(ghost, -1);
310 }
311 result
312 }
313
314 /// Find the first lefthand ancestor of `tip_key` that merged `merged_key`.
315 ///
316 /// Walks the lefthand ancestry of `tip_key` one step at a time, stopping
317 /// as soon as a candidate is not a descendant of `merged_key`. Returns
318 /// the last candidate that *was* a descendant — or `None` if none is.
319 pub fn find_lefthand_merger(&self, merged_key: K, tip_key: K) -> Option<K>
320 where
321 K: Ord,
322 {
323 let descendants = self.find_descendants(merged_key, tip_key.clone());
324 let mut last_candidate: Option<K> = None;
325 let mut next_key = tip_key;
326 loop {
327 if !descendants.contains(&next_key) {
328 return last_candidate;
329 }
330 let pm = self.get_parent_map(std::iter::once(next_key.clone()));
331 let parents = match pm.get(&next_key) {
332 Some(Parents::Known(ps)) => ps.clone(),
333 _ => {
334 // Missing entry or ghost — treat as end of walk.
335 return Some(next_key);
336 }
337 };
338 last_candidate = Some(next_key);
339 if parents.is_empty() {
340 return last_candidate;
341 }
342 next_key = parents.into_iter().next().unwrap();
343 }
344 }
345
346 /// Compute `(left_only, right_only)` — the set difference between the
347 /// ancestries of `left` and `right`.
348 pub fn find_difference(&self, left: K, right: K) -> (FxHashSet<K>, FxHashSet<K>)
349 where
350 K: Ord,
351 {
352 let (_border, common, searchers) = self.find_border_ancestors([left, right]);
353 // find_border_ancestors always returns one searcher per input
354 // revision, so for a 2-element input we know we get exactly two.
355 let mut pair: [BfsState<K>; 2] = match <[BfsState<K>; 2]>::try_from(searchers) {
356 Ok(pair) => pair,
357 Err(_) => unreachable!("find_border_ancestors returned a non-2 pair"),
358 };
359 self.search_for_extra_common(&common, &mut pair);
360 let [left_searcher, right_searcher] = pair;
361 let left_seen = &left_searcher.seen;
362 let right_seen = &right_searcher.seen;
363 (
364 left_seen.difference(right_seen).cloned().collect(),
365 right_seen.difference(left_seen).cloned().collect(),
366 )
367 }
368
369 /// Run the "extra common" reconvergence pass on a pair of searchers
370 /// left in the state they finished `find_border_ancestors` in. Mirrors
371 /// Python's `_search_for_extra_common`.
372 ///
373 /// Takes a fixed-size `[BfsState; 2]` so the two-searcher restriction
374 /// is enforced at compile time instead of via a runtime assertion.
375 fn search_for_extra_common(&self, _common: &FxHashSet<K>, searchers: &mut [BfsState<K>; 2])
376 where
377 K: Ord,
378 {
379 let unique: FxHashSet<K> = searchers[0]
380 .seen
381 .symmetric_difference(&searchers[1].seen)
382 .cloned()
383 .collect();
384 if unique.is_empty() {
385 return;
386 }
387 let parent_map = self.get_parent_map(unique.iter().cloned());
388 let unique = Self::remove_simple_descendants(&unique, &parent_map);
389
390 // Build unique-searchers: one per unique revision.
391 let mut unique_searchers: Vec<BfsState<K>> = Vec::new();
392 for revision_id in unique.iter() {
393 let revs_to_search: FxHashSet<K> = {
394 let parent_idx = if searchers[0].seen.contains(revision_id) {
395 0
396 } else {
397 1
398 };
399 let seed = [revision_id.clone()];
400 let anc = searchers[parent_idx].find_seen_ancestors(seed, &self.provider);
401 if anc.is_empty() {
402 [revision_id.clone()].into_iter().collect()
403 } else {
404 anc
405 }
406 };
407 let mut s = BfsState::new(revs_to_search);
408 s.next_set(&self.provider);
409 unique_searchers.push(s);
410 }
411
412 // Compute initial ancestor_all_unique: intersection of all seen sets.
413 let mut ancestor_all_unique: FxHashSet<K> = FxHashSet::default();
414 for (i, s) in unique_searchers.iter().enumerate() {
415 if i == 0 {
416 ancestor_all_unique = s.seen.clone();
417 } else {
418 ancestor_all_unique = ancestor_all_unique.intersection(&s.seen).cloned().collect();
419 }
420 }
421
422 loop {
423 let mut newly_seen_common: FxHashSet<K> = FxHashSet::default();
424 for s in searchers.iter_mut() {
425 if let Some(set) = s.next_set(&self.provider) {
426 newly_seen_common.extend(set);
427 }
428 }
429 let mut newly_seen_unique: FxHashSet<K> = FxHashSet::default();
430 for s in unique_searchers.iter_mut() {
431 if let Some(set) = s.next_set(&self.provider) {
432 newly_seen_unique.extend(set);
433 }
434 }
435 let mut new_common_unique: FxHashSet<K> = FxHashSet::default();
436 for revision in &newly_seen_unique {
437 if unique_searchers.iter().all(|s| s.seen.contains(revision)) {
438 new_common_unique.insert(revision.clone());
439 }
440 }
441 if !newly_seen_common.is_empty() {
442 // Merge newly_seen_common seen-ancestors from each common searcher.
443 let mut expanded = newly_seen_common.clone();
444 for s in searchers.iter() {
445 expanded
446 .extend(s.find_seen_ancestors(expanded.iter().cloned(), &self.provider));
447 }
448 let expanded_frozen = expanded;
449 for s in searchers.iter_mut() {
450 s.start_searching(expanded_frozen.iter().cloned(), &self.provider);
451 }
452 let stop_searching_common: FxHashSet<K> = ancestor_all_unique
453 .intersection(&expanded_frozen)
454 .cloned()
455 .collect();
456 if !stop_searching_common.is_empty() {
457 for s in searchers.iter_mut() {
458 s.stop_searching_any(stop_searching_common.iter().cloned());
459 }
460 }
461 }
462 if !new_common_unique.is_empty() {
463 let mut expanded = new_common_unique.clone();
464 for s in unique_searchers.iter() {
465 expanded
466 .extend(s.find_seen_ancestors(expanded.iter().cloned(), &self.provider));
467 }
468 for s in searchers.iter() {
469 expanded
470 .extend(s.find_seen_ancestors(expanded.iter().cloned(), &self.provider));
471 }
472 for s in unique_searchers.iter_mut() {
473 s.start_searching(expanded.iter().cloned(), &self.provider);
474 }
475 for s in searchers.iter_mut() {
476 s.stop_searching_any(expanded.iter().cloned());
477 }
478 ancestor_all_unique.extend(expanded);
479
480 // Collapse unique searchers that ended up with the same frontier.
481 let mut seen_frontiers: std::collections::HashSet<Vec<K>> =
482 std::collections::HashSet::new();
483 let mut next_unique: Vec<BfsState<K>> = Vec::new();
484 for searcher in unique_searchers {
485 let mut key: Vec<K> = searcher.next_query().iter().cloned().collect();
486 key.sort_by_key(|k| {
487 use std::collections::hash_map::DefaultHasher;
488 use std::hash::Hasher;
489 let mut h = DefaultHasher::new();
490 k.hash(&mut h);
491 h.finish()
492 });
493 if seen_frontiers.insert(key) {
494 next_unique.push(searcher);
495 }
496 }
497 unique_searchers = next_unique;
498 }
499
500 let any_common_active = searchers.iter().any(|s| !s.next_query().is_empty());
501 if !any_common_active {
502 return;
503 }
504 }
505 }
506
507 /// Find a unique lowest common ancestor by iterating `find_lca`.
508 ///
509 /// If there are multiple LCAs, recursively find the LCA of that set
510 /// until exactly one remains. Returns `None` if there is no common
511 /// ancestor. If `count_steps` is true, also returns the number of
512 /// iterations.
513 pub fn find_unique_lca(&self, left: K, right: K, null: &K) -> Option<(K, usize)> {
514 let mut revisions: Vec<K> = vec![left, right];
515 let mut steps: usize = 0;
516 loop {
517 steps += 1;
518 let lca = self.find_lca(revisions.iter().cloned(), null);
519 match lca.len() {
520 1 => return lca.into_iter().next().map(|k| (k, steps)),
521 0 => return None,
522 _ => revisions = lca.into_iter().collect(),
523 }
524 }
525 }
526
527 /// Find the unique ancestors of `unique_revision` relative to
528 /// `common_revisions`.
529 ///
530 /// Returns the set of revisions that are ancestors of `unique_revision`
531 /// but not of any of `common_revisions`. If `unique_revision` is itself
532 /// in `common_revisions`, returns an empty set.
533 ///
534 /// Algorithm description:
535 ///
536 /// 1. Walk backwards from the unique node and all common nodes.
537 /// 2. When a node is seen by both sides, stop searching it in the unique
538 /// walker, include it in the common walker.
539 /// 3. Stop searching when there are no nodes left for the unique walker.
540 /// At this point, you have a maximal set of unique nodes. Some of
541 /// them may actually be common, and you haven't reached them yet.
542 /// 4. Start new searchers for the unique nodes, seeded with the
543 /// information you have so far.
544 /// 5. Continue searching, stopping the common searches when the search
545 /// tip is an ancestor of all unique nodes.
546 /// 6. Aggregate together unique searchers when they are searching the
547 /// same tips. When all unique searchers are searching the same node,
548 /// stop move it to a single 'all_unique_searcher'.
549 /// 7. The 'all_unique_searcher' represents the very 'tip' of searching.
550 /// Most of the time this produces very little important information.
551 /// So don't step it as quickly as the other searchers.
552 /// 8. Search is done when all common searchers have completed.
553 pub fn find_unique_ancestors(
554 &self,
555 unique_revision: K,
556 common_revisions: impl IntoIterator<Item = K>,
557 ) -> FxHashSet<K>
558 where
559 K: Ord,
560 {
561 let common_revisions: Vec<K> = common_revisions.into_iter().collect();
562 if common_revisions.contains(&unique_revision) {
563 return FxHashSet::default();
564 }
565
566 // Phase 1: find maximal unique set.
567 let (mut unique_searcher, mut common_searcher) =
568 self.find_initial_unique_nodes([unique_revision], common_revisions);
569 let unique_nodes: FxHashSet<K> = unique_searcher
570 .seen
571 .difference(&common_searcher.seen)
572 .cloned()
573 .collect();
574 if unique_nodes.is_empty() {
575 return unique_nodes;
576 }
577
578 // Phase 2: refine via unique-tip searchers.
579 let (mut all_unique_searcher, mut unique_tip_searchers) =
580 self.make_unique_searchers(&unique_nodes, &mut unique_searcher, &mut common_searcher);
581 self.refine_unique_nodes(
582 &mut unique_searcher,
583 &mut all_unique_searcher,
584 &mut unique_tip_searchers,
585 &mut common_searcher,
586 );
587 unique_nodes
588 .difference(&common_searcher.seen)
589 .cloned()
590 .collect()
591 }
592
593 /// Phase 1 of find_unique_ancestors: find the maximal unique set.
594 fn find_initial_unique_nodes(
595 &self,
596 unique_revisions: impl IntoIterator<Item = K>,
597 common_revisions: impl IntoIterator<Item = K>,
598 ) -> (BfsState<K>, BfsState<K>) {
599 let mut unique_searcher = BfsState::new(unique_revisions);
600 // Skip past the starting unique revisions themselves.
601 unique_searcher.next_set(&self.provider);
602 let mut common_searcher = BfsState::new(common_revisions);
603
604 while !unique_searcher.next_query().is_empty() {
605 let next_unique_nodes: FxHashSet<K> =
606 unique_searcher.next_set(&self.provider).unwrap_or_default();
607 let next_common_nodes: FxHashSet<K> =
608 common_searcher.next_set(&self.provider).unwrap_or_default();
609
610 let mut unique_are_common_nodes: FxHashSet<K> = next_unique_nodes
611 .intersection(&common_searcher.seen)
612 .cloned()
613 .collect();
614 unique_are_common_nodes.extend(
615 next_common_nodes
616 .intersection(&unique_searcher.seen)
617 .cloned(),
618 );
619 if !unique_are_common_nodes.is_empty() {
620 let mut ancestors =
621 unique_searcher.find_seen_ancestors(unique_are_common_nodes, &self.provider);
622 let more = common_searcher.find_seen_ancestors(ancestors.clone(), &self.provider);
623 ancestors.extend(more);
624 unique_searcher.stop_searching_any(ancestors.iter().cloned());
625 common_searcher.start_searching(ancestors, &self.provider);
626 }
627 }
628 (unique_searcher, common_searcher)
629 }
630
631 /// Phase 2 setup: create a searcher for each unique-node tip plus an
632 /// `all_unique_searcher` covering ancestry shared by every unique tip.
633 fn make_unique_searchers(
634 &self,
635 unique_nodes: &FxHashSet<K>,
636 unique_searcher: &mut BfsState<K>,
637 common_searcher: &mut BfsState<K>,
638 ) -> (BfsState<K>, Vec<BfsState<K>>)
639 where
640 K: Ord,
641 {
642 let parent_map = self.get_parent_map(unique_nodes.iter().cloned());
643 let unique_tips = Self::remove_simple_descendants(unique_nodes, &parent_map);
644
645 let mut unique_tip_searchers: Vec<BfsState<K>> = Vec::new();
646 let ancestor_all_unique: FxHashSet<K> = if unique_tips.len() == 1 {
647 unique_searcher.find_seen_ancestors(unique_tips, &self.provider)
648 } else {
649 for tip in unique_tips {
650 let mut revs_to_search =
651 unique_searcher.find_seen_ancestors([tip.clone()], &self.provider);
652 let more =
653 common_searcher.find_seen_ancestors(revs_to_search.clone(), &self.provider);
654 revs_to_search.extend(more);
655 let mut searcher = BfsState::new(revs_to_search);
656 // Skip past the starting nodes — we don't care about them.
657 searcher.next_set(&self.provider);
658 unique_tip_searchers.push(searcher);
659 }
660 // Fold the intersection from the borrowed `seen` sets so we
661 // don't have to snapshot each searcher's seen set as we go.
662 unique_tip_searchers
663 .iter()
664 .map(|s| &s.seen)
665 .fold(None::<FxHashSet<K>>, |acc, s| match acc {
666 None => Some(s.clone()),
667 Some(a) => Some(a.intersection(s).cloned().collect()),
668 })
669 .unwrap_or_default()
670 };
671
672 // Collapse all common nodes into a single searcher covering the
673 // `ancestor_all_unique` set, then advance it once.
674 let mut all_unique_searcher = BfsState::new(ancestor_all_unique.iter().cloned());
675 if !ancestor_all_unique.is_empty() {
676 all_unique_searcher.next_set(&self.provider);
677
678 // Stop common-searcher tips that are already ancestors of all uniques.
679 let to_stop = common_searcher
680 .find_seen_ancestors(ancestor_all_unique.iter().cloned(), &self.provider);
681 common_searcher.stop_searching_any(to_stop);
682
683 for searcher in unique_tip_searchers.iter_mut() {
684 let to_stop = searcher
685 .find_seen_ancestors(ancestor_all_unique.iter().cloned(), &self.provider);
686 searcher.stop_searching_any(to_stop);
687 }
688 }
689
690 (all_unique_searcher, unique_tip_searchers)
691 }
692
693 /// Remove revisions which are descendants (via the parent_map) of other
694 /// revisions in the set. This is a cheap O(E) pass that doesn't walk
695 /// ancestry — it just drops keys whose parents are already in `revisions`.
696 fn remove_simple_descendants(
697 revisions: &FxHashSet<K>,
698 parent_map: &ParentMap<K>,
699 ) -> FxHashSet<K> {
700 let mut simple = revisions.clone();
701 for (revision, parents) in parent_map.iter() {
702 if let Parents::Known(ps) = parents {
703 for parent_id in ps {
704 if revisions.contains(parent_id) {
705 simple.remove(revision);
706 break;
707 }
708 }
709 }
710 }
711 simple
712 }
713
714 /// One BFS step across unique tip searchers, the unique_searcher, and
715 /// the common_searcher, propagating find_seen_ancestors cross-checks.
716 fn step_unique_and_common_searchers(
717 &self,
718 common_searcher: &mut BfsState<K>,
719 unique_tip_searchers: &mut [BfsState<K>],
720 unique_searcher: &BfsState<K>,
721 ) -> (FxHashSet<K>, FxHashSet<K>) {
722 let newly_seen_common: FxHashSet<K> =
723 common_searcher.next_set(&self.provider).unwrap_or_default();
724
725 let mut newly_seen_unique: FxHashSet<K> = FxHashSet::default();
726 // Snapshot seen sets of all tip searchers so we can cross-reference
727 // without re-borrowing mid-loop.
728 let tip_count = unique_tip_searchers.len();
729 // Collect (index, next_step) pairs first.
730 let mut per_tip_next: Vec<(usize, FxHashSet<K>)> = Vec::with_capacity(tip_count);
731 for (i, s) in unique_tip_searchers.iter_mut().enumerate() {
732 let mut next_set = s.next_set(&self.provider).unwrap_or_default();
733 // Include ancestors already known to the main unique_searcher.
734 next_set.extend(unique_searcher.find_seen_ancestors(next_set.clone(), &self.provider));
735 // And to the common_searcher.
736 next_set.extend(common_searcher.find_seen_ancestors(next_set.clone(), &self.provider));
737 per_tip_next.push((i, next_set));
738 }
739 // Cross-check: each tip pulls in seen ancestors from every other tip.
740 // We need to compute additions per tip from the current (pre-start)
741 // state of the other tips, so snapshot their seen sets first.
742 let seen_per_tip: Vec<FxHashSet<K>> = unique_tip_searchers
743 .iter()
744 .map(|s| s.seen.clone())
745 .collect();
746 for (i, next_set) in per_tip_next.iter_mut() {
747 for (j, seen_j) in seen_per_tip.iter().enumerate() {
748 if *i == j {
749 continue;
750 }
751 // We can't call `alt_searcher.find_seen_ancestors` here
752 // because that would re-borrow the slice we're already
753 // iterating. Use the free-standing equivalent that takes
754 // the other searcher's seen set by reference.
755 let additions =
756 Self::find_seen_ancestors_against(next_set.clone(), seen_j, &self.provider);
757 next_set.extend(additions);
758 }
759 }
760 // Apply start_searching and accumulate newly_seen_unique.
761 for (i, next_set) in per_tip_next {
762 unique_tip_searchers[i].start_searching(next_set.iter().cloned(), &self.provider);
763 newly_seen_unique.extend(next_set);
764 }
765 (newly_seen_common, newly_seen_unique)
766 }
767
768 /// Free-standing equivalent of `BfsState::find_seen_ancestors` that
769 /// walks the provider restricted to a given `seen` set. Used by
770 /// `step_unique_and_common_searchers` to cross-check tip searchers
771 /// without mid-loop re-borrows of the slice.
772 fn find_seen_ancestors_against(
773 revisions: FxHashSet<K>,
774 seen: &FxHashSet<K>,
775 provider: &P,
776 ) -> FxHashSet<K> {
777 let mut pending: FxHashSet<K> =
778 revisions.into_iter().filter(|r| seen.contains(r)).collect();
779 let mut seen_ancestors: FxHashSet<K> = pending.iter().cloned().collect();
780 while !pending.is_empty() {
781 let mut std_set: std::collections::HashSet<K> =
782 std::collections::HashSet::with_capacity(pending.len());
783 for k in &pending {
784 std_set.insert(k.clone());
785 }
786 let parent_map = provider.get_parent_map(&std_set);
787 let mut all_parents: Vec<K> = Vec::new();
788 for (_, parents) in parent_map.iter() {
789 if let Parents::Known(ps) = parents {
790 all_parents.extend(ps.iter().cloned());
791 }
792 }
793 let mut next_pending: FxHashSet<K> = FxHashSet::default();
794 for p in all_parents {
795 if seen.contains(&p) && !seen_ancestors.contains(&p) {
796 next_pending.insert(p);
797 }
798 }
799 seen_ancestors.extend(next_pending.iter().cloned());
800 pending = next_pending;
801 }
802 seen_ancestors
803 }
804
805 /// Find nodes common to all unique tip searchers (and optionally step
806 /// the `all_unique_searcher`).
807 fn find_nodes_common_to_all_unique(
808 &self,
809 unique_tip_searchers: &[BfsState<K>],
810 all_unique_searcher: &mut BfsState<K>,
811 newly_seen_unique: &FxHashSet<K>,
812 step_all_unique: bool,
813 ) -> FxHashSet<K> {
814 let mut common: FxHashSet<K> = newly_seen_unique.clone();
815 for searcher in unique_tip_searchers {
816 common = common.intersection(&searcher.seen).cloned().collect();
817 }
818 common = common
819 .intersection(&all_unique_searcher.seen)
820 .cloned()
821 .collect();
822 if step_all_unique {
823 if let Some(nodes) = all_unique_searcher.next_set(&self.provider) {
824 common.extend(nodes);
825 }
826 }
827 common
828 }
829
830 /// Combine unique tip searchers that are searching the same frontier.
831 fn collapse_unique_searchers(
832 &self,
833 unique_tip_searchers: Vec<BfsState<K>>,
834 common_to_all_unique_nodes: &FxHashSet<K>,
835 ) -> Vec<BfsState<K>> {
836 // First pass: stop searching the common-to-all set on each searcher
837 // and bucket by resulting frontier.
838 let mut buckets: FxHashMap<Vec<K>, Vec<BfsState<K>>> = FxHashMap::default();
839 let mut empty_bucket: Vec<BfsState<K>> = Vec::new();
840 for mut searcher in unique_tip_searchers {
841 searcher.stop_searching_any(common_to_all_unique_nodes.iter().cloned());
842 let nq = searcher.next_query().clone();
843 if nq.is_empty() {
844 empty_bucket.push(searcher);
845 continue;
846 }
847 // Sort the frontier by hash for a deterministic bucket key.
848 let mut key: Vec<K> = nq.into_iter().collect();
849 key.sort_by_key(|k| {
850 use std::collections::hash_map::DefaultHasher;
851 use std::hash::Hasher;
852 let mut h = DefaultHasher::new();
853 k.hash(&mut h);
854 h.finish()
855 });
856 buckets.entry(key).or_default().push(searcher);
857 }
858 let _ = empty_bucket; // drop empties — those searchers are done.
859
860 let mut next_unique_searchers: Vec<BfsState<K>> = Vec::new();
861 for (_key, mut searchers) in buckets {
862 if searchers.len() == 1 {
863 next_unique_searchers.push(searchers.pop().unwrap());
864 } else {
865 // Combine: intersect all their seen sets into the first.
866 let mut first = searchers.remove(0);
867 for s in searchers {
868 first.seen = first.seen.intersection(&s.seen).cloned().collect();
869 }
870 next_unique_searchers.push(first);
871 }
872 }
873 next_unique_searchers
874 }
875
876 /// Phase 2 main loop: refine unique-vs-common by stepping searchers
877 /// until `common_searcher` has nothing left to search.
878 fn refine_unique_nodes(
879 &self,
880 unique_searcher: &mut BfsState<K>,
881 all_unique_searcher: &mut BfsState<K>,
882 unique_tip_searchers: &mut Vec<BfsState<K>>,
883 common_searcher: &mut BfsState<K>,
884 ) {
885 // Step the all_unique_searcher every N steps (Python's
886 // STEP_UNIQUE_SEARCHER_EVERY = 5).
887 const STEP_ALL_UNIQUE_EVERY: usize = 5;
888 let mut step_all_unique_counter: usize = 0;
889
890 while !common_searcher.next_query().is_empty() {
891 let (newly_seen_common, newly_seen_unique) = self.step_unique_and_common_searchers(
892 common_searcher,
893 unique_tip_searchers,
894 unique_searcher,
895 );
896 let common_to_all_unique_nodes = self.find_nodes_common_to_all_unique(
897 unique_tip_searchers,
898 all_unique_searcher,
899 &newly_seen_unique,
900 step_all_unique_counter == 0,
901 );
902 step_all_unique_counter = (step_all_unique_counter + 1) % STEP_ALL_UNIQUE_EVERY;
903
904 if !newly_seen_common.is_empty() {
905 let stop: FxHashSet<K> = all_unique_searcher
906 .seen
907 .intersection(&newly_seen_common)
908 .cloned()
909 .collect();
910 common_searcher.stop_searching_any(stop);
911 }
912 if !common_to_all_unique_nodes.is_empty() {
913 let mut expanded = common_to_all_unique_nodes.clone();
914 expanded.extend(common_searcher.find_seen_ancestors(
915 common_to_all_unique_nodes.iter().cloned(),
916 &self.provider,
917 ));
918 all_unique_searcher.start_searching(expanded.iter().cloned(), &self.provider);
919 common_searcher.stop_searching_any(expanded);
920 }
921 let old_searchers = std::mem::take(unique_tip_searchers);
922 *unique_tip_searchers =
923 self.collapse_unique_searchers(old_searchers, &common_to_all_unique_nodes);
924 }
925 }
926
927 /// Find ancestors of `new_key` that may be descendants of `old_key`.
928 ///
929 /// Drives two parallel searchers: `stop` walks up from `old_key` and
930 /// `descendants` walks up from `new_key`. For each iteration, prune
931 /// nodes already seen by `stop` from `descendants`, then advance `stop`
932 /// and prune any nodes in the newly-visited stop set that `descendants`
933 /// has already reached (via `find_seen_ancestors`).
934 ///
935 /// Returns the set of keys reached by `descendants` but not by `stop`.
936 pub fn find_descendant_ancestors(&self, old_key: K, new_key: K) -> FxHashSet<K> {
937 let mut stop = BfsState::new([old_key]);
938 let mut descendants = BfsState::new([new_key]);
939 // Python's `for revisions in descendants:` iterates `next()` until
940 // StopIteration. Our next_set returns None to signal the end.
941 while let Some(revisions) = descendants.next_set(&self.provider) {
942 let old_stop: FxHashSet<K> = stop.seen.intersection(&revisions).cloned().collect();
943 descendants.stop_searching_any(old_stop);
944 let step = stop.next_set(&self.provider).unwrap_or_default();
945 let seen_stop = descendants.find_seen_ancestors(step, &self.provider);
946 descendants.stop_searching_any(seen_stop);
947 }
948 descendants.seen.difference(&stop.seen).cloned().collect()
949 }
950
951 /// Find border ancestors of a set of revisions via a concurrent BFS.
952 ///
953 /// Returns `(border_ancestors, common_ancestors, searchers)`. The
954 /// searchers are left in the state they finished in so callers can
955 /// inspect `seen` for graph-difference calculations.
956 pub fn find_border_ancestors(
957 &self,
958 revisions: impl IntoIterator<Item = K>,
959 ) -> (FxHashSet<K>, FxHashSet<K>, Vec<BfsState<K>>) {
960 let revisions: Vec<K> = revisions.into_iter().collect();
961 let mut searchers: Vec<BfsState<K>> = revisions
962 .iter()
963 .map(|r| BfsState::new([r.clone()]))
964 .collect();
965 let mut common_ancestors: FxHashSet<K> = FxHashSet::default();
966 let mut border_ancestors: FxHashSet<K> = FxHashSet::default();
967
968 loop {
969 let mut newly_seen: FxHashSet<K> = FxHashSet::default();
970 for searcher in searchers.iter_mut() {
971 if let Some(new_ancestors) = searcher.next_set(&self.provider) {
972 newly_seen.extend(new_ancestors);
973 }
974 }
975 let mut new_common: FxHashSet<K> = FxHashSet::default();
976 for revision in &newly_seen {
977 if common_ancestors.contains(revision) {
978 new_common.insert(revision.clone());
979 continue;
980 }
981 if searchers.iter().all(|s| s.seen.contains(revision)) {
982 border_ancestors.insert(revision.clone());
983 new_common.insert(revision.clone());
984 }
985 }
986 if !new_common.is_empty() {
987 // Pull in ancestors that are already seen by each searcher.
988 // We can't borrow searchers twice in one pass, so snapshot
989 // each searcher's contribution and merge.
990 let mut expanded = new_common.clone();
991 for searcher in searchers.iter() {
992 let seen_anc = searcher.find_seen_ancestors(new_common.clone(), &self.provider);
993 expanded.extend(seen_anc);
994 }
995 let new_common = expanded;
996 for searcher in searchers.iter_mut() {
997 searcher.start_searching(new_common.iter().cloned(), &self.provider);
998 }
999 common_ancestors.extend(new_common);
1000 }
1001
1002 // Convergence check: if all searchers have the same next query,
1003 // we've merged into a single common line and can stop.
1004 let first_frontier: FxHashSet<K> = searchers
1005 .first()
1006 .map(|s| s.next_query().clone())
1007 .unwrap_or_default();
1008 let all_same = searchers.iter().all(|s| s.next_query() == &first_frontier);
1009 if all_same {
1010 let uncommon: FxHashSet<K> = first_frontier
1011 .difference(&common_ancestors)
1012 .cloned()
1013 .collect();
1014 if !uncommon.is_empty() {
1015 // Shouldn't happen in well-formed graphs, but instead of
1016 // panicking we just continue — matches Python's
1017 // AssertionError shape without crashing.
1018 // (Callers of find_difference etc. will see this as an
1019 // empty difference; tests never exercise this path.)
1020 }
1021 break;
1022 }
1023 }
1024
1025 (border_ancestors, common_ancestors, searchers)
1026 }
1027
1028 /// Return the heads from amongst `keys`.
1029 ///
1030 /// This walks each candidate's ancestry and prunes any key reachable
1031 /// from another. The `null` parameter is the sentinel the caller uses
1032 /// for the origin (`b"null:"` in the Python layer); passing it lets the
1033 /// Rust core stay string-typed without baking bytes into the API.
1034 pub fn heads_with_null(&self, keys: impl IntoIterator<Item = K>, null: &K) -> FxHashSet<K> {
1035 let mut candidate_heads: FxHashSet<K> = keys.into_iter().collect();
1036 if candidate_heads.contains(null) {
1037 candidate_heads.remove(null);
1038 if candidate_heads.is_empty() {
1039 let mut r = FxHashSet::default();
1040 r.insert(null.clone());
1041 return r;
1042 }
1043 }
1044 if candidate_heads.len() < 2 {
1045 return candidate_heads;
1046 }
1047 // One searcher per candidate, keyed by the candidate revision.
1048 let mut searchers: FxHashMap<K, BfsState<K>> = candidate_heads
1049 .iter()
1050 .map(|c| (c.clone(), BfsState::new([c.clone()])))
1051 .collect();
1052 let mut active: FxHashSet<K> = candidate_heads.iter().cloned().collect();
1053 // Skip the first yield (the candidate itself).
1054 for (_, searcher) in searchers.iter_mut() {
1055 searcher.next_set(&self.provider);
1056 }
1057 // Common walker: tracks nodes known to be common across all
1058 // searchers, so that a searcher hitting one can stop early.
1059 let mut common_walker: BfsState<K> = BfsState::new([] as [K; 0]);
1060 while !active.is_empty() {
1061 let mut ancestors: FxHashSet<K> = FxHashSet::default();
1062 // Advance the common walker one step if there's anything to advance.
1063 common_walker.next_set(&self.provider);
1064 // Advance each active searcher one step.
1065 let active_list: Vec<K> = active.iter().cloned().collect();
1066 for candidate in active_list {
1067 let finished = {
1068 let searcher = searchers.get_mut(&candidate).unwrap();
1069 match searcher.next_set(&self.provider) {
1070 Some(set) => {
1071 ancestors.extend(set);
1072 false
1073 }
1074 None => true,
1075 }
1076 };
1077 if finished {
1078 active.remove(&candidate);
1079 }
1080 }
1081 // Process found ancestors.
1082 let mut new_common: FxHashSet<K> = FxHashSet::default();
1083 for ancestor in ancestors {
1084 if candidate_heads.contains(&ancestor) {
1085 candidate_heads.remove(&ancestor);
1086 searchers.remove(&ancestor);
1087 active.remove(&ancestor);
1088 }
1089 if common_walker.seen.contains(&ancestor) {
1090 // Known common: tell every searcher to stop on it.
1091 let stop_set: FxHashSet<K> = [ancestor].into_iter().collect();
1092 for searcher in searchers.values_mut() {
1093 searcher.stop_searching_any(stop_set.iter().cloned());
1094 }
1095 } else if searchers.values().all(|s| s.seen.contains(&ancestor)) {
1096 // All searchers have reached this node — it's newly
1097 // common. Stop any of its seen ancestors in each searcher.
1098 new_common.insert(ancestor.clone());
1099 // Collect seen ancestors per searcher, then apply stops.
1100 let seen_per_searcher: Vec<FxHashSet<K>> = searchers
1101 .values()
1102 .map(|s| s.find_seen_ancestors([ancestor.clone()], &self.provider))
1103 .collect();
1104 for (searcher, seen_anc) in searchers.values_mut().zip(seen_per_searcher) {
1105 searcher.stop_searching_any(seen_anc);
1106 }
1107 }
1108 }
1109 common_walker.start_searching(new_common, &self.provider);
1110 }
1111 candidate_heads
1112 }
1113
1114 /// Find the lowest common ancestors of `revisions`.
1115 pub fn find_lca(&self, revisions: impl IntoIterator<Item = K>, null: &K) -> FxHashSet<K> {
1116 let (border_common, _common, _searchers) = self.find_border_ancestors(revisions);
1117 self.heads_with_null(border_common, null)
1118 }
1119
1120 /// Return whether `candidate_ancestor` is an ancestor of `candidate_descendant`.
1121 pub fn is_ancestor(&self, candidate_ancestor: K, candidate_descendant: K, null: &K) -> bool {
1122 let heads = self.heads_with_null(
1123 [candidate_ancestor.clone(), candidate_descendant.clone()],
1124 null,
1125 );
1126 heads.len() == 1 && heads.contains(&candidate_descendant)
1127 }
1128
1129 /// Return whether `revid` is between `lower_bound_revid` and
1130 /// `upper_bound_revid` (inclusive). `None` bounds are skipped.
1131 pub fn is_between(
1132 &self,
1133 revid: K,
1134 lower_bound_revid: Option<K>,
1135 upper_bound_revid: Option<K>,
1136 null: &K,
1137 ) -> bool {
1138 let upper_ok = match upper_bound_revid {
1139 None => true,
1140 Some(upper) => self.is_ancestor(revid.clone(), upper, null),
1141 };
1142 if !upper_ok {
1143 return false;
1144 }
1145 match lower_bound_revid {
1146 None => true,
1147 Some(lower) => self.is_ancestor(lower, revid, null),
1148 }
1149 }
1150
1151 /// Find the order in which `lca_revision_ids` were merged into `tip`.
1152 ///
1153 /// Walks backwards from `tip` with a stack, left-first, collecting the
1154 /// LCA revisions in the order they are encountered.
1155 pub fn find_merge_order(
1156 &self,
1157 tip: K,
1158 lca_revision_ids: impl IntoIterator<Item = K>,
1159 ) -> Vec<K> {
1160 let mut looking_for: FxHashSet<K> = lca_revision_ids.into_iter().collect();
1161 if looking_for.len() == 1 {
1162 return looking_for.into_iter().collect();
1163 }
1164 let mut stack: Vec<K> = vec![tip];
1165 let mut found: Vec<K> = Vec::new();
1166 let mut stop: FxHashSet<K> = FxHashSet::default();
1167 while !stack.is_empty() && !looking_for.is_empty() {
1168 let next_key = stack.pop().unwrap();
1169 stop.insert(next_key.clone());
1170 if looking_for.remove(&next_key) {
1171 found.push(next_key);
1172 if looking_for.len() == 1 {
1173 // Only one LCA left — add it and break without walking.
1174 let last = looking_for.iter().next().cloned().unwrap();
1175 looking_for.clear();
1176 found.push(last);
1177 break;
1178 }
1179 continue;
1180 }
1181 let pm = self.get_parent_map(std::iter::once(next_key.clone()));
1182 let parents = match pm.get(&next_key) {
1183 Some(Parents::Known(ps)) if !ps.is_empty() => ps.clone(),
1184 _ => continue,
1185 };
1186 // Walk parents in reverse so the left-most parent is popped first.
1187 for parent_id in parents.into_iter().rev() {
1188 if !stop.contains(&parent_id) {
1189 stack.push(parent_id.clone());
1190 }
1191 stop.insert(parent_id);
1192 }
1193 }
1194 found
1195 }
1196
1197 /// Find descendants of `old_key` that are ancestors of `new_key`.
1198 ///
1199 /// Uses [`find_descendant_ancestors`](Self::find_descendant_ancestors)
1200 /// to narrow down candidates, then walks forwards through the child
1201 /// relationships by running a BFS over a [`DictParentsProvider`] built
1202 /// from the inverted parent map.
1203 pub fn find_descendants(&self, old_key: K, new_key: K) -> FxHashSet<K>
1204 where
1205 K: Ord,
1206 {
1207 let candidates = self.find_descendant_ancestors(old_key.clone(), new_key);
1208 let child_map = self.get_child_map(candidates);
1209 // Walk forwards via a DictParentsProvider built from the child map.
1210 let dict: HashMap<K, Vec<K>> = child_map.into_iter().collect();
1211 let provider = DictParentsProvider::from(dict);
1212 let mut searcher = BfsState::new([old_key]);
1213 while searcher.next_set(&provider).is_some() {}
1214 searcher.seen
1215 }
1216 }
1217
1218 #[cfg(test)]
1219 mod tests {
1220 use super::*;
1221 use crate::DictParentsProvider;
1222 use std::collections::HashMap;
1223
1224 const NULL: &str = "null:";
1225
1226 fn make(
1227 edges: &[(&'static str, &[&'static str])],
1228 ) -> Graph<&'static str, DictParentsProvider<&'static str>> {
1229 let map: HashMap<&'static str, Vec<&'static str>> =
1230 edges.iter().map(|(k, ps)| (*k, ps.to_vec())).collect();
1231 Graph::new(DictParentsProvider::from(map))
1232 }
1233
1234 #[test]
1235 fn get_parent_map_basic() {
1236 let g = make(&[("a", &[]), ("b", &["a"])]);
1237 let pm = g.get_parent_map(vec!["a", "b", "missing"]);
1238 assert_eq!(pm.get(&"a"), Some(&Parents::Known(vec![])));
1239 assert_eq!(pm.get(&"b"), Some(&Parents::Known(vec!["a"])));
1240 assert_eq!(pm.get(&"missing"), None);
1241 }
1242
1243 #[test]
1244 fn get_child_map_inverts() {
1245 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]);
1246 let cm = g.get_child_map(vec!["a", "b", "c", "d"]);
1247 assert_eq!(cm.get(&"a"), Some(&vec!["b", "c"]));
1248 assert_eq!(cm.get(&"b"), Some(&vec!["d"]));
1249 assert_eq!(cm.get(&"c"), Some(&vec!["d"]));
1250 assert_eq!(cm.get(&"d"), None);
1251 }
1252
1253 #[test]
1254 fn iter_lefthand_ancestry_linear() {
1255 // null <- a <- b <- c
1256 let g = make(&[("a", &[NULL]), ("b", &["a"]), ("c", &["b"])]);
1257 let out = g.iter_lefthand_ancestry("c", [NULL]).unwrap();
1258 assert_eq!(out, vec!["c", "b", "a"]);
1259 }
1260
1261 #[test]
1262 fn find_distance_to_null_linear() {
1263 // null <- a (1) <- b (2) <- c (3)
1264 let g = make(&[("a", &[NULL]), ("b", &["a"]), ("c", &["b"])]);
1265 assert_eq!(
1266 g.find_distance_to_null("c", std::iter::empty(), NULL)
1267 .unwrap(),
1268 3
1269 );
1270 assert_eq!(
1271 g.find_distance_to_null("a", std::iter::empty(), NULL)
1272 .unwrap(),
1273 1
1274 );
1275 }
1276
1277 #[test]
1278 fn find_distance_to_null_with_known_seed() {
1279 // null <- a (1) <- b (2) <- c (3) <- d (4)
1280 let g = make(&[("a", &[NULL]), ("b", &["a"]), ("c", &["b"]), ("d", &["c"])]);
1281 assert_eq!(
1282 g.find_distance_to_null("d", std::iter::once(("b", 2)), NULL)
1283 .unwrap(),
1284 4
1285 );
1286 }
1287
1288 #[test]
1289 fn find_lefthand_distances_all() {
1290 let g = make(&[("a", &[NULL]), ("b", &["a"]), ("c", &["b"])]);
1291 let d = g.find_lefthand_distances(vec!["a", "b", "c"], NULL);
1292 assert_eq!(d.get(&"a"), Some(&1));
1293 assert_eq!(d.get(&"b"), Some(&2));
1294 assert_eq!(d.get(&"c"), Some(&3));
1295 }
1296
1297 #[test]
1298 fn iter_topo_order_parents_first() {
1299 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]);
1300 let order = g.iter_topo_order(vec!["a", "b", "c", "d"]).unwrap();
1301 let pos = |x: &&str| order.iter().position(|n| n == x).unwrap();
1302 assert!(pos(&"a") < pos(&"b"));
1303 assert!(pos(&"a") < pos(&"c"));
1304 assert!(pos(&"b") < pos(&"d"));
1305 assert!(pos(&"c") < pos(&"d"));
1306 }
1307
1308 #[test]
1309 fn iter_ancestry_reaches_all() {
1310 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]);
1311 let anc = g.iter_ancestry(vec!["d"]);
1312 let keys: FxHashSet<&'static str> = anc.iter().map(|(k, _)| *k).collect();
1313 let expected: FxHashSet<&'static str> = ["a", "b", "c", "d"].into_iter().collect();
1314 assert_eq!(keys, expected);
1315 }
1316
1317 #[test]
1318 fn find_descendants_diamond() {
1319 // a
1320 // / \
1321 // b c
1322 // \ /
1323 // d
1324 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]);
1325 let descendants = g.find_descendants("a", "d");
1326 let expected: FxHashSet<&'static str> = ["a", "b", "c", "d"].into_iter().collect();
1327 assert_eq!(descendants, expected);
1328 }
1329
1330 #[test]
1331 fn find_descendants_linear() {
1332 // a <- b <- c <- d
1333 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["b"]), ("d", &["c"])]);
1334 let descendants = g.find_descendants("b", "d");
1335 let expected: FxHashSet<&'static str> = ["b", "c", "d"].into_iter().collect();
1336 assert_eq!(descendants, expected);
1337 }
1338
1339 #[test]
1340 fn heads_single_candidate() {
1341 let g = make(&[("a", &[]), ("b", &["a"])]);
1342 let h = g.heads_with_null(vec!["b"], &NULL);
1343 assert_eq!(h, ["b"].into_iter().collect());
1344 }
1345
1346 #[test]
1347 fn heads_prunes_ancestors() {
1348 // a <- b <- c
1349 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["b"])]);
1350 let h = g.heads_with_null(vec!["a", "c"], &NULL);
1351 assert_eq!(h, ["c"].into_iter().collect());
1352 }
1353
1354 #[test]
1355 fn heads_diamond_returns_both() {
1356 // a
1357 // / \
1358 // b c
1359 // \ /
1360 // d
1361 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]);
1362 let h = g.heads_with_null(vec!["b", "c"], &NULL);
1363 let expected: FxHashSet<_> = ["b", "c"].into_iter().collect();
1364 assert_eq!(h, expected);
1365 }
1366
1367 #[test]
1368 fn heads_null_alone() {
1369 let g = make(&[("a", &[])]);
1370 let h = g.heads_with_null(vec![NULL], &NULL);
1371 assert_eq!(h, [NULL].into_iter().collect());
1372 }
1373
1374 #[test]
1375 fn find_lca_diamond() {
1376 // a
1377 // / \
1378 // b c
1379 // \ /
1380 // d
1381 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]);
1382 let lca = g.find_lca(vec!["b", "c"], &NULL);
1383 assert_eq!(lca, ["a"].into_iter().collect());
1384 }
1385
1386 #[test]
1387 fn is_ancestor_true_and_false() {
1388 // a <- b <- c
1389 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["b"])]);
1390 assert!(g.is_ancestor("a", "c", &NULL));
1391 assert!(g.is_ancestor("b", "c", &NULL));
1392 assert!(!g.is_ancestor("c", "a", &NULL));
1393 }
1394
1395 #[test]
1396 fn find_merge_order_single() {
1397 let g = make(&[("a", &[]), ("b", &["a"])]);
1398 let order = g.find_merge_order("b", vec!["a"]);
1399 assert_eq!(order, vec!["a"]);
1400 }
1401
1402 #[test]
1403 fn find_descendants_unrelated() {
1404 // new_key is not a descendant of old_key.
1405 let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"])]);
1406 let descendants = g.find_descendants("b", "c");
1407 // b is not reachable from c, so no descendants of b among c's ancestry.
1408 assert!(descendants.is_empty() || descendants == ["b"].into_iter().collect());
1409 }
1410
1411 /// Build a set literal from an array of strings.
1412 fn set<const N: usize>(xs: [&'static str; N]) -> FxHashSet<&'static str> {
1413 xs.into_iter().collect()
1414 }
1415
1416 fn ancestry_1() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1417 make(&[
1418 ("rev1", &[NULL]),
1419 ("rev2a", &["rev1"]),
1420 ("rev2b", &["rev1"]),
1421 ("rev3", &["rev2a"]),
1422 ("rev4", &["rev3", "rev2b"]),
1423 ])
1424 }
1425
1426 fn ancestry_2() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1427 make(&[
1428 ("rev1a", &[NULL]),
1429 ("rev2a", &["rev1a"]),
1430 ("rev1b", &[NULL]),
1431 ("rev3a", &["rev2a"]),
1432 ("rev4a", &["rev3a"]),
1433 ])
1434 }
1435
1436 fn criss_cross() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1437 make(&[
1438 ("rev1", &[NULL]),
1439 ("rev2a", &["rev1"]),
1440 ("rev2b", &["rev1"]),
1441 ("rev3a", &["rev2a", "rev2b"]),
1442 ("rev3b", &["rev2b", "rev2a"]),
1443 ])
1444 }
1445
1446 fn criss_cross2() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1447 make(&[
1448 ("rev1a", &[NULL]),
1449 ("rev1b", &[NULL]),
1450 ("rev2a", &["rev1a", "rev1b"]),
1451 ("rev2b", &["rev1b", "rev1a"]),
1452 ])
1453 }
1454
1455 fn history_shortcut() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1456 make(&[
1457 ("rev1", &[NULL]),
1458 ("rev2a", &["rev1"]),
1459 ("rev2b", &["rev1"]),
1460 ("rev2c", &["rev1"]),
1461 ("rev3a", &["rev2a", "rev2b"]),
1462 ("rev3b", &["rev2b", "rev2c"]),
1463 ])
1464 }
1465
1466 fn extended_history_shortcut() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1467 make(&[
1468 ("a", &[NULL]),
1469 ("b", &["a"]),
1470 ("c", &["b"]),
1471 ("d", &["c"]),
1472 ("e", &["d"]),
1473 ("f", &["a", "d"]),
1474 ])
1475 }
1476
1477 fn double_shortcut_fixture() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1478 make(&[
1479 ("a", &[NULL]),
1480 ("b", &["a"]),
1481 ("c", &["b"]),
1482 ("d", &["c"]),
1483 ("e", &["c"]),
1484 ("f", &["a", "d"]),
1485 ("g", &["a", "e"]),
1486 ])
1487 }
1488
1489 fn complex_shortcut() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1490 make(&[
1491 ("a", &[NULL]),
1492 ("b", &["a"]),
1493 ("c", &["b"]),
1494 ("d", &["c"]),
1495 ("e", &["d"]),
1496 ("f", &["d"]),
1497 ("g", &["f"]),
1498 ("h", &["f"]),
1499 ("i", &["e", "g"]),
1500 ("j", &["g"]),
1501 ("k", &["j"]),
1502 ("l", &["k"]),
1503 ("m", &["i", "l"]),
1504 ("n", &["l", "h"]),
1505 ])
1506 }
1507
1508 fn complex_shortcut2() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1509 make(&[
1510 ("a", &[NULL]),
1511 ("b", &["a"]),
1512 ("c", &["b"]),
1513 ("d", &["c"]),
1514 ("e", &["d"]),
1515 ("f", &["e"]),
1516 ("g", &["f"]),
1517 ("h", &["d"]),
1518 ("i", &["g"]),
1519 ("j", &["h"]),
1520 ("k", &["h", "i"]),
1521 ("l", &["k"]),
1522 ("m", &["l"]),
1523 ("n", &["m"]),
1524 ("o", &["n"]),
1525 ("p", &["o"]),
1526 ("q", &["p"]),
1527 ("r", &["q"]),
1528 ("s", &["r"]),
1529 ("t", &["i", "s"]),
1530 ("u", &["s", "j"]),
1531 ])
1532 }
1533
1534 fn multiple_interesting_unique() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1535 make(&[
1536 ("a", &[NULL]),
1537 ("b", &["a"]),
1538 ("c", &["b"]),
1539 ("d", &["c"]),
1540 ("e", &["d"]),
1541 ("f", &["d"]),
1542 ("g", &["e"]),
1543 ("h", &["e"]),
1544 ("i", &["f"]),
1545 ("j", &["g"]),
1546 ("k", &["g"]),
1547 ("l", &["h"]),
1548 ("m", &["i"]),
1549 ("n", &["k", "l"]),
1550 ("o", &["m"]),
1551 ("p", &["m", "l"]),
1552 ("q", &["n", "o"]),
1553 ("r", &["q"]),
1554 ("s", &["r"]),
1555 ("t", &["s"]),
1556 ("u", &["t"]),
1557 ("v", &["u"]),
1558 ("w", &["v"]),
1559 ("x", &["w"]),
1560 ("y", &["j", "x"]),
1561 ("z", &["x", "p"]),
1562 ])
1563 }
1564
1565 fn shortcut_extra_root() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1566 make(&[
1567 ("a", &[NULL]),
1568 ("b", &["a"]),
1569 ("c", &["b"]),
1570 ("d", &["c"]),
1571 ("e", &["d"]),
1572 ("f", &["a", "d", "g"]),
1573 ("g", &[NULL]),
1574 ])
1575 }
1576
1577 fn boundary() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1578 make(&[
1579 ("a", &["b"]),
1580 ("c", &["b", "d"]),
1581 ("b", &["e"]),
1582 ("d", &["e"]),
1583 ("e", &["f"]),
1584 ("f", &[NULL]),
1585 ])
1586 }
1587
1588 #[test]
1589 fn test_lca_ancestry_1() {
1590 let g = ancestry_1();
1591 assert_eq!(g.find_lca([NULL, NULL], &NULL), set([NULL]));
1592 assert_eq!(g.find_lca([NULL, "rev1"], &NULL), set([NULL]));
1593 assert_eq!(g.find_lca(["rev1", "rev1"], &NULL), set(["rev1"]));
1594 assert_eq!(g.find_lca(["rev2a", "rev2b"], &NULL), set(["rev1"]));
1595 }
1596
1597 #[test]
1598 fn test_lca_criss_cross() {
1599 let g = criss_cross();
1600 assert_eq!(
1601 g.find_lca(["rev3a", "rev3b"], &NULL),
1602 set(["rev2a", "rev2b"])
1603 );
1604 }
1605
1606 #[test]
1607 fn test_lca_shortcut() {
1608 let g = history_shortcut();
1609 assert_eq!(g.find_lca(["rev3a", "rev3b"], &NULL), set(["rev2b"]));
1610 }
1611
1612 #[test]
1613 fn test_lca_double_shortcut() {
1614 let g = double_shortcut_fixture();
1615 assert_eq!(g.find_lca(["f", "g"], &NULL), set(["c"]));
1616 }
1617
1618 #[test]
1619 fn test_unique_lca_ancestry_1() {
1620 let g = ancestry_1();
1621 assert_eq!(g.find_unique_lca(NULL, NULL, &NULL), Some((NULL, 1)));
1622 assert_eq!(g.find_unique_lca(NULL, "rev1", &NULL), Some((NULL, 1)));
1623 assert_eq!(g.find_unique_lca("rev1", "rev1", &NULL), Some(("rev1", 1)));
1624 assert_eq!(
1625 g.find_unique_lca("rev2a", "rev2b", &NULL),
1626 Some(("rev1", 1))
1627 );
1628 }
1629
1630 #[test]
1631 fn test_unique_lca_criss_cross() {
1632 let g = criss_cross();
1633 assert_eq!(
1634 g.find_unique_lca("rev3a", "rev3b", &NULL),
1635 Some(("rev1", 2))
1636 );
1637 }
1638
1639 #[test]
1640 fn test_unique_lca_null_revision_criss_cross2() {
1641 let g = criss_cross2();
1642 assert_eq!(
1643 g.find_unique_lca("rev2a", "rev1b", &NULL).map(|(k, _)| k),
1644 Some("rev1b")
1645 );
1646 assert_eq!(
1647 g.find_unique_lca("rev2a", "rev2b", &NULL).map(|(k, _)| k),
1648 Some(NULL)
1649 );
1650 }
1651
1652 #[test]
1653 fn test_unique_lca_separate_ancestry() {
1654 let g = ancestry_2();
1655 assert_eq!(
1656 g.find_unique_lca("rev4a", "rev1b", &NULL).map(|(k, _)| k),
1657 Some(NULL)
1658 );
1659 }
1660
1661 #[test]
1662 fn test_heads_null() {
1663 let g = ancestry_1();
1664 assert_eq!(g.heads_with_null([NULL], &NULL), set([NULL]));
1665 assert_eq!(g.heads_with_null([NULL, "rev1"], &NULL), set(["rev1"]));
1666 assert_eq!(g.heads_with_null(["rev1", NULL], &NULL), set(["rev1"]));
1667 }
1668
1669 #[test]
1670 fn test_heads_one() {
1671 let g = ancestry_1();
1672 for key in [NULL, "rev1", "rev2a", "rev2b", "rev3", "rev4"] {
1673 assert_eq!(g.heads_with_null([key], &NULL), set([key]));
1674 }
1675 }
1676
1677 #[test]
1678 fn test_heads_single_from_pair() {
1679 let g = ancestry_1();
1680 assert_eq!(g.heads_with_null([NULL, "rev4"], &NULL), set(["rev4"]));
1681 assert_eq!(g.heads_with_null(["rev1", "rev2a"], &NULL), set(["rev2a"]));
1682 assert_eq!(g.heads_with_null(["rev1", "rev2b"], &NULL), set(["rev2b"]));
1683 assert_eq!(g.heads_with_null(["rev1", "rev3"], &NULL), set(["rev3"]));
1684 assert_eq!(g.heads_with_null(["rev1", "rev4"], &NULL), set(["rev4"]));
1685 assert_eq!(g.heads_with_null(["rev2a", "rev4"], &NULL), set(["rev4"]));
1686 assert_eq!(g.heads_with_null(["rev2b", "rev4"], &NULL), set(["rev4"]));
1687 assert_eq!(g.heads_with_null(["rev3", "rev4"], &NULL), set(["rev4"]));
1688 }
1689
1690 #[test]
1691 fn test_heads_two_heads() {
1692 let g = ancestry_1();
1693 assert_eq!(
1694 g.heads_with_null(["rev2a", "rev2b"], &NULL),
1695 set(["rev2a", "rev2b"])
1696 );
1697 assert_eq!(
1698 g.heads_with_null(["rev3", "rev2b"], &NULL),
1699 set(["rev3", "rev2b"])
1700 );
1701 }
1702
1703 #[test]
1704 fn test_heads_criss_cross() {
1705 let g = criss_cross();
1706 assert_eq!(g.heads_with_null(["rev2a", "rev1"], &NULL), set(["rev2a"]));
1707 assert_eq!(g.heads_with_null(["rev2b", "rev1"], &NULL), set(["rev2b"]));
1708 assert_eq!(g.heads_with_null(["rev3a", "rev1"], &NULL), set(["rev3a"]));
1709 assert_eq!(g.heads_with_null(["rev3b", "rev1"], &NULL), set(["rev3b"]));
1710 assert_eq!(
1711 g.heads_with_null(["rev2a", "rev2b"], &NULL),
1712 set(["rev2a", "rev2b"])
1713 );
1714 assert_eq!(g.heads_with_null(["rev3a", "rev2a"], &NULL), set(["rev3a"]));
1715 assert_eq!(g.heads_with_null(["rev3a", "rev2b"], &NULL), set(["rev3a"]));
1716 assert_eq!(
1717 g.heads_with_null(["rev3a", "rev2a", "rev2b"], &NULL),
1718 set(["rev3a"])
1719 );
1720 assert_eq!(g.heads_with_null(["rev3b", "rev2a"], &NULL), set(["rev3b"]));
1721 assert_eq!(g.heads_with_null(["rev3b", "rev2b"], &NULL), set(["rev3b"]));
1722 assert_eq!(
1723 g.heads_with_null(["rev3b", "rev2a", "rev2b"], &NULL),
1724 set(["rev3b"])
1725 );
1726 assert_eq!(
1727 g.heads_with_null(["rev3a", "rev3b"], &NULL),
1728 set(["rev3a", "rev3b"])
1729 );
1730 assert_eq!(
1731 g.heads_with_null(["rev3a", "rev3b", "rev2a", "rev2b"], &NULL),
1732 set(["rev3a", "rev3b"])
1733 );
1734 }
1735
1736 #[test]
1737 fn test_heads_shortcut() {
1738 let g = history_shortcut();
1739 assert_eq!(
1740 g.heads_with_null(["rev2a", "rev2b", "rev2c"], &NULL),
1741 set(["rev2a", "rev2b", "rev2c"])
1742 );
1743 assert_eq!(
1744 g.heads_with_null(["rev3a", "rev3b"], &NULL),
1745 set(["rev3a", "rev3b"])
1746 );
1747 assert_eq!(
1748 g.heads_with_null(["rev2a", "rev3a", "rev3b"], &NULL),
1749 set(["rev3a", "rev3b"])
1750 );
1751 assert_eq!(
1752 g.heads_with_null(["rev2a", "rev3b"], &NULL),
1753 set(["rev2a", "rev3b"])
1754 );
1755 assert_eq!(
1756 g.heads_with_null(["rev2c", "rev3a"], &NULL),
1757 set(["rev2c", "rev3a"])
1758 );
1759 }
1760
1761 #[test]
1762 fn test_graph_difference_ancestry_1() {
1763 let g = ancestry_1();
1764 assert_eq!(
1765 g.find_difference("rev1", "rev1"),
1766 (FxHashSet::default(), FxHashSet::default())
1767 );
1768 assert_eq!(
1769 g.find_difference(NULL, "rev1"),
1770 (FxHashSet::default(), set(["rev1"]))
1771 );
1772 assert_eq!(
1773 g.find_difference("rev1", NULL),
1774 (set(["rev1"]), FxHashSet::default())
1775 );
1776 assert_eq!(
1777 g.find_difference("rev3", "rev2b"),
1778 (set(["rev2a", "rev3"]), set(["rev2b"]))
1779 );
1780 assert_eq!(
1781 g.find_difference("rev4", "rev2b"),
1782 (set(["rev4", "rev3", "rev2a"]), FxHashSet::default())
1783 );
1784 }
1785
1786 #[test]
1787 fn test_graph_difference_separate_ancestry() {
1788 let g = ancestry_2();
1789 assert_eq!(
1790 g.find_difference("rev1a", "rev1b"),
1791 (set(["rev1a"]), set(["rev1b"]))
1792 );
1793 assert_eq!(
1794 g.find_difference("rev4a", "rev1b"),
1795 (set(["rev1a", "rev2a", "rev3a", "rev4a"]), set(["rev1b"]))
1796 );
1797 }
1798
1799 #[test]
1800 fn test_graph_difference_criss_cross() {
1801 let g = criss_cross();
1802 assert_eq!(
1803 g.find_difference("rev3a", "rev3b"),
1804 (set(["rev3a"]), set(["rev3b"]))
1805 );
1806 assert_eq!(
1807 g.find_difference("rev2a", "rev3b"),
1808 (FxHashSet::default(), set(["rev3b", "rev2b"]))
1809 );
1810 }
1811
1812 #[test]
1813 fn test_graph_difference_extended_history() {
1814 let g = extended_history_shortcut();
1815 assert_eq!(g.find_difference("e", "f"), (set(["e"]), set(["f"])));
1816 assert_eq!(g.find_difference("f", "e"), (set(["f"]), set(["e"])));
1817 }
1818
1819 #[test]
1820 fn test_graph_difference_double_shortcut() {
1821 let g = double_shortcut_fixture();
1822 assert_eq!(
1823 g.find_difference("f", "g"),
1824 (set(["d", "f"]), set(["e", "g"]))
1825 );
1826 }
1827
1828 #[test]
1829 fn test_graph_difference_complex_shortcut() {
1830 let g = complex_shortcut();
1831 assert_eq!(
1832 g.find_difference("m", "n"),
1833 (set(["m", "i", "e"]), set(["n", "h"]))
1834 );
1835 }
1836
1837 #[test]
1838 fn test_graph_difference_complex_shortcut2() {
1839 let g = complex_shortcut2();
1840 assert_eq!(g.find_difference("t", "u"), (set(["t"]), set(["j", "u"])));
1841 }
1842
1843 #[test]
1844 fn test_graph_difference_shortcut_extra_root() {
1845 let g = shortcut_extra_root();
1846 assert_eq!(g.find_difference("e", "f"), (set(["e"]), set(["f", "g"])));
1847 }
1848
1849 #[test]
1850 fn test_unique_ancestors_empty_set() {
1851 let g = ancestry_1();
1852 assert_eq!(
1853 g.find_unique_ancestors("rev1", ["rev1"]),
1854 FxHashSet::default()
1855 );
1856 assert_eq!(
1857 g.find_unique_ancestors("rev2b", ["rev2b"]),
1858 FxHashSet::default()
1859 );
1860 assert_eq!(
1861 g.find_unique_ancestors("rev3", ["rev1", "rev3"]),
1862 FxHashSet::default()
1863 );
1864 }
1865
1866 #[test]
1867 fn test_unique_ancestors_single_node() {
1868 let g = ancestry_1();
1869 assert_eq!(g.find_unique_ancestors("rev2a", ["rev1"]), set(["rev2a"]));
1870 assert_eq!(g.find_unique_ancestors("rev2b", ["rev1"]), set(["rev2b"]));
1871 assert_eq!(g.find_unique_ancestors("rev3", ["rev2a"]), set(["rev3"]));
1872 }
1873
1874 #[test]
1875 fn test_unique_ancestors_in_ancestry() {
1876 let g = ancestry_1();
1877 assert_eq!(
1878 g.find_unique_ancestors("rev1", ["rev3"]),
1879 FxHashSet::default()
1880 );
1881 assert_eq!(
1882 g.find_unique_ancestors("rev2b", ["rev4"]),
1883 FxHashSet::default()
1884 );
1885 }
1886
1887 #[test]
1888 fn test_unique_ancestors_multiple_revisions() {
1889 let g = ancestry_1();
1890 assert_eq!(
1891 g.find_unique_ancestors("rev4", ["rev3", "rev2b"]),
1892 set(["rev4"])
1893 );
1894 assert_eq!(
1895 g.find_unique_ancestors("rev4", ["rev2b"]),
1896 set(["rev2a", "rev3", "rev4"])
1897 );
1898 }
1899
1900 #[test]
1901 fn test_unique_ancestors_complex_shortcut() {
1902 let g = complex_shortcut();
1903 assert_eq!(g.find_unique_ancestors("n", ["m"]), set(["h", "n"]));
1904 assert_eq!(g.find_unique_ancestors("m", ["n"]), set(["e", "i", "m"]));
1905 }
1906
1907 #[test]
1908 fn test_unique_ancestors_complex_shortcut2() {
1909 let g = complex_shortcut2();
1910 assert_eq!(g.find_unique_ancestors("u", ["t"]), set(["j", "u"]));
1911 assert_eq!(g.find_unique_ancestors("t", ["u"]), set(["t"]));
1912 }
1913
1914 #[test]
1915 fn test_unique_ancestors_multiple_interesting_unique() {
1916 let g = multiple_interesting_unique();
1917 assert_eq!(g.find_unique_ancestors("y", ["z"]), set(["j", "y"]));
1918 assert_eq!(g.find_unique_ancestors("z", ["y"]), set(["p", "z"]));
1919 }
1920
1921 #[test]
1922 fn test_is_ancestor_ancestry_1() {
1923 let g = ancestry_1();
1924 assert!(g.is_ancestor(NULL, NULL, &NULL));
1925 assert!(g.is_ancestor(NULL, "rev1", &NULL));
1926 assert!(!g.is_ancestor("rev1", NULL, &NULL));
1927 assert!(g.is_ancestor(NULL, "rev4", &NULL));
1928 assert!(!g.is_ancestor("rev4", NULL, &NULL));
1929 assert!(!g.is_ancestor("rev4", "rev2b", &NULL));
1930 assert!(g.is_ancestor("rev2b", "rev4", &NULL));
1931 assert!(!g.is_ancestor("rev2b", "rev3", &NULL));
1932 assert!(!g.is_ancestor("rev3", "rev2b", &NULL));
1933 }
1934
1935 #[test]
1936 fn test_is_ancestor_boundary() {
1937 // Python's test_is_ancestor_boundary: verify a is not an ancestor
1938 // of c despite both sharing a common ancestor further down.
1939 let g = boundary();
1940 assert!(!g.is_ancestor("a", "c", &NULL));
1941 }
1942
1943 #[test]
1944 fn test_is_between_ancestry_1() {
1945 let g = ancestry_1();
1946 assert!(g.is_between(NULL, Some(NULL), Some(NULL), &NULL));
1947 assert!(g.is_between("rev1", Some(NULL), Some("rev1"), &NULL));
1948 assert!(g.is_between("rev1", Some("rev1"), Some("rev4"), &NULL));
1949 assert!(g.is_between("rev4", Some("rev1"), Some("rev4"), &NULL));
1950 assert!(g.is_between("rev3", Some("rev1"), Some("rev4"), &NULL));
1951 assert!(!g.is_between("rev4", Some("rev1"), Some("rev3"), &NULL));
1952 assert!(!g.is_between("rev1", Some("rev2a"), Some("rev4"), &NULL));
1953 assert!(!g.is_between(NULL, Some("rev1"), Some("rev4"), &NULL));
1954 }
1955
1956 #[test]
1957 fn test_find_merge_order_single_lca() {
1958 let g = ancestry_1();
1959 assert_eq!(g.find_merge_order("rev4", ["rev2b"]), vec!["rev2b"]);
1960 }
1961
1962 fn with_ghost() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1963 // NULL_REVISION itself is explicitly included as a root so it
1964 // survives as a key in iter_ancestry's output.
1965 make(&[
1966 ("a", &["b"]),
1967 ("c", &["b", "d"]),
1968 ("b", &["e"]),
1969 ("d", &["e", "g"]),
1970 ("e", &["f"]),
1971 ("f", &[NULL]),
1972 (NULL, &[]),
1973 ])
1974 }
1975
1976 fn racing_shortcuts() -> Graph<&'static str, DictParentsProvider<&'static str>> {
1977 make(&[
1978 ("a", &[NULL]),
1979 ("b", &["a"]),
1980 ("c", &["b"]),
1981 ("d", &["c"]),
1982 ("e", &["d"]),
1983 ("f", &["e"]),
1984 ("g", &["f"]),
1985 ("h", &["g"]),
1986 ("i", &["h", "o"]),
1987 ("j", &["i", "y"]),
1988 ("k", &["d"]),
1989 ("l", &["k"]),
1990 ("m", &["l"]),
1991 ("n", &["m"]),
1992 ("o", &["n", "g"]),
1993 ("p", &["f"]),
1994 ("q", &["p", "m"]),
1995 ("r", &["o"]),
1996 ("s", &["r"]),
1997 ("t", &["s"]),
1998 ("u", &["t"]),
1999 ("v", &["u"]),
2000 ("w", &["v"]),
2001 ("x", &["w"]),
2002 ("y", &["x"]),
2003 ("z", &["x", "q"]),
2004 ])
2005 }
2006
2007 /// Python's `alt_merge` fixture.
2008 ///
2009 /// ```text
2010 /// a
2011 /// |\
2012 /// b |
2013 /// | |
2014 /// c |
2015 /// \|
2016 /// d
2017 /// ```
2018 fn alt_merge() -> Graph<&'static str, DictParentsProvider<&'static str>> {
2019 make(&[("a", &[]), ("b", &["a"]), ("c", &["b"]), ("d", &["a", "c"])])
2020 }
2021
2022 #[test]
2023 fn test_heads_alt_merge() {
2024 let g = alt_merge();
2025 assert_eq!(g.heads_with_null(["a", "c"], &NULL), set(["c"]));
2026 }
2027
2028 #[test]
2029 fn test_heads_with_ghost_fixture() {
2030 let g = with_ghost();
2031 assert_eq!(g.heads_with_null(["e", "g"], &NULL), set(["e", "g"]));
2032 assert_eq!(g.heads_with_null(["a", "c"], &NULL), set(["a", "c"]));
2033 assert_eq!(g.heads_with_null(["a", "g"], &NULL), set(["a", "g"]));
2034 assert_eq!(g.heads_with_null(["f", "g"], &NULL), set(["f", "g"]));
2035 assert_eq!(g.heads_with_null(["c", "g"], &NULL), set(["c"]));
2036 assert_eq!(g.heads_with_null(["c", "b", "d", "g"], &NULL), set(["c"]));
2037 assert_eq!(
2038 g.heads_with_null(["a", "c", "e", "g"], &NULL),
2039 set(["a", "c"])
2040 );
2041 assert_eq!(g.heads_with_null(["a", "c", "f"], &NULL), set(["a", "c"]));
2042 }
2043
2044 #[test]
2045 fn test_filter_candidate_lca() {
2046 // Corner case from Python:
2047 // NULL
2048 // / \
2049 // a e
2050 // | |
2051 // b d
2052 // \ /
2053 // c
2054 // `a`'s descendant is `c`; `e`'s descendant is also `c`. So
2055 // heads([a, c, e]) should be just {c}.
2056 let g = make(&[
2057 ("c", &["b", "d"]),
2058 ("d", &["e"]),
2059 ("b", &["a"]),
2060 ("a", &[NULL]),
2061 ("e", &[NULL]),
2062 ]);
2063 assert_eq!(g.heads_with_null(["a", "c", "e"], &NULL), set(["c"]));
2064 }
2065
2066 #[test]
2067 fn test_iter_topo_order_ancestry_1() {
2068 let g = ancestry_1();
2069 let order = g.iter_topo_order(["rev2a", "rev3", "rev1"]).unwrap();
2070 let pos = |k: &&str| order.iter().position(|n| n == k).unwrap();
2071 assert_eq!(
2072 order.iter().cloned().collect::<FxHashSet<_>>(),
2073 set(["rev1", "rev2a", "rev3"])
2074 );
2075 assert!(pos(&"rev2a") > pos(&"rev1"));
2076 assert!(pos(&"rev2a") < pos(&"rev3"));
2077 }
2078
2079 #[test]
2080 fn test_iter_ancestry_boundary() {
2081 let g = with_ghost();
2082 // `a` is not in the ancestry of `c`; everything else is.
2083 let anc = g.iter_ancestry(["c"]);
2084 let keys: FxHashSet<&'static str> = anc.iter().map(|(k, _)| *k).collect();
2085 assert!(!keys.contains(&"a"));
2086 assert!(keys.contains(&"c"));
2087 assert!(keys.contains(&"b"));
2088 assert!(keys.contains(&"d"));
2089 assert!(keys.contains(&"e"));
2090 assert!(keys.contains(&"f"));
2091 }
2092
2093 #[test]
2094 fn test_iter_ancestry_with_ghost_reports_none() {
2095 let g = with_ghost();
2096 // `g` is a ghost (present as parent of `d` but not as key).
2097 // iter_ancestry should yield it with Parents::Ghost.
2098 let anc = g.iter_ancestry(["a", "c"]);
2099 let mut ghost_seen = false;
2100 for (k, parents) in &anc {
2101 if *k == "g" {
2102 ghost_seen = true;
2103 assert!(matches!(parents, Parents::Ghost));
2104 }
2105 }
2106 assert!(ghost_seen, "ghost `g` should appear in iter_ancestry");
2107 }
2108
2109 #[test]
2110 fn test_find_lefthand_merger_rev2b() {
2111 // In ancestry_1, rev4 merged rev2b (rev4 has parents [rev3, rev2b]).
2112 // Walking rev4's lefthand ancestry from rev2b: rev4 is the merger.
2113 let g = ancestry_1();
2114 assert_eq!(g.find_lefthand_merger("rev2b", "rev4"), Some("rev4"));
2115 }
2116
2117 #[test]
2118 fn test_find_lefthand_merger_rev2a() {
2119 // rev2a is itself a lefthand ancestor of rev4 (via rev3), so it's
2120 // its own "merger".
2121 let g = ancestry_1();
2122 assert_eq!(g.find_lefthand_merger("rev2a", "rev4"), Some("rev2a"));
2123 }
2124
2125 #[test]
2126 fn test_find_lefthand_merger_rev4_not_ancestor() {
2127 // rev4 is a descendant of rev2a, not an ancestor.
2128 let g = ancestry_1();
2129 assert_eq!(g.find_lefthand_merger("rev4", "rev2a"), None);
2130 }
2131
2132 #[test]
2133 fn test_unique_lca_recursive_ancestry_1() {
2134 // In ancestry_1, rev1 is the unique LCA of rev2a and rev2b.
2135 let g = ancestry_1();
2136 let (key, steps) = g.find_unique_lca("rev2a", "rev2b", &NULL).unwrap();
2137 assert_eq!(key, "rev1");
2138 assert_eq!(steps, 1);
2139 }
2140
2141 #[test]
2142 fn test_unique_lca_no_common_ancestor() {
2143 // Two disjoint ancestries share only NULL_REVISION as a common
2144 // ancestor. find_unique_lca returns NULL (never errors).
2145 let g = ancestry_2();
2146 let (key, _steps) = g.find_unique_lca("rev4a", "rev1b", &NULL).unwrap();
2147 assert_eq!(key, NULL);
2148 }
2149
2150 #[test]
2151 fn test_unique_ancestors_racing_shortcuts() {
2152 let g = racing_shortcuts();
2153 assert_eq!(g.find_unique_ancestors("z", ["y"]), set(["p", "q", "z"]));
2154 assert_eq!(
2155 g.find_unique_ancestors("j", ["z"]),
2156 set(["h", "i", "j", "y"])
2157 );
2158 }
2159
2160 #[test]
2161 fn test_find_distance_to_null_ancestry_1() {
2162 let g = ancestry_1();
2163 assert_eq!(
2164 g.find_distance_to_null(NULL, std::iter::empty(), NULL)
2165 .unwrap(),
2166 0
2167 );
2168 assert_eq!(
2169 g.find_distance_to_null("rev1", std::iter::empty(), NULL)
2170 .unwrap(),
2171 1
2172 );
2173 assert_eq!(
2174 g.find_distance_to_null("rev2a", std::iter::empty(), NULL)
2175 .unwrap(),
2176 2
2177 );
2178 assert_eq!(
2179 g.find_distance_to_null("rev2b", std::iter::empty(), NULL)
2180 .unwrap(),
2181 2
2182 );
2183 assert_eq!(
2184 g.find_distance_to_null("rev3", std::iter::empty(), NULL)
2185 .unwrap(),
2186 3
2187 );
2188 assert_eq!(
2189 g.find_distance_to_null("rev4", std::iter::empty(), NULL)
2190 .unwrap(),
2191 4
2192 );
2193 }
2194
2195 #[test]
2196 fn test_find_lefthand_distances_ghosts() {
2197 let g = make(&[("nonghost", &[NULL]), ("toghost", &["ghost"])]);
2198 let d = g.find_lefthand_distances(vec!["nonghost", "toghost"], NULL);
2199 assert_eq!(d.get(&"nonghost"), Some(&1));
2200 // Ghosts are reported as distance -1.
2201 assert_eq!(d.get(&"toghost"), Some(&-1));
2202 }
2203
2204 #[test]
2205 fn test_find_lefthand_distances_smoke() {
2206 let g = make(&[
2207 ("rev1", &[NULL]),
2208 ("rev2a", &["rev1"]),
2209 ("rev2b", &["rev1"]),
2210 ("rev2c", &["rev1"]),
2211 ("rev3a", &["rev2a", "rev2b"]),
2212 ("rev3b", &["rev2b", "rev2c"]),
2213 ]);
2214 let d = g.find_lefthand_distances(vec!["rev3b", "rev2a"], NULL);
2215 assert_eq!(d.get(&"rev2a"), Some(&2));
2216 assert_eq!(d.get(&"rev3b"), Some(&3));
2217 }
2218
2219 #[test]
2220 fn test_get_child_map_ancestry_1() {
2221 let g = ancestry_1();
2222 let cm = g.get_child_map(vec!["rev4", "rev3", "rev2a", "rev2b"]);
2223 assert_eq!(cm.get(&"rev1"), Some(&vec!["rev2a", "rev2b"]));
2224 assert_eq!(cm.get(&"rev2a"), Some(&vec!["rev3"]));
2225 assert_eq!(cm.get(&"rev2b"), Some(&vec!["rev4"]));
2226 assert_eq!(cm.get(&"rev3"), Some(&vec!["rev4"]));
2227 }
2228 }