Debian Codegraph @

rust/hg-core/src/discovery.rs

raw
1 // discovery.rs
2 //
3 // Copyright 2019 Georges Racinet <[email protected]>
4 //
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
7
8 //! Discovery operations
9 //!
10 //! This is a Rust counterpart to the `partialdiscovery` class of
11 //! `mercurial.setdiscovery`
12
13 use std::cmp::max;
14 use std::cmp::min;
15 use std::collections::HashSet;
16 use std::collections::VecDeque;
17
18 use rand::seq::SliceRandom;
19 use rand::RngCore;
20 use rand::SeedableRng;
21
22 use super::Graph;
23 use super::GraphError;
24 use super::Revision;
25 use super::NULL_REVISION;
26 use crate::ancestors::MissingAncestors;
27 use crate::dagops;
28 use crate::FastHashMap;
29
30 type Rng = rand_pcg::Pcg32;
31 type Seed = [u8; 16];
32
33 pub struct PartialDiscovery<G: Graph + Clone> {
34 target_heads: Option<Vec<Revision>>,
35 graph: G, // plays the role of self._repo
36 common: MissingAncestors<G>,
37 undecided: Option<HashSet<Revision>>,
38 children_cache: Option<FastHashMap<Revision, Vec<Revision>>>,
39 missing: HashSet<Revision>,
40 rng: Rng,
41 respect_size: bool,
42 randomize: bool,
43 }
44
45 pub struct DiscoveryStats {
46 pub undecided: Option<usize>,
47 }
48
49 /// Update an existing sample to match the expected size
50 ///
51 /// The sample is updated with revisions exponentially distant from each
52 /// element of `heads`.
53 ///
54 /// If a target size is specified, the sampling will stop once this size is
55 /// reached. Otherwise sampling will happen until roots of the <revs> set are
56 /// reached.
57 ///
58 /// - `revs`: set of revs we want to discover (if None, `assume` the whole dag
59 /// represented by `parentfn`
60 /// - `heads`: set of DAG head revs
61 /// - `sample`: a sample to update
62 /// - `parentfn`: a callable to resolve parents for a revision
63 /// - `quicksamplesize`: optional target size of the sample
64 fn update_sample<I>(
65 revs: Option<&HashSet<Revision>>,
66 heads: impl IntoIterator<Item = Revision>,
67 sample: &mut HashSet<Revision>,
68 parentsfn: impl Fn(Revision) -> Result<I, GraphError>,
69 quicksamplesize: Option<usize>,
70 ) -> Result<(), GraphError>
71 where
72 I: Iterator<Item = Revision>,
73 {
74 let mut distances: FastHashMap<Revision, u32> = FastHashMap::default();
75 let mut visit: VecDeque<Revision> = heads.into_iter().collect();
76 let mut factor: u32 = 1;
77 let mut seen: HashSet<Revision> = HashSet::new();
78 while let Some(current) = visit.pop_front() {
79 if !seen.insert(current) {
80 continue;
81 }
82
83 let d = *distances.entry(current).or_insert(1);
84 if d > factor {
85 factor *= 2;
86 }
87 if d == factor {
88 sample.insert(current);
89 if let Some(sz) = quicksamplesize {
90 if sample.len() >= sz {
91 return Ok(());
92 }
93 }
94 }
95 for p in parentsfn(current)? {
96 if let Some(revs) = revs {
97 if !revs.contains(&p) {
98 continue;
99 }
100 }
101 distances.entry(p).or_insert(d + 1);
102 visit.push_back(p);
103 }
104 }
105 Ok(())
106 }
107
108 struct ParentsIterator {
109 parents: [Revision; 2],
110 cur: usize,
111 }
112
113 impl ParentsIterator {
114 fn graph_parents(
115 graph: &impl Graph,
116 r: Revision,
117 ) -> Result<ParentsIterator, GraphError> {
118 Ok(ParentsIterator { parents: graph.parents(r)?, cur: 0 })
119 }
120 }
121
122 impl Iterator for ParentsIterator {
123 type Item = Revision;
124
125 fn next(&mut self) -> Option<Revision> {
126 if self.cur > 1 {
127 return None;
128 }
129 let rev = self.parents[self.cur];
130 self.cur += 1;
131 if rev == NULL_REVISION {
132 return self.next();
133 }
134 Some(rev)
135 }
136 }
137
138 impl<G: Graph + Clone> PartialDiscovery<G> {
139 /// Create a PartialDiscovery object, with the intent
140 /// of comparing our `::<target_heads>` revset to the contents of another
141 /// repo.
142 ///
143 /// For now `target_heads` is passed as a vector, and will be used
144 /// at the first call to `ensure_undecided()`.
145 ///
146 /// If we want to make the signature more flexible,
147 /// we'll have to make it a type argument of `PartialDiscovery` or a trait
148 /// object since we'll keep it in the meanwhile
149 ///
150 /// The `respect_size` boolean controls how the sampling methods
151 /// will interpret the size argument requested by the caller. If it's
152 /// `false`, they are allowed to produce a sample whose size is more
153 /// appropriate to the situation (typically bigger).
154 ///
155 /// The `randomize` boolean affects sampling, and specifically how
156 /// limiting or last-minute expanding is been done:
157 ///
158 /// If `true`, both will perform random picking from `self.undecided`.
159 /// This is currently the best for actual discoveries.
160 ///
161 /// If `false`, a reproductible picking strategy is performed. This is
162 /// useful for integration tests.
163 pub fn new(
164 graph: G,
165 target_heads: Vec<Revision>,
166 respect_size: bool,
167 randomize: bool,
168 ) -> Self {
169 let mut seed = [0; 16];
170 if randomize {
171 rand::rng().fill_bytes(&mut seed);
172 }
173 Self::new_with_seed(graph, target_heads, seed, respect_size, randomize)
174 }
175
176 pub fn new_with_seed(
177 graph: G,
178 target_heads: Vec<Revision>,
179 seed: Seed,
180 respect_size: bool,
181 randomize: bool,
182 ) -> Self {
183 PartialDiscovery {
184 undecided: None,
185 children_cache: None,
186 target_heads: Some(target_heads),
187 graph: graph.clone(),
188 common: MissingAncestors::new(graph, vec![]),
189 missing: HashSet::new(),
190 rng: Rng::from_seed(seed),
191 respect_size,
192 randomize,
193 }
194 }
195
196 /// Extract at most `size` random elements from sample and return them
197 /// as a vector
198 fn limit_sample(
199 &mut self,
200 mut sample: Vec<Revision>,
201 size: usize,
202 ) -> Vec<Revision> {
203 if !self.randomize {
204 sample.sort_unstable();
205 sample.truncate(size);
206 return sample;
207 }
208 let sample_len = sample.len();
209 if sample_len <= size {
210 return sample;
211 }
212 let rng = &mut self.rng;
213 let dropped_size = sample_len - size;
214 let limited_slice = if size < dropped_size {
215 sample.partial_shuffle(rng, size).0
216 } else {
217 sample.partial_shuffle(rng, dropped_size).1
218 };
219 limited_slice.to_owned()
220 }
221
222 /// Register revisions known as being common
223 pub fn add_common_revisions(
224 &mut self,
225 common: impl IntoIterator<Item = Revision>,
226 ) -> Result<(), GraphError> {
227 let before_len = self.common.get_bases().len();
228 self.common.add_bases(common);
229 if self.common.get_bases().len() == before_len {
230 return Ok(());
231 }
232 if let Some(ref mut undecided) = self.undecided {
233 self.common.remove_ancestors_from(undecided)?;
234 }
235 Ok(())
236 }
237
238 /// Register revisions known as being missing
239 ///
240 /// # Performance note
241 ///
242 /// Except in the most trivial case, the first call of this method has
243 /// the side effect of computing `self.undecided` set for the first time,
244 /// and the related caches it might need for efficiency of its internal
245 /// computation. This is typically faster if more information is
246 /// available in `self.common`. Therefore, for good performance, the
247 /// caller should avoid calling this too early.
248 pub fn add_missing_revisions(
249 &mut self,
250 missing: impl IntoIterator<Item = Revision>,
251 ) -> Result<(), GraphError> {
252 let mut tovisit: VecDeque<Revision> = missing.into_iter().collect();
253 if tovisit.is_empty() {
254 return Ok(());
255 }
256 self.ensure_children_cache()?;
257 self.ensure_undecided()?; // for safety of possible future refactors
258 let children = self.children_cache.as_ref().unwrap();
259 let mut seen: HashSet<Revision> = HashSet::new();
260 let undecided_mut = self.undecided.as_mut().unwrap();
261 while let Some(rev) = tovisit.pop_front() {
262 if !self.missing.insert(rev) {
263 // either it's known to be missing from a previous
264 // invocation, and there's no need to iterate on its
265 // children (we now they are all missing)
266 // or it's from a previous iteration of this loop
267 // and its children have already been queued
268 continue;
269 }
270 undecided_mut.remove(&rev);
271 match children.get(&rev) {
272 None => {
273 continue;
274 }
275 Some(this_children) => {
276 for child in this_children.iter().cloned() {
277 if seen.insert(child) {
278 tovisit.push_back(child);
279 }
280 }
281 }
282 }
283 }
284 Ok(())
285 }
286
287 /// Do we have any information about the peer?
288 pub fn has_info(&self) -> bool {
289 self.common.has_bases()
290 }
291
292 /// Did we acquire full knowledge of our Revisions that the peer has?
293 pub fn is_complete(&self) -> bool {
294 self.undecided.as_ref().is_some_and(HashSet::is_empty)
295 }
296
297 /// Return the heads of the currently known common set of revisions.
298 ///
299 /// If the discovery process is not complete (see `is_complete()`), the
300 /// caller must be aware that this is an intermediate state.
301 ///
302 /// On the other hand, if it is complete, then this is currently
303 /// the only way to retrieve the end results of the discovery process.
304 ///
305 /// We may introduce in the future an `into_common_heads` call that
306 /// would be more appropriate for normal Rust callers, dropping `self`
307 /// if it is complete.
308 pub fn common_heads(&self) -> Result<HashSet<Revision>, GraphError> {
309 self.common.bases_heads()
310 }
311
312 /// Force first computation of `self.undecided`
313 ///
314 /// After this, `self.undecided.as_ref()` and `.as_mut()` can be
315 /// unwrapped to get workable immutable or mutable references without
316 /// any panic.
317 ///
318 /// This is an imperative call instead of an access with added lazyness
319 /// to reduce easily the scope of mutable borrow for the caller,
320 /// compared to undecided(&'a mut self) -> &'a… that would keep it
321 /// as long as the resulting immutable one.
322 fn ensure_undecided(&mut self) -> Result<(), GraphError> {
323 if self.undecided.is_some() {
324 return Ok(());
325 }
326 let tgt = self.target_heads.take().unwrap();
327 self.undecided =
328 Some(self.common.missing_ancestors(tgt)?.into_iter().collect());
329 Ok(())
330 }
331
332 fn ensure_children_cache(&mut self) -> Result<(), GraphError> {
333 if self.children_cache.is_some() {
334 return Ok(());
335 }
336 self.ensure_undecided()?;
337
338 let mut children: FastHashMap<Revision, Vec<Revision>> =
339 FastHashMap::default();
340 for &rev in self.undecided.as_ref().unwrap() {
341 for p in ParentsIterator::graph_parents(&self.graph, rev)? {
342 children.entry(p).or_default().push(rev);
343 }
344 }
345 self.children_cache = Some(children);
346 Ok(())
347 }
348
349 /// Provide statistics about the current state of the discovery process
350 pub fn stats(&self) -> DiscoveryStats {
351 DiscoveryStats { undecided: self.undecided.as_ref().map(HashSet::len) }
352 }
353
354 pub fn take_quick_sample(
355 &mut self,
356 headrevs: impl IntoIterator<Item = Revision>,
357 size: usize,
358 ) -> Result<Vec<Revision>, GraphError> {
359 self.ensure_undecided()?;
360 let mut sample = {
361 let undecided = self.undecided.as_ref().unwrap();
362 if undecided.len() <= size {
363 return Ok(undecided.iter().cloned().collect());
364 }
365 dagops::heads(&self.graph, undecided.iter())?
366 };
367 if sample.len() >= size {
368 return Ok(self.limit_sample(sample.into_iter().collect(), size));
369 }
370 update_sample(
371 None,
372 headrevs,
373 &mut sample,
374 |r| ParentsIterator::graph_parents(&self.graph, r),
375 Some(size),
376 )?;
377 Ok(sample.into_iter().collect())
378 }
379
380 /// Extract a sample from `self.undecided`, going from its heads and roots.
381 ///
382 /// The `size` parameter is used to avoid useless computations if
383 /// it turns out to be bigger than the whole set of undecided Revisions.
384 ///
385 /// The sample is taken by using `update_sample` from the heads, then
386 /// from the roots, working on the reverse DAG,
387 /// expressed by `self.children_cache`.
388 ///
389 /// No effort is being made to complete or limit the sample to `size`
390 /// but this method returns another interesting size that it derives
391 /// from its knowledge of the structure of the various sets, leaving
392 /// to the caller the decision to use it or not.
393 fn bidirectional_sample(
394 &mut self,
395 size: usize,
396 ) -> Result<(HashSet<Revision>, usize), GraphError> {
397 self.ensure_undecided()?;
398 {
399 // we don't want to compute children_cache before this
400 // but doing it after extracting self.undecided takes a mutable
401 // ref to self while a shareable one is still active.
402 let undecided = self.undecided.as_ref().unwrap();
403 if undecided.len() <= size {
404 return Ok((undecided.clone(), size));
405 }
406 }
407
408 self.ensure_children_cache()?;
409 let revs = self.undecided.as_ref().unwrap();
410 let mut sample: HashSet<Revision> = revs.clone();
411
412 // it's possible that leveraging the children cache would be more
413 // efficient here
414 dagops::retain_heads(&self.graph, &mut sample)?;
415 let revsheads = sample.clone(); // was again heads(revs) in python
416
417 // update from heads
418 update_sample(
419 Some(revs),
420 revsheads.iter().cloned(),
421 &mut sample,
422 |r| ParentsIterator::graph_parents(&self.graph, r),
423 None,
424 )?;
425
426 // update from roots
427 let revroots: HashSet<Revision> =
428 dagops::roots(&self.graph, revs)?.into_iter().collect();
429 let prescribed_size = max(size, min(revroots.len(), revsheads.len()));
430
431 let children = self.children_cache.as_ref().unwrap();
432 let empty_vec: Vec<Revision> = Vec::new();
433 update_sample(
434 Some(revs),
435 revroots,
436 &mut sample,
437 |r| Ok(children.get(&r).unwrap_or(&empty_vec).iter().cloned()),
438 None,
439 )?;
440 Ok((sample, prescribed_size))
441 }
442
443 /// Fill up sample up to the wished size with random undecided Revisions.
444 ///
445 /// This is intended to be used as a last resort completion if the
446 /// regular sampling algorithm returns too few elements.
447 fn random_complete_sample(
448 &mut self,
449 sample: &mut Vec<Revision>,
450 size: usize,
451 ) {
452 let sample_len = sample.len();
453 if size <= sample_len {
454 return;
455 }
456 let take_from: Vec<Revision> = self
457 .undecided
458 .as_ref()
459 .unwrap()
460 .iter()
461 .filter(|&r| !sample.contains(r))
462 .cloned()
463 .collect();
464 sample.extend(self.limit_sample(take_from, size - sample_len));
465 }
466
467 pub fn take_full_sample(
468 &mut self,
469 size: usize,
470 ) -> Result<Vec<Revision>, GraphError> {
471 let (sample_set, prescribed_size) = self.bidirectional_sample(size)?;
472 let size = if self.respect_size {
473 size
474 } else {
475 prescribed_size
476 };
477 let mut sample =
478 self.limit_sample(sample_set.into_iter().collect(), size);
479 self.random_complete_sample(&mut sample, size);
480 Ok(sample)
481 }
482 }
483
484 #[cfg(test)]
485 mod tests {
486 use super::*;
487 use crate::testing::SampleGraph;
488
489 /// Shorthand to reduce boilerplate when creating [`Revision`] for testing
490 macro_rules! R {
491 ($revision:literal) => {
492 Revision($revision)
493 };
494 }
495
496 /// A PartialDiscovery as for pushing all the heads of `SampleGraph`
497 ///
498 /// To avoid actual randomness in these tests, we give it a fixed
499 /// random seed, but by default we'll test the random version.
500 fn full_disco() -> PartialDiscovery<SampleGraph> {
501 PartialDiscovery::new_with_seed(
502 SampleGraph,
503 vec![R!(10), R!(11), R!(12), R!(13)],
504 [0; 16],
505 true,
506 true,
507 )
508 }
509
510 /// A PartialDiscovery as for pushing the 12 head of `SampleGraph`
511 ///
512 /// To avoid actual randomness in tests, we give it a fixed random seed.
513 fn disco12() -> PartialDiscovery<SampleGraph> {
514 PartialDiscovery::new_with_seed(
515 SampleGraph,
516 vec![R!(12)],
517 [0; 16],
518 true,
519 true,
520 )
521 }
522
523 fn sorted_undecided(
524 disco: &PartialDiscovery<SampleGraph>,
525 ) -> Vec<Revision> {
526 let mut as_vec: Vec<Revision> =
527 disco.undecided.as_ref().unwrap().iter().cloned().collect();
528 as_vec.sort_unstable();
529 as_vec
530 }
531
532 fn sorted_missing(disco: &PartialDiscovery<SampleGraph>) -> Vec<Revision> {
533 let mut as_vec: Vec<Revision> = disco.missing.iter().cloned().collect();
534 as_vec.sort_unstable();
535 as_vec
536 }
537
538 fn sorted_common_heads(
539 disco: &PartialDiscovery<SampleGraph>,
540 ) -> Result<Vec<Revision>, GraphError> {
541 let mut as_vec: Vec<Revision> =
542 disco.common_heads()?.iter().cloned().collect();
543 as_vec.sort_unstable();
544 Ok(as_vec)
545 }
546
547 #[test]
548 fn test_add_common_get_undecided() -> Result<(), GraphError> {
549 let mut disco = full_disco();
550 assert_eq!(disco.undecided, None);
551 assert!(!disco.has_info());
552 assert_eq!(disco.stats().undecided, None);
553
554 disco.add_common_revisions(vec![R!(11), R!(12)])?;
555 assert!(disco.has_info());
556 assert!(!disco.is_complete());
557 assert!(disco.missing.is_empty());
558
559 // add_common_revisions did not trigger a premature computation
560 // of `undecided`, let's check that and ask for them
561 assert_eq!(disco.undecided, None);
562 disco.ensure_undecided()?;
563 assert_eq!(sorted_undecided(&disco), vec![5, 8, 10, 13]);
564 assert_eq!(disco.stats().undecided, Some(4));
565 Ok(())
566 }
567
568 /// in this test, we pretend that our peer misses exactly (8+10)::
569 /// and we're comparing all our repo to it (as in a bare push)
570 #[test]
571 fn test_discovery() -> Result<(), GraphError> {
572 let mut disco = full_disco();
573 disco.add_common_revisions(vec![R!(11), R!(12)])?;
574 disco.add_missing_revisions(vec![R!(8), R!(10)])?;
575 assert_eq!(sorted_undecided(&disco), vec![5]);
576 assert_eq!(sorted_missing(&disco), vec![8, 10, 13]);
577 assert!(!disco.is_complete());
578
579 disco.add_common_revisions(vec![R!(5)])?;
580 assert_eq!(sorted_undecided(&disco), Vec::<Revision>::new());
581 assert_eq!(sorted_missing(&disco), vec![8, 10, 13]);
582 assert!(disco.is_complete());
583 assert_eq!(sorted_common_heads(&disco)?, vec![5, 11, 12]);
584 Ok(())
585 }
586
587 #[test]
588 fn test_add_missing_early_continue() -> Result<(), GraphError> {
589 eprintln!("test_add_missing_early_stop");
590 let mut disco = full_disco();
591 disco.add_common_revisions(vec![R!(13), R!(3), R!(4)])?;
592 disco.ensure_children_cache()?;
593 // 12 is grand-child of 6 through 9
594 // passing them in this order maximizes the chances of the
595 // early continue to do the wrong thing
596 disco.add_missing_revisions(vec![R!(6), R!(9), R!(12)])?;
597 assert_eq!(sorted_undecided(&disco), vec![5, 7, 10, 11]);
598 assert_eq!(sorted_missing(&disco), vec![6, 9, 12]);
599 assert!(!disco.is_complete());
600 Ok(())
601 }
602
603 #[test]
604 fn test_limit_sample_no_need_to() {
605 let sample = vec![R!(1), R!(2), R!(3), R!(4)];
606 assert_eq!(full_disco().limit_sample(sample, 10), vec![1, 2, 3, 4]);
607 }
608
609 #[test]
610 fn test_limit_sample_less_than_half() {
611 assert_eq!(
612 full_disco().limit_sample((1..6).map(Revision).collect(), 2),
613 vec![3, 5]
614 );
615 }
616
617 #[test]
618 fn test_limit_sample_more_than_half() {
619 assert_eq!(
620 full_disco().limit_sample((1..4).map(Revision).collect(), 2),
621 vec![1, 3]
622 );
623 }
624
625 #[test]
626 fn test_limit_sample_no_random() {
627 let mut disco = full_disco();
628 disco.randomize = false;
629 assert_eq!(
630 disco.limit_sample(
631 vec![R!(1), R!(8), R!(13), R!(5), R!(7), R!(3)],
632 4
633 ),
634 vec![1, 3, 5, 7]
635 );
636 }
637
638 #[test]
639 fn test_quick_sample_enough_undecided_heads() -> Result<(), GraphError> {
640 let mut disco = full_disco();
641 disco.undecided = Some((1..=13).map(Revision).collect());
642
643 let mut sample_vec = disco.take_quick_sample(vec![], 4)?;
644 sample_vec.sort_unstable();
645 assert_eq!(sample_vec, vec![10, 11, 12, 13]);
646 Ok(())
647 }
648
649 #[test]
650 fn test_quick_sample_climbing_from_12() -> Result<(), GraphError> {
651 let mut disco = disco12();
652 disco.ensure_undecided()?;
653
654 let mut sample_vec = disco.take_quick_sample(vec![R!(12)], 4)?;
655 sample_vec.sort_unstable();
656 // r12's only parent is r9, whose unique grand-parent through the
657 // diamond shape is r4. This ends there because the distance from r4
658 // to the root is only 3.
659 assert_eq!(sample_vec, vec![4, 9, 12]);
660 Ok(())
661 }
662
663 #[test]
664 fn test_children_cache() -> Result<(), GraphError> {
665 let mut disco = full_disco();
666 disco.ensure_children_cache()?;
667
668 let cache = disco.children_cache.unwrap();
669 assert_eq!(cache.get(&R!(2)).cloned(), Some(vec![R!(4)]));
670 assert_eq!(cache.get(&R!(10)).cloned(), None);
671
672 let mut children_4 = cache.get(&R!(4)).cloned().unwrap();
673 children_4.sort_unstable();
674 assert_eq!(children_4, vec![R!(5), R!(6), R!(7)]);
675
676 let mut children_7 = cache.get(&R!(7)).cloned().unwrap();
677 children_7.sort_unstable();
678 assert_eq!(children_7, vec![R!(9), R!(11)]);
679
680 Ok(())
681 }
682
683 #[test]
684 fn test_complete_sample() {
685 let mut disco = full_disco();
686 let undecided: HashSet<Revision> =
687 [4, 7, 9, 2, 3].iter().cloned().map(Revision).collect();
688 disco.undecided = Some(undecided);
689
690 let mut sample = vec![R!(0)];
691 disco.random_complete_sample(&mut sample, 3);
692 assert_eq!(sample.len(), 3);
693
694 let mut sample = vec![R!(2), R!(4), R!(7)];
695 disco.random_complete_sample(&mut sample, 1);
696 assert_eq!(sample.len(), 3);
697 }
698
699 #[test]
700 fn test_bidirectional_sample() -> Result<(), GraphError> {
701 let mut disco = full_disco();
702 disco.undecided = Some((0..=13).map(Revision).collect());
703
704 let (sample_set, size) = disco.bidirectional_sample(7)?;
705 assert_eq!(size, 7);
706 let mut sample: Vec<Revision> = sample_set.into_iter().collect();
707 sample.sort_unstable();
708 // our DAG is a bit too small for the results to be really interesting
709 // at least it shows that
710 // - we went both ways
711 // - we didn't take all Revisions (6 is not in the sample)
712 assert_eq!(sample, vec![0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13]);
713 Ok(())
714 }
715 }