Skip to main content

gix_commitgraph/
verify.rs

1//! Auxiliary types used by graph verification methods.
2use gix_error::Result;
3use std::{
4    cmp::{max, min},
5    collections::BTreeMap,
6};
7
8use gix_error::{ResultExt, bail};
9
10use crate::{
11    GENERATION_NUMBER_MAX, Graph,
12    file::{self},
13};
14
15/// Statistics gathered while verifying the integrity of the graph as returned by [`Graph::verify_integrity()`].
16#[derive(Clone, Debug, Eq, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
18pub struct Outcome {
19    /// The length of the longest path between any two commits in this graph.
20    ///
21    /// For example, this will be `Some(9)` for a commit graph containing 10 linear commits.
22    /// This will be `Some(0)` for a commit graph containing 0 or 1 commits.
23    /// If the longest path length is too large to fit in a [u32], then this will be [None].
24    pub longest_path_length: Option<u32>,
25    /// The total number of commits traversed.
26    pub num_commits: u32,
27    /// A mapping of `N -> number of commits with N parents`.
28    pub parent_counts: BTreeMap<u32, u32>,
29}
30
31impl Graph {
32    /// Traverse all commits in the graph and call `processor(&commit) -> Result<(), E>` on it while verifying checksums.
33    ///
34    /// When `processor` returns an error, the entire verification is stopped and the error returned.
35    pub fn verify_integrity<E>(
36        &self,
37        mut processor: impl FnMut(&file::Commit<'_>) -> std::result::Result<(), E>,
38    ) -> Result<Outcome>
39    where
40        E: std::error::Error + Send + Sync + 'static,
41    {
42        let mut stats = Outcome {
43            longest_path_length: None,
44            num_commits: 0,
45            parent_counts: BTreeMap::new(),
46        };
47        let mut max_generation = 0u32;
48
49        // TODO: Detect duplicate commit IDs across different files. Not sure how to do this without
50        //   a separate loop, e.g. self.iter_sorted_ids().
51
52        for (file_index, file) in self.files.iter().enumerate() {
53            if usize::from(file.base_graph_count()) != file_index {
54                bail!(
55                    "\"{}\" should have {} base graphs, but claims {} base graphs".corrupted(),
56                    file.path().display(),
57                    file_index,
58                    file.base_graph_count()
59                );
60            }
61
62            for (base_graph_index, (expected, actual)) in self
63                .files
64                .iter()
65                .take(file_index)
66                .map(crate::File::checksum)
67                .zip(file.iter_base_graph_ids())
68                .enumerate()
69            {
70                if actual != expected {
71                    bail!(
72                        "\"{}\" base graph at index {} should have ID {} but is {}".corrupted(),
73                        file.path().display(),
74                        base_graph_index,
75                        expected,
76                        actual
77                    );
78                }
79            }
80
81            let file_stats = file.traverse(|commit| {
82                let mut max_parent_generation = 0u32;
83                let mut has_uncomputed_parent_generation = false;
84                for parent_pos in commit.iter_parents() {
85                    let parent_pos = parent_pos?;
86                    let parent = self.commit_at(parent_pos);
87                    max_parent_generation = max(max_parent_generation, parent.generation());
88                    has_uncomputed_parent_generation |= parent.generation() == 0;
89                }
90
91                // Zero denotes legacy, uncomputed generations, not corrupt data.
92                if commit.generation() == 0 || has_uncomputed_parent_generation {
93                    bail!(
94                        "Cannot verify generation numbers for commit {} because it or a parent has an uncomputed generation".unsupported(),
95                        commit.id()
96                    );
97                }
98
99                // If the max parent generation is GENERATION_NUMBER_MAX, then this commit's
100                // generation should be GENERATION_NUMBER_MAX too.
101                let expected_generation = min(max_parent_generation + 1, GENERATION_NUMBER_MAX);
102                if commit.generation() != expected_generation {
103                    bail!(
104                        "Commit {}'s generation should be {expected_generation} but is {}".corrupted(),
105                        commit.id(),
106                        commit.generation()
107                    );
108                }
109
110                processor(commit).or_error()?;
111
112                Ok(())
113            })?;
114
115            max_generation = max(max_generation, file_stats.max_generation);
116            stats.num_commits += file_stats.num_commits;
117            for (key, value) in file_stats.parent_counts.into_iter() {
118                *stats.parent_counts.entry(key).or_insert(0) += value;
119            }
120        }
121
122        stats.longest_path_length = if max_generation < GENERATION_NUMBER_MAX {
123            Some(max_generation.saturating_sub(1))
124        } else {
125            None
126        };
127        Ok(stats)
128    }
129}