OXYGENHUB

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

147 of 158 lines run, 7 of 14 functions · run #339 on proposal/124 · 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` (their working copies only within the shorter
6
//! `core.snapshot-retention`), reference attestations, and the policy; receipts
7
//! live as long as the changes of their state. Operation
8
//! objects are always kept so the log stays walkable, but an operation older
9
//! than the retention window no longer keeps its states alive, so undoing
10
//! that far back may fail once its objects are gone.
11
12
use super::*;
13
use crate::store::{PackReport, PruneReport, RetiredReport};
14
use std::collections::HashSet;
15
16
#[derive(Debug, Clone, Default, PartialEq, Eq)]
17
pub struct GcReport {
18
    pub packed: PackReport,
19
    pub pruned: PruneReport,
20
    pub reachable: usize,
21
    /// Packs folded into the one a full repack writes.
22
    pub merged_packs: usize,
23
    /// Packs and loose objects earlier repacks retired, deleted now that
24
    /// [`crate::store::RETIRED_FOR`] has passed (oxygenhub#249).
25
    pub retired: RetiredReport,
26
}
27
28
impl Repo {
29
    /// Delete what earlier repacks retired more than
30
    /// [`crate::store::RETIRED_FOR`] ago, prune unreachable objects older
31
    /// than the grace period (`now` ignores it, but not the retired
32
    /// files' hour), then repack everything into one pack (spec §13.4).
33
    /// The packs and loose objects this repack replaces are retired in
34
    /// turn, for the next collection.
3521×
    pub fn gc(&self, now: bool) -> Result<GcReport> {
36114×
        self.gc_with(now, &mut |_| {})
3721×
    }
38
39
    /// [`Repo::gc`], reporting each phase and the packing's progress
40
    /// (oxygen#66), for a spinner or a log.
4122×
    pub fn gc_with(&self, now: bool, progress: crate::store::Progress) -> Result<GcReport> {
4222×
        self.gc_keeping(now, &[], progress)
4322×
    }
44
45
    /// [`Repo::gc_with`], keeping `extra` blobs and their chunks as well:
46
    /// objects a host stored for itself and names from outside the
47
    /// repository's history, such as a forge's job artifacts
48
    /// (oxygenhub#126).
4923×
    pub fn gc_keeping(
5023×
        &self,
5123×
        now: bool,
5223×
        extra: &[ObjectRef],
5323×
        progress: crate::store::Progress,
5423×
    ) -> Result<GcReport> {
55
        // Retired files first: the readers that used them have had their
56
        // hour, and what replaced them is in the packs read from here on.
5723×
        let retired = self
5823×
            .store
5923×
            .expire_retired(crate::store::RETIRED_FOR, progress)?;
6023×
        progress("finding what is reachable");
6123×
        let mut keep = self.reachable()?;
6223×
        for r in extra {
631×
            if !self.store.has(r) || !keep.insert(*r) {
640×
                continue;
651×
            }
661×
            if let Ok(body) = self.store.get_typed(r, ObjectType::Blob) {
671×
                if let Ok(blob) = Blob::decode(&body) {
681×
                    keep.extend(blob.chunks);
691×
                }
700×
            }
71
        }
7223×
        let grace = if now {
7321×
            std::time::Duration::ZERO
74
        } else {
752×
            std::time::Duration::from_secs(self.config.gc_grace_days * 86_400)
76
        };
7723×
        let pruned = self.store.prune_with(&keep, grace, progress)?;
78
        // Then everything left in one pack, compressed harder than a
79
        // commit's (spec §13.4), as `git gc` repacks.
8023×
        let (packed, merged_packs) = self
8123×
            .store
8223×
            .repack_all_with(crate::store::REPACK_ZSTD_LEVEL, progress)?;
8323×
        Ok(GcReport {
8423×
            packed,
8523×
            pruned,
8623×
            reachable: keep.len(),
8723×
            merged_packs,
8823×
            retired,
8923×
        })
9023×
    }
91
92
    /// Every object that must survive garbage collection.
9323×
    pub fn reachable(&self) -> Result<HashSet<ObjectRef>> {
9423×
        let mut keep: HashSet<ObjectRef> = HashSet::new();
9523×
        let mut states: Vec<ObjectRef> = Vec::new();
9623×
        let mut changes: Vec<ChangeHash> = Vec::new();
9723×
        let mut attests: Vec<ObjectRef> = Vec::new();
9823×
        let mut policies: Vec<ObjectRef> = Vec::new();
99
100
        // Operations: always kept; views within retention are roots. Past
101
        // working copies only within the shorter `core.snapshot-retention`
102
        // (oxygen#98): a file only ever snapshotted, such as a build output
103
        // a status took in, goes once they expire.
10423×
        let now_ms = Hlc::now().wall_ms;
10523×
        let cutoff = now_ms.saturating_sub(self.config.op_retention_days * 86_400_000);
10623×
        let wc_cutoff = now_ms
10723×
            .saturating_sub(self.config.snapshot_retention_days * 86_400_000)
10823×
            .max(cutoff);
109148×
        for (i, (r, op)) in self.op_log()?.into_iter().enumerate() {
110148×
            keep.insert(r);
111148×
            if i == 0 || op.hlc.wall_ms >= cutoff {
112110×
                states.extend(op.view.bookmarks.values().copied());
113110×
                states.extend(op.view.remotes.values().flat_map(|b| b.values().copied()));
114110×
                policies.extend(op.view.policy);
11538×
            }
116148×
            if i == 0 || (self.config.snapshot_retention_days > 0 && op.hlc.wall_ms >= wc_cutoff) {
117107×
                changes.extend(op.view.workspaces.values().copied());
118107×
            }
119
        }
120
        // Checkpoints: the object, its payload blob, and the blob's chunks.
12123×
        for r in self.checkpoint_refs()? {
1222×
            if let Ok(bytes) = self.store.get_typed(&r, ObjectType::Checkpoint) {
1232×
                keep.insert(r);
1242×
                let cp = crate::objects::Checkpoint::decode(&bytes)?;
1252×
                keep.insert(cp.payload);
1262×
                if let Ok(b) = self.store.get_typed(&cp.payload, ObjectType::Blob) {
1272×
                    keep.extend(Blob::decode(&b)?.chunks);
1280×
                }
129
                // A version 2 payload's graph blobs and their chunks.
1302×
                for g in self.checkpoint_graph_blobs(&cp).unwrap_or_default() {
1311×
                    keep.insert(g);
1321×
                    if let Ok(b) = self.store.get_typed(&g, ObjectType::Blob) {
1331×
                        keep.extend(Blob::decode(&b)?.chunks);
1340×
                    }
135
                }
1360×
            }
137
        }
138
        // Tags: their states and attestations.
13923×
        let view_now = self.view()?;
14023×
        states.extend(view_now.tags.values().copied());
14123×
        for name in view_now.tags.keys() {
1423×
            if let Some((r, _)) = self.tag_attest(name)? {
1433×
                attests.push(r);
1443×
            }
145
        }
146
        // Reference attestations.
14723×
        for name in self.view()?.bookmarks.keys() {
14823×
            if let Some((r, _)) = self.latest_ref_attest(name)? {
149
                // With a host's acceptance of it (spec §14.7).
1501×
                if let Some(acc) = self.acceptance_of(&r)? {
1511×
                    attests.push(acc.attest.hash());
1521×
                }
1531×
                attests.push(r);
15422×
            }
155
        }
156
        // A historical view may name objects pruned under an earlier, shorter
157
        // retention; there is nothing to keep for those.
158129×
        for st in states {
159129×
            if keep.insert(st) {
16076×
                match self.store.get_state(&st) {
16173×
                    Ok(s) => changes.extend(s.heads),
1623×
                    Err(StoreError::NotFound(_)) => continue,
1630×
                    Err(e) => return Err(e.into()),
164
                }
16553×
            }
166
        }
16723×
        for p in policies {
1689×
            if keep.insert(p) {
1693×
                let bytes = match self.store.get_typed(&p, ObjectType::Policy) {
1703×
                    Ok(b) => b,
1710×
                    Err(StoreError::NotFound(_)) => continue,
1720×
                    Err(e) => return Err(e.into()),
173
                };
1743×
                let policy = crate::policy::Policy::decode(&bytes)?;
1754×
                for id in &policy.identities {
1764×
                    keep.insert(id.hash());
1774×
                }
1783×
                for sig in self.store.signatures(&p)? {
1793×
                    keep.insert(sig.key);
1803×
                }
1816×
            }
182
        }
183
        // Changes: their closure, identities, blobs, chunks, seals.
18423×
        let mut stack = changes;
185386×
        while let Some(h) = stack.pop() {
186363×
            if !keep.insert(h) {
187203×
                continue;
188160×
            }
189
            // Beyond the shallow boundary, or pruned under an earlier
190
            // retention, there is nothing to keep.
191160×
            let c = match self.store.get_change_parts(&h) {
192150×
                Ok((c, texts)) => {
193150×
                    keep.extend(texts);
194150×
                    c
195
                }
19610×
                Err(StoreError::NotFound(_)) => continue,
1970×
                Err(e) => return Err(e.into()),
198
            };
199150×
            stack.extend(c.deps.iter().copied());
200150×
            if !c.author.is_zero() {
20132×
                keep.insert(c.author);
202118×
            }
203150×
            for sig in self.store.signatures(&h)? {
20413×
                self.keep_signer(&mut keep, sig.key)?;
205
            }
206150×
            for e in &c.edits {
207133×
                if let Edit::Replace { old, new, .. } = e {
20818×
                    for b in [old, new].into_iter().flatten() {
20918×
                        if keep.insert(*b) {
21018×
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
21118×
                                keep.extend(Blob::decode(&bytes)?.chunks);
2120×
                            }
2130×
                        }
214
                    }
215115×
                }
216
            }
217150×
            attests.extend(self.store.seals_for(&h)?);
218
        }
21923×
        self.reachable_receipts(&mut keep)?;
22023×
        self.reachable_approvals(&mut keep)?;
22123×
        for a in attests {
2229×
            if keep.insert(a) {
2238×
                for sig in self.store.signatures(&a)? {
2248×
                    self.keep_signer(&mut keep, sig.key)?;
225
                }
2261×
            }
227
        }
22823×
        Ok(keep)
22923×
    }
230
231
    /// Keep a signer's identity and, for a short-lived key, its
232
    /// certificate and the certificate's issuer (spec §14.7).
23323×
    pub(crate) fn keep_signer(&self, keep: &mut HashSet<ObjectRef>, key: ObjectRef) -> Result<()> {
23423×
        keep.insert(key);
23523×
        if let Some(c) = self.store.certificate_of(&key)? {
2363×
            keep.insert(c);
2373×
            if let Ok(cert) = self.store.get_certificate(&c) {
2383×
                keep.insert(cert.cert.issuer);
2393×
            }
24020×
        }
24123×
        Ok(())
24223×
    }
243
}