| 1 | //! KnownGraph: graph algorithms that assume the full ancestry is already loaded. |
| 2 | //! |
| 3 | //! Ported from `vcsgraph/known_graph.py`. |
| 4 | |
| 5 | use crate::tsort::MergeSorter; |
| 6 | use crate::{Error, RevnoVec}; |
| 7 | use rustc_hash::{FxHashMap, FxHashSet}; |
| 8 | use std::cmp::Reverse; |
| 9 | use std::collections::{BinaryHeap, HashMap, VecDeque}; |
| 10 | use std::hash::Hash; |
| 11 | |
| 12 | /// A key that may either be a real node or the synthetic "origin" sentinel |
| 13 | /// (equivalent to `NULL_REVISION` in the Python implementation). |
| 14 | /// |
| 15 | /// Only used by [`KnownGraph::heads`], which has special semantics for the |
| 16 | /// origin: it is only considered a head when it is the sole candidate. |
| 17 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 18 | pub enum Key<K> { |
| 19 | Origin, |
| 20 | Node(K), |
| 21 | } |
| 22 | |
| 23 | #[derive(Debug, Clone)] |
| 24 | struct KnownGraphNode<K> { |
| 25 | parent_keys: Option<Vec<K>>, |
| 26 | child_keys: Vec<K>, |
| 27 | gdfo: Option<u64>, |
| 28 | } |
| 29 | |
| 30 | /// Produce a Vec of `items` ordered by hash of each element. Used as a stable |
| 31 | /// (within one process) cache key for unordered sets when `K: Ord` is not |
| 32 | /// required. |
| 33 | fn sort_by_hash<K: Hash, I: IntoIterator<Item = K>>(items: I) -> Vec<K> { |
| 34 | use std::collections::hash_map::DefaultHasher; |
| 35 | use std::hash::Hasher; |
| 36 | let hash_of = |k: &K| { |
| 37 | let mut h = DefaultHasher::new(); |
| 38 | k.hash(&mut h); |
| 39 | h.finish() |
| 40 | }; |
| 41 | let mut v: Vec<K> = items.into_iter().collect(); |
| 42 | v.sort_by_key(hash_of); |
| 43 | v |
| 44 | } |
| 45 | |
| 46 | impl<K> KnownGraphNode<K> { |
| 47 | fn new(parent_keys: Option<Vec<K>>) -> Self { |
| 48 | KnownGraphNode { |
| 49 | parent_keys, |
| 50 | child_keys: Vec::new(), |
| 51 | gdfo: None, |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | fn is_ghost(&self) -> bool { |
| 56 | self.parent_keys.is_none() |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// Information about a node in a merge-sorted graph. |
| 61 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 62 | pub struct MergeSortNode<K> { |
| 63 | pub key: K, |
| 64 | pub merge_depth: usize, |
| 65 | pub revno: RevnoVec, |
| 66 | pub end_of_merge: bool, |
| 67 | } |
| 68 | |
| 69 | /// A graph where the full ancestry is already known. |
| 70 | /// |
| 71 | /// Supports gdfo-based queries like [`heads`](Self::heads), plus various |
| 72 | /// topological orderings. |
| 73 | #[derive(Debug, Clone)] |
| 74 | pub struct KnownGraph<K: Hash + Eq + Clone> { |
| 75 | nodes: FxHashMap<K, KnownGraphNode<K>>, |
| 76 | known_heads: FxHashMap<Vec<K>, FxHashSet<K>>, |
| 77 | do_cache: bool, |
| 78 | } |
| 79 | |
| 80 | impl<K: Hash + Eq + Clone> KnownGraph<K> { |
| 81 | /// Build a new KnownGraph from a parent map. |
| 82 | pub fn new<I>(parent_map: I, do_cache: bool) -> Self |
| 83 | where |
| 84 | I: IntoIterator<Item = (K, Vec<K>)>, |
| 85 | { |
| 86 | let iter = parent_map.into_iter(); |
| 87 | // Use the lower bound of size_hint to pre-allocate when the caller |
| 88 | // passes a sized iterator (HashMap, Vec, etc). Ghosts will grow the |
| 89 | // map a little beyond this. |
| 90 | let cap = iter.size_hint().0; |
| 91 | let mut g = KnownGraph { |
| 92 | nodes: HashMap::with_capacity_and_hasher(cap, Default::default()), |
| 93 | known_heads: FxHashMap::default(), |
| 94 | do_cache, |
| 95 | }; |
| 96 | g.initialize_nodes(iter); |
| 97 | g.find_gdfo(); |
| 98 | g |
| 99 | } |
| 100 | |
| 101 | fn initialize_nodes<I>(&mut self, parent_map: I) |
| 102 | where |
| 103 | I: IntoIterator<Item = (K, Vec<K>)>, |
| 104 | { |
| 105 | for (key, parent_keys) in parent_map { |
| 106 | // Ensure all parent nodes exist and record the reverse edge. |
| 107 | for parent_key in &parent_keys { |
| 108 | self.nodes |
| 109 | .entry(parent_key.clone()) |
| 110 | .or_insert_with(|| KnownGraphNode::new(None)) |
| 111 | .child_keys |
| 112 | .push(key.clone()); |
| 113 | } |
| 114 | // Insert or update the node itself. |
| 115 | let node = self |
| 116 | .nodes |
| 117 | .entry(key) |
| 118 | .or_insert_with(|| KnownGraphNode::new(None)); |
| 119 | node.parent_keys = Some(parent_keys); |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | fn find_tails(&self) -> Vec<K> { |
| 124 | // A "tail" has no parents — either a real root (Some(empty)) or a |
| 125 | // ghost (None). Both kinds are treated as gdfo=1 starting points, |
| 126 | // matching the Python `not node.parent_keys` check. |
| 127 | self.nodes |
| 128 | .iter() |
| 129 | .filter_map(|(k, n)| match &n.parent_keys { |
| 130 | Some(p) if p.is_empty() => Some(k.clone()), |
| 131 | None => Some(k.clone()), |
| 132 | _ => None, |
| 133 | }) |
| 134 | .collect() |
| 135 | } |
| 136 | |
| 137 | fn find_tips(&self) -> Vec<K> { |
| 138 | self.nodes |
| 139 | .iter() |
| 140 | .filter_map(|(k, n)| { |
| 141 | if n.child_keys.is_empty() { |
| 142 | Some(k.clone()) |
| 143 | } else { |
| 144 | None |
| 145 | } |
| 146 | }) |
| 147 | .collect() |
| 148 | } |
| 149 | |
| 150 | fn find_gdfo(&mut self) { |
| 151 | let mut known_parent_gdfos: FxHashMap<K, usize> = FxHashMap::default(); |
| 152 | let mut pending: Vec<K> = Vec::new(); |
| 153 | |
| 154 | for key in self.find_tails() { |
| 155 | self.nodes.get_mut(&key).unwrap().gdfo = Some(1); |
| 156 | pending.push(key); |
| 157 | } |
| 158 | |
| 159 | while let Some(node_key) = pending.pop() { |
| 160 | let node_gdfo = self.nodes[&node_key].gdfo.unwrap(); |
| 161 | let child_keys = self.nodes[&node_key].child_keys.clone(); |
| 162 | for child_key in child_keys { |
| 163 | let (known_gdfo, present) = match known_parent_gdfos.get(&child_key) { |
| 164 | Some(v) => (*v + 1, true), |
| 165 | None => (1, false), |
| 166 | }; |
| 167 | let child = self.nodes.get_mut(&child_key).unwrap(); |
| 168 | let new_gdfo = node_gdfo + 1; |
| 169 | if child.gdfo.is_none_or(|g| new_gdfo > g) { |
| 170 | child.gdfo = Some(new_gdfo); |
| 171 | } |
| 172 | let parent_len = child.parent_keys.as_ref().map(|p| p.len()).unwrap_or(0); |
| 173 | if known_gdfo == parent_len { |
| 174 | pending.push(child_key.clone()); |
| 175 | if present { |
| 176 | known_parent_gdfos.remove(&child_key); |
| 177 | } |
| 178 | } else { |
| 179 | known_parent_gdfos.insert(child_key, known_gdfo); |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | /// Return the parent keys for `key`. Returns `None` if `key` is a ghost, |
| 186 | /// and an error-equivalent `None` lookup via `contains_key` otherwise. |
| 187 | /// |
| 188 | /// Matches the Python semantics: `None` means ghost, missing key would |
| 189 | /// raise `KeyError` in Python — here the caller should check |
| 190 | /// [`contains`](Self::contains) if disambiguation is needed. |
| 191 | pub fn get_parent_keys(&self, key: &K) -> Option<&[K]> { |
| 192 | self.nodes.get(key)?.parent_keys.as_deref() |
| 193 | } |
| 194 | |
| 195 | /// Return the child keys for `key`. Returns an empty slice for tips. |
| 196 | pub fn get_child_keys(&self, key: &K) -> Option<&[K]> { |
| 197 | self.nodes.get(key).map(|n| n.child_keys.as_slice()) |
| 198 | } |
| 199 | |
| 200 | /// Return whether `key` is present in the graph at all (including ghosts). |
| 201 | pub fn contains(&self, key: &K) -> bool { |
| 202 | self.nodes.contains_key(key) |
| 203 | } |
| 204 | |
| 205 | /// Return the number of nodes in the graph (including ghosts). |
| 206 | pub fn len(&self) -> usize { |
| 207 | self.nodes.len() |
| 208 | } |
| 209 | |
| 210 | /// Return whether the graph is empty. |
| 211 | pub fn is_empty(&self) -> bool { |
| 212 | self.nodes.is_empty() |
| 213 | } |
| 214 | |
| 215 | /// Iterate over all node keys in the graph (including ghosts). |
| 216 | pub fn keys(&self) -> impl Iterator<Item = &K> { |
| 217 | self.nodes.keys() |
| 218 | } |
| 219 | |
| 220 | /// Return the gdfo (greatest distance from origin) of `key`, if known. |
| 221 | pub fn gdfo(&self, key: &K) -> Option<u64> { |
| 222 | self.nodes.get(key).and_then(|n| n.gdfo) |
| 223 | } |
| 224 | |
| 225 | /// Add a new node to the graph, possibly filling in a ghost. |
| 226 | pub fn add_node(&mut self, key: K, parent_keys: Vec<K>) -> Result<(), Error<K>> { |
| 227 | // Validate against existing state, then ensure the node exists with |
| 228 | // its parents recorded. We hold off on inserting parents into the |
| 229 | // graph until after this match, so the borrow of `existing` ends. |
| 230 | match self.nodes.get_mut(&key) { |
| 231 | Some(existing) => match &existing.parent_keys { |
| 232 | Some(existing_parents) if existing_parents == &parent_keys => return Ok(()), |
| 233 | Some(existing_parents) => { |
| 234 | return Err(Error::ParentMismatch { |
| 235 | expected: existing_parents.clone(), |
| 236 | actual: parent_keys, |
| 237 | key, |
| 238 | }); |
| 239 | } |
| 240 | None => { |
| 241 | // Filling in a ghost: the heads cache is no longer |
| 242 | // trustworthy. |
| 243 | existing.parent_keys = Some(parent_keys.clone()); |
| 244 | self.known_heads.clear(); |
| 245 | } |
| 246 | }, |
| 247 | None => { |
| 248 | self.nodes |
| 249 | .insert(key.clone(), KnownGraphNode::new(Some(parent_keys.clone()))); |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | let mut parent_gdfo: u64 = 0; |
| 254 | for parent_key in &parent_keys { |
| 255 | let parent_node = self.nodes.entry(parent_key.clone()).or_insert_with(|| { |
| 256 | let mut n = KnownGraphNode::new(None); |
| 257 | // Ghosts and roots have gdfo 1. |
| 258 | n.gdfo = Some(1); |
| 259 | n |
| 260 | }); |
| 261 | if let Some(g) = parent_node.gdfo { |
| 262 | parent_gdfo = parent_gdfo.max(g); |
| 263 | } |
| 264 | parent_node.child_keys.push(key.clone()); |
| 265 | } |
| 266 | self.nodes.get_mut(&key).unwrap().gdfo = Some(parent_gdfo + 1); |
| 267 | |
| 268 | // Propagate gdfo updates to descendants (BFS). |
| 269 | let mut pending: VecDeque<K> = VecDeque::new(); |
| 270 | pending.push_back(key); |
| 271 | while let Some(node_key) = pending.pop_front() { |
| 272 | let next_gdfo = self.nodes[&node_key].gdfo.unwrap() + 1; |
| 273 | let child_keys = self.nodes[&node_key].child_keys.clone(); |
| 274 | for child_key in child_keys { |
| 275 | let child = self.nodes.get_mut(&child_key).unwrap(); |
| 276 | if child.gdfo.is_none_or(|g| g < next_gdfo) { |
| 277 | child.gdfo = Some(next_gdfo); |
| 278 | pending.push_back(child_key); |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | Ok(()) |
| 283 | } |
| 284 | |
| 285 | /// Return the heads from amongst `keys`. |
| 286 | /// |
| 287 | /// Any key reachable from another key is filtered out. This method is |
| 288 | /// sentinel-free on the core; the caller handles origin semantics by |
| 289 | /// wrapping `K` in [`Key<K>`] and calling [`heads_with_origin`]. |
| 290 | /// |
| 291 | /// All keys in `candidates` must be present in the graph (not ghosts). |
| 292 | pub fn heads<I>(&mut self, candidates: I) -> FxHashSet<K> |
| 293 | where |
| 294 | I: IntoIterator<Item = K>, |
| 295 | { |
| 296 | let candidates: FxHashSet<K> = candidates.into_iter().collect(); |
| 297 | if candidates.len() < 2 { |
| 298 | return candidates; |
| 299 | } |
| 300 | |
| 301 | // Build a process-stable cache key by sorting candidates by their |
| 302 | // hash. Hash collisions in the comparator just produce non-unique |
| 303 | // orderings; the resulting Vec still uniquely identifies the input |
| 304 | // set within a single process (different sets differ in length or |
| 305 | // contents). We can't use BTreeSet here because K is not required |
| 306 | // to be Ord. |
| 307 | let heads_cache_key = sort_by_hash(candidates.iter().cloned()); |
| 308 | if let Some(cached) = self.known_heads.get(&heads_cache_key) { |
| 309 | return cached.clone(); |
| 310 | } |
| 311 | |
| 312 | let mut seen: FxHashSet<K> = FxHashSet::default(); |
| 313 | let mut pending: Vec<K> = Vec::new(); |
| 314 | let mut min_gdfo: Option<u64> = None; |
| 315 | for key in &candidates { |
| 316 | let node = &self.nodes[key]; |
| 317 | if let Some(parents) = &node.parent_keys { |
| 318 | pending.extend(parents.iter().cloned()); |
| 319 | } |
| 320 | if let Some(g) = node.gdfo { |
| 321 | min_gdfo = Some(min_gdfo.map_or(g, |m| m.min(g))); |
| 322 | } |
| 323 | } |
| 324 | let min_gdfo = min_gdfo.unwrap_or(0); |
| 325 | while let Some(node_key) = pending.pop() { |
| 326 | if !seen.insert(node_key.clone()) { |
| 327 | continue; |
| 328 | } |
| 329 | let node = &self.nodes[&node_key]; |
| 330 | if node.gdfo.is_some_and(|g| g <= min_gdfo) { |
| 331 | continue; |
| 332 | } |
| 333 | if let Some(parents) = &node.parent_keys { |
| 334 | pending.extend(parents.iter().cloned()); |
| 335 | } |
| 336 | } |
| 337 | let heads: FxHashSet<K> = candidates.difference(&seen).cloned().collect(); |
| 338 | if self.do_cache { |
| 339 | self.known_heads.insert(heads_cache_key, heads.clone()); |
| 340 | } |
| 341 | heads |
| 342 | } |
| 343 | |
| 344 | /// Return the nodes of the graph in topological order (parents first). |
| 345 | /// |
| 346 | /// Errors with [`Error::Cycle`] if the graph is not fully connected via |
| 347 | /// gdfo (i.e. contains a cycle). |
| 348 | pub fn topo_sort(&self) -> Result<Vec<K>, Error<K>> { |
| 349 | let unreachable: Vec<K> = self |
| 350 | .nodes |
| 351 | .iter() |
| 352 | .filter(|(_, n)| n.gdfo.is_none()) |
| 353 | .map(|(k, _)| k.clone()) |
| 354 | .collect(); |
| 355 | if !unreachable.is_empty() { |
| 356 | return Err(Error::Cycle(unreachable)); |
| 357 | } |
| 358 | let mut pending = self.find_tails(); |
| 359 | let mut num_seen_parents: FxHashMap<K, usize> = |
| 360 | self.nodes.keys().map(|k| (k.clone(), 0)).collect(); |
| 361 | let mut topo_order: Vec<K> = Vec::with_capacity(self.nodes.len()); |
| 362 | while let Some(node_key) = pending.pop() { |
| 363 | let node = &self.nodes[&node_key]; |
| 364 | // Skip ghosts in the output (matches Python behavior). |
| 365 | if !node.is_ghost() { |
| 366 | topo_order.push(node_key.clone()); |
| 367 | } |
| 368 | let child_keys = node.child_keys.clone(); |
| 369 | for child_key in child_keys { |
| 370 | let child = &self.nodes[&child_key]; |
| 371 | let seen_parents = num_seen_parents[&child_key] + 1; |
| 372 | let parent_len = child.parent_keys.as_ref().map(|p| p.len()).unwrap_or(0); |
| 373 | if seen_parents == parent_len { |
| 374 | pending.push(child_key.clone()); |
| 375 | num_seen_parents.remove(&child_key); |
| 376 | } else { |
| 377 | num_seen_parents.insert(child_key, seen_parents); |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | Ok(topo_order) |
| 382 | } |
| 383 | |
| 384 | /// Return a reverse topological ordering grouped by prefix. |
| 385 | /// |
| 386 | /// `prefix_of` maps each key to its prefix bucket. Within each bucket the |
| 387 | /// ordering is lexicographic (by `K: Ord`), which mirrors Python's use of |
| 388 | /// tuple/bytes ordering there. Ghost nodes are skipped in the output. |
| 389 | pub fn gc_sort<P, PFX>(&self, mut prefix_of: P) -> Vec<K> |
| 390 | where |
| 391 | K: Ord, |
| 392 | P: FnMut(&K) -> PFX, |
| 393 | PFX: Ord + Hash, |
| 394 | { |
| 395 | let mut prefix_tips: FxHashMap<PFX, Vec<K>> = FxHashMap::default(); |
| 396 | for key in self.find_tips() { |
| 397 | prefix_tips.entry(prefix_of(&key)).or_default().push(key); |
| 398 | } |
| 399 | let mut num_seen_children: FxHashMap<K, usize> = |
| 400 | self.nodes.keys().map(|k| (k.clone(), 0)).collect(); |
| 401 | |
| 402 | let mut prefix_list: Vec<(PFX, Vec<K>)> = prefix_tips.into_iter().collect(); |
| 403 | prefix_list.sort_by(|a, b| a.0.cmp(&b.0)); |
| 404 | |
| 405 | let mut result: Vec<K> = Vec::with_capacity(self.nodes.len()); |
| 406 | for (_prefix, tips) in prefix_list { |
| 407 | // A min-heap (via Reverse) keeps the next-smallest key at the top |
| 408 | // in O(log n), instead of re-sorting the pending vector after |
| 409 | // every parent insertion. |
| 410 | let mut pending: BinaryHeap<Reverse<K>> = tips.into_iter().map(Reverse).collect(); |
| 411 | while let Some(Reverse(node_key)) = pending.pop() { |
| 412 | let node = &self.nodes[&node_key]; |
| 413 | if node.is_ghost() { |
| 414 | continue; |
| 415 | } |
| 416 | let parent_keys = node.parent_keys.as_deref().unwrap_or(&[]); |
| 417 | for parent_key in parent_keys { |
| 418 | let parent_node = &self.nodes[parent_key]; |
| 419 | let seen_children = num_seen_children[parent_key] + 1; |
| 420 | if seen_children == parent_node.child_keys.len() { |
| 421 | pending.push(Reverse(parent_key.clone())); |
| 422 | num_seen_children.remove(parent_key); |
| 423 | } else { |
| 424 | num_seen_children.insert(parent_key.clone(), seen_children); |
| 425 | } |
| 426 | } |
| 427 | result.push(node_key); |
| 428 | } |
| 429 | } |
| 430 | result |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | impl<K: Hash + Eq + Clone + std::fmt::Debug> KnownGraph<K> { |
| 435 | /// Merge-sort the graph starting from `tip_key`. |
| 436 | /// |
| 437 | /// Requires `K: Debug` because the underlying [`MergeSorter`] does. |
| 438 | pub fn merge_sort(&self, tip_key: K) -> Result<Vec<MergeSortNode<K>>, Error<K>> { |
| 439 | let as_parent_map: HashMap<K, Vec<K>> = self |
| 440 | .nodes |
| 441 | .iter() |
| 442 | .filter_map(|(k, n)| n.parent_keys.as_ref().map(|p| (k.clone(), p.clone()))) |
| 443 | .collect(); |
| 444 | MergeSorter::new(as_parent_map, Some(tip_key), None, true) |
| 445 | .map(|item| { |
| 446 | item.map(|(_, key, merge_depth, revno, end_of_merge)| MergeSortNode { |
| 447 | key, |
| 448 | merge_depth, |
| 449 | revno: revno.unwrap_or_default(), |
| 450 | end_of_merge, |
| 451 | }) |
| 452 | }) |
| 453 | .collect() |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | impl<K: Hash + Eq + Clone> KnownGraph<Key<K>> { |
| 458 | /// `heads()` variant that implements the Python `NULL_REVISION` filter: |
| 459 | /// [`Key::Origin`] is only a head if it is the sole candidate. |
| 460 | pub fn heads_with_origin<I>(&mut self, candidates: I) -> FxHashSet<Key<K>> |
| 461 | where |
| 462 | I: IntoIterator<Item = Key<K>>, |
| 463 | { |
| 464 | let mut candidates: FxHashSet<Key<K>> = candidates.into_iter().collect(); |
| 465 | if candidates.contains(&Key::Origin) { |
| 466 | candidates.remove(&Key::Origin); |
| 467 | if candidates.is_empty() { |
| 468 | let mut r = FxHashSet::default(); |
| 469 | r.insert(Key::Origin); |
| 470 | return r; |
| 471 | } |
| 472 | } |
| 473 | self.heads(candidates) |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | #[cfg(test)] |
| 478 | mod tests { |
| 479 | use super::*; |
| 480 | |
| 481 | fn make(edges: &[(&'static str, &[&'static str])]) -> KnownGraph<&'static str> { |
| 482 | let pm = edges.iter().map(|(k, ps)| (*k, ps.to_vec())); |
| 483 | KnownGraph::new(pm, true) |
| 484 | } |
| 485 | |
| 486 | #[test] |
| 487 | fn gdfo_linear() { |
| 488 | // a -> b -> c |
| 489 | let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["b"])]); |
| 490 | assert_eq!(g.gdfo(&"a"), Some(1)); |
| 491 | assert_eq!(g.gdfo(&"b"), Some(2)); |
| 492 | assert_eq!(g.gdfo(&"c"), Some(3)); |
| 493 | } |
| 494 | |
| 495 | #[test] |
| 496 | fn gdfo_diamond() { |
| 497 | // a |
| 498 | // / \ |
| 499 | // b c |
| 500 | // \ / |
| 501 | // d |
| 502 | let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]); |
| 503 | assert_eq!(g.gdfo(&"a"), Some(1)); |
| 504 | assert_eq!(g.gdfo(&"b"), Some(2)); |
| 505 | assert_eq!(g.gdfo(&"c"), Some(2)); |
| 506 | assert_eq!(g.gdfo(&"d"), Some(3)); |
| 507 | } |
| 508 | |
| 509 | #[test] |
| 510 | fn heads_trivial() { |
| 511 | let mut g = make(&[("a", &[]), ("b", &["a"])]); |
| 512 | let h = g.heads(vec!["a", "b"]); |
| 513 | let expected: FxHashSet<_> = ["b"].iter().copied().collect(); |
| 514 | assert_eq!(h, expected); |
| 515 | } |
| 516 | |
| 517 | #[test] |
| 518 | fn heads_diamond() { |
| 519 | let mut g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]); |
| 520 | let h = g.heads(vec!["b", "c"]); |
| 521 | let expected: FxHashSet<_> = ["b", "c"].iter().copied().collect(); |
| 522 | assert_eq!(h, expected); |
| 523 | let h2 = g.heads(vec!["a", "d"]); |
| 524 | let expected2: FxHashSet<_> = ["d"].iter().copied().collect(); |
| 525 | assert_eq!(h2, expected2); |
| 526 | } |
| 527 | |
| 528 | #[test] |
| 529 | fn heads_with_origin_only() { |
| 530 | let mut g: KnownGraph<Key<&'static str>> = |
| 531 | KnownGraph::new(vec![(Key::Node("a"), vec![Key::Origin])], true); |
| 532 | let h = g.heads_with_origin(vec![Key::Origin]); |
| 533 | assert_eq!(h.len(), 1); |
| 534 | assert!(h.contains(&Key::Origin)); |
| 535 | } |
| 536 | |
| 537 | #[test] |
| 538 | fn heads_with_origin_ignored() { |
| 539 | let mut g: KnownGraph<Key<&'static str>> = |
| 540 | KnownGraph::new(vec![(Key::Node("a"), vec![Key::Origin])], true); |
| 541 | let h = g.heads_with_origin(vec![Key::Origin, Key::Node("a")]); |
| 542 | let expected: FxHashSet<_> = [Key::Node("a")].iter().cloned().collect(); |
| 543 | assert_eq!(h, expected); |
| 544 | } |
| 545 | |
| 546 | #[test] |
| 547 | fn topo_sort_basic() { |
| 548 | let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["a"]), ("d", &["b", "c"])]); |
| 549 | let order = g.topo_sort().unwrap(); |
| 550 | // a must come before b, c; b, c must come before d. |
| 551 | let pos = |x: &&str| order.iter().position(|n| n == x).unwrap(); |
| 552 | assert!(pos(&"a") < pos(&"b")); |
| 553 | assert!(pos(&"a") < pos(&"c")); |
| 554 | assert!(pos(&"b") < pos(&"d")); |
| 555 | assert!(pos(&"c") < pos(&"d")); |
| 556 | } |
| 557 | |
| 558 | #[test] |
| 559 | fn add_node_fills_ghost() { |
| 560 | // Start with b having ghost parent a. |
| 561 | let mut g = make(&[("b", &["a"])]); |
| 562 | // a is a ghost: present with None parents. |
| 563 | assert!(g.get_parent_keys(&"a").is_none()); |
| 564 | g.add_node("a", vec![]).unwrap(); |
| 565 | assert_eq!(g.get_parent_keys(&"a"), Some(&[][..])); |
| 566 | assert_eq!(g.gdfo(&"a"), Some(1)); |
| 567 | assert_eq!(g.gdfo(&"b"), Some(2)); |
| 568 | } |
| 569 | |
| 570 | #[test] |
| 571 | fn add_node_duplicate_ok() { |
| 572 | let mut g = make(&[("a", &[]), ("b", &["a"])]); |
| 573 | g.add_node("b", vec!["a"]).unwrap(); |
| 574 | } |
| 575 | |
| 576 | #[test] |
| 577 | fn add_node_mismatch_errors() { |
| 578 | let mut g = make(&[("a", &[]), ("b", &["a"])]); |
| 579 | let r = g.add_node("b", vec![]); |
| 580 | assert!(matches!(r, Err(Error::ParentMismatch { .. }))); |
| 581 | } |
| 582 | |
| 583 | #[test] |
| 584 | fn merge_sort_simple() { |
| 585 | // a -> b -> c, linear |
| 586 | let g = make(&[("a", &[]), ("b", &["a"]), ("c", &["b"])]); |
| 587 | let ms = g.merge_sort("c").unwrap(); |
| 588 | let keys: Vec<_> = ms.iter().map(|n| n.key).collect(); |
| 589 | assert_eq!(keys, vec!["c", "b", "a"]); |
| 590 | } |
| 591 | |
| 592 | /// Shared fixtures mirrored from `vcsgraph/tests/test_graph.py`. |
| 593 | const NULL: &str = "null:"; |
| 594 | |
| 595 | fn ancestry_1() -> KnownGraph<&'static str> { |
| 596 | make(&[ |
| 597 | ("rev1", &[NULL]), |
| 598 | ("rev2a", &["rev1"]), |
| 599 | ("rev2b", &["rev1"]), |
| 600 | ("rev3", &["rev2a"]), |
| 601 | ("rev4", &["rev3", "rev2b"]), |
| 602 | ]) |
| 603 | } |
| 604 | |
| 605 | fn feature_branch() -> KnownGraph<&'static str> { |
| 606 | make(&[ |
| 607 | ("rev1", &[NULL]), |
| 608 | ("rev2b", &["rev1"]), |
| 609 | ("rev3b", &["rev2b"]), |
| 610 | ]) |
| 611 | } |
| 612 | |
| 613 | fn extended_history_shortcut() -> KnownGraph<&'static str> { |
| 614 | make(&[ |
| 615 | ("a", &[NULL]), |
| 616 | ("b", &["a"]), |
| 617 | ("c", &["b"]), |
| 618 | ("d", &["c"]), |
| 619 | ("e", &["d"]), |
| 620 | ("f", &["a", "d"]), |
| 621 | ]) |
| 622 | } |
| 623 | |
| 624 | fn with_ghost() -> KnownGraph<&'static str> { |
| 625 | // A graph with a ghost at `g`. |
| 626 | make(&[ |
| 627 | ("a", &["b"]), |
| 628 | ("c", &["b", "d"]), |
| 629 | ("b", &["e"]), |
| 630 | ("d", &["e", "g"]), |
| 631 | ("e", &["f"]), |
| 632 | ("f", &[NULL]), |
| 633 | (NULL, &[]), |
| 634 | ]) |
| 635 | } |
| 636 | |
| 637 | fn criss_cross() -> KnownGraph<&'static str> { |
| 638 | make(&[ |
| 639 | ("rev1", &[NULL]), |
| 640 | ("rev2a", &["rev1"]), |
| 641 | ("rev2b", &["rev1"]), |
| 642 | ("rev3a", &["rev2a", "rev2b"]), |
| 643 | ("rev3b", &["rev2b", "rev2a"]), |
| 644 | ]) |
| 645 | } |
| 646 | |
| 647 | fn history_shortcut() -> KnownGraph<&'static str> { |
| 648 | make(&[ |
| 649 | ("rev1", &[NULL]), |
| 650 | ("rev2a", &["rev1"]), |
| 651 | ("rev2b", &["rev1"]), |
| 652 | ("rev2c", &["rev1"]), |
| 653 | ("rev3a", &["rev2a", "rev2b"]), |
| 654 | ("rev3b", &["rev2b", "rev2c"]), |
| 655 | ]) |
| 656 | } |
| 657 | |
| 658 | /// Equivalent of Python's `alt_merge` fixture. |
| 659 | fn alt_merge() -> KnownGraph<&'static str> { |
| 660 | make(&[("a", &[]), ("b", &["a"]), ("c", &["b"]), ("d", &["a", "c"])]) |
| 661 | } |
| 662 | |
| 663 | fn set<const N: usize>(xs: [&'static str; N]) -> FxHashSet<&'static str> { |
| 664 | xs.into_iter().collect() |
| 665 | } |
| 666 | |
| 667 | #[test] |
| 668 | fn test_children_ancestry1() { |
| 669 | let g = ancestry_1(); |
| 670 | assert_eq!(g.get_child_keys(&NULL), Some(&["rev1"][..])); |
| 671 | let mut rev1_children: Vec<_> = g.get_child_keys(&"rev1").unwrap().to_vec(); |
| 672 | rev1_children.sort(); |
| 673 | assert_eq!(rev1_children, vec!["rev2a", "rev2b"]); |
| 674 | assert_eq!(g.get_child_keys(&"rev2a"), Some(&["rev3"][..])); |
| 675 | assert_eq!(g.get_child_keys(&"rev3"), Some(&["rev4"][..])); |
| 676 | assert_eq!(g.get_child_keys(&"rev2b"), Some(&["rev4"][..])); |
| 677 | assert_eq!(g.get_child_keys(&"not_in_graph"), None); |
| 678 | } |
| 679 | |
| 680 | #[test] |
| 681 | fn test_parent_ancestry1() { |
| 682 | let g = ancestry_1(); |
| 683 | assert_eq!(g.get_parent_keys(&"rev1"), Some(&[NULL][..])); |
| 684 | assert_eq!(g.get_parent_keys(&"rev2a"), Some(&["rev1"][..])); |
| 685 | assert_eq!(g.get_parent_keys(&"rev2b"), Some(&["rev1"][..])); |
| 686 | assert_eq!(g.get_parent_keys(&"rev3"), Some(&["rev2a"][..])); |
| 687 | let mut rev4_parents: Vec<_> = g.get_parent_keys(&"rev4").unwrap().to_vec(); |
| 688 | rev4_parents.sort(); |
| 689 | assert_eq!(rev4_parents, vec!["rev2b", "rev3"]); |
| 690 | } |
| 691 | |
| 692 | #[test] |
| 693 | fn test_parent_with_ghost() { |
| 694 | // In `with_ghost`, "g" is a ghost: present as a parent of `d` but |
| 695 | // has no parent_keys of its own. |
| 696 | let g = with_ghost(); |
| 697 | assert_eq!(g.get_parent_keys(&"g"), None); |
| 698 | } |
| 699 | |
| 700 | #[test] |
| 701 | fn test_gdfo_ancestry_1() { |
| 702 | let g = ancestry_1(); |
| 703 | assert_eq!(g.gdfo(&"rev1"), Some(2)); |
| 704 | assert_eq!(g.gdfo(&"rev2a"), Some(3)); |
| 705 | assert_eq!(g.gdfo(&"rev2b"), Some(3)); |
| 706 | assert_eq!(g.gdfo(&"rev3"), Some(4)); |
| 707 | assert_eq!(g.gdfo(&"rev4"), Some(5)); |
| 708 | } |
| 709 | |
| 710 | #[test] |
| 711 | fn test_gdfo_feature_branch() { |
| 712 | let g = feature_branch(); |
| 713 | assert_eq!(g.gdfo(&"rev1"), Some(2)); |
| 714 | assert_eq!(g.gdfo(&"rev2b"), Some(3)); |
| 715 | assert_eq!(g.gdfo(&"rev3b"), Some(4)); |
| 716 | } |
| 717 | |
| 718 | #[test] |
| 719 | fn test_gdfo_extended_history_shortcut() { |
| 720 | let g = extended_history_shortcut(); |
| 721 | assert_eq!(g.gdfo(&"a"), Some(2)); |
| 722 | assert_eq!(g.gdfo(&"b"), Some(3)); |
| 723 | assert_eq!(g.gdfo(&"c"), Some(4)); |
| 724 | assert_eq!(g.gdfo(&"d"), Some(5)); |
| 725 | assert_eq!(g.gdfo(&"e"), Some(6)); |
| 726 | assert_eq!(g.gdfo(&"f"), Some(6)); |
| 727 | } |
| 728 | |
| 729 | #[test] |
| 730 | fn test_gdfo_with_ghost() { |
| 731 | let g = with_ghost(); |
| 732 | assert_eq!(g.gdfo(&"f"), Some(2)); |
| 733 | assert_eq!(g.gdfo(&"e"), Some(3)); |
| 734 | assert_eq!(g.gdfo(&"g"), Some(1)); |
| 735 | assert_eq!(g.gdfo(&"b"), Some(4)); |
| 736 | assert_eq!(g.gdfo(&"d"), Some(4)); |
| 737 | assert_eq!(g.gdfo(&"a"), Some(5)); |
| 738 | assert_eq!(g.gdfo(&"c"), Some(5)); |
| 739 | } |
| 740 | |
| 741 | #[test] |
| 742 | fn test_add_existing_node_noop() { |
| 743 | let mut g = ancestry_1(); |
| 744 | assert_eq!(g.gdfo(&"rev4"), Some(5)); |
| 745 | g.add_node("rev4", vec!["rev3", "rev2b"]).unwrap(); |
| 746 | assert_eq!(g.gdfo(&"rev4"), Some(5)); |
| 747 | } |
| 748 | |
| 749 | #[test] |
| 750 | fn test_add_existing_node_mismatched_parents() { |
| 751 | let mut g = ancestry_1(); |
| 752 | let r = g.add_node("rev4", vec!["rev2b", "rev3"]); |
| 753 | assert!(matches!(r, Err(Error::ParentMismatch { .. }))); |
| 754 | } |
| 755 | |
| 756 | #[test] |
| 757 | fn test_add_node_with_ghost_parent() { |
| 758 | let mut g = ancestry_1(); |
| 759 | g.add_node("rev5", vec!["rev2b", "revGhost"]).unwrap(); |
| 760 | assert_eq!(g.gdfo(&"rev5"), Some(4)); |
| 761 | assert_eq!(g.gdfo(&"revGhost"), Some(1)); |
| 762 | } |
| 763 | |
| 764 | #[test] |
| 765 | fn test_add_new_root() { |
| 766 | let mut g = ancestry_1(); |
| 767 | g.add_node("rev5", vec![]).unwrap(); |
| 768 | assert_eq!(g.gdfo(&"rev5"), Some(1)); |
| 769 | } |
| 770 | |
| 771 | #[test] |
| 772 | fn test_add_with_all_ghost_parents() { |
| 773 | let mut g = ancestry_1(); |
| 774 | g.add_node("rev5", vec!["ghost"]).unwrap(); |
| 775 | assert_eq!(g.gdfo(&"rev5"), Some(2)); |
| 776 | assert_eq!(g.gdfo(&"ghost"), Some(1)); |
| 777 | } |
| 778 | |
| 779 | #[test] |
| 780 | fn test_gdfo_after_add_node() { |
| 781 | let mut g = ancestry_1(); |
| 782 | assert_eq!(g.get_child_keys(&"rev4"), Some(&[][..])); |
| 783 | g.add_node("rev5", vec!["rev4"]).unwrap(); |
| 784 | assert_eq!(g.get_parent_keys(&"rev5"), Some(&["rev4"][..])); |
| 785 | assert_eq!(g.get_child_keys(&"rev4"), Some(&["rev5"][..])); |
| 786 | assert_eq!(g.get_child_keys(&"rev5"), Some(&[][..])); |
| 787 | assert_eq!(g.gdfo(&"rev5"), Some(6)); |
| 788 | g.add_node("rev6", vec!["rev2b"]).unwrap(); |
| 789 | g.add_node("rev7", vec!["rev6"]).unwrap(); |
| 790 | g.add_node("rev8", vec!["rev7", "rev5"]).unwrap(); |
| 791 | assert_eq!(g.gdfo(&"rev5"), Some(6)); |
| 792 | assert_eq!(g.gdfo(&"rev6"), Some(4)); |
| 793 | assert_eq!(g.gdfo(&"rev7"), Some(5)); |
| 794 | assert_eq!(g.gdfo(&"rev8"), Some(7)); |
| 795 | } |
| 796 | |
| 797 | #[test] |
| 798 | fn test_fill_in_ghost() { |
| 799 | // Add a few new roots, then fill in the ghost `g` so the |
| 800 | // children's gdfos get renumbered. |
| 801 | let mut g = with_ghost(); |
| 802 | g.add_node("x", vec![]).unwrap(); |
| 803 | g.add_node("y", vec!["x"]).unwrap(); |
| 804 | g.add_node("z", vec!["y"]).unwrap(); |
| 805 | g.add_node("g", vec!["z"]).unwrap(); |
| 806 | assert_eq!(g.gdfo(&"f"), Some(2)); |
| 807 | assert_eq!(g.gdfo(&"e"), Some(3)); |
| 808 | assert_eq!(g.gdfo(&"x"), Some(1)); |
| 809 | assert_eq!(g.gdfo(&"y"), Some(2)); |
| 810 | assert_eq!(g.gdfo(&"z"), Some(3)); |
| 811 | assert_eq!(g.gdfo(&"g"), Some(4)); |
| 812 | assert_eq!(g.gdfo(&"b"), Some(4)); |
| 813 | assert_eq!(g.gdfo(&"d"), Some(5)); |
| 814 | assert_eq!(g.gdfo(&"a"), Some(5)); |
| 815 | assert_eq!(g.gdfo(&"c"), Some(6)); |
| 816 | } |
| 817 | |
| 818 | /// Rust-side `heads()` is sentinel-free; callers are expected to filter |
| 819 | /// NULL themselves. These tests use the core method directly (not |
| 820 | /// `heads_with_origin`) and only test non-null cases — NULL-filtering |
| 821 | /// semantics are covered by existing `heads_with_origin_*` tests. |
| 822 | #[test] |
| 823 | fn test_heads_one_non_null() { |
| 824 | let mut g = ancestry_1(); |
| 825 | for key in ["rev1", "rev2a", "rev2b", "rev3", "rev4"] { |
| 826 | assert_eq!(g.heads(vec![key]), set([key])); |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | #[test] |
| 831 | fn test_heads_single_from_ancestry_1() { |
| 832 | let mut g = ancestry_1(); |
| 833 | assert_eq!(g.heads(vec!["rev1", "rev2a"]), set(["rev2a"])); |
| 834 | assert_eq!(g.heads(vec!["rev1", "rev2b"]), set(["rev2b"])); |
| 835 | assert_eq!(g.heads(vec!["rev1", "rev3"]), set(["rev3"])); |
| 836 | assert_eq!(g.heads(vec!["rev3", "rev2a"]), set(["rev3"])); |
| 837 | assert_eq!(g.heads(vec!["rev1", "rev4"]), set(["rev4"])); |
| 838 | assert_eq!(g.heads(vec!["rev2a", "rev4"]), set(["rev4"])); |
| 839 | assert_eq!(g.heads(vec!["rev2b", "rev4"]), set(["rev4"])); |
| 840 | assert_eq!(g.heads(vec!["rev3", "rev4"]), set(["rev4"])); |
| 841 | } |
| 842 | |
| 843 | #[test] |
| 844 | fn test_heads_two_heads_from_ancestry_1() { |
| 845 | let mut g = ancestry_1(); |
| 846 | assert_eq!(g.heads(vec!["rev2a", "rev2b"]), set(["rev2a", "rev2b"])); |
| 847 | assert_eq!(g.heads(vec!["rev3", "rev2b"]), set(["rev3", "rev2b"])); |
| 848 | } |
| 849 | |
| 850 | #[test] |
| 851 | fn test_heads_criss_cross_fixture() { |
| 852 | let mut g = criss_cross(); |
| 853 | assert_eq!(g.heads(vec!["rev2a", "rev1"]), set(["rev2a"])); |
| 854 | assert_eq!(g.heads(vec!["rev2b", "rev1"]), set(["rev2b"])); |
| 855 | assert_eq!(g.heads(vec!["rev3a", "rev1"]), set(["rev3a"])); |
| 856 | assert_eq!(g.heads(vec!["rev3b", "rev1"]), set(["rev3b"])); |
| 857 | assert_eq!(g.heads(vec!["rev2a", "rev2b"]), set(["rev2a", "rev2b"])); |
| 858 | assert_eq!(g.heads(vec!["rev3a", "rev2a"]), set(["rev3a"])); |
| 859 | assert_eq!(g.heads(vec!["rev3a", "rev2b"]), set(["rev3a"])); |
| 860 | assert_eq!(g.heads(vec!["rev3a", "rev2a", "rev2b"]), set(["rev3a"])); |
| 861 | assert_eq!(g.heads(vec!["rev3b", "rev2a"]), set(["rev3b"])); |
| 862 | assert_eq!(g.heads(vec!["rev3b", "rev2b"]), set(["rev3b"])); |
| 863 | assert_eq!(g.heads(vec!["rev3b", "rev2a", "rev2b"]), set(["rev3b"])); |
| 864 | assert_eq!(g.heads(vec!["rev3a", "rev3b"]), set(["rev3a", "rev3b"])); |
| 865 | assert_eq!( |
| 866 | g.heads(vec!["rev3a", "rev3b", "rev2a", "rev2b"]), |
| 867 | set(["rev3a", "rev3b"]) |
| 868 | ); |
| 869 | } |
| 870 | |
| 871 | #[test] |
| 872 | fn test_heads_history_shortcut_fixture() { |
| 873 | let mut g = history_shortcut(); |
| 874 | assert_eq!( |
| 875 | g.heads(vec!["rev2a", "rev2b", "rev2c"]), |
| 876 | set(["rev2a", "rev2b", "rev2c"]) |
| 877 | ); |
| 878 | assert_eq!(g.heads(vec!["rev3a", "rev3b"]), set(["rev3a", "rev3b"])); |
| 879 | assert_eq!( |
| 880 | g.heads(vec!["rev2a", "rev3a", "rev3b"]), |
| 881 | set(["rev3a", "rev3b"]) |
| 882 | ); |
| 883 | assert_eq!(g.heads(vec!["rev2a", "rev3b"]), set(["rev2a", "rev3b"])); |
| 884 | assert_eq!(g.heads(vec!["rev2c", "rev3a"]), set(["rev2c", "rev3a"])); |
| 885 | } |
| 886 | |
| 887 | #[test] |
| 888 | fn test_heads_alt_merge() { |
| 889 | let mut g = alt_merge(); |
| 890 | assert_eq!(g.heads(vec!["a", "c"]), set(["c"])); |
| 891 | } |
| 892 | |
| 893 | #[test] |
| 894 | fn test_heads_with_ghost_fixture() { |
| 895 | let mut g = with_ghost(); |
| 896 | assert_eq!(g.heads(vec!["e", "g"]), set(["e", "g"])); |
| 897 | assert_eq!(g.heads(vec!["a", "c"]), set(["a", "c"])); |
| 898 | assert_eq!(g.heads(vec!["a", "g"]), set(["a", "g"])); |
| 899 | assert_eq!(g.heads(vec!["f", "g"]), set(["f", "g"])); |
| 900 | assert_eq!(g.heads(vec!["c", "g"]), set(["c"])); |
| 901 | assert_eq!(g.heads(vec!["c", "b", "d", "g"]), set(["c"])); |
| 902 | assert_eq!(g.heads(vec!["a", "c", "e", "g"]), set(["a", "c"])); |
| 903 | assert_eq!(g.heads(vec!["a", "c", "f"]), set(["a", "c"])); |
| 904 | } |
| 905 | |
| 906 | #[test] |
| 907 | fn test_filling_in_ghosts_resets_head_cache() { |
| 908 | let mut g = with_ghost(); |
| 909 | assert_eq!(g.heads(vec!["e", "g"]), set(["e", "g"])); |
| 910 | // Fill in the ghost so that `g` descends from `e`; the heads |
| 911 | // cache must be invalidated, otherwise the second query would |
| 912 | // return the stale result. |
| 913 | g.add_node("g", vec!["e"]).unwrap(); |
| 914 | assert_eq!(g.heads(vec!["e", "g"]), set(["g"])); |
| 915 | } |
| 916 | |
| 917 | /// Helper: assert that `topo_sort` yields a valid topological order |
| 918 | /// for the given parent map. |
| 919 | fn assert_topo_sort_order(edges: &[(&'static str, &[&'static str])]) { |
| 920 | let pm: FxHashMap<&'static str, Vec<&'static str>> = |
| 921 | edges.iter().map(|(k, ps)| (*k, ps.to_vec())).collect(); |
| 922 | let g = KnownGraph::new(pm.clone(), true); |
| 923 | let result = g.topo_sort().unwrap(); |
| 924 | assert_eq!(result.len(), pm.len()); |
| 925 | let idx: FxHashMap<&str, usize> = result.iter().enumerate().map(|(i, k)| (*k, i)).collect(); |
| 926 | for (node, parents) in &pm { |
| 927 | for parent in parents { |
| 928 | if !pm.contains_key(parent) { |
| 929 | continue; // ghost |
| 930 | } |
| 931 | assert!( |
| 932 | idx[node] > idx[parent], |
| 933 | "parent {parent} must come before child {node}: {:?}", |
| 934 | result |
| 935 | ); |
| 936 | } |
| 937 | } |
| 938 | } |
| 939 | |
| 940 | #[test] |
| 941 | fn test_topo_sort_empty() { |
| 942 | assert_topo_sort_order(&[]); |
| 943 | } |
| 944 | |
| 945 | #[test] |
| 946 | fn test_topo_sort_easy() { |
| 947 | assert_topo_sort_order(&[("a", &[])]); |
| 948 | } |
| 949 | |
| 950 | #[test] |
| 951 | fn test_topo_sort_cycle_simple() { |
| 952 | let pm = [("a", vec!["b"]), ("b", vec!["a"])]; |
| 953 | let g = KnownGraph::new(pm, true); |
| 954 | assert!(matches!(g.topo_sort(), Err(Error::Cycle(_)))); |
| 955 | } |
| 956 | |
| 957 | #[test] |
| 958 | fn test_topo_sort_cycle_long() { |
| 959 | let pm = [("a", vec!["b"]), ("b", vec!["c"]), ("c", vec!["a"])]; |
| 960 | let g = KnownGraph::new(pm, true); |
| 961 | assert!(matches!(g.topo_sort(), Err(Error::Cycle(_)))); |
| 962 | } |
| 963 | |
| 964 | #[test] |
| 965 | fn test_topo_sort_cycle_with_tail() { |
| 966 | let pm = [ |
| 967 | ("a", vec!["b"]), |
| 968 | ("b", vec!["c"]), |
| 969 | ("c", vec!["d", "e"]), |
| 970 | ("d", vec!["a"]), |
| 971 | ("e", vec![]), |
| 972 | ]; |
| 973 | let g = KnownGraph::new(pm, true); |
| 974 | assert!(matches!(g.topo_sort(), Err(Error::Cycle(_)))); |
| 975 | } |
| 976 | |
| 977 | #[test] |
| 978 | fn test_topo_sort_nontrivial() { |
| 979 | assert_topo_sort_order(&[ |
| 980 | ("a", &["d"]), |
| 981 | ("b", &["e"]), |
| 982 | ("c", &["b", "e"]), |
| 983 | ("d", &[]), |
| 984 | ("e", &["a", "d"]), |
| 985 | ]); |
| 986 | } |
| 987 | |
| 988 | #[test] |
| 989 | fn test_topo_sort_partial() { |
| 990 | assert_topo_sort_order(&[ |
| 991 | ("a", &[]), |
| 992 | ("b", &["a"]), |
| 993 | ("c", &["a"]), |
| 994 | ("d", &["a"]), |
| 995 | ("e", &["b", "c", "d"]), |
| 996 | ("f", &["b", "c"]), |
| 997 | ("g", &["b", "c"]), |
| 998 | ("h", &["c", "d"]), |
| 999 | ("i", &["a", "b", "e", "f", "g"]), |
| 1000 | ]); |
| 1001 | } |
| 1002 | |
| 1003 | #[test] |
| 1004 | fn test_topo_sort_ghost_parent() { |
| 1005 | // `b` is a ghost parent of `a` (not in the map). `c`'s parent |
| 1006 | // `b` references the same. Output order must place `a` after `b` |
| 1007 | // and `b` after `c` (treating `b` as a tail since it has no |
| 1008 | // known parents in the output graph). |
| 1009 | assert_topo_sort_order(&[("a", &["b"]), ("b", &["c"])]); |
| 1010 | } |
| 1011 | |
| 1012 | /// Merge-sort assertion helper: compares against Python-shaped |
| 1013 | /// (key, merge_depth, revno, end_of_merge) tuples. |
| 1014 | fn assert_merge_sort( |
| 1015 | edges: &[(&'static str, &[&'static str])], |
| 1016 | tip: &'static str, |
| 1017 | expected: &[(&'static str, usize, &[usize], bool)], |
| 1018 | ) { |
| 1019 | let pm: FxHashMap<&'static str, Vec<&'static str>> = |
| 1020 | edges.iter().map(|(k, ps)| (*k, ps.to_vec())).collect(); |
| 1021 | let g = KnownGraph::new(pm, true); |
| 1022 | let result = g.merge_sort(tip).unwrap(); |
| 1023 | assert_eq!( |
| 1024 | result.len(), |
| 1025 | expected.len(), |
| 1026 | "length mismatch: got {:?}", |
| 1027 | result |
| 1028 | .iter() |
| 1029 | .map(|n| (n.key, n.merge_depth, n.revno.clone(), n.end_of_merge)) |
| 1030 | .collect::<Vec<_>>() |
| 1031 | ); |
| 1032 | for (i, ((got_key, got_depth, got_eom), (exp_key, exp_depth, exp_revno, exp_eom))) in result |
| 1033 | .iter() |
| 1034 | .map(|n| (n.key, n.merge_depth, n.end_of_merge)) |
| 1035 | .zip(expected.iter()) |
| 1036 | .enumerate() |
| 1037 | { |
| 1038 | let got_revno: Vec<usize> = result[i].revno.clone().into_iter().collect(); |
| 1039 | let exp_revno_v: Vec<usize> = exp_revno.to_vec(); |
| 1040 | assert_eq!( |
| 1041 | (got_key, got_depth, got_revno.clone(), got_eom), |
| 1042 | (*exp_key, *exp_depth, exp_revno_v.clone(), *exp_eom), |
| 1043 | "row {i} mismatch" |
| 1044 | ); |
| 1045 | } |
| 1046 | } |
| 1047 | |
| 1048 | #[test] |
| 1049 | fn test_merge_sort_one_revision() { |
| 1050 | assert_merge_sort(&[("id", &[])], "id", &[("id", 0, &[1], true)]); |
| 1051 | } |
| 1052 | |
| 1053 | #[test] |
| 1054 | fn test_merge_sort_sequence_no_merges() { |
| 1055 | assert_merge_sort( |
| 1056 | &[("A", &[]), ("B", &["A"]), ("C", &["B"])], |
| 1057 | "C", |
| 1058 | &[ |
| 1059 | ("C", 0, &[3], false), |
| 1060 | ("B", 0, &[2], false), |
| 1061 | ("A", 0, &[1], true), |
| 1062 | ], |
| 1063 | ); |
| 1064 | } |
| 1065 | |
| 1066 | #[test] |
| 1067 | fn test_merge_sort_sequence_with_merges() { |
| 1068 | assert_merge_sort( |
| 1069 | &[("A", &[]), ("B", &["A"]), ("C", &["A", "B"])], |
| 1070 | "C", |
| 1071 | &[ |
| 1072 | ("C", 0, &[2], false), |
| 1073 | ("B", 1, &[1, 1, 1], true), |
| 1074 | ("A", 0, &[1], true), |
| 1075 | ], |
| 1076 | ); |
| 1077 | } |
| 1078 | |
| 1079 | #[test] |
| 1080 | fn test_merge_sort_merge_depth_with_nested_merges() { |
| 1081 | assert_merge_sort( |
| 1082 | &[ |
| 1083 | ("A", &["D", "B"]), |
| 1084 | ("B", &["C", "F"]), |
| 1085 | ("C", &["H"]), |
| 1086 | ("D", &["H", "E"]), |
| 1087 | ("E", &["G", "F"]), |
| 1088 | ("F", &["G"]), |
| 1089 | ("G", &["H"]), |
| 1090 | ("H", &[]), |
| 1091 | ], |
| 1092 | "A", |
| 1093 | &[ |
| 1094 | ("A", 0, &[3], false), |
| 1095 | ("B", 1, &[1, 3, 2], false), |
| 1096 | ("C", 1, &[1, 3, 1], true), |
| 1097 | ("D", 0, &[2], false), |
| 1098 | ("E", 1, &[1, 1, 2], false), |
| 1099 | ("F", 2, &[1, 2, 1], true), |
| 1100 | ("G", 1, &[1, 1, 1], true), |
| 1101 | ("H", 0, &[1], true), |
| 1102 | ], |
| 1103 | ); |
| 1104 | } |
| 1105 | |
| 1106 | #[test] |
| 1107 | fn test_merge_sort_end_of_merge_not_last() { |
| 1108 | assert_merge_sort( |
| 1109 | &[("A", &["B"]), ("B", &[])], |
| 1110 | "A", |
| 1111 | &[("A", 0, &[2], false), ("B", 0, &[1], true)], |
| 1112 | ); |
| 1113 | } |
| 1114 | |
| 1115 | #[test] |
| 1116 | fn test_merge_sort_parallel_roots() { |
| 1117 | assert_merge_sort( |
| 1118 | &[("A", &[]), ("B", &[]), ("C", &["A", "B"])], |
| 1119 | "C", |
| 1120 | &[ |
| 1121 | ("C", 0, &[2], false), |
| 1122 | ("B", 1, &[0, 1, 1], true), |
| 1123 | ("A", 0, &[1], true), |
| 1124 | ], |
| 1125 | ); |
| 1126 | } |
| 1127 | |
| 1128 | #[test] |
| 1129 | fn test_merge_sort_cycle_errors() { |
| 1130 | // E <- D <- C <- B, B <- D creates a cycle B-C-D-B |
| 1131 | let pm = [ |
| 1132 | ("A", vec![] as Vec<&'static str>), |
| 1133 | ("B", vec!["D"]), |
| 1134 | ("C", vec!["B"]), |
| 1135 | ("D", vec!["C"]), |
| 1136 | ("E", vec!["D"]), |
| 1137 | ]; |
| 1138 | let g = KnownGraph::new(pm, true); |
| 1139 | let r = g.merge_sort("E"); |
| 1140 | assert!(matches!(r, Err(Error::Cycle(_)))); |
| 1141 | } |
| 1142 | } |