OXYGENHUB

Coverage / crates/oxy-core/src/repo/gc.rs 91.7%

111 of 121 lines run, 5 of 10 functions · run #254 on main · run missed

1
//! Garbage collection (spec §21): delete objects
2
//! nothing reachable refers to.
3
//!
4
//! Roots: the current view, the views of every operation newer than
5
//! `core.op-retention`, reference attestations, and the policy; receipts
6
//! live as long as the changes of their state. Operation
7
//! objects are always kept so the log stays walkable, but an operation older
8
//! than the retention window no longer keeps its states alive, so undoing
9
//! that far back may fail once its objects are gone.
10
11
use super::*;
12
use crate::store::{PackReport, PruneReport};
13
use std::collections::HashSet;
14
15
#[derive(Debug, Clone, Default, PartialEq, Eq)]
16
pub struct GcReport {
17
    pub packed: PackReport,
18
    pub pruned: PruneReport,
19
    pub reachable: usize,
20
    /// Packs folded into the one a full repack writes.
21
    pub merged_packs: usize,
22
}
23
24
impl Repo {
25
    /// Prune unreachable objects older than the grace period (`now`
26
    /// ignores it), then repack everything into one pack (spec §13.4).
2711×
    pub fn gc(&self, now: bool) -> Result<GcReport> {
2859×
        self.gc_with(now, &mut |_| {})
2911×
    }
30
31
    /// [`Repo::gc`], reporting each phase and the packing's progress
32
    /// (oxygen#66), for a spinner or a log.
3312×
    pub fn gc_with(&self, now: bool, progress: crate::store::Progress) -> Result<GcReport> {
3412×
        progress("finding what is reachable");
3512×
        let keep = self.reachable()?;
3612×
        let grace = if now {
3710×
            std::time::Duration::ZERO
38
        } else {
392×
            std::time::Duration::from_secs(self.config.gc_grace_days * 86_400)
40
        };
4112×
        let pruned = self.store.prune_with(&keep, grace, progress)?;
42
        // Then everything left in one pack, compressed harder than a
43
        // commit's (spec §13.4), as `git gc` repacks.
4412×
        let (packed, merged_packs) = self
4512×
            .store
4612×
            .repack_all_with(crate::store::REPACK_ZSTD_LEVEL, progress)?;
4712×
        Ok(GcReport {
4812×
            packed,
4912×
            pruned,
5012×
            reachable: keep.len(),
5112×
            merged_packs,
5212×
        })
5312×
    }
54
55
    /// Every object that must survive garbage collection.
5612×
    pub fn reachable(&self) -> Result<HashSet<ObjectRef>> {
5712×
        let mut keep: HashSet<ObjectRef> = HashSet::new();
5812×
        let mut states: Vec<ObjectRef> = Vec::new();
5912×
        let mut changes: Vec<ChangeHash> = Vec::new();
6012×
        let mut attests: Vec<ObjectRef> = Vec::new();
6112×
        let mut policies: Vec<ObjectRef> = Vec::new();
62
63
        // Operations: always kept; views within retention are roots.
6412×
        let cutoff = Hlc::now()
6512×
            .wall_ms
6612×
            .saturating_sub(self.config.op_retention_days * 86_400_000);
67104×
        for (i, (r, op)) in self.op_log()?.into_iter().enumerate() {
68104×
            keep.insert(r);
69104×
            if i == 0 || op.hlc.wall_ms >= cutoff {
7066×
                states.extend(op.view.bookmarks.values().copied());
7166×
                states.extend(op.view.remotes.values().flat_map(|b| b.values().copied()));
7266×
                changes.extend(op.view.workspaces.values().copied());
7366×
                policies.extend(op.view.policy);
7438×
            }
75
        }
76
        // Checkpoints: the object, its payload blob, and the blob's chunks.
7712×
        for r in self.checkpoint_refs()? {
782×
            if let Ok(bytes) = self.store.get_typed(&r, ObjectType::Checkpoint) {
792×
                keep.insert(r);
802×
                let cp = crate::objects::Checkpoint::decode(&bytes)?;
812×
                keep.insert(cp.payload);
822×
                if let Ok(b) = self.store.get_typed(&cp.payload, ObjectType::Blob) {
832×
                    keep.extend(Blob::decode(&b)?.chunks);
840×
                }
85
                // A version 2 payload's graph blobs and their chunks.
862×
                for g in self.checkpoint_graph_blobs(&cp).unwrap_or_default() {
871×
                    keep.insert(g);
881×
                    if let Ok(b) = self.store.get_typed(&g, ObjectType::Blob) {
891×
                        keep.extend(Blob::decode(&b)?.chunks);
900×
                    }
91
                }
920×
            }
93
        }
94
        // Tags: their states and attestations.
9512×
        let view_now = self.view()?;
9612×
        states.extend(view_now.tags.values().copied());
9712×
        for name in view_now.tags.keys() {
983×
            if let Some((r, _)) = self.tag_attest(name)? {
993×
                attests.push(r);
1003×
            }
101
        }
102
        // Reference attestations.
10312×
        for name in self.view()?.bookmarks.keys() {
10412×
            if let Some((r, _)) = self.latest_ref_attest(name)? {
1050×
                attests.push(r);
10612×
            }
107
        }
108
        // A historical view may name objects pruned under an earlier, shorter
109
        // retention; there is nothing to keep for those.
11085×
        for st in states {
11185×
            if keep.insert(st) {
11239×
                match self.store.get_state(&st) {
11336×
                    Ok(s) => changes.extend(s.heads),
1143×
                    Err(StoreError::NotFound(_)) => continue,
1150×
                    Err(e) => return Err(e.into()),
116
                }
11746×
            }
118
        }
11912×
        for p in policies {
1204×
            if keep.insert(p) {
1211×
                let bytes = match self.store.get_typed(&p, ObjectType::Policy) {
1221×
                    Ok(b) => b,
1230×
                    Err(StoreError::NotFound(_)) => continue,
1240×
                    Err(e) => return Err(e.into()),
125
                };
1261×
                let policy = crate::policy::Policy::decode(&bytes)?;
1271×
                for id in &policy.identities {
1281×
                    keep.insert(id.hash());
1291×
                }
1301×
                for sig in self.store.signatures(&p)? {
1311×
                    keep.insert(sig.key);
1321×
                }
1333×
            }
134
        }
135
        // Changes: their closure, identities, blobs, chunks, seals.
13612×
        let mut stack = changes;
137218×
        while let Some(h) = stack.pop() {
138206×
            if !keep.insert(h) {
139107×
                continue;
14099×
            }
141
            // Beyond the shallow boundary, or pruned under an earlier
142
            // retention, there is nothing to keep.
14399×
            let c = match self.store.get_change_parts(&h) {
14489×
                Ok((c, texts)) => {
14589×
                    keep.extend(texts);
14689×
                    c
147
                }
14810×
                Err(StoreError::NotFound(_)) => continue,
1490×
                Err(e) => return Err(e.into()),
150
            };
15189×
            stack.extend(c.deps.iter().copied());
15289×
            if !c.author.is_zero() {
15330×
                keep.insert(c.author);
15459×
            }
15589×
            for sig in self.store.signatures(&h)? {
15613×
                keep.insert(sig.key);
15713×
            }
158106×
            for e in &c.edits {
159106×
                if let Edit::Replace { old, new, .. } = e {
16017×
                    for b in [old, new].into_iter().flatten() {
16117×
                        if keep.insert(*b) {
16217×
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
16317×
                                keep.extend(Blob::decode(&bytes)?.chunks);
1640×
                            }
1650×
                        }
166
                    }
16789×
                }
168
            }
16989×
            attests.extend(self.store.seals_for(&h)?);
170
        }
17112×
        self.reachable_receipts(&mut keep)?;
17212×
        for a in attests {
1735×
            if keep.insert(a) {
1744×
                for sig in self.store.signatures(&a)? {
1754×
                    keep.insert(sig.key);
1764×
                }
1771×
            }
178
        }
17912×
        Ok(keep)
18012×
    }
181
}