OXYGENHUB

Coverage / crates/oxy-core/src/repo/fsck.rs 71.6%

262 of 366 lines run, 25 of 64 functions · run #251 on main · run missed

1
//! Repository integrity check (spec §21.1): `oxy fsck`.
2
//!
3
//! Reads everything and changes nothing. Four passes:
4
//!
5
//! 1. every stored object: header, length, hash, and that its body decodes
6
//!    as its type says;
7
//! 2. the operation log: every operation reachable from the head is
8
//!    present and decodes, and clocks never run backwards;
9
//! 3. references: the current view's bookmarks, tags, remote bookmarks,
10
//!    workspaces and policy, then the dependency closure of everything
11
//!    they name, with each change's author identity, blobs and chunks,
12
//!    and each change's signatures or seals;
13
//! 4. derived data: every bookmark's state validates, every checkpoint
14
//!    restores exactly the state it names, and reference and tag
15
//!    attestations carry good signatures.
16
//!
17
//! Missing blobs are warnings, not errors, in a partial clone
18
//! (`filter.max-blob` or a sparse filter), and changes beyond a shallow
19
//! boundary are expected to be absent.
20
21
use super::*;
22
use std::collections::{HashSet, VecDeque};
23
24
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
25
pub enum Severity {
26
    /// Worth knowing; the repository is still sound.
27
    Warning,
28
    /// Data is missing, corrupt or fails verification.
29
    Error,
30
}
31
32
#[derive(Clone, Debug, PartialEq, Eq)]
33
pub struct Problem {
34
    pub severity: Severity,
35
    /// The object the problem is about, when there is one.
36
    pub object: Option<ObjectRef>,
37
    pub what: String,
38
}
39
40
#[derive(Clone, Debug, Default, PartialEq, Eq)]
41
pub struct FsckReport {
42
    pub objects: usize,
43
    pub ops: usize,
44
    /// Changes checked, working-copy changes included.
45
    pub changes: usize,
46
    /// Committed changes authenticated by their own signature or by a seal.
47
    pub signed: usize,
48
    pub unsigned: usize,
49
    pub checkpoints: usize,
50
    pub attestations: usize,
51
    pub problems: Vec<Problem>,
52
}
53
54
impl FsckReport {
5568×
    pub fn errors(&self) -> usize {
5668×
        self.problems
5768×
            .iter()
5868×
            .filter(|p| p.severity == Severity::Error)
5968×
            .count()
6068×
    }
61
620×
    pub fn warnings(&self) -> usize {
630×
        self.problems
640×
            .iter()
650×
            .filter(|p| p.severity == Severity::Warning)
660×
            .count()
670×
    }
68
6911×
    fn error(&mut self, object: Option<ObjectRef>, what: impl Into<String>) {
7011×
        self.problems.push(Problem {
7111×
            severity: Severity::Error,
7211×
            object,
7311×
            what: what.into(),
7411×
        });
7511×
    }
76
770×
    fn warn(&mut self, object: Option<ObjectRef>, what: impl Into<String>) {
780×
        self.problems.push(Problem {
790×
            severity: Severity::Warning,
800×
            object,
810×
            what: what.into(),
820×
        });
830×
    }
84
}
85
86
/// Whether `body` decodes as an object of type `ty`.
871652×
fn decodes(ty: ObjectType, body: &[u8]) -> std::result::Result<(), String> {
881652×
    let r = match ty {
89126×
        ObjectType::Chunk => Ok(()),
9076×
        ObjectType::Blob => Blob::decode(body).map(|_| ()),
91
        // Structure only: the text blobs are checked with the change graph.
92
        ObjectType::Change => {
93423×
            Change::decode_with(body, &mut |_, _, _| Ok(crate::lines::Lines::default())).map(|_| ())
94
        }
9512×
        ObjectType::Checkpoint => crate::objects::Checkpoint::decode(body).map(|_| ()),
96472×
        ObjectType::Op => match Op::decode(body) {
97472×
            Ok(_) => Ok(()),
980×
            Err(e) => Op::decode_format1(body).map(|_| ()).map_err(|_| e),
99
        },
100228×
        ObjectType::Attest => Attest::decode(body).map(|_| ()),
10167×
        ObjectType::Identity => Identity::decode(body).map(|_| ()),
1020×
        ObjectType::Policy => crate::policy::Policy::decode(body).map(|_| ()),
1031×
        ObjectType::Receipt => crate::receipt::Receipt::decode(body).map(|_| ()),
104247×
        ObjectType::State => crate::objects::StateObject::decode(body).map(|_| ()),
105
    };
1061652×
    r.map_err(|e| e.to_string())
1071652×
}
108
109
impl Repo {
110
    /// Check the whole repository; see the module documentation.
11176×
    pub fn fsck(&self) -> Result<FsckReport> {
11276×
        let mut rep = FsckReport::default();
11376×
        let bad = {
11476×
            let _t = crate::timing::phase("fsck: objects");
11576×
            self.fsck_objects(&mut rep)?
116
        };
11776×
        {
11876×
            let _t = crate::timing::phase("fsck: operations");
11976×
            self.fsck_ops(&mut rep, &bad);
12076×
        }
121
        {
12276×
            let _t = crate::timing::phase("fsck: references");
12376×
            self.fsck_references(&mut rep, &bad)?;
124
        }
125
        {
12676×
            let _t = crate::timing::phase("fsck: states and checkpoints");
12776×
            self.fsck_derived(&mut rep)?;
128
        }
12976×
        rep.problems.sort_by_key(|p| std::cmp::Reverse(p.severity));
13076×
        Ok(rep)
13176×
    }
132
133
    /// Pass 1. Returns the objects that failed, so later passes report
134
    /// them once rather than at every reference.
13576×
    fn fsck_objects(&self, rep: &mut FsckReport) -> Result<HashSet<ObjectRef>> {
136
        use rayon::prelude::*;
13776×
        let mut bad = HashSet::new();
138
        // A chunk at a time, read (and verified) and decoded on every core.
13976×
        for refs in self.store.list()?.chunks(8192) {
14076×
            let checked: Vec<std::result::Result<(), String>> = self
14176×
                .store
14276×
                .get_many(refs)
14376×
                .into_par_iter()
1441653×
                .map(|got| match got {
1451652×
                    Ok((ty, body)) => decodes(ty, &body)
1461652×
                        .map_err(|e| format!("{} object does not decode: {e}", ty.name())),
1471×
                    Err(e) => Err(format!("unreadable object: {e}")),
1481653×
                })
14976×
                .collect();
1501653×
            for (r, c) in refs.iter().zip(checked) {
1511653×
                rep.objects += 1;
1521653×
                if let Err(e) = c {
1531×
                    rep.error(Some(*r), e);
1541×
                    bad.insert(*r);
1551652×
                }
156
            }
157
        }
15876×
        Ok(bad)
15976×
    }
160
161
    /// Pass 2.
16276×
    fn fsck_ops(&self, rep: &mut FsckReport, bad: &HashSet<ObjectRef>) {
16376×
        let head = match self.read_head() {
16475×
            Ok((h, _)) => h,
1651×
            Err(RepoError::Msg(m)) if m.starts_with("corrupt") => {
1661×
                rep.error(None, ".oxy/ops/head does not hold an object reference");
1671×
                return;
168
            }
1690×
            Err(e) => {
1700×
                rep.error(None, format!("cannot read .oxy/ops/head: {e}"));
1710×
                return;
172
            }
173
        };
17475×
        let mut seen = HashSet::new();
17575×
        let mut queue: VecDeque<(ObjectRef, Option<(ObjectRef, u64)>)> =
17675×
            VecDeque::from([(head, None)]);
177538×
        while let Some((r, child)) = queue.pop_front() {
178463×
            if !seen.insert(r) {
1799×
                continue;
180454×
            }
181454×
            if bad.contains(&r) {
1820×
                continue;
183454×
            }
184454×
            let body = match self.store.get_typed(&r, ObjectType::Op) {
185454×
                Ok(b) => b,
186
                Err(StoreError::NotFound(_)) => {
1870×
                    let by = child
1880×
                        .map(|(c, _)| format!(", the parent of operation {}", c.short(12)))
1890×
                        .unwrap_or_default();
1900×
                    rep.error(
1910×
                        Some(r),
1920×
                        format!("operation missing{by}; the log is cut here"),
193
                    );
1940×
                    continue;
195
                }
1960×
                Err(e) => {
1970×
                    rep.error(Some(r), format!("operation unreadable: {e}"));
1980×
                    continue;
199
                }
200
            };
201454×
            rep.ops += 1;
202454×
            let (parents, wall_ms) = match Op::decode(&body) {
203454×
                Ok(op) => (op.parents, op.hlc.wall_ms),
2040×
                Err(_) => match Op::decode_format1(&body) {
2050×
                    Ok(op) => (op.parents, op.hlc.wall_ms),
2060×
                    Err(e) => {
2070×
                        rep.error(Some(r), format!("operation does not decode: {e}"));
2080×
                        continue;
209
                    }
210
                },
211
            };
212454×
            if let Some((c, child_ms)) = child {
213379×
                if wall_ms > child_ms {
2140×
                    rep.warn(
2150×
                        Some(c),
2160×
                        format!(
2170×
                            "operation is timed before its parent {} (a clock was wrong)",
2180×
                            r.short(12)
2190×
                        ),
2200×
                    );
221379×
                }
22275×
            }
223454×
            queue.extend(parents.into_iter().map(|p| (p, Some((r, wall_ms)))));
224
        }
22576×
    }
226
227
    /// Pass 3.
22876×
    fn fsck_references(&self, rep: &mut FsckReport, bad: &HashSet<ObjectRef>) -> Result<()> {
22976×
        let view = match self.view() {
23075×
            Ok(v) => v,
2311×
            Err(e) => {
2321×
                rep.error(None, format!("cannot read the current view: {e}"));
2331×
                return Ok(());
234
            }
235
        };
23675×
        let boundary = self.boundary();
23775×
        let partial = self.config.max_blob.is_some() || !self.config.sparse_paths.is_empty();
238
23975×
        let mut roots: Vec<(ChangeHash, String)> = Vec::new();
24075×
        let mut states: Vec<(ObjectRef, String)> = Vec::new();
24175×
        states.extend(
24275×
            view.bookmarks
24375×
                .iter()
24476×
                .map(|(n, s)| (*s, format!("bookmark {n}"))),
245
        );
24675×
        states.extend(view.tags.iter().map(|(n, s)| (*s, format!("tag {n}"))));
24775×
        for (remote, bms) in &view.remotes {
24847×
            states.extend(bms.iter().map(|(n, s)| (*s, format!("{remote}/{n}"))));
249
        }
250131×
        for (st, what) in states {
251131×
            match self.store.get_state(&st) {
252190×
                Ok(s) => roots.extend(s.heads.into_iter().map(|h| (h, what.clone()))),
2530×
                Err(e) if !bad.contains(&st) => {
2540×
                    rep.error(Some(st), format!("state of {what} unusable: {e}"))
255
                }
2560×
                Err(_) => {}
257
            }
258
        }
25976×
        for (ws, h) in &view.workspaces {
26076×
            roots.push((*h, format!("workspace {}", ws.to_hex())));
26176×
        }
26275×
        if let Some(p) = view.policy {
2630×
            match self.store.get_typed(&p, ObjectType::Policy) {
2640×
                Ok(bytes) => {
2650×
                    if let Ok(policy) = crate::policy::Policy::decode(&bytes) {
2660×
                        for id in &policy.identities {
2670×
                            if !self.store.has(&id.hash()) {
2680×
                                rep.warn(
2690×
                                    Some(id.hash()),
2700×
                                    "an identity the policy names is not stored",
2710×
                                );
2720×
                            }
273
                        }
2740×
                    }
275
                }
2760×
                Err(e) if !bad.contains(&p) => {
2770×
                    rep.error(Some(p), format!("the policy is unusable: {e}"))
278
                }
2790×
                Err(_) => {}
280
            }
28175×
        }
282
283
        // Working-copy changes are never signed; they are checked but not tallied.
28475×
        let working: HashSet<ChangeHash> = view.workspaces.values().copied().collect();
28575×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
28675×
        let mut blobs_seen: HashSet<ObjectRef> = HashSet::new();
28775×
        let mut stack = roots;
288477×
        while let Some((h, needed_by)) = stack.pop() {
289402×
            if !seen.insert(h) {
290170×
                continue;
291232×
            }
292
            // The skeleton: the text is checked as the blobs it is stored
293
            // in, not decoded (the objects pass checked every object).
294232×
            let (c, texts) = match self.store.get_change_lazy(&h) {
295230×
                Ok(c) => c,
2961×
                Err(StoreError::NotFound(_)) if boundary.contains(&h) => continue,
297
                Err(StoreError::NotFound(_)) => {
2981×
                    rep.error(Some(h), format!("change missing, needed by {needed_by}"));
2991×
                    continue;
300
                }
3011×
                Err(e) => {
3021×
                    if !bad.contains(&h) {
3030×
                        rep.error(Some(h), format!("change unusable: {e}"));
3041×
                    }
3051×
                    continue;
306
                }
307
            };
308230×
            rep.changes += 1;
309230×
            let label = format!("change {}", h.short(12));
310230×
            stack.extend(c.deps.iter().map(|d| (*d, label.clone())));
311230×
            if !c.author.is_zero() && !self.store.has(&c.author) {
3120×
                rep.warn(
3130×
                    Some(h),
3140×
                    format!("author identity {} is not stored", c.author.short(12)),
3150×
                );
316230×
            }
317230×
            for t in texts {
318197×
                if let crate::objects::TextRef::Blob(b, _, _) = t {
31946×
                    if blobs_seen.insert(b) {
32046×
                        // A change cannot be read without its text: never partial.
32146×
                        self.fsck_blob(rep, b, &label, false, bad);
32246×
                    }
323151×
                }
324
            }
325230×
            for e in &c.edits {
326206×
                let Edit::Replace { old, new, .. } = e else {
327200×
                    continue;
328
                };
3296×
                for b in [old, new].into_iter().flatten() {
3306×
                    if !blobs_seen.insert(*b) {
3310×
                        continue;
3326×
                    }
3336×
                    self.fsck_blob(rep, *b, &label, partial, bad);
334
                }
335
            }
336230×
            if working.contains(&h) {
33776×
                continue;
338154×
            }
339154×
            match self.authenticate_change(&h) {
340105×
                Ok(SignatureStatus::Valid { .. }) => rep.signed += 1,
34149×
                Ok(SignatureStatus::Unsigned) => rep.unsigned += 1,
3420×
                Ok(SignatureStatus::Invalid(why)) => {
3430×
                    rep.error(Some(h), format!("bad signature: {why}"))
344
                }
3450×
                Err(e) => rep.error(Some(h), format!("cannot check signatures: {e}")),
346
            }
347
        }
34875×
        Ok(())
34976×
    }
350
35152×
    fn fsck_blob(
35252×
        &self,
35352×
        rep: &mut FsckReport,
35452×
        b: ObjectRef,
35552×
        used_by: &str,
35652×
        partial: bool,
35752×
        bad: &HashSet<ObjectRef>,
35852×
    ) {
35952×
        match self.store.get_typed(&b, ObjectType::Blob) {
36050×
            Ok(bytes) => {
36150×
                let Ok(blob) = Blob::decode(&bytes) else {
3620×
                    return;
363
                };
36489×
                for ch in blob.chunks {
36589×
                    if !self.store.has(&ch) {
3660×
                        rep.error(
3670×
                            Some(ch),
3680×
                            format!("chunk missing from blob {} ({used_by})", b.short(12)),
3690×
                        );
37089×
                    }
371
                }
372
            }
3730×
            Err(StoreError::NotFound(_)) if partial => rep.warn(
3740×
                Some(b),
3750×
                format!("blob not fetched ({used_by}); expected in a partial clone"),
376
            ),
3772×
            Err(StoreError::NotFound(_)) => rep.error(Some(b), format!("blob missing ({used_by})")),
3780×
            Err(e) if !bad.contains(&b) => {
3790×
                rep.error(Some(b), format!("blob unusable ({used_by}): {e}"))
380
            }
3810×
            Err(_) => {}
382
        }
38352×
    }
384
385
    /// Whether `heads` form a valid state: its history loads and every file
386
    /// graph builds. Graphs are built a batch at a time and dropped, so the
387
    /// check needs the memory of a batch, not of the whole tree.
38876×
    fn check_state(&self, heads: &[ChangeHash]) -> Result<()> {
38976×
        let mut st = self.load_state_history(heads)?;
39076×
        let nodes = st.unbuilt_nodes();
39176×
        for batch in nodes.chunks(2048) {
39275×
            self.load_graphs_of(&mut st, batch)?;
39373×
            st.drop_graphs(batch);
394
        }
39574×
        Ok(())
39676×
    }
397
398
    /// Pass 4.
39976×
    fn fsck_derived(&self, rep: &mut FsckReport) -> Result<()> {
40076×
        let Ok(view) = self.view() else { return Ok(()) };
40175×
        let shallow = self.is_shallow();
40275×
        if !shallow {
40375×
            let mut checked: HashSet<ObjectRef> = HashSet::new();
40476×
            for (name, st) in &view.bookmarks {
40576×
                if !checked.insert(*st) {
4060×
                    continue;
40776×
                }
40876×
                let Ok(s) = self.store.get_state(st) else {
4090×
                    continue;
410
                };
41176×
                if let Err(e) = self.check_state(&s.heads) {
4122×
                    rep.error(
4132×
                        Some(*st),
4142×
                        format!("bookmark {name} does not form a valid state: {e}"),
4152×
                    );
41674×
                }
417
            }
4180×
        }
41975×
        for r in self.checkpoint_refs()? {
4209×
            rep.checkpoints += 1;
4219×
            let cp = match self.store.get_typed(&r, ObjectType::Checkpoint) {
4229×
                Ok(b) => match crate::objects::Checkpoint::decode(&b) {
4239×
                    Ok(cp) => cp,
4240×
                    Err(_) => continue,
425
                },
426
                Err(StoreError::NotFound(_)) => {
4270×
                    rep.warn(
4280×
                        Some(r),
429
                        "checkpoint pointer names a missing checkpoint; it will be rewritten",
430
                    );
4310×
                    continue;
432
                }
4330×
                Err(_) => continue,
434
            };
4359×
            let payload = match self.read_blob(&cp.payload) {
4369×
                Ok(p) => p,
4370×
                Err(e) => {
4380×
                    rep.error(Some(r), format!("checkpoint payload unreadable: {e}"));
4390×
                    continue;
440
                }
441
            };
4429×
            if let Err(e) = self.state_from_checkpoint(&payload) {
4431×
                rep.error(Some(r), format!("checkpoint payload does not decode: {e}"));
4441×
                continue;
4458×
            }
446
            // The payload must be what the named changes produce, in its own version.
4478×
            let version = crate::cbor::decode(&payload).ok().and_then(|v| {
4488×
                crate::objects::map(&v, "payload").ok().and_then(|m| {
4498×
                    m.get(&0)
4508×
                        .and_then(|x| crate::objects::uint(x, "version").ok())
4518×
                })
4528×
            });
4538×
            let expected = |full: &State| {
4546×
                if version == Some(crate::state::CHECKPOINT_INDEX_VERSION) {
4555×
                    full.checkpoint_index(&full.checkpoint_file_graphs(), Repo::blob_ref)
456
                } else {
4571×
                    full.checkpoint_payload()
458
                }
4596×
            };
4608×
            if !shallow {
4618×
                match self.load_state_full(&cp.heads) {
4626×
                    Ok(full) if expected(&full) != payload => {
4630×
                        rep.error(Some(r), "checkpoint disagrees with the changes it names")
464
                    }
4656×
                    Ok(_) => {}
4662×
                    Err(e) => rep.error(
4672×
                        Some(r),
4682×
                        format!("checkpoint names changes that do not form a state: {e}"),
469
                    ),
470
                }
4710×
            }
472
        }
47375×
        let mut attests = Vec::new();
47476×
        for name in view.bookmarks.keys() {
47576×
            if let Ok(Some((r, _))) = self.latest_ref_attest(name) {
47621×
                attests.push((r, format!("bookmark {name}")));
47755×
            }
478
        }
47975×
        for name in view.tags.keys() {
4808×
            if let Ok(Some((r, _))) = self.tag_attest(name) {
4818×
                attests.push((r, format!("tag {name}")));
4828×
            }
483
        }
48475×
        for (r, what) in attests {
48529×
            rep.attestations += 1;
48629×
            let sigs = self.store.signatures(&r)?;
48729×
            if sigs.is_empty() {
4880×
                rep.warn(Some(r), format!("attestation for {what} is unsigned"));
48929×
            }
49029×
            for sig in sigs {
49129×
                match self.store.get_identity(&sig.key) {
49229×
                    Ok(id) => {
49329×
                        if let Err(e) = verify_signature(&id, &sig, Domain::Attest, &r) {
4940×
                            rep.error(
4950×
                                Some(r),
4960×
                                format!("attestation for {what} has a bad signature: {e}"),
4970×
                            );
49829×
                        }
499
                    }
5000×
                    Err(_) => rep.warn(
5010×
                        Some(r),
5020×
                        format!(
503
                            "attestation for {what} is signed by {}, whose identity is not stored",
5040×
                            sig.key.short(12)
505
                        ),
506
                    ),
507
                }
508
            }
509
        }
51075×
        Ok(())
51176×
    }
512
}