| 1 | //! Breadth-first ancestry search. |
| 2 | //! |
| 3 | //! Ported from the `_BreadthFirstSearcher` class in `vcsgraph/graph.py`. |
| 4 | //! The searcher walks the ancestry of a set of revisions, optionally with |
| 5 | //! ghosts split out, and supports mid-walk modifications via |
| 6 | //! [`BfsState::start_searching`] and [`BfsState::stop_searching_any`]. |
| 7 | //! |
| 8 | //! The state is decoupled from the parents provider: each advance method |
| 9 | //! takes a `&impl ParentsProvider<K>` explicitly. This lets Python bindings |
| 10 | //! keep the provider adapter and the state as sibling fields in the same |
| 11 | //! pyclass without running into self-reference problems. |
| 12 | |
| 13 | use crate::{ParentMap, Parents, ParentsProvider}; |
| 14 | use rustc_hash::{FxHashMap, FxHashSet}; |
| 15 | use std::collections::HashSet; |
| 16 | use std::hash::Hash; |
| 17 | |
| 18 | /// Which kind of result the searcher returned on its most recent call. |
| 19 | /// |
| 20 | /// Callers can interleave `next` and `next_with_ghosts` calls; the searcher |
| 21 | /// transparently advances the underlying state when the mode flips. |
| 22 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 23 | enum ReturnMode { |
| 24 | /// Most recent return was a plain `next()` — revisions yielded before |
| 25 | /// their parents were queried, so ghosts are mixed in with real nodes. |
| 26 | Next, |
| 27 | /// Most recent return was `next_with_ghosts()` — revisions yielded after |
| 28 | /// their parents were queried, so ghosts are split out. |
| 29 | NextWithGhosts, |
| 30 | } |
| 31 | |
| 32 | /// Outcome of a `_do_query` step. |
| 33 | struct QueryResult<K> { |
| 34 | /// Nodes present in the provider's response. |
| 35 | found: FxHashSet<K>, |
| 36 | /// Nodes not found (ghosts). |
| 37 | ghosts: FxHashSet<K>, |
| 38 | /// Parents of the found nodes that we haven't seen before. |
| 39 | next: FxHashSet<K>, |
| 40 | /// The full parent map returned by the provider for the queried keys. |
| 41 | parents: FxHashMap<K, Vec<K>>, |
| 42 | } |
| 43 | |
| 44 | /// Mutable state of a breadth-first ancestry search. |
| 45 | /// |
| 46 | /// Constructed via [`BfsState::new`]; advanced with [`next`](Self::next) or |
| 47 | /// [`next_with_ghosts`](Self::next_with_ghosts), which both take a reference |
| 48 | /// to a parents provider. Mid-walk mutations go through |
| 49 | /// [`start_searching`](Self::start_searching) and |
| 50 | /// [`stop_searching_any`](Self::stop_searching_any). |
| 51 | pub struct BfsState<K: Hash + Eq + Clone> { |
| 52 | /// All revisions the searcher has ever visited (seen or about to visit). |
| 53 | pub seen: FxHashSet<K>, |
| 54 | /// Revisions the caller originally asked to search from, plus any added |
| 55 | /// via `start_searching`. |
| 56 | pub started_keys: FxHashSet<K>, |
| 57 | /// Revisions the caller explicitly asked to not descend through, plus |
| 58 | /// any ghosts encountered. Ghosts are implicit stop points so the search |
| 59 | /// can be repeated after ghosts are filled in. |
| 60 | pub stopped_keys: FxHashSet<K>, |
| 61 | |
| 62 | next_query: FxHashSet<K>, |
| 63 | current_present: FxHashSet<K>, |
| 64 | current_ghosts: FxHashSet<K>, |
| 65 | current_parents: FxHashMap<K, Vec<K>>, |
| 66 | returning: ReturnMode, |
| 67 | iterations: usize, |
| 68 | } |
| 69 | |
| 70 | impl<K: Hash + Eq + Clone> BfsState<K> { |
| 71 | /// Start a new search from `revisions`. |
| 72 | pub fn new<I: IntoIterator<Item = K>>(revisions: I) -> Self { |
| 73 | let next_query: FxHashSet<K> = revisions.into_iter().collect(); |
| 74 | let started_keys: FxHashSet<K> = next_query.iter().cloned().collect(); |
| 75 | BfsState { |
| 76 | seen: FxHashSet::default(), |
| 77 | started_keys, |
| 78 | stopped_keys: FxHashSet::default(), |
| 79 | next_query, |
| 80 | current_present: FxHashSet::default(), |
| 81 | current_ghosts: FxHashSet::default(), |
| 82 | current_parents: FxHashMap::default(), |
| 83 | returning: ReturnMode::NextWithGhosts, |
| 84 | iterations: 0, |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// Return the number of iterations performed so far. |
| 89 | pub fn iterations(&self) -> usize { |
| 90 | self.iterations |
| 91 | } |
| 92 | |
| 93 | /// Borrow the current frontier (next query set). |
| 94 | /// |
| 95 | /// Exposed so bindings can reflect Python's `_next_query` attribute, |
| 96 | /// which existing callers in `graph.py` read (but do not mutate). |
| 97 | pub fn next_query(&self) -> &FxHashSet<K> { |
| 98 | &self.next_query |
| 99 | } |
| 100 | |
| 101 | /// Borrow the present revisions from the most recent advance. |
| 102 | /// |
| 103 | /// Exposed so bindings can reflect Python's `_current_present` |
| 104 | /// attribute. Empty until the first advance. |
| 105 | pub fn current_present(&self) -> &FxHashSet<K> { |
| 106 | &self.current_present |
| 107 | } |
| 108 | |
| 109 | /// Borrow the ghost revisions from the most recent advance. |
| 110 | /// |
| 111 | /// Exposed so bindings can reflect Python's `_current_ghosts` |
| 112 | /// attribute. Empty until the first advance. |
| 113 | pub fn current_ghosts(&self) -> &FxHashSet<K> { |
| 114 | &self.current_ghosts |
| 115 | } |
| 116 | |
| 117 | /// Borrow the parent map of present revisions from the most recent |
| 118 | /// advance. |
| 119 | /// |
| 120 | /// Exposed so bindings can reflect Python's `_current_parents` |
| 121 | /// attribute. Empty until the first advance. |
| 122 | pub fn current_parents(&self) -> &FxHashMap<K, Vec<K>> { |
| 123 | &self.current_parents |
| 124 | } |
| 125 | |
| 126 | /// Snapshot of `(started_keys, excludes, included_keys)` describing what |
| 127 | /// the searcher has reached. Matches Python's `get_state` return shape. |
| 128 | /// |
| 129 | /// This method intentionally calls the provider if the searcher is in |
| 130 | /// `Next` mode, since we need the current query's children in order to |
| 131 | /// list their parents as excludes. The subsequent iteration advances |
| 132 | /// normally; the preview read is backed out of `seen`. |
| 133 | pub fn get_state<P: ParentsProvider<K>>( |
| 134 | &mut self, |
| 135 | provider: &P, |
| 136 | ) -> (FxHashSet<K>, FxHashSet<K>, FxHashSet<K>) { |
| 137 | let next_query = if self.returning == ReturnMode::Next { |
| 138 | let result = Self::do_query(&mut self.seen, &self.next_query, provider); |
| 139 | // Undo the `seen` updates the preview made. |
| 140 | for k in &result.next { |
| 141 | self.seen.remove(k); |
| 142 | } |
| 143 | let mut nq = result.next; |
| 144 | nq.extend(result.ghosts); |
| 145 | nq |
| 146 | } else { |
| 147 | self.next_query.clone() |
| 148 | }; |
| 149 | let mut excludes = self.stopped_keys.clone(); |
| 150 | excludes.extend(next_query); |
| 151 | let included: FxHashSet<K> = self.seen.difference(&excludes).cloned().collect(); |
| 152 | (self.started_keys.clone(), excludes, included) |
| 153 | } |
| 154 | |
| 155 | /// Advance the searcher and return the set yielded by Python's |
| 156 | /// `__next__` / `next`. |
| 157 | /// |
| 158 | /// Each call yields the current query before its parents are queried, |
| 159 | /// so ghosts are mixed in with present revisions. |
| 160 | /// |
| 161 | /// Returns `None` when there is nothing left to search. |
| 162 | pub fn next_set<P: ParentsProvider<K>>(&mut self, provider: &P) -> Option<FxHashSet<K>> { |
| 163 | if self.returning != ReturnMode::Next { |
| 164 | self.returning = ReturnMode::Next; |
| 165 | self.iterations += 1; |
| 166 | } else { |
| 167 | self.advance(provider); |
| 168 | } |
| 169 | if self.next_query.is_empty() { |
| 170 | return None; |
| 171 | } |
| 172 | self.seen.extend(self.next_query.iter().cloned()); |
| 173 | Some(self.next_query.clone()) |
| 174 | } |
| 175 | |
| 176 | /// Advance the searcher and return `(present, ghosts)` the way Python's |
| 177 | /// `next_with_ghosts` does. |
| 178 | /// |
| 179 | /// Returns `None` when there is nothing left to search. |
| 180 | pub fn next_with_ghosts<P: ParentsProvider<K>>( |
| 181 | &mut self, |
| 182 | provider: &P, |
| 183 | ) -> Option<(FxHashSet<K>, FxHashSet<K>)> { |
| 184 | if self.returning != ReturnMode::NextWithGhosts { |
| 185 | self.returning = ReturnMode::NextWithGhosts; |
| 186 | self.advance(provider); |
| 187 | } |
| 188 | if self.next_query.is_empty() { |
| 189 | return None; |
| 190 | } |
| 191 | self.advance(provider); |
| 192 | Some((self.current_present.clone(), self.current_ghosts.clone())) |
| 193 | } |
| 194 | |
| 195 | fn advance<P: ParentsProvider<K>>(&mut self, provider: &P) { |
| 196 | self.iterations += 1; |
| 197 | // Split borrow: `do_query` only needs to read `next_query` and |
| 198 | // write `seen`, so we pass them as separate references and avoid |
| 199 | // cloning `next_query` on every advance. |
| 200 | let result = Self::do_query(&mut self.seen, &self.next_query, provider); |
| 201 | self.current_present = result.found; |
| 202 | self.current_ghosts = result.ghosts; |
| 203 | self.next_query = result.next; |
| 204 | self.current_parents = result.parents; |
| 205 | // Ghosts become implicit stop points. |
| 206 | self.stopped_keys |
| 207 | .extend(self.current_ghosts.iter().cloned()); |
| 208 | } |
| 209 | |
| 210 | fn do_query<P: ParentsProvider<K>>( |
| 211 | seen: &mut FxHashSet<K>, |
| 212 | revisions: &FxHashSet<K>, |
| 213 | provider: &P, |
| 214 | ) -> QueryResult<K> { |
| 215 | seen.extend(revisions.iter().cloned()); |
| 216 | |
| 217 | // ParentsProvider takes a std HashSet by reference. |
| 218 | let mut std_set: HashSet<K> = HashSet::with_capacity(revisions.len()); |
| 219 | for k in revisions { |
| 220 | std_set.insert(k.clone()); |
| 221 | } |
| 222 | let parent_map: ParentMap<K> = provider.get_parent_map(&std_set); |
| 223 | |
| 224 | let mut found: FxHashSet<K> = FxHashSet::default(); |
| 225 | let mut parents_of_found: FxHashSet<K> = FxHashSet::default(); |
| 226 | let mut parents_owned: FxHashMap<K, Vec<K>> = FxHashMap::default(); |
| 227 | for (rev_id, parents) in parent_map.iter() { |
| 228 | found.insert(rev_id.clone()); |
| 229 | match parents { |
| 230 | Parents::Known(ps) => { |
| 231 | parents_owned.insert(rev_id.clone(), ps.clone()); |
| 232 | for p in ps { |
| 233 | if !seen.contains(p) { |
| 234 | parents_of_found.insert(p.clone()); |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | // Python treats None parents as "continue" — no new parents |
| 239 | // contributed. |
| 240 | Parents::Ghost => {} |
| 241 | } |
| 242 | } |
| 243 | let ghosts: FxHashSet<K> = revisions.difference(&found).cloned().collect(); |
| 244 | QueryResult { |
| 245 | found, |
| 246 | ghosts, |
| 247 | next: parents_of_found, |
| 248 | parents: parents_owned, |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | /// Find already-seen ancestors of `revisions`. |
| 253 | /// |
| 254 | /// This walks backwards from `revisions` through `seen` keys only, |
| 255 | /// querying the provider for parents. It matches the Python behavior: |
| 256 | /// nodes not yet searched (in `next_query` when we're in `Next` mode) |
| 257 | /// are skipped so we don't probe ahead of the search frontier. |
| 258 | pub fn find_seen_ancestors<I, P>(&self, revisions: I, provider: &P) -> FxHashSet<K> |
| 259 | where |
| 260 | I: IntoIterator<Item = K>, |
| 261 | P: ParentsProvider<K>, |
| 262 | { |
| 263 | let mut pending: FxHashSet<K> = revisions |
| 264 | .into_iter() |
| 265 | .filter(|r| self.seen.contains(r)) |
| 266 | .collect(); |
| 267 | let mut seen_ancestors: FxHashSet<K> = pending.iter().cloned().collect(); |
| 268 | |
| 269 | // In `Next` mode `seen` contains nodes that have been *returned* but |
| 270 | // whose parents haven't been queried yet. Skip those so we don't |
| 271 | // probe ahead of the search frontier. |
| 272 | let empty: FxHashSet<K> = FxHashSet::default(); |
| 273 | let not_searched_yet: &FxHashSet<K> = if self.returning == ReturnMode::Next { |
| 274 | &self.next_query |
| 275 | } else { |
| 276 | &empty |
| 277 | }; |
| 278 | |
| 279 | pending.retain(|k| !not_searched_yet.contains(k)); |
| 280 | |
| 281 | while !pending.is_empty() { |
| 282 | let mut std_set: HashSet<K> = HashSet::with_capacity(pending.len()); |
| 283 | for k in &pending { |
| 284 | std_set.insert(k.clone()); |
| 285 | } |
| 286 | let parent_map = provider.get_parent_map(&std_set); |
| 287 | let mut all_parents: Vec<K> = Vec::new(); |
| 288 | for (_, parents) in parent_map.iter() { |
| 289 | if let Parents::Known(ps) = parents { |
| 290 | all_parents.extend(ps.iter().cloned()); |
| 291 | } |
| 292 | } |
| 293 | let mut next_pending: FxHashSet<K> = FxHashSet::default(); |
| 294 | for p in all_parents { |
| 295 | if self.seen.contains(&p) && !seen_ancestors.contains(&p) { |
| 296 | next_pending.insert(p); |
| 297 | } |
| 298 | } |
| 299 | seen_ancestors.extend(next_pending.iter().cloned()); |
| 300 | next_pending.retain(|k| !not_searched_yet.contains(k)); |
| 301 | pending = next_pending; |
| 302 | } |
| 303 | seen_ancestors |
| 304 | } |
| 305 | |
| 306 | /// Stop searching any of `revisions`. Returns the set of revisions |
| 307 | /// actually removed from the current search frontier (not the ones that |
| 308 | /// had already passed). |
| 309 | pub fn stop_searching_any<I: IntoIterator<Item = K>>(&mut self, revisions: I) -> FxHashSet<K> { |
| 310 | let revisions: FxHashSet<K> = revisions.into_iter().collect(); |
| 311 | let stopped: FxHashSet<K> = if self.returning == ReturnMode::Next { |
| 312 | let stopped: FxHashSet<K> = self.next_query.intersection(&revisions).cloned().collect(); |
| 313 | self.next_query.retain(|k| !revisions.contains(k)); |
| 314 | stopped |
| 315 | } else { |
| 316 | let stopped_present: FxHashSet<K> = self |
| 317 | .current_present |
| 318 | .intersection(&revisions) |
| 319 | .cloned() |
| 320 | .collect(); |
| 321 | let stopped_ghosts: FxHashSet<K> = self |
| 322 | .current_ghosts |
| 323 | .intersection(&revisions) |
| 324 | .cloned() |
| 325 | .collect(); |
| 326 | let stopped: FxHashSet<K> = stopped_present.union(&stopped_ghosts).cloned().collect(); |
| 327 | self.current_present.retain(|k| !revisions.contains(k)); |
| 328 | self.current_ghosts.retain(|k| !revisions.contains(k)); |
| 329 | |
| 330 | // Stopping X should stop returning parents of X — but only if no |
| 331 | // other current node still references the same parent. Count |
| 332 | // references to each parent from stopped_present, then decrement |
| 333 | // for each non-stopped reference. |
| 334 | let mut stop_rev_references: FxHashMap<K, i64> = FxHashMap::default(); |
| 335 | for rev in &stopped_present { |
| 336 | if let Some(parents) = self.current_parents.get(rev) { |
| 337 | for parent_id in parents { |
| 338 | *stop_rev_references.entry(parent_id.clone()).or_insert(0) += 1; |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | for parents in self.current_parents.values() { |
| 343 | for parent_id in parents { |
| 344 | if let Some(count) = stop_rev_references.get_mut(parent_id) { |
| 345 | *count -= 1; |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | let stop_parents: FxHashSet<K> = stop_rev_references |
| 350 | .into_iter() |
| 351 | .filter_map(|(k, refs)| if refs == 0 { Some(k) } else { None }) |
| 352 | .collect(); |
| 353 | self.next_query.retain(|k| !stop_parents.contains(k)); |
| 354 | stopped |
| 355 | }; |
| 356 | self.stopped_keys.extend(stopped.iter().cloned()); |
| 357 | self.stopped_keys.extend(revisions); |
| 358 | stopped |
| 359 | } |
| 360 | |
| 361 | /// Add more revisions to the search. |
| 362 | /// |
| 363 | /// In `NextWithGhosts` mode this performs an immediate query on the new |
| 364 | /// revisions and returns `Some((present, ghosts))`. In `Next` mode the |
| 365 | /// new revisions join the current query without a provider call and the |
| 366 | /// function returns `None`. |
| 367 | pub fn start_searching<I, P>( |
| 368 | &mut self, |
| 369 | revisions: I, |
| 370 | provider: &P, |
| 371 | ) -> Option<(FxHashSet<K>, FxHashSet<K>)> |
| 372 | where |
| 373 | I: IntoIterator<Item = K>, |
| 374 | P: ParentsProvider<K>, |
| 375 | { |
| 376 | let revisions: FxHashSet<K> = revisions.into_iter().collect(); |
| 377 | self.started_keys.extend(revisions.iter().cloned()); |
| 378 | let new_revisions: FxHashSet<K> = revisions.difference(&self.seen).cloned().collect(); |
| 379 | if self.returning == ReturnMode::Next { |
| 380 | self.next_query.extend(new_revisions.iter().cloned()); |
| 381 | self.seen.extend(new_revisions); |
| 382 | None |
| 383 | } else { |
| 384 | let result = Self::do_query(&mut self.seen, &revisions, provider); |
| 385 | self.stopped_keys.extend(result.ghosts.iter().cloned()); |
| 386 | self.current_present.extend(result.found.iter().cloned()); |
| 387 | self.current_ghosts.extend(result.ghosts.iter().cloned()); |
| 388 | self.next_query.extend(result.next); |
| 389 | for (k, v) in result.parents { |
| 390 | self.current_parents.insert(k, v); |
| 391 | } |
| 392 | Some((result.found, result.ghosts)) |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | #[cfg(test)] |
| 398 | mod tests { |
| 399 | use super::*; |
| 400 | use crate::DictParentsProvider; |
| 401 | use std::collections::HashMap; |
| 402 | |
| 403 | fn provider(edges: &[(&'static str, &[&'static str])]) -> DictParentsProvider<&'static str> { |
| 404 | let map: HashMap<&'static str, Vec<&'static str>> = |
| 405 | edges.iter().map(|(k, ps)| (*k, ps.to_vec())).collect(); |
| 406 | DictParentsProvider::from(map) |
| 407 | } |
| 408 | |
| 409 | fn as_set<const N: usize>(xs: [&'static str; N]) -> FxHashSet<&'static str> { |
| 410 | xs.into_iter().collect() |
| 411 | } |
| 412 | |
| 413 | #[test] |
| 414 | fn next_walks_linear() { |
| 415 | // a <- b <- c |
| 416 | let p = provider(&[("a", &[]), ("b", &["a"]), ("c", &["b"])]); |
| 417 | let mut s = BfsState::new(["c"]); |
| 418 | assert_eq!(s.next_set(&p), Some(as_set(["c"]))); |
| 419 | assert_eq!(s.next_set(&p), Some(as_set(["b"]))); |
| 420 | assert_eq!(s.next_set(&p), Some(as_set(["a"]))); |
| 421 | assert_eq!(s.next_set(&p), None); |
| 422 | } |
| 423 | |
| 424 | #[test] |
| 425 | fn next_with_ghosts_splits() { |
| 426 | // head -> present -> (child, ghost); child has no parents; ghost missing |
| 427 | let p = provider(&[ |
| 428 | ("head", &["present"]), |
| 429 | ("present", &["child", "ghost"]), |
| 430 | ("child", &[]), |
| 431 | ]); |
| 432 | let mut s = BfsState::new(["head"]); |
| 433 | assert_eq!(s.next_with_ghosts(&p), Some((as_set(["head"]), as_set([])))); |
| 434 | assert_eq!( |
| 435 | s.next_with_ghosts(&p), |
| 436 | Some((as_set(["present"]), as_set([]))) |
| 437 | ); |
| 438 | assert_eq!( |
| 439 | s.next_with_ghosts(&p), |
| 440 | Some((as_set(["child"]), as_set(["ghost"]))) |
| 441 | ); |
| 442 | assert_eq!(s.next_with_ghosts(&p), None); |
| 443 | } |
| 444 | |
| 445 | #[test] |
| 446 | fn next_mode_mixes_ghosts_in_with_present() { |
| 447 | // Same graph as above, but via next() — ghost should appear alongside child. |
| 448 | let p = provider(&[ |
| 449 | ("head", &["present"]), |
| 450 | ("present", &["child", "ghost"]), |
| 451 | ("child", &[]), |
| 452 | ]); |
| 453 | let mut s = BfsState::new(["head"]); |
| 454 | assert_eq!(s.next_set(&p), Some(as_set(["head"]))); |
| 455 | assert_eq!(s.next_set(&p), Some(as_set(["present"]))); |
| 456 | assert_eq!(s.next_set(&p), Some(as_set(["child", "ghost"]))); |
| 457 | assert_eq!(s.next_set(&p), None); |
| 458 | } |
| 459 | |
| 460 | #[test] |
| 461 | fn stop_searching_any_next_mode() { |
| 462 | // In Next mode, `next_query` holds the set just returned by `next()` |
| 463 | // (since the caller is given the query, not the results). So stopping |
| 464 | // the set that was just yielded removes it from the frontier. |
| 465 | let p = provider(&[ |
| 466 | ("head", &["present"]), |
| 467 | ("present", &["stopped"]), |
| 468 | ("stopped", &[]), |
| 469 | ]); |
| 470 | let mut s = BfsState::new(["head"]); |
| 471 | assert_eq!(s.next_set(&p), Some(as_set(["head"]))); |
| 472 | assert_eq!(s.next_set(&p), Some(as_set(["present"]))); |
| 473 | let stopped = s.stop_searching_any(["present"]); |
| 474 | assert_eq!(stopped, as_set(["present"])); |
| 475 | // With `present` stopped before its parents are queried, the search |
| 476 | // is now exhausted. |
| 477 | assert_eq!(s.next_set(&p), None); |
| 478 | } |
| 479 | |
| 480 | #[test] |
| 481 | fn start_searching_next_with_ghosts_queries_immediately() { |
| 482 | let p = provider(&[("new_root", &["its_parent"]), ("its_parent", &[])]); |
| 483 | let mut s: BfsState<&'static str> = BfsState::new([] as [&'static str; 0]); |
| 484 | let (found, ghosts) = s.start_searching(["new_root", "ghost"], &p).unwrap(); |
| 485 | assert!(found.contains(&"new_root")); |
| 486 | assert!(ghosts.contains(&"ghost")); |
| 487 | } |
| 488 | |
| 489 | /// Translated from `test_breadth_first_search_start_ghosts` in |
| 490 | /// `vcsgraph/tests/test_graph.py`: starting with only a ghost, the first |
| 491 | /// step yields just the ghost and then the search is exhausted. |
| 492 | #[test] |
| 493 | fn start_with_only_a_ghost() { |
| 494 | let p = provider(&[("a-ghost", &[])]); |
| 495 | let mut s = BfsState::new(["a-ghost"]); |
| 496 | assert_eq!(s.next_set(&p), Some(as_set(["a-ghost"]))); |
| 497 | assert_eq!(s.next_set(&p), None); |
| 498 | } |
| 499 | |
| 500 | /// Translated from `test_breadth_first_change_search`: stop the current |
| 501 | /// frontier, start a new search from an unrelated revision, and |
| 502 | /// verify the BFS picks up the new revision's ancestors. |
| 503 | #[test] |
| 504 | fn change_search_via_stop_and_start() { |
| 505 | let p = provider(&[ |
| 506 | ("head", &["present"]), |
| 507 | ("present", &["stopped"]), |
| 508 | ("stopped", &[]), |
| 509 | ("other", &["other_2"]), |
| 510 | ("other_2", &[]), |
| 511 | ]); |
| 512 | let mut s = BfsState::new(["head"]); |
| 513 | assert_eq!(s.next_with_ghosts(&p), Some((as_set(["head"]), as_set([])))); |
| 514 | assert_eq!( |
| 515 | s.next_with_ghosts(&p), |
| 516 | Some((as_set(["present"]), as_set([]))) |
| 517 | ); |
| 518 | assert_eq!(s.stop_searching_any(["present"]), as_set(["present"])); |
| 519 | let (present, ghosts) = s.start_searching(["other", "other_ghost"], &p).unwrap(); |
| 520 | assert_eq!(present, as_set(["other"])); |
| 521 | assert_eq!(ghosts, as_set(["other_ghost"])); |
| 522 | assert_eq!( |
| 523 | s.next_with_ghosts(&p), |
| 524 | Some((as_set(["other_2"]), as_set([]))) |
| 525 | ); |
| 526 | assert_eq!(s.next_with_ghosts(&p), None); |
| 527 | } |
| 528 | |
| 529 | const NULL: &str = "null:"; |
| 530 | |
| 531 | /// Mirrors `test_breadth_first_search_change_next_to_next_with_ghosts`: |
| 532 | /// interleave `next()` and `next_with_ghosts()` on the same searcher |
| 533 | /// and verify both modes produce sensible values. |
| 534 | #[test] |
| 535 | fn change_next_to_next_with_ghosts() { |
| 536 | let p = provider(&[ |
| 537 | ("head", &["present"]), |
| 538 | ("present", &["child", "ghost"]), |
| 539 | ("child", &[]), |
| 540 | ]); |
| 541 | let mut s = BfsState::new(["head"]); |
| 542 | assert_eq!(s.next_with_ghosts(&p), Some((as_set(["head"]), as_set([])))); |
| 543 | assert_eq!(s.next_set(&p), Some(as_set(["present"]))); |
| 544 | assert_eq!( |
| 545 | s.next_with_ghosts(&p), |
| 546 | Some((as_set(["child"]), as_set(["ghost"]))) |
| 547 | ); |
| 548 | assert_eq!(s.next_set(&p), None); |
| 549 | |
| 550 | // Symmetric: start with next(), switch to next_with_ghosts(). |
| 551 | let mut s = BfsState::new(["head"]); |
| 552 | assert_eq!(s.next_set(&p), Some(as_set(["head"]))); |
| 553 | assert_eq!( |
| 554 | s.next_with_ghosts(&p), |
| 555 | Some((as_set(["present"]), as_set([]))) |
| 556 | ); |
| 557 | assert_eq!(s.next_set(&p), Some(as_set(["child", "ghost"]))); |
| 558 | assert_eq!(s.next_with_ghosts(&p), None); |
| 559 | } |
| 560 | |
| 561 | /// Mirrors `test_breadth_first_get_result_excludes_current_pending`: |
| 562 | /// at the start, nothing is seen; after each advance, `get_state()` |
| 563 | /// reports the started keys, the excluded set, and the included |
| 564 | /// (fully explored) set. |
| 565 | #[test] |
| 566 | fn get_state_excludes_current_pending() { |
| 567 | let p = provider(&[("head", &["child"]), ("child", &[NULL]), (NULL, &[])]); |
| 568 | let mut s = BfsState::new(["head"]); |
| 569 | let (started, excludes, included) = s.get_state(&p); |
| 570 | assert_eq!(started, as_set(["head"])); |
| 571 | assert_eq!(excludes, as_set(["head"])); |
| 572 | assert_eq!(included, as_set([])); |
| 573 | assert_eq!(s.seen, as_set([])); |
| 574 | |
| 575 | // After next: head is yielded, still excluded because child is |
| 576 | // the next frontier. |
| 577 | s.next_set(&p); |
| 578 | let (_, excludes, included) = s.get_state(&p); |
| 579 | assert_eq!(excludes, as_set(["child"])); |
| 580 | assert_eq!(included, as_set(["head"])); |
| 581 | assert_eq!(s.seen, as_set(["head"])); |
| 582 | |
| 583 | // After child: null is the next frontier. |
| 584 | s.next_set(&p); |
| 585 | let (_, excludes, included) = s.get_state(&p); |
| 586 | assert_eq!(excludes, as_set([NULL])); |
| 587 | assert_eq!(included, as_set(["head", "child"])); |
| 588 | |
| 589 | // After null: nothing left in the frontier. |
| 590 | s.next_set(&p); |
| 591 | let (_, excludes, included) = s.get_state(&p); |
| 592 | assert_eq!(excludes, as_set([])); |
| 593 | assert_eq!(included, as_set(["head", "child", NULL])); |
| 594 | } |
| 595 | |
| 596 | /// Mirrors `test_breadth_first_stop_searching_not_queried`: a client |
| 597 | /// may tell the searcher to stop a key, and stopped_keys records it |
| 598 | /// for later exclusion from the result's included-set. |
| 599 | #[test] |
| 600 | fn stop_searching_records_stops() { |
| 601 | let p = provider(&[ |
| 602 | ("head", &["child", "ghost1"]), |
| 603 | ("child", &[NULL]), |
| 604 | (NULL, &[]), |
| 605 | ]); |
| 606 | let mut s = BfsState::new(["head"]); |
| 607 | s.next_set(&p); // yields head |
| 608 | s.stop_searching_any([NULL, "ghost1"]); |
| 609 | // The stopped keys are in stopped_keys regardless of whether |
| 610 | // they've been visited yet. |
| 611 | assert!(s.stopped_keys.contains(&NULL)); |
| 612 | assert!(s.stopped_keys.contains(&"ghost1")); |
| 613 | // get_state() should exclude the stopped keys from the |
| 614 | // "included" snapshot. |
| 615 | let (_, excludes, included) = s.get_state(&p); |
| 616 | assert!(excludes.contains(&NULL)); |
| 617 | assert!(excludes.contains(&"ghost1")); |
| 618 | assert!(!included.contains(&NULL)); |
| 619 | assert!(!included.contains(&"ghost1")); |
| 620 | } |
| 621 | |
| 622 | /// Mirrors `test_breadth_first_stop_searching_late`: stopping a key |
| 623 | /// from an older iteration should still exclude it from the result. |
| 624 | #[test] |
| 625 | fn stop_searching_late() { |
| 626 | let p = provider(&[ |
| 627 | ("head", &["middle"]), |
| 628 | ("middle", &["child"]), |
| 629 | ("child", &[NULL]), |
| 630 | (NULL, &[]), |
| 631 | ]); |
| 632 | let mut s = BfsState::new(["head"]); |
| 633 | s.next_set(&p); // yields head |
| 634 | s.next_set(&p); // yields middle |
| 635 | s.next_set(&p); // yields child |
| 636 | // Now stop both middle and child retroactively. |
| 637 | s.stop_searching_any(["middle", "child"]); |
| 638 | assert!(s.stopped_keys.contains(&"middle")); |
| 639 | assert!(s.stopped_keys.contains(&"child")); |
| 640 | // After the stop, the remaining state reflects that only the |
| 641 | // original head is included. |
| 642 | let (_, excludes, included) = s.get_state(&p); |
| 643 | assert!(excludes.contains(&"middle")); |
| 644 | assert!(excludes.contains(&"child")); |
| 645 | assert_eq!(included, as_set(["head"])); |
| 646 | } |
| 647 | |
| 648 | /// Mirrors `test_breadth_first_get_result_starting_a_ghost_ghost_is_excluded`: |
| 649 | /// start_searching a ghost key mid-walk. The ghost is recorded in seen |
| 650 | /// but gets filed under stopped_keys so it is excluded from included(). |
| 651 | #[test] |
| 652 | fn start_searching_a_ghost_excludes_it() { |
| 653 | let p = provider(&[("head", &["child"]), ("child", &[NULL]), (NULL, &[])]); |
| 654 | let mut s = BfsState::new(["head"]); |
| 655 | // Start-searching a ghost while in next_with_ghosts mode (the |
| 656 | // default after construction). This returns (present, ghosts). |
| 657 | let (present, ghosts) = s.start_searching(["ghost"], &p).unwrap(); |
| 658 | assert_eq!(present, as_set([])); |
| 659 | assert_eq!(ghosts, as_set(["ghost"])); |
| 660 | // ghost is now in stopped_keys so included() doesn't report it. |
| 661 | assert!(s.stopped_keys.contains(&"ghost")); |
| 662 | } |
| 663 | |
| 664 | /// Mirrors `test_breadth_first_revision_count_includes_NULL_REVISION`: |
| 665 | /// walking to the sentinel should count it as part of `seen`. |
| 666 | #[test] |
| 667 | fn walk_includes_null_revision() { |
| 668 | let p = provider(&[("head", &[NULL]), (NULL, &[])]); |
| 669 | let mut s = BfsState::new(["head"]); |
| 670 | s.next_set(&p); // yields head |
| 671 | s.next_set(&p); // yields null |
| 672 | assert_eq!(s.seen, as_set(["head", NULL])); |
| 673 | assert_eq!(s.next_set(&p), None); |
| 674 | } |
| 675 | |
| 676 | /// Mirrors `test_breadth_first_search_get_result_after_StopIteration`: |
| 677 | /// hitting StopIteration should not invalidate the searcher; a |
| 678 | /// subsequent get_state() still works. |
| 679 | #[test] |
| 680 | fn get_state_after_stop_iteration() { |
| 681 | let p = provider(&[("head", &[NULL]), (NULL, &[])]); |
| 682 | let mut s = BfsState::new(["head"]); |
| 683 | while s.next_set(&p).is_some() {} |
| 684 | // No more to yield. |
| 685 | assert_eq!(s.next_set(&p), None); |
| 686 | let (started, _excludes, included) = s.get_state(&p); |
| 687 | assert_eq!(started, as_set(["head"])); |
| 688 | assert!(included.contains(&"head")); |
| 689 | assert!(included.contains(&NULL)); |
| 690 | } |
| 691 | |
| 692 | /// find_seen_ancestors should walk the parent chain and collect all |
| 693 | /// ancestors already in `seen` — not new ones. |
| 694 | #[test] |
| 695 | fn find_seen_ancestors_walks_seen_chain() { |
| 696 | let p = provider(&[ |
| 697 | ("head", &["middle"]), |
| 698 | ("middle", &["child"]), |
| 699 | ("child", &[NULL]), |
| 700 | (NULL, &[]), |
| 701 | ]); |
| 702 | let mut s = BfsState::new(["head"]); |
| 703 | // Walk the whole thing. |
| 704 | while s.next_set(&p).is_some() {} |
| 705 | // Ask for ancestors of "middle" — should find middle, child, null. |
| 706 | let anc = s.find_seen_ancestors(["middle"], &p); |
| 707 | assert!(anc.contains(&"middle")); |
| 708 | assert!(anc.contains(&"child")); |
| 709 | assert!(anc.contains(&NULL)); |
| 710 | } |
| 711 | |
| 712 | /// find_seen_ancestors should filter out keys not in seen. |
| 713 | #[test] |
| 714 | fn find_seen_ancestors_skips_unseen() { |
| 715 | let p = provider(&[("head", &[NULL]), (NULL, &[]), ("unrelated", &[])]); |
| 716 | let mut s = BfsState::new(["head"]); |
| 717 | s.next_set(&p); // yields head |
| 718 | let anc = s.find_seen_ancestors(["unrelated"], &p); |
| 719 | // "unrelated" isn't in seen, so find_seen_ancestors returns an |
| 720 | // empty set for it. |
| 721 | assert!(!anc.contains(&"unrelated")); |
| 722 | } |
| 723 | |
| 724 | /// stop_searching_any should return only the keys that were actually |
| 725 | /// removed from the current frontier (not keys that had already been |
| 726 | /// processed). |
| 727 | #[test] |
| 728 | fn stop_searching_any_returns_only_effective_stops() { |
| 729 | let p = provider(&[("head", &["a"]), ("a", &["b"]), ("b", &[])]); |
| 730 | let mut s = BfsState::new(["head"]); |
| 731 | s.next_set(&p); // yields head |
| 732 | s.next_set(&p); // yields a |
| 733 | // `head` is already returned; stopping it should report it as |
| 734 | // stopped but a no longer in frontier means only keys that are in |
| 735 | // next_query at stop time get returned. |
| 736 | let stopped = s.stop_searching_any(["a"]); |
| 737 | assert_eq!(stopped, as_set(["a"])); |
| 738 | // After stopping a, the search is exhausted. |
| 739 | assert_eq!(s.next_set(&p), None); |
| 740 | } |
| 741 | |
| 742 | /// Starting an already-seen key should be a no-op on `seen` and the |
| 743 | /// key should not be re-queried. |
| 744 | #[test] |
| 745 | fn start_searching_already_seen_is_noop() { |
| 746 | let p = provider(&[("head", &["child"]), ("child", &[])]); |
| 747 | let mut s = BfsState::new(["head"]); |
| 748 | s.next_set(&p); // yields head, frontier now contains "child" |
| 749 | let pre_seen = s.seen.clone(); |
| 750 | s.start_searching(["head"], &p); |
| 751 | // seen should be unchanged (head was already there). |
| 752 | assert_eq!(s.seen, pre_seen); |
| 753 | } |
| 754 | } |