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