Skip to main content

dag/
integrity.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8//! Integrity checks.
9
10use std::collections::BTreeSet;
11
12use futures::StreamExt;
13use futures::TryStreamExt;
14
15use crate::Group;
16use crate::Id;
17use crate::Result;
18use crate::Vertex;
19use crate::dag::AbstractDag;
20use crate::iddag::IdDag;
21use crate::iddagstore::IdDagStore;
22use crate::idmap::IdMapAssignHead;
23use crate::ops::CheckIntegrity;
24use crate::ops::DagAlgorithm;
25use crate::ops::IdConvert;
26use crate::ops::Persist;
27use crate::ops::TryClone;
28use crate::segment::SegmentFlags;
29use crate::set::Set;
30
31#[async_trait::async_trait]
32impl<IS, M, P, S> CheckIntegrity for AbstractDag<IdDag<IS>, M, P, S>
33where
34    IS: IdDagStore + Persist + 'static,
35    IdDag<IS>: TryClone,
36    M: TryClone + IdMapAssignHead + Persist + Send + Sync + 'static,
37    P: TryClone + Send + Sync + 'static,
38    S: TryClone + Persist + Send + Sync + 'static,
39{
40    async fn check_universal_ids(&self) -> Result<Vec<Id>> {
41        let universal_ids: Vec<Id> = self.dag.universal_ids()?.into_iter().collect();
42        tracing::debug!("{} universally known vertexes", universal_ids.len());
43        let exists = self.map.contains_vertex_id_locally(&universal_ids).await?;
44        let missing_ids = universal_ids
45            .into_iter()
46            .zip(exists)
47            .filter_map(|(id, b)| if b { None } else { Some(id) })
48            .collect();
49        Ok(missing_ids)
50    }
51
52    async fn check_segments(&self) -> Result<Vec<String>> {
53        // Detected problems.
54        let mut problems = Vec::new();
55
56        // Track heads and roots in the graph.
57        let mut heads: BTreeSet<Id> = Default::default();
58        let mut roots: BTreeSet<Id> = Default::default();
59
60        for level in 0..=self.dag.max_level()? {
61            let mut expected_low = Id::MIN;
62
63            // Check all levels.
64            for seg in self.dag.iter_segments_ascending(Id::MIN, level)? {
65                let seg = seg?;
66                let span = seg.span()?;
67                let mut add_problem =
68                    |msg| problems.push(format!("Level {level} segment {seg:?} {msg}"));
69
70                // Spans need to be sorted and non-overlapping within a group.
71                if span.low.group() > expected_low.group() {
72                    expected_low = span.low.group().min_id();
73                }
74                if span.low > span.high || span.low.group() != span.high.group() {
75                    add_problem(format!("has invalid span {span:?}"));
76                }
77                if span.low < expected_low {
78                    add_problem(format!(
79                        "has unexpected span ({span:?}), expected low ({expected_low:?})"
80                    ));
81                }
82                expected_low = span.high + 1;
83
84                // Parents should be < low to avoid cycles, and should not have duplicates.
85                let mut parents = seg.parents()?;
86                let orig_parents_len = parents.len();
87                parents.sort_unstable();
88                parents.dedup();
89                if parents.len() < orig_parents_len {
90                    add_problem("has duplicated parents".to_string());
91                }
92                if parents.iter().any(|&p| p >= span.low) {
93                    add_problem("has parents that might cause cycles".to_string());
94                }
95
96                // Maintain heads and roots. This can only be calculated from flat segments.
97                if level == 0 {
98                    let previous_head = heads.iter().next_back().cloned();
99                    if let Some(head) = previous_head {
100                        if span.low <= head {
101                            add_problem(format!(
102                                "overlapped segments: {span:?} with previous head {head:?}"
103                            ));
104                        }
105                    }
106                    for p in &parents {
107                        heads.remove(p);
108                    }
109                    heads.insert(span.high);
110                    if parents.is_empty() {
111                        roots.insert(span.low);
112                    }
113                }
114
115                // Check flags. min: must have flags, max: all possible flags.
116                let mut expected_flags_max = SegmentFlags::empty();
117                let mut expected_flags_min = SegmentFlags::empty();
118                if roots.range(span.low..=span.high).take(1).count() > 0 {
119                    expected_flags_min |= SegmentFlags::HAS_ROOT;
120                    expected_flags_max |= SegmentFlags::HAS_ROOT;
121                }
122                if level == 0 && heads.len() == 1 && span.high.group() == Group::MASTER {
123                    // ONLY_HEAD is optional.
124                    expected_flags_max |= SegmentFlags::ONLY_HEAD;
125                }
126                let flags = seg.flags()?;
127                if !flags.contains(expected_flags_min) || !expected_flags_max.contains(flags) {
128                    add_problem(format!(
129                        "has unexpected flags: {flags:?} (expected: min: {expected_flags_min:?}, max: {expected_flags_max:?})"
130                    ));
131                }
132
133                // Check parents for high-level segments.
134                if level > 0 {
135                    let mut expected_parents = Vec::with_capacity(parents.len());
136                    for seg in self.dag.iter_segments_ascending(span.low, level - 1)? {
137                        let seg = seg?;
138                        let subspan = seg.span()?;
139                        if subspan.high > span.high && subspan.low <= span.high {
140                            add_problem(format!("does not align with low-level segment {seg:?}"));
141                        }
142                        if subspan.low > span.high {
143                            break;
144                        }
145                        for p in seg.parents()? {
146                            if p < span.low {
147                                expected_parents.push(p);
148                            }
149                        }
150                    }
151                    expected_parents.sort_unstable();
152                    expected_parents.dedup();
153                    if parents != expected_parents {
154                        add_problem(format!(
155                            "has unexpected parents (expected: {expected_parents:?})"
156                        ));
157                    }
158                }
159            }
160        }
161        Ok(problems)
162    }
163
164    async fn check_isomorphic_graph(
165        &self,
166        other: &dyn DagAlgorithm,
167        heads: Set,
168    ) -> Result<Vec<String>> {
169        let mut problems = Vec::new();
170
171        // Prefetch merges and their parents in both graphs' master group.
172        // This reduces round-trips.
173        tracing::debug!("prefetching merges and parents");
174        for graph in [self, other] as [&dyn DagAlgorithm; 2] {
175            if !graph.is_vertex_lazy() {
176                continue;
177            }
178            let related = graph.master_group().await? & graph.ancestors(heads.clone()).await?;
179            let merges = graph.merges(related).await?;
180            let parents = graph.parents(merges.clone()).await?;
181            let prefetch = merges | parents;
182            let mut iter = prefetch.iter().await?;
183            while (iter.next().await).is_some() {}
184        }
185        tracing::trace!("prefetched merges and parents");
186
187        // To verify two graphs are isomorphic. Start from some heads,
188        // check and compare their linear ancestors recursively.
189        //
190        // For example, starting from "to_check" having just "E":
191        //
192        //      A--C--D--E      B--C--D--E
193        //        /               /
194        //       B               A
195        //
196        // 1. Figure out the linear portion (C--D--E).
197        // 2. Check the linear portion is the same in both graphs.
198        //    (only its root C can be a merge and C has the same parents)
199        // 3. Remove the head (E) from "to_check", insert root (C)'s parents
200        //    to "to_check".
201        // 4. Repeat from 1 until "to_check" is empty.
202        let mut to_check: Vec<Vertex> = heads.iter().await?.try_collect().await?;
203        let mut visited: BTreeSet<Vertex> = Default::default();
204        while let Some(head) = to_check.pop() {
205            if !visited.insert(head.clone()) {
206                continue;
207            }
208
209            // Use flat segment to figure out the linear portion.
210            let head_id = self.vertex_id(head.clone()).await?;
211            let seg = match self.dag.find_flat_segment_including_id(head_id)? {
212                Some(seg) => seg,
213                None => {
214                    problems.push(format!(
215                        "head_id {head_id:?} should be covered by a flat segment"
216                    ));
217                    continue;
218                }
219            };
220            let span = seg.span()?;
221            let root_id = span.low;
222            let root = self.vertex_name(root_id).await?;
223            let parents = self.parent_names(root.clone()).await?;
224            let mut add_problem = |msg| {
225                problems.push(format!(
226                    "range {root:?}::{head:?} with parents {parents:?}: {msg}"
227                ));
228            };
229            tracing::trace!("checking range {:?}::{:?}", &root, &head);
230
231            // Check against the other graph for various properties.
232            // Check vertex count in the range.
233            let this_count = head_id.0 - root_id.0 + 1;
234            let set = match other.range(root.clone().into(), head.clone().into()).await {
235                Ok(set) => set,
236                Err(e) => {
237                    add_problem(format!("cannot resolve range on the other graph: {e:?}"));
238                    continue;
239                }
240            };
241            let other_count = set.count_slow().await?;
242            if other_count != this_count {
243                add_problem(format!("length mismatch: {this_count} != {other_count}"));
244            }
245
246            // Check that merge can only be at most 1 (`root`).
247            let other_merges = other.merges(set).await?.count_slow().await?;
248            let this_merges = if parents.len() > 1 { 1 } else { 0 };
249            if other_merges != this_merges {
250                add_problem(format!("merge mismatch: {this_merges} != {other_merges}"));
251            }
252
253            // Check parents of root.
254            let other_parents = match other.parent_names(root.clone()).await {
255                Ok(ps) => ps,
256                Err(e) => {
257                    add_problem(format!(
258                        "cannot get parents of {root:?} on the other graph: {e:?}"
259                    ));
260                    continue;
261                }
262            };
263            if other_parents != parents {
264                add_problem(format!(
265                    "parents mismatch: {parents:?} != {other_parents:?}"
266                ));
267            }
268
269            // Check parents recursively.
270            to_check.extend(parents);
271        }
272
273        Ok(problems)
274    }
275}