mod commit_dag;
use alloc::{collections::BTreeSet, vec::Vec};
use crate::{
collections::{Entry, Map, Set},
crypto::{
digest::Digest,
fingerprint::{Fingerprint, FingerprintSeed},
},
depth::{Depth, DepthMetric, MAX_STRATA_DEPTH},
fragment::{Fragment, FragmentSpec, checkpoint::Checkpoint, id::FragmentId},
id::SedimentreeId,
loose_commit::{LooseCommit, id::CommitId},
};
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct FingerprintSummary {
seed: FingerprintSeed,
commit_fingerprints: BTreeSet<Fingerprint<CommitId>>,
fragment_fingerprints: BTreeSet<Fingerprint<FragmentId>>,
}
impl FingerprintSummary {
#[must_use]
pub const fn new(
seed: FingerprintSeed,
commit_fingerprints: BTreeSet<Fingerprint<CommitId>>,
fragment_fingerprints: BTreeSet<Fingerprint<FragmentId>>,
) -> Self {
Self {
seed,
commit_fingerprints,
fragment_fingerprints,
}
}
#[must_use]
pub const fn seed(&self) -> &FingerprintSeed {
&self.seed
}
#[must_use]
pub const fn commit_fingerprints(&self) -> &BTreeSet<Fingerprint<CommitId>> {
&self.commit_fingerprints
}
#[must_use]
pub const fn fragment_fingerprints(&self) -> &BTreeSet<Fingerprint<FragmentId>> {
&self.fragment_fingerprints
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FingerprintDiff<'a> {
pub local_only_fragments: Vec<&'a Fragment>,
pub local_only_commits: Vec<&'a LooseCommit>,
pub remote_only_commit_fingerprints: Vec<Fingerprint<CommitId>>,
pub remote_only_fragment_fingerprints: Vec<Fingerprint<FragmentId>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diff<'a> {
pub left_missing_fragments: Vec<&'a Fragment>,
pub left_missing_commits: Vec<&'a LooseCommit>,
pub right_missing_fragments: Vec<&'a Fragment>,
pub right_missing_commits: Vec<&'a LooseCommit>,
}
#[derive(Default, Clone, PartialEq, Eq)]
#[cfg_attr(not(feature = "std"), derive(PartialOrd, Ord, Hash))]
pub struct Sedimentree {
fragments: Map<Digest<Fragment>, Fragment>,
commits: Map<Digest<LooseCommit>, LooseCommit>,
}
impl Sedimentree {
#[must_use]
pub fn new(fragments: Vec<Fragment>, commits: Vec<LooseCommit>) -> Self {
Self {
fragments: fragments
.into_iter()
.map(|f| (Digest::hash(&f), f))
.collect(),
commits: commits.into_iter().map(|c| (Digest::hash(&c), c)).collect(),
}
}
pub fn merge(&mut self, other: Sedimentree) {
self.fragments.extend(other.fragments);
self.commits.extend(other.commits);
}
#[must_use]
pub fn minimal_hash<M: DepthMetric>(&self, depth_metric: &M) -> MinimalTreeHash {
let minimal = self.minimize(depth_metric);
let mut digests: Vec<Digest<LooseCommit>> = minimal
.fragments()
.flat_map(|s| core::iter::once(s.head()).chain(s.boundary().iter().copied()))
.chain(minimal.commits.keys().copied())
.collect();
digests.sort();
let mut h = blake3::Hasher::new();
for d in &digests {
h.update(d.as_bytes());
}
let mut checkpoints: Vec<Checkpoint> = minimal
.fragments()
.flat_map(|s| s.checkpoints().iter().copied())
.collect();
checkpoints.sort();
for cp in &checkpoints {
h.update(cp.as_bytes());
}
MinimalTreeHash(*h.finalize().as_bytes())
}
pub fn add_commit(&mut self, commit: LooseCommit) -> bool {
let digest = Digest::hash(&commit);
match self.commits.entry(digest) {
Entry::Vacant(e) => {
e.insert(commit);
true
}
Entry::Occupied(_) => false,
}
}
pub fn add_fragment(&mut self, fragment: Fragment) -> bool {
let digest = Digest::hash(&fragment);
match self.fragments.entry(digest) {
Entry::Vacant(e) => {
e.insert(fragment);
true
}
Entry::Occupied(_) => false,
}
}
#[must_use]
pub fn diff<'a>(&'a self, other: &'a Sedimentree) -> Diff<'a> {
let self_commit_keys: Set<_> = self.commits.keys().collect();
let other_commit_keys: Set<_> = other.commits.keys().collect();
let self_fragment_keys: Set<_> = self.fragments.keys().collect();
let other_fragment_keys: Set<_> = other.fragments.keys().collect();
Diff {
left_missing_fragments: other_fragment_keys
.difference(&self_fragment_keys)
.filter_map(|k| other.fragments.get(k))
.collect(),
left_missing_commits: other_commit_keys
.difference(&self_commit_keys)
.filter_map(|k| other.commits.get(k))
.collect(),
right_missing_fragments: self_fragment_keys
.difference(&other_fragment_keys)
.filter_map(|k| self.fragments.get(k))
.collect(),
right_missing_commits: self_commit_keys
.difference(&other_commit_keys)
.filter_map(|k| self.commits.get(k))
.collect(),
}
}
pub fn fragments(&self) -> impl Iterator<Item = &Fragment> {
self.fragments.values()
}
pub fn loose_commits(&self) -> impl Iterator<Item = &LooseCommit> {
self.commits.values()
}
#[must_use]
pub fn has_loose_commit(&self, digest: Digest<LooseCommit>) -> bool {
self.commits.contains_key(&digest)
}
#[must_use]
pub fn has_fragment_starting_with<M: DepthMetric>(
&self,
digest: Digest<LooseCommit>,
depth_metric: &M,
) -> bool {
self.heads(depth_metric).contains(&digest)
}
#[must_use]
pub fn minimize<M: DepthMetric>(&self, depth_metric: &M) -> Sedimentree {
let mut by_depth: Map<Depth, Vec<&Fragment>> = Map::new();
for fragment in self.fragments.values() {
by_depth
.entry(fragment.depth(depth_metric))
.or_default()
.push(fragment);
}
let mut depths: Vec<Depth> = by_depth.keys().copied().collect();
depths.sort_by(|a, b| b.cmp(a));
let mut minimized_fragments = Vec::<Fragment>::new();
let mut supported: Set<Checkpoint> = Set::new();
for depth in depths {
if let Some(group) = by_depth.remove(&depth) {
for fragment in group {
let dominated = supported.contains(&Checkpoint::new(fragment.head()))
&& fragment
.summary()
.boundary()
.iter()
.all(|b| supported.contains(&Checkpoint::new(*b)));
if !dominated {
supported.insert(Checkpoint::new(fragment.head()));
supported.extend(fragment.checkpoints().iter().copied());
for b in fragment.summary().boundary() {
supported.insert(Checkpoint::new(*b));
}
minimized_fragments.push(fragment.clone());
}
}
}
}
let dag = commit_dag::CommitDag::from_commits(self.commits.values());
let simplified_dag = dag.simplify(&minimized_fragments, depth_metric);
let commits = self
.commits
.iter()
.filter(|(digest, _)| simplified_dag.contains_commit(digest))
.map(|(_, c)| c.clone())
.collect();
Sedimentree::new(minimized_fragments, commits)
}
#[must_use]
pub fn fingerprint_summarize(&self, seed: &FingerprintSeed) -> FingerprintSummary {
let commit_fingerprints = self
.commits
.values()
.map(|c| Fingerprint::new(seed, &c.commit_id()))
.collect();
let fragment_fingerprints = self
.fragments
.values()
.map(|f| Fingerprint::new(seed, &f.fragment_id()))
.collect();
FingerprintSummary::new(*seed, commit_fingerprints, fragment_fingerprints)
}
#[must_use]
pub fn diff_remote_fingerprints<'a>(
&'a self,
remote: &FingerprintSummary,
) -> FingerprintDiff<'a> {
let seed = remote.seed();
let local_only_commits: Vec<&LooseCommit> = self
.commits
.values()
.filter(|c| {
!remote
.commit_fingerprints
.contains(&Fingerprint::new(seed, &c.commit_id()))
})
.collect();
let local_only_fragments: Vec<&Fragment> = self
.fragments
.values()
.filter(|f| {
!remote
.fragment_fingerprints
.contains(&Fingerprint::new(seed, &f.fragment_id()))
})
.collect();
let local_commit_fps: BTreeSet<Fingerprint<CommitId>> = self
.commits
.values()
.map(|c| Fingerprint::new(seed, &c.commit_id()))
.collect();
let local_fragment_fps: BTreeSet<Fingerprint<FragmentId>> = self
.fragments
.values()
.map(|f| Fingerprint::new(seed, &f.fragment_id()))
.collect();
let remote_only_commit_fingerprints: Vec<Fingerprint<CommitId>> = remote
.commit_fingerprints
.iter()
.filter(|fp| !local_commit_fps.contains(fp))
.copied()
.collect();
let remote_only_fragment_fingerprints: Vec<Fingerprint<FragmentId>> = remote
.fragment_fingerprints
.iter()
.filter(|fp| !local_fragment_fps.contains(fp))
.copied()
.collect();
FingerprintDiff {
local_only_fragments,
local_only_commits,
remote_only_commit_fingerprints,
remote_only_fragment_fingerprints,
}
}
#[must_use]
pub fn heads<M: DepthMetric>(&self, depth_metric: &M) -> Vec<Digest<LooseCommit>> {
let minimized = self.minimize(depth_metric);
let dag = commit_dag::CommitDag::from_commits(minimized.commits.values());
let mut heads = Vec::<Digest<LooseCommit>>::new();
for fragment in minimized.fragments.values() {
if !minimized
.fragments
.values()
.any(|s| s.boundary().contains(&fragment.head()))
&& fragment
.boundary()
.iter()
.all(|end| !dag.contains_commit(end))
{
heads.extend(fragment.boundary().iter().copied());
}
}
heads.extend(dag.heads());
heads
}
pub fn into_items(self) -> impl Iterator<Item = CommitOrFragment> {
self.fragments
.into_values()
.map(CommitOrFragment::Fragment)
.chain(self.commits.into_values().map(CommitOrFragment::Commit))
}
#[must_use]
pub fn missing_fragments<M: DepthMetric>(
&self,
id: SedimentreeId,
seed: &FingerprintSeed,
depth_metric: &M,
) -> Vec<FragmentSpec> {
let dag = commit_dag::CommitDag::from_commits(self.commits.values());
let mut runs_by_level =
Map::<crate::depth::Depth, (Digest<LooseCommit>, Vec<Digest<LooseCommit>>)>::new();
let mut all_bundles = Vec::new();
let fragment_refs: Vec<&Fragment> = self.fragments.values().collect();
for commit_hash in dag.canonical_sequence(&fragment_refs, depth_metric) {
let level = depth_metric.to_depth(commit_hash);
for (run_level, (_start, checkpoints)) in &mut runs_by_level {
if run_level < &level {
checkpoints.push(commit_hash);
}
}
if level >= MAX_STRATA_DEPTH
&& let Some((head, checkpoints)) = runs_by_level.remove(&level)
{
if self
.fragments
.values()
.any(|s| s.supports_block(commit_hash))
{
runs_by_level.insert(level, (commit_hash, Vec::new()));
} else {
let checkpoint_fps = checkpoints
.iter()
.map(|d| {
Fingerprint::new(
seed,
&CommitId::new(Digest::force_from_bytes(d.into_bytes())),
)
})
.collect();
all_bundles.push(FragmentSpec::new(
id,
head,
*seed,
checkpoint_fps,
BTreeSet::from([commit_hash]),
));
}
}
}
all_bundles
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommitOrFragment {
Commit(LooseCommit),
Fragment(Fragment),
}
impl core::fmt::Debug for Sedimentree {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Sedimentree")
.field("fragments", &self.fragments.len())
.field("commits", &self.commits.len())
.finish()
}
}
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Sedimentree {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let fragments: Vec<Fragment> = u.arbitrary()?;
let commits: Vec<LooseCommit> = u.arbitrary()?;
Ok(Self::new(fragments, commits))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct MinimalTreeHash([u8; 32]);
impl MinimalTreeHash {
#[must_use]
pub const fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
impl From<[u8; 32]> for MinimalTreeHash {
fn from(value: [u8; 32]) -> Self {
Self(value)
}
}
pub fn has_commit_boundary<
I: IntoIterator<Item = D>,
D: Into<Digest<LooseCommit>>,
M: DepthMetric,
>(
commits: I,
depth_metric: &M,
) -> bool {
commits
.into_iter()
.any(|digest| depth_metric.to_depth(digest.into()) <= MAX_STRATA_DEPTH)
}
#[cfg(test)]
mod tests {
use alloc::vec;
use crate::blob::{Blob, BlobMeta};
use super::*;
fn make_sedimentree_id(seed: u8) -> SedimentreeId {
SedimentreeId::new([seed; 32])
}
fn make_blob_meta(seed: u8) -> BlobMeta {
let blob = Blob::new(vec![seed]);
BlobMeta::new(&blob)
}
fn make_commit(seed: u8) -> LooseCommit {
let sedimentree_id = make_sedimentree_id(seed);
let blob = Blob::from(&[seed][..]);
let blob_meta = BlobMeta::new(&blob);
LooseCommit::new(sedimentree_id, BTreeSet::new(), blob_meta)
}
fn make_fragment(seed: u8) -> Fragment {
let sedimentree_id = make_sedimentree_id(seed);
let mut head_bytes = [0u8; 32];
head_bytes[0] = seed;
let mut boundary_bytes = [0u8; 32];
boundary_bytes[0] = seed;
boundary_bytes[1] = 1;
let blob = Blob::from(&[seed][..]);
let blob_meta = BlobMeta::new(&blob);
Fragment::new(
sedimentree_id,
Digest::force_from_bytes(head_bytes),
BTreeSet::from([Digest::force_from_bytes(boundary_bytes)]),
&[],
blob_meta,
)
}
#[test]
fn diff_identical_non_empty_trees() {
let commits = vec![make_commit(1), make_commit(2), make_commit(3)];
let fragments = vec![make_fragment(1), make_fragment(2)];
let a = Sedimentree::new(fragments.clone(), commits.clone());
let b = Sedimentree::new(fragments, commits);
let diff = a.diff(&b);
assert!(
diff.left_missing_commits.is_empty(),
"identical trees have no left missing commits"
);
assert!(
diff.right_missing_commits.is_empty(),
"identical trees have no right missing commits"
);
assert!(
diff.left_missing_fragments.is_empty(),
"identical trees have no left missing fragments"
);
assert!(
diff.right_missing_fragments.is_empty(),
"identical trees have no right missing fragments"
);
}
#[test]
fn diff_superset_commits() {
let shared = vec![make_commit(1), make_commit(2)];
let extra = vec![make_commit(3), make_commit(4)];
let a = Sedimentree::new(vec![], shared.clone());
let b = Sedimentree::new(vec![], [shared, extra.clone()].concat());
let diff = a.diff(&b);
assert_eq!(diff.left_missing_commits.len(), 2);
assert!(diff.right_missing_commits.is_empty());
assert!(diff.left_missing_fragments.is_empty());
assert!(diff.right_missing_fragments.is_empty());
}
#[test]
fn diff_superset_fragments() {
let shared = vec![make_fragment(1), make_fragment(2)];
let extra = vec![make_fragment(3)];
let a = Sedimentree::new(shared.clone(), vec![]);
let b = Sedimentree::new([shared, extra].concat(), vec![]);
let diff = a.diff(&b);
assert_eq!(diff.left_missing_fragments.len(), 1);
assert!(diff.right_missing_fragments.is_empty());
assert!(diff.left_missing_commits.is_empty());
assert!(diff.right_missing_commits.is_empty());
}
#[test]
fn diff_diverged_with_overlap() {
let shared_commits = vec![make_commit(1), make_commit(2)];
let a_only_commits = vec![make_commit(10), make_commit(11)];
let b_only_commits = vec![make_commit(20), make_commit(21), make_commit(22)];
let shared_fragments = vec![make_fragment(1)];
let a_only_fragments = vec![make_fragment(10)];
let b_only_fragments = vec![make_fragment(20), make_fragment(21)];
let a = Sedimentree::new(
[shared_fragments.clone(), a_only_fragments.clone()].concat(),
[shared_commits.clone(), a_only_commits.clone()].concat(),
);
let b = Sedimentree::new(
[shared_fragments, b_only_fragments].concat(),
[shared_commits, b_only_commits].concat(),
);
let diff = a.diff(&b);
assert_eq!(diff.left_missing_commits.len(), 3); assert_eq!(diff.left_missing_fragments.len(), 2);
assert_eq!(diff.right_missing_commits.len(), 2); assert_eq!(diff.right_missing_fragments.len(), 1); }
#[cfg(all(test, feature = "bolero"))]
#[allow(clippy::similar_names)]
mod proptests {
use alloc::vec;
use core::sync::atomic::{AtomicU64, Ordering};
use rand::{Rng, SeedableRng, rngs::SmallRng};
use crate::{blob::BlobMeta, commit::CountLeadingZeroBytes, fragment::FragmentSummary};
use super::super::*;
static SEED_COUNTER: AtomicU64 = AtomicU64::new(0);
fn hash_with_leading_zeros(zeros_count: u32) -> Digest<LooseCommit> {
let seed = SEED_COUNTER.fetch_add(1, Ordering::Relaxed);
let mut rng = SmallRng::seed_from_u64(seed);
let mut byte_arr: [u8; 32] = rng.r#gen::<[u8; 32]>();
for slot in byte_arr.iter_mut().take(zeros_count as usize) {
*slot = 0;
}
if (zeros_count as usize) < 32 {
let idx = zeros_count as usize;
#[allow(clippy::indexing_slicing)]
if byte_arr[idx] == 0 {
byte_arr[idx] = 1; }
}
Digest::force_from_bytes(byte_arr)
}
#[test]
fn fragment_supports_higher_levels() {
#[derive(Debug)]
struct Scenario {
deeper: Fragment,
shallower: FragmentSummary,
}
impl<'a> arbitrary::Arbitrary<'a> for Scenario {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
#[allow(clippy::enum_variant_names)]
#[derive(arbitrary::Arbitrary)]
enum ShallowerDepthType {
StartsAtStartBoundaryAtCheckpoint,
StartsAtCheckpointBoundaryAtCheckpoint,
StartsAtCheckpointBoundaryAtBoundary,
}
let start_hash = hash_with_leading_zeros(10);
let deeper_boundary_hash = hash_with_leading_zeros(10);
let shallower_start_hash: Digest<LooseCommit>;
let shallower_boundary_hash: Digest<LooseCommit>;
let mut checkpoints = Vec::<Digest<LooseCommit>>::arbitrary(u)?;
let lower_level_type = ShallowerDepthType::arbitrary(u)?;
match lower_level_type {
ShallowerDepthType::StartsAtStartBoundaryAtCheckpoint => {
shallower_start_hash = start_hash;
shallower_boundary_hash = hash_with_leading_zeros(9);
checkpoints.push(shallower_boundary_hash);
}
ShallowerDepthType::StartsAtCheckpointBoundaryAtCheckpoint => {
shallower_start_hash = hash_with_leading_zeros(9);
shallower_boundary_hash = hash_with_leading_zeros(9);
checkpoints.push(shallower_start_hash);
checkpoints.push(shallower_boundary_hash);
}
ShallowerDepthType::StartsAtCheckpointBoundaryAtBoundary => {
shallower_start_hash = hash_with_leading_zeros(9);
checkpoints.push(shallower_start_hash);
shallower_boundary_hash = deeper_boundary_hash;
}
}
let deeper = Fragment::new(
SedimentreeId::arbitrary(u)?,
start_hash,
BTreeSet::from([deeper_boundary_hash]),
&checkpoints,
BlobMeta::arbitrary(u)?,
);
let shallower = FragmentSummary::new(
shallower_start_hash,
BTreeSet::from([shallower_boundary_hash]),
BlobMeta::arbitrary(u)?,
);
Ok(Self { deeper, shallower })
}
}
bolero::check!().with_arbitrary::<Scenario>().for_each(
|Scenario { deeper, shallower }| {
assert!(deeper.supports(shallower, &CountLeadingZeroBytes));
},
);
}
#[test]
fn minimized_loose_commit_dag_doesnt_change() {
#[derive(Debug)]
struct Scenario {
commits: Vec<LooseCommit>,
}
impl<'a> arbitrary::Arbitrary<'a> for Scenario {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let sedimentree_id = SedimentreeId::arbitrary(u)?;
let mut frontier: Vec<Digest<LooseCommit>> = Vec::new();
let num_commits: u32 = u.int_in_range(1..=20)?;
let mut result = Vec::with_capacity(num_commits as usize);
for _ in 0..num_commits {
let contents = Vec::<u8>::arbitrary(u)?;
let blob = crate::blob::Blob::from(contents);
let blob_meta = BlobMeta::new(&blob);
let mut parents = BTreeSet::new();
let mut num_parents = u.int_in_range(0..=frontier.len())?;
let mut parent_choices = frontier.iter().collect::<Vec<_>>();
while num_parents > 0 {
let parent = u.choose(&parent_choices)?;
parents.insert(**parent);
#[allow(clippy::unwrap_used)]
parent_choices
.remove(parent_choices.iter().position(|p| p == parent).unwrap());
num_parents -= 1;
}
let commit = LooseCommit::new(sedimentree_id, parents, blob_meta);
frontier.retain(|p| !commit.parents().contains(p));
frontier.push(Digest::hash(&commit));
result.push(commit);
}
Ok(Scenario { commits: result })
}
}
bolero::check!()
.with_arbitrary::<Scenario>()
.for_each(|Scenario { commits }| {
let tree = Sedimentree::new(vec![], commits.clone());
let minimized = tree.minimize(&CountLeadingZeroBytes);
assert_eq!(tree, minimized);
});
}
#[test]
fn diff_self_is_empty() {
bolero::check!()
.with_arbitrary::<Sedimentree>()
.for_each(|tree| {
let diff = tree.diff(tree);
assert!(
diff.left_missing_fragments.is_empty(),
"self-diff should have no left missing fragments"
);
assert!(
diff.left_missing_commits.is_empty(),
"self-diff should have no left missing commits"
);
assert!(
diff.right_missing_fragments.is_empty(),
"self-diff should have no right missing fragments"
);
assert!(
diff.right_missing_commits.is_empty(),
"self-diff should have no right missing commits"
);
});
}
#[test]
fn diff_is_symmetric() {
bolero::check!()
.with_arbitrary::<(Sedimentree, Sedimentree)>()
.for_each(|(a, b)| {
let ab = a.diff(b);
let ba = b.diff(a);
assert_eq!(
ab.left_missing_fragments.len(),
ba.right_missing_fragments.len(),
"left_missing in a.diff(b) should equal right_missing in b.diff(a)"
);
assert_eq!(
ab.right_missing_fragments.len(),
ba.left_missing_fragments.len(),
"right_missing in a.diff(b) should equal left_missing in b.diff(a)"
);
assert_eq!(
ab.left_missing_commits.len(),
ba.right_missing_commits.len(),
"left_missing commits in a.diff(b) should equal right_missing in b.diff(a)"
);
assert_eq!(
ab.right_missing_commits.len(),
ba.left_missing_commits.len(),
"right_missing commits in a.diff(b) should equal left_missing in b.diff(a)"
);
});
}
#[test]
fn diff_merge_produces_equal_trees() {
bolero::check!()
.with_arbitrary::<(Sedimentree, Sedimentree)>()
.for_each(|(a, b)| {
let diff = a.diff(b);
let mut a_updated = a.clone();
let mut b_updated = b.clone();
for fragment in diff.left_missing_fragments {
a_updated.add_fragment(fragment.clone());
}
for commit in diff.left_missing_commits {
a_updated.add_commit(commit.clone());
}
for fragment in diff.right_missing_fragments {
b_updated.add_fragment(fragment.clone());
}
for commit in diff.right_missing_commits {
b_updated.add_commit(commit.clone());
}
assert_eq!(
a_updated, b_updated,
"after applying diff, trees should be equal"
);
});
}
#[test]
fn minimize_output_subset_of_input() {
bolero::check!()
.with_arbitrary::<Sedimentree>()
.for_each(|tree| {
let minimized = tree.minimize(&CountLeadingZeroBytes);
let input_set: Set<_> = tree.fragments().cloned().collect();
for fragment in minimized.fragments() {
assert!(
input_set.contains(fragment),
"minimized output contains fragment not in input"
);
}
});
}
#[test]
fn minimize_no_mutual_support() {
bolero::check!()
.with_arbitrary::<Sedimentree>()
.for_each(|tree| {
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments: Vec<_> = minimized.fragments().collect();
for (i, f1) in fragments.iter().enumerate() {
for (j, f2) in fragments.iter().enumerate() {
if i != j {
assert!(
!f1.supports(f2.summary(), &CountLeadingZeroBytes),
"fragment {i} supports fragment {j} in minimized output"
);
}
}
}
});
}
#[test]
fn minimize_idempotent() {
bolero::check!()
.with_arbitrary::<Sedimentree>()
.for_each(|tree| {
let once = tree.minimize(&CountLeadingZeroBytes);
let twice = once.minimize(&CountLeadingZeroBytes);
let once_set: Set<_> = once.fragments().cloned().collect();
let twice_set: Set<_> = twice.fragments().cloned().collect();
assert_eq!(
once_set, twice_set,
"minimize should be idempotent: minimize(minimize(x)) == minimize(x)"
);
});
}
}
#[allow(clippy::similar_names)]
mod minimize_tests {
use alloc::{collections::BTreeSet, vec, vec::Vec};
use super::{make_blob_meta, make_sedimentree_id};
use crate::{
commit::CountLeadingZeroBytes,
fragment::Fragment,
sedimentree::Sedimentree,
test_utils::{digest_with_depth, make_fragment_at_depth},
};
fn collect_fragments(tree: &Sedimentree) -> Vec<Fragment> {
tree.fragments().cloned().collect()
}
#[test]
fn minimize_empty_sedimentree() {
let tree = Sedimentree::new(vec![], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
assert_eq!(minimized.fragments().count(), 0);
assert_eq!(minimized.loose_commits().count(), 0);
}
#[test]
fn minimize_single_fragment() {
let boundary_digest = digest_with_depth(1, 100);
let fragment = make_fragment_at_depth(2, 1, BTreeSet::from([boundary_digest]), &[]);
let tree = Sedimentree::new(vec![fragment.clone()], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments = collect_fragments(&minimized);
assert_eq!(fragments.len(), 1);
assert!(fragments.contains(&fragment));
}
#[test]
fn minimize_multi_depth_deep_dominates_shallow() {
let deep_boundary = digest_with_depth(1, 100);
let shallow_head = digest_with_depth(2, 1);
let shallow_boundary = digest_with_depth(1, 101);
let deep_fragment = make_fragment_at_depth(
3,
1,
BTreeSet::from([deep_boundary]),
&[shallow_head, shallow_boundary],
);
let shallow_fragment =
make_fragment_at_depth(2, 1, BTreeSet::from([shallow_boundary]), &[]);
let tree = Sedimentree::new(
vec![deep_fragment.clone(), shallow_fragment.clone()],
vec![],
);
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments = collect_fragments(&minimized);
assert_eq!(fragments.len(), 1);
assert!(fragments.contains(&deep_fragment));
assert!(!fragments.contains(&shallow_fragment));
}
#[test]
fn minimize_same_depth_partial_overlap_keeps_both() {
let boundary1 = digest_with_depth(1, 100);
let boundary2 = digest_with_depth(1, 101);
let fragment1 = make_fragment_at_depth(2, 1, BTreeSet::from([boundary1]), &[]);
let fragment2 = make_fragment_at_depth(2, 2, BTreeSet::from([boundary2]), &[]);
let tree = Sedimentree::new(vec![fragment1.clone(), fragment2.clone()], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments = collect_fragments(&minimized);
assert_eq!(fragments.len(), 2);
assert!(fragments.contains(&fragment1));
assert!(fragments.contains(&fragment2));
}
#[test]
fn minimize_all_same_depth() {
let input_fragments: Vec<Fragment> = (0..5)
.map(|i| {
let boundary = digest_with_depth(1, 100 + i);
make_fragment_at_depth(2, i, BTreeSet::from([boundary]), &[])
})
.collect();
let tree = Sedimentree::new(input_fragments.clone(), vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments = collect_fragments(&minimized);
assert_eq!(fragments.len(), 5);
for fragment in &input_fragments {
assert!(fragments.contains(fragment));
}
}
#[test]
fn minimize_deep_partial_support_keeps_shallow() {
let deep_boundary = digest_with_depth(1, 100);
let shallow_head = digest_with_depth(2, 1);
let shallow_boundary = digest_with_depth(1, 101);
let deep_fragment = make_fragment_at_depth(
3,
1,
BTreeSet::from([deep_boundary]),
&[shallow_head], );
let shallow_fragment =
make_fragment_at_depth(2, 1, BTreeSet::from([shallow_boundary]), &[]);
let tree = Sedimentree::new(
vec![deep_fragment.clone(), shallow_fragment.clone()],
vec![],
);
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments = collect_fragments(&minimized);
assert_eq!(fragments.len(), 2);
}
#[test]
fn minimize_collective_support() {
let shallow_head = digest_with_depth(2, 1);
let shallow_boundary = digest_with_depth(1, 101);
let deep1_boundary = digest_with_depth(1, 100);
let deep1 =
make_fragment_at_depth(3, 1, BTreeSet::from([deep1_boundary]), &[shallow_head]);
let deep2_boundary = digest_with_depth(1, 102);
let deep2 =
make_fragment_at_depth(3, 2, BTreeSet::from([deep2_boundary]), &[shallow_boundary]);
let shallow = make_fragment_at_depth(2, 1, BTreeSet::from([shallow_boundary]), &[]);
let tree =
Sedimentree::new(vec![deep1.clone(), deep2.clone(), shallow.clone()], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments = collect_fragments(&minimized);
assert_eq!(fragments.len(), 2);
assert!(fragments.contains(&deep1));
assert!(fragments.contains(&deep2));
assert!(!fragments.contains(&shallow));
}
#[test]
fn minimize_unsupported_shallow_kept() {
let deep_boundary = digest_with_depth(1, 100);
let deep_checkpoint = digest_with_depth(2, 50);
let deep =
make_fragment_at_depth(3, 1, BTreeSet::from([deep_boundary]), &[deep_checkpoint]);
let shallow_boundary = digest_with_depth(1, 200);
let shallow = make_fragment_at_depth(2, 10, BTreeSet::from([shallow_boundary]), &[]);
let tree = Sedimentree::new(vec![deep.clone(), shallow.clone()], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments = collect_fragments(&minimized);
assert_eq!(fragments.len(), 2);
assert!(fragments.contains(&deep));
assert!(fragments.contains(&shallow));
}
#[test]
fn minimize_fragment_empty_checkpoints() {
let boundary = digest_with_depth(1, 100);
let fragment = make_fragment_at_depth(2, 1, BTreeSet::from([boundary]), &[]);
let tree = Sedimentree::new(vec![fragment.clone()], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
assert_eq!(minimized.fragments().count(), 1);
}
#[test]
fn minimize_fragment_empty_boundary() {
let sedimentree_id = make_sedimentree_id(1);
let head = digest_with_depth(2, 1);
let blob_meta = make_blob_meta(1);
let fragment = Fragment::new(sedimentree_id, head, BTreeSet::new(), &[], blob_meta);
let tree = Sedimentree::new(vec![fragment.clone()], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
assert_eq!(minimized.fragments().count(), 1);
}
#[test]
fn minimize_head_equals_boundary() {
let sedimentree_id = make_sedimentree_id(1);
let head = digest_with_depth(2, 1);
let blob_meta = make_blob_meta(1);
let fragment =
Fragment::new(sedimentree_id, head, BTreeSet::from([head]), &[], blob_meta);
let tree = Sedimentree::new(vec![fragment.clone()], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
assert_eq!(minimized.fragments().count(), 1);
}
#[test]
fn minimize_head_in_checkpoints() {
let sedimentree_id = make_sedimentree_id(1);
let head = digest_with_depth(2, 1);
let boundary = digest_with_depth(1, 100);
let blob_meta = make_blob_meta(1);
let fragment = Fragment::new(
sedimentree_id,
head,
BTreeSet::from([boundary]),
&[head],
blob_meta,
);
let tree = Sedimentree::new(vec![fragment.clone()], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
assert_eq!(minimized.fragments().count(), 1);
}
#[test]
fn minimize_output_subset_of_input() {
let input_fragments: Vec<Fragment> = (0..10)
.map(|i| {
let boundary = digest_with_depth(1, 100 + i);
make_fragment_at_depth(2, i, BTreeSet::from([boundary]), &[])
})
.collect();
let tree = Sedimentree::new(input_fragments.clone(), vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
for fragment in minimized.fragments() {
assert!(
input_fragments.contains(fragment),
"minimized output contains fragment not in input"
);
}
}
#[test]
fn minimize_no_mutual_support_in_output() {
let deep_boundary = digest_with_depth(1, 100);
let shallow_head = digest_with_depth(2, 1);
let shallow_boundary = digest_with_depth(1, 101);
let deep = make_fragment_at_depth(
3,
1,
BTreeSet::from([deep_boundary]),
&[shallow_head, shallow_boundary],
);
let shallow = make_fragment_at_depth(2, 1, BTreeSet::from([shallow_boundary]), &[]);
let unrelated =
make_fragment_at_depth(2, 5, BTreeSet::from([digest_with_depth(1, 200)]), &[]);
let tree = Sedimentree::new(vec![deep, shallow, unrelated], vec![]);
let minimized = tree.minimize(&CountLeadingZeroBytes);
let fragments = collect_fragments(&minimized);
for (i, f1) in fragments.iter().enumerate() {
for (j, f2) in fragments.iter().enumerate() {
if i != j {
assert!(
!f1.supports(f2.summary(), &CountLeadingZeroBytes),
"fragment {i} supports fragment {j} in minimized output"
);
}
}
}
}
#[test]
fn minimize_idempotent() {
let deep_boundary = digest_with_depth(1, 100);
let shallow_head = digest_with_depth(2, 1);
let shallow_boundary = digest_with_depth(1, 101);
let deep = make_fragment_at_depth(
3,
1,
BTreeSet::from([deep_boundary]),
&[shallow_head, shallow_boundary],
);
let shallow = make_fragment_at_depth(2, 1, BTreeSet::from([shallow_boundary]), &[]);
let tree = Sedimentree::new(vec![deep, shallow], vec![]);
let minimized1 = tree.minimize(&CountLeadingZeroBytes);
let minimized2 = minimized1.minimize(&CountLeadingZeroBytes);
let fragments1 = collect_fragments(&minimized1);
let fragments2 = collect_fragments(&minimized2);
assert_eq!(
fragments1.len(),
fragments2.len(),
"minimize should be idempotent"
);
for f in &fragments1 {
assert!(fragments2.contains(f));
}
}
}
}