OXYGENHUB
◆ v0.10.0 oxygen / crates / oxy-core / src / repo / fsck.rs
19.7 KiB · Rust · last changed The artifact as an object type of its own: oxy-core's artifact module, named by its object hash, checked by fsck (refs #108) 7 days ago source blame history raw
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 {
55
    pub fn errors(&self) -> usize {
56
        self.problems
57
            .iter()
58
            .filter(|p| p.severity == Severity::Error)
59
            .count()
60
    }
61
62
    pub fn warnings(&self) -> usize {
63
        self.problems
64
            .iter()
65
            .filter(|p| p.severity == Severity::Warning)
66
            .count()
67
    }
68
69
    fn error(&mut self, object: Option<ObjectRef>, what: impl Into<String>) {
70
        self.problems.push(Problem {
71
            severity: Severity::Error,
72
            object,
73
            what: what.into(),
74
        });
75
    }
76
77
    fn warn(&mut self, object: Option<ObjectRef>, what: impl Into<String>) {
78
        self.problems.push(Problem {
79
            severity: Severity::Warning,
80
            object,
81
            what: what.into(),
82
        });
83
    }
84
}
85
86
/// Whether `body` decodes as an object of type `ty`.
87
fn decodes(ty: ObjectType, body: &[u8]) -> std::result::Result<(), String> {
88
    let r = match ty {
89
        ObjectType::Chunk => Ok(()),
90
        ObjectType::Blob => Blob::decode(body).map(|_| ()),
91
        // Structure only: the text blobs are checked with the change graph.
92
        ObjectType::Change => {
93
            Change::decode_with(body, &mut |_, _, _| Ok(crate::lines::Lines::default())).map(|_| ())
94
        }
95
        ObjectType::Checkpoint => crate::objects::Checkpoint::decode(body).map(|_| ()),
96
        ObjectType::Op => match Op::decode(body) {
97
            Ok(_) => Ok(()),
98
            Err(e) => Op::decode_format1(body).map(|_| ()).map_err(|_| e),
99
        },
100
        ObjectType::Attest => Attest::decode(body).map(|_| ()),
101
        ObjectType::Identity => Identity::decode(body).map(|_| ()),
102
        ObjectType::Policy => crate::policy::Policy::decode(body).map(|_| ()),
103
        ObjectType::Receipt => crate::receipt::Receipt::decode(body).map(|_| ()),
104
        ObjectType::Certificate => crate::cert::Certificate::decode(body).map(|_| ()),
105
        ObjectType::Grant => crate::cert::Grant::decode(body).map(|_| ()),
106
        ObjectType::Artifact => crate::artifact::Artifact::decode(body).map(|_| ()),
107
        ObjectType::State => crate::objects::StateObject::decode(body).map(|_| ()),
108
    };
109
    r.map_err(|e| e.to_string())
110
}
111
112
impl Repo {
113
    /// Check the whole repository; see the module documentation.
114
    pub fn fsck(&self) -> Result<FsckReport> {
115
        // The head as it is now, as the operations pass reads it.
116
        self.forget_head();
117
        let mut rep = FsckReport::default();
118
        let bad = {
119
            let _t = crate::timing::phase("fsck: objects");
120
            self.fsck_objects(&mut rep)?
121
        };
122
        {
123
            let _t = crate::timing::phase("fsck: operations");
124
            self.fsck_ops(&mut rep, &bad);
125
        }
126
        {
127
            let _t = crate::timing::phase("fsck: references");
128
            self.fsck_references(&mut rep, &bad)?;
129
        }
130
        {
131
            let _t = crate::timing::phase("fsck: states and checkpoints");
132
            self.fsck_derived(&mut rep)?;
133
        }
134
        rep.problems.sort_by_key(|p| std::cmp::Reverse(p.severity));
135
        Ok(rep)
136
    }
137
138
    /// Pass 1. Returns the objects that failed, so later passes report
139
    /// them once rather than at every reference.
140
    fn fsck_objects(&self, rep: &mut FsckReport) -> Result<HashSet<ObjectRef>> {
141
        use rayon::prelude::*;
142
        let mut bad = HashSet::new();
143
        // A chunk at a time, read (and verified) and decoded on every core.
144
        for refs in self.store.list()?.chunks(8192) {
145
            let checked: Vec<std::result::Result<(), String>> = self
146
                .store
147
                .get_many(refs)
148
                .into_par_iter()
149
                .map(|got| match got {
150
                    Ok((ty, body)) => decodes(ty, &body)
151
                        .map_err(|e| format!("{} object does not decode: {e}", ty.name())),
152
                    Err(e) => Err(format!("unreadable object: {e}")),
153
                })
154
                .collect();
155
            for (r, c) in refs.iter().zip(checked) {
156
                rep.objects += 1;
157
                if let Err(e) = c {
158
                    rep.error(Some(*r), e);
159
                    bad.insert(*r);
160
                }
161
            }
162
        }
163
        Ok(bad)
164
    }
165
166
    /// Pass 2.
167
    fn fsck_ops(&self, rep: &mut FsckReport, bad: &HashSet<ObjectRef>) {
168
        let head = match self.read_head() {
169
            Ok((h, _)) => h,
170
            Err(RepoError::Msg(m)) if m.starts_with("corrupt") => {
171
                rep.error(None, ".oxy/ops/head does not hold an object reference");
172
                return;
173
            }
174
            Err(e) => {
175
                rep.error(None, format!("cannot read .oxy/ops/head: {e}"));
176
                return;
177
            }
178
        };
179
        let mut seen = HashSet::new();
180
        let mut queue: VecDeque<(ObjectRef, Option<(ObjectRef, u64)>)> =
181
            VecDeque::from([(head, None)]);
182
        while let Some((r, child)) = queue.pop_front() {
183
            if !seen.insert(r) {
184
                continue;
185
            }
186
            if bad.contains(&r) {
187
                continue;
188
            }
189
            let body = match self.store.get_typed(&r, ObjectType::Op) {
190
                Ok(b) => b,
191
                Err(StoreError::NotFound(_)) => {
192
                    let by = child
193
                        .map(|(c, _)| format!(", the parent of operation {}", c.short(12)))
194
                        .unwrap_or_default();
195
                    rep.error(
196
                        Some(r),
197
                        format!("operation missing{by}; the log is cut here"),
198
                    );
199
                    continue;
200
                }
201
                Err(e) => {
202
                    rep.error(Some(r), format!("operation unreadable: {e}"));
203
                    continue;
204
                }
205
            };
206
            rep.ops += 1;
207
            let (parents, wall_ms) = match Op::decode(&body) {
208
                Ok(op) => (op.parents, op.hlc.wall_ms),
209
                Err(_) => match Op::decode_format1(&body) {
210
                    Ok(op) => (op.parents, op.hlc.wall_ms),
211
                    Err(e) => {
212
                        rep.error(Some(r), format!("operation does not decode: {e}"));
213
                        continue;
214
                    }
215
                },
216
            };
217
            if let Some((c, child_ms)) = child {
218
                if wall_ms > child_ms {
219
                    rep.warn(
220
                        Some(c),
221
                        format!(
222
                            "operation is timed before its parent {} (a clock was wrong)",
223
                            r.short(12)
224
                        ),
225
                    );
226
                }
227
            }
228
            queue.extend(parents.into_iter().map(|p| (p, Some((r, wall_ms)))));
229
        }
230
    }
231
232
    /// Pass 3.
233
    fn fsck_references(&self, rep: &mut FsckReport, bad: &HashSet<ObjectRef>) -> Result<()> {
234
        let view = match self.view() {
235
            Ok(v) => v,
236
            Err(e) => {
237
                rep.error(None, format!("cannot read the current view: {e}"));
238
                return Ok(());
239
            }
240
        };
241
        let boundary = self.boundary();
242
        let partial = self.config.max_blob.is_some() || !self.config.sparse_paths.is_empty();
243
244
        let mut roots: Vec<(ChangeHash, String)> = Vec::new();
245
        let mut states: Vec<(ObjectRef, String)> = Vec::new();
246
        states.extend(
247
            view.bookmarks
248
                .iter()
249
                .map(|(n, s)| (*s, format!("bookmark {n}"))),
250
        );
251
        states.extend(view.tags.iter().map(|(n, s)| (*s, format!("tag {n}"))));
252
        for (remote, bms) in &view.remotes {
253
            states.extend(bms.iter().map(|(n, s)| (*s, format!("{remote}/{n}"))));
254
        }
255
        for (st, what) in states {
256
            match self.store.get_state(&st) {
257
                Ok(s) => roots.extend(s.heads.into_iter().map(|h| (h, what.clone()))),
258
                Err(e) if !bad.contains(&st) => {
259
                    rep.error(Some(st), format!("state of {what} unusable: {e}"))
260
                }
261
                Err(_) => {}
262
            }
263
        }
264
        for (ws, h) in &view.workspaces {
265
            roots.push((*h, format!("workspace {}", ws.to_hex())));
266
        }
267
        if let Some(p) = view.policy {
268
            match self.store.get_typed(&p, ObjectType::Policy) {
269
                Ok(bytes) => {
270
                    if let Ok(policy) = crate::policy::Policy::decode(&bytes) {
271
                        for id in &policy.identities {
272
                            if !self.store.has(&id.hash()) {
273
                                rep.warn(
274
                                    Some(id.hash()),
275
                                    "an identity the policy names is not stored",
276
                                );
277
                            }
278
                        }
279
                    }
280
                }
281
                Err(e) if !bad.contains(&p) => {
282
                    rep.error(Some(p), format!("the policy is unusable: {e}"))
283
                }
284
                Err(_) => {}
285
            }
286
        }
287
288
        // Working-copy changes are never signed; they are checked but not tallied.
289
        let working: HashSet<ChangeHash> = view.workspaces.values().copied().collect();
290
        let mut seen: HashSet<ChangeHash> = HashSet::new();
291
        let mut blobs_seen: HashSet<ObjectRef> = HashSet::new();
292
        let mut stack = roots;
293
        while let Some((h, needed_by)) = stack.pop() {
294
            if !seen.insert(h) {
295
                continue;
296
            }
297
            // The skeleton: the text is checked as the blobs it is stored
298
            // in, not decoded (the objects pass checked every object).
299
            let (c, texts) = match self.store.get_change_lazy(&h) {
300
                Ok(c) => c,
301
                Err(StoreError::NotFound(_)) if boundary.contains(&h) => continue,
302
                Err(StoreError::NotFound(_)) => {
303
                    rep.error(Some(h), format!("change missing, needed by {needed_by}"));
304
                    continue;
305
                }
306
                Err(e) => {
307
                    if !bad.contains(&h) {
308
                        rep.error(Some(h), format!("change unusable: {e}"));
309
                    }
310
                    continue;
311
                }
312
            };
313
            rep.changes += 1;
314
            let label = format!("change {}", h.short(12));
315
            stack.extend(c.deps.iter().map(|d| (*d, label.clone())));
316
            if !c.author.is_zero() && !self.store.has(&c.author) {
317
                rep.warn(
318
                    Some(h),
319
                    format!("author identity {} is not stored", c.author.short(12)),
320
                );
321
            }
322
            for t in texts {
323
                if let crate::objects::TextRef::Blob(b, _, _) = t {
324
                    if blobs_seen.insert(b) {
325
                        // A change cannot be read without its text: never partial.
326
                        self.fsck_blob(rep, b, &label, false, bad);
327
                    }
328
                }
329
            }
330
            for e in &c.edits {
331
                let Edit::Replace { old, new, .. } = e else {
332
                    continue;
333
                };
334
                for b in [old, new].into_iter().flatten() {
335
                    if !blobs_seen.insert(*b) {
336
                        continue;
337
                    }
338
                    self.fsck_blob(rep, *b, &label, partial, bad);
339
                }
340
            }
341
            if working.contains(&h) {
342
                continue;
343
            }
344
            match self.authenticate_change(&h) {
345
                Ok(SignatureStatus::Valid { .. }) => rep.signed += 1,
346
                Ok(SignatureStatus::Unsigned) => rep.unsigned += 1,
347
                Ok(SignatureStatus::Invalid(why)) => {
348
                    rep.error(Some(h), format!("bad signature: {why}"))
349
                }
350
                Err(e) => rep.error(Some(h), format!("cannot check signatures: {e}")),
351
            }
352
        }
353
        Ok(())
354
    }
355
356
    fn fsck_blob(
357
        &self,
358
        rep: &mut FsckReport,
359
        b: ObjectRef,
360
        used_by: &str,
361
        partial: bool,
362
        bad: &HashSet<ObjectRef>,
363
    ) {
364
        match self.store.get_typed(&b, ObjectType::Blob) {
365
            Ok(bytes) => {
366
                let Ok(blob) = Blob::decode(&bytes) else {
367
                    return;
368
                };
369
                for ch in blob.chunks {
370
                    if !self.store.has(&ch) {
371
                        rep.error(
372
                            Some(ch),
373
                            format!("chunk missing from blob {} ({used_by})", b.short(12)),
374
                        );
375
                    }
376
                }
377
            }
378
            Err(StoreError::NotFound(_)) if partial => rep.warn(
379
                Some(b),
380
                format!("blob not fetched ({used_by}); expected in a partial clone"),
381
            ),
382
            Err(StoreError::NotFound(_)) => rep.error(Some(b), format!("blob missing ({used_by})")),
383
            Err(e) if !bad.contains(&b) => {
384
                rep.error(Some(b), format!("blob unusable ({used_by}): {e}"))
385
            }
386
            Err(_) => {}
387
        }
388
    }
389
390
    /// Whether `heads` form a valid state: its history loads and every file
391
    /// graph builds. Graphs are built a batch at a time and dropped, so the
392
    /// check needs the memory of a batch, not of the whole tree.
393
    fn check_state(&self, heads: &[ChangeHash]) -> Result<()> {
394
        let mut st = self.load_state_history(heads)?;
395
        let nodes = st.unbuilt_nodes();
396
        for batch in nodes.chunks(2048) {
397
            self.load_graphs_of(&mut st, batch)?;
398
            st.drop_graphs(batch);
399
        }
400
        Ok(())
401
    }
402
403
    /// Pass 4.
404
    fn fsck_derived(&self, rep: &mut FsckReport) -> Result<()> {
405
        let Ok(view) = self.view() else { return Ok(()) };
406
        let shallow = self.is_shallow();
407
        if !shallow {
408
            let mut checked: HashSet<ObjectRef> = HashSet::new();
409
            for (name, st) in &view.bookmarks {
410
                if !checked.insert(*st) {
411
                    continue;
412
                }
413
                let Ok(s) = self.store.get_state(st) else {
414
                    continue;
415
                };
416
                if let Err(e) = self.check_state(&s.heads) {
417
                    rep.error(
418
                        Some(*st),
419
                        format!("bookmark {name} does not form a valid state: {e}"),
420
                    );
421
                }
422
            }
423
        }
424
        for r in self.checkpoint_refs()? {
425
            rep.checkpoints += 1;
426
            let cp = match self.store.get_typed(&r, ObjectType::Checkpoint) {
427
                Ok(b) => match crate::objects::Checkpoint::decode(&b) {
428
                    Ok(cp) => cp,
429
                    Err(_) => continue,
430
                },
431
                Err(StoreError::NotFound(_)) => {
432
                    rep.warn(
433
                        Some(r),
434
                        "checkpoint pointer names a missing checkpoint; it will be rewritten",
435
                    );
436
                    continue;
437
                }
438
                Err(_) => continue,
439
            };
440
            let payload = match self.read_blob(&cp.payload) {
441
                Ok(p) => p,
442
                Err(e) => {
443
                    rep.error(Some(r), format!("checkpoint payload unreadable: {e}"));
444
                    continue;
445
                }
446
            };
447
            if let Err(e) = self.state_from_checkpoint(&payload) {
448
                rep.error(Some(r), format!("checkpoint payload does not decode: {e}"));
449
                continue;
450
            }
451
            // The payload must be what the named changes produce, in its own version.
452
            let version = crate::cbor::decode(&payload).ok().and_then(|v| {
453
                crate::objects::map(&v, "payload").ok().and_then(|m| {
454
                    m.get(&0)
455
                        .and_then(|x| crate::objects::uint(x, "version").ok())
456
                })
457
            });
458
            let expected = |full: &State| {
459
                if version == Some(crate::state::CHECKPOINT_INDEX_VERSION) {
460
                    full.checkpoint_index(&full.checkpoint_file_graphs(), Repo::blob_ref)
461
                } else {
462
                    full.checkpoint_payload()
463
                }
464
            };
465
            if !shallow {
466
                match self.load_state_full(&cp.heads) {
467
                    Ok(full) if expected(&full) != payload => {
468
                        rep.error(Some(r), "checkpoint disagrees with the changes it names")
469
                    }
470
                    Ok(_) => {}
471
                    Err(e) => rep.error(
472
                        Some(r),
473
                        format!("checkpoint names changes that do not form a state: {e}"),
474
                    ),
475
                }
476
            }
477
        }
478
        let mut attests = Vec::new();
479
        for name in view.bookmarks.keys() {
480
            if let Ok(Some((r, _))) = self.latest_ref_attest(name) {
481
                attests.push((r, format!("bookmark {name}")));
482
            }
483
        }
484
        for name in view.tags.keys() {
485
            if let Ok(Some((r, _))) = self.tag_attest(name) {
486
                attests.push((r, format!("tag {name}")));
487
            }
488
        }
489
        for (r, what) in attests {
490
            rep.attestations += 1;
491
            let sigs = self.store.signatures(&r)?;
492
            if sigs.is_empty() {
493
                rep.warn(Some(r), format!("attestation for {what} is unsigned"));
494
            }
495
            for sig in sigs {
496
                match self.store.get_identity(&sig.key) {
497
                    Ok(id) => {
498
                        if let Err(e) = verify_signature(&id, &sig, Domain::Attest, &r) {
499
                            rep.error(
500
                                Some(r),
501
                                format!("attestation for {what} has a bad signature: {e}"),
502
                            );
503
                        }
504
                    }
505
                    Err(_) => rep.warn(
506
                        Some(r),
507
                        format!(
508
                            "attestation for {what} is signed by {}, whose identity is not stored",
509
                            sig.key.short(12)
510
                        ),
511
                    ),
512
                }
513
            }
514
        }
515
        Ok(())
516
    }
517
}