Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

revset: refactor collect_dag_range() and walk_*() helpers #2688

Merged
merged 4 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions lib/src/default_index_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use std::fmt::{Debug, Formatter};
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::{Read, Write};
use std::iter::FusedIterator;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::Arc;
Expand Down Expand Up @@ -1381,6 +1382,18 @@ impl<'a> RevWalk<'a> {
self.take_while(move |entry| entry.position() >= bottom_position)
}

/// Fully consumes the ancestors and walks back from `root_positions`.
///
/// The returned iterator yields entries in order of ascending index
/// position.
pub fn descendants(self, root_positions: &[IndexPosition]) -> RevWalkDescendants<'a> {
RevWalkDescendants {
candidate_entries: self.take_until_roots(root_positions).collect(),
root_positions: root_positions.iter().copied().collect(),
reachable_positions: HashSet::new(),
}
}

/// Fully consumes the ancestors and walks back from `root_positions` within
/// `generation_range`.
///
Expand Down Expand Up @@ -1589,6 +1602,46 @@ impl RevWalkItemGenerationRange {
}
}

/// Walks descendants from the roots, in order of ascending index position.
#[derive(Clone)]
pub struct RevWalkDescendants<'a> {
candidate_entries: Vec<IndexEntry<'a>>,
root_positions: HashSet<IndexPosition>,
reachable_positions: HashSet<IndexPosition>,
}

impl RevWalkDescendants<'_> {
/// Builds a set of index positions reachable from the roots.
///
/// This is equivalent to `.map(|entry| entry.position()).collect()` on
/// the new iterator, but returns the internal buffer instead.
pub fn collect_positions_set(mut self) -> HashSet<IndexPosition> {
self.by_ref().for_each(drop);
self.reachable_positions
}
}

impl<'a> Iterator for RevWalkDescendants<'a> {
type Item = IndexEntry<'a>;

fn next(&mut self) -> Option<Self::Item> {
while let Some(candidate) = self.candidate_entries.pop() {
if self.root_positions.contains(&candidate.position())
|| candidate
.parent_positions()
.iter()
.any(|parent_pos| self.reachable_positions.contains(parent_pos))
{
self.reachable_positions.insert(candidate.position());
return Some(candidate);
}
}
None
}
}

impl FusedIterator for RevWalkDescendants<'_> {}

/// Removes the greatest items (including duplicates) from the heap, returns
/// one.
fn dedup_pop<T: Ord>(heap: &mut BinaryHeap<T>) -> Option<T> {
Expand Down
131 changes: 44 additions & 87 deletions lib/src/default_revset_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ use std::sync::Arc;
use itertools::Itertools;

use crate::backend::{ChangeId, CommitId, MillisSinceEpoch};
use crate::default_index_store::{
CompositeIndex, IndexEntry, IndexEntryByPosition, IndexPosition, RevWalk,
};
use crate::default_index_store::{CompositeIndex, IndexEntry, IndexEntryByPosition, IndexPosition};
use crate::default_revset_graph_iterator::RevsetGraphIterator;
use crate::id_prefix::{IdIndex, IdIndexSource, IdIndexSourceEntry};
use crate::index::{HexPrefix, PrefixResolution};
Expand Down Expand Up @@ -538,7 +536,8 @@ impl<'index> EvaluationContext<'index> {
}
ResolvedExpression::Ancestors { heads, generation } => {
let head_set = self.evaluate(heads)?;
let walk = self.walk_ancestors(&*head_set);
let head_positions = head_set.iter().map(|entry| entry.position()).collect_vec();
let walk = self.index.walk_revs(&head_positions, &[]);
if generation == &GENERATION_RANGE_FULL {
Ok(Box::new(RevWalkRevset { walk }))
} else {
Expand Down Expand Up @@ -568,26 +567,47 @@ impl<'index> EvaluationContext<'index> {
heads,
generation_from_roots,
} => {
let index = self.index;
let root_set = self.evaluate(roots)?;
let root_positions = root_set.iter().map(|entry| entry.position()).collect_vec();
let head_set = self.evaluate(heads)?;
let head_positions = head_set.iter().map(|entry| entry.position()).collect_vec();
if generation_from_roots == &(1..2) {
Ok(Box::new(self.walk_children(&*root_set, &*head_set)))
let walk = index
.walk_revs(&head_positions, &[])
.take_until_roots(&root_positions);
let root_positions_set: HashSet<_> = root_positions.into_iter().collect();
let candidates = Box::new(RevWalkRevset { walk });
let predicate = PurePredicateFn(move |entry: &IndexEntry| {
entry
.parent_positions()
.iter()
.any(|parent_pos| root_positions_set.contains(parent_pos))
});
// TODO: Suppose heads include all visible heads, ToPredicateFn version can be
// optimized to only test the predicate()
Ok(Box::new(FilterRevset {
candidates,
predicate,
}))
} else if generation_from_roots == &GENERATION_RANGE_FULL {
let (dag_range_set, _) = self.collect_dag_range(&*root_set, &*head_set);
Ok(Box::new(dag_range_set))
let mut index_entries = index
.walk_revs(&head_positions, &[])
.descendants(&root_positions)
.collect_vec();
index_entries.reverse();
Ok(Box::new(EagerRevset { index_entries }))
} else {
// For small generation range, it might be better to build a reachable map
// with generation bit set, which can be calculated incrementally from roots:
// reachable[pos] = (reachable[parent_pos] | ...) << 1
let root_positions =
root_set.iter().map(|entry| entry.position()).collect_vec();
let walk = self
.walk_ancestors(&*head_set)
let mut index_entries = index
.walk_revs(&head_positions, &[])
.descendants_filtered_by_generation(
&root_positions,
to_u32_generation_range(generation_from_roots)?,
);
let mut index_entries = walk.collect_vec();
)
.collect_vec();
index_entries.reverse();
Ok(Box::new(EagerRevset { index_entries }))
}
Expand All @@ -605,12 +625,18 @@ impl<'index> EvaluationContext<'index> {
Ok(Box::new(EagerRevset { index_entries }))
}
ResolvedExpression::Roots(candidates) => {
let candidate_set = EagerRevset {
index_entries: self.evaluate(candidates)?.iter().collect(),
};
let (_, filled) = self.collect_dag_range(&candidate_set, &candidate_set);
let candidate_entries = self.evaluate(candidates)?.iter().collect_vec();
let candidate_positions = candidate_entries
.iter()
.map(|entry| entry.position())
.collect_vec();
let filled = self
.index
.walk_revs(&candidate_positions, &[])
.descendants(&candidate_positions)
.collect_positions_set();
let mut index_entries = vec![];
for candidate in candidate_set.iter() {
for candidate in candidate_entries {
if !candidate
.parent_positions()
.iter()
Expand Down Expand Up @@ -677,75 +703,6 @@ impl<'index> EvaluationContext<'index> {
}
}

fn walk_ancestors<'a, S>(&self, head_set: &S) -> RevWalk<'index>
where
S: InternalRevset<'a> + ?Sized,
{
let head_positions = head_set.iter().map(|entry| entry.position()).collect_vec();
self.index.walk_revs(&head_positions, &[])
}

fn walk_children<'a, 'b, S, T>(
&self,
root_set: &S,
head_set: &T,
) -> impl InternalRevset<'index> + 'index
where
S: InternalRevset<'a> + ?Sized,
T: InternalRevset<'b> + ?Sized,
{
let root_positions = root_set.iter().map(|entry| entry.position()).collect_vec();
let walk = self
.walk_ancestors(head_set)
.take_until_roots(&root_positions);
let root_positions: HashSet<_> = root_positions.into_iter().collect();
let candidates = Box::new(RevWalkRevset { walk });
let predicate = PurePredicateFn(move |entry: &IndexEntry| {
entry
.parent_positions()
.iter()
.any(|parent_pos| root_positions.contains(parent_pos))
});
// TODO: Suppose heads include all visible heads, ToPredicateFn version can be
// optimized to only test the predicate()
FilterRevset {
candidates,
predicate,
}
}

/// Calculates `root_set::head_set`.
fn collect_dag_range<'a, 'b, S, T>(
&self,
root_set: &S,
head_set: &T,
) -> (EagerRevset<'index>, HashSet<IndexPosition>)
where
S: InternalRevset<'a> + ?Sized,
T: InternalRevset<'b> + ?Sized,
{
let root_positions = root_set.iter().map(|entry| entry.position()).collect_vec();
let walk = self
.walk_ancestors(head_set)
.take_until_roots(&root_positions);
let root_positions: HashSet<_> = root_positions.into_iter().collect();
let mut reachable_positions = HashSet::new();
let mut index_entries = vec![];
for candidate in walk.collect_vec().into_iter().rev() {
if root_positions.contains(&candidate.position())
|| candidate
.parent_positions()
.iter()
.any(|parent_pos| reachable_positions.contains(parent_pos))
{
reachable_positions.insert(candidate.position());
index_entries.push(candidate);
}
}
index_entries.reverse();
(EagerRevset { index_entries }, reachable_positions)
}

fn revset_for_commit_ids(&self, commit_ids: &[CommitId]) -> EagerRevset<'index> {
let mut index_entries = vec![];
for id in commit_ids {
Expand Down