OXYGENHUB

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

148 of 159 lines run, 7 of 14 functions · run #361 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` (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. A store that is not this disk's
35
    /// directory then folds its signatures and index entries (§13.7).
3621×
    pub fn gc(&self, now: bool) -> Result<GcReport> {
37116×
        self.gc_with(now, &mut |_| {})
3821×
    }
39
40
    /// [`Repo::gc`], reporting each phase and the packing's progress
41
    /// (oxygen#66), for a spinner or a log.
4222×
    pub fn gc_with(&self, now: bool, progress: crate::store::Progress) -> Result<GcReport> {
4322×
        self.gc_keeping(now, &[], progress)
4422×
    }
45
46
    /// [`Repo::gc_with`], keeping `extra` blobs and their chunks as well:
47
    /// objects a host stored for itself and names from outside the
48
    /// repository's history, such as a forge's job artifacts
49
    /// (oxygenhub#126).
5023×
    pub fn gc_keeping(
5123×
        &self,
5223×
        now: bool,
5323×
        extra: &[ObjectRef],
5423×
        progress: crate::store::Progress,
5523×
    ) -> Result<GcReport> {
56
        // Retired files first: the readers that used them have had their
57
        // hour, and what replaced them is in the packs read from here on.
5823×
        let retired = self
5923×
            .store
6023×
            .expire_retired(crate::store::RETIRED_FOR, progress)?;
6123×
        progress("finding what is reachable");
6223×
        let mut keep = self.reachable()?;
6323×
        for r in extra {
641×
            if !self.store.has(r) || !keep.insert(*r) {
650×
                continue;
661×
            }
671×
            if let Ok(body) = self.store.get_typed(r, ObjectType::Blob) {
681×
                if let Ok(blob) = Blob::decode(&body) {
691×
                    keep.extend(blob.chunks);
701×
                }
710×
            }
72
        }
7323×
        let grace = if now {
7421×
            std::time::Duration::ZERO
75
        } else {
762×
            std::time::Duration::from_secs(self.config.gc_grace_days * 86_400)
77
        };
7823×
        let pruned = self.store.prune_with(&keep, grace, progress)?;
79
        // Then everything left in one pack, compressed harder than a
80
        // commit's (spec §13.4), as `git gc` repacks.
8123×
        let (packed, merged_packs) = self
8223×
            .store
8323×
            .repack_all_with(crate::store::REPACK_ZSTD_LEVEL, progress)?;
84
        // Last, on a store that is not this disk's directory, every
85
        // signature and index entry into one list (spec §13.7, #116).
8623×
        self.store.fold_entries(progress)?;
8723×
        Ok(GcReport {
8823×
            packed,
8923×
            pruned,
9023×
            reachable: keep.len(),
9123×
            merged_packs,
9223×
            retired,
9323×
        })
9423×
    }
95
96
    /// Every object that must survive garbage collection.
9723×
    pub fn reachable(&self) -> Result<HashSet<ObjectRef>> {
9823×
        let mut keep: HashSet<ObjectRef> = HashSet::new();
9923×
        let mut states: Vec<ObjectRef> = Vec::new();
10023×
        let mut changes: Vec<ChangeHash> = Vec::new();
10123×
        let mut attests: Vec<ObjectRef> = Vec::new();
10223×
        let mut policies: Vec<ObjectRef> = Vec::new();
103
104
        // Operations: always kept; views within retention are roots. Past
105
        // working copies only within the shorter `core.snapshot-retention`
106
        // (oxygen#98): a file only ever snapshotted, such as a build output
107
        // a status took in, goes once they expire.
10823×
        let now_ms = Hlc::now().wall_ms;
10923×
        let cutoff = now_ms.saturating_sub(self.config.op_retention_days * 86_400_000);
11023×
        let wc_cutoff = now_ms
11123×
            .saturating_sub(self.config.snapshot_retention_days * 86_400_000)
11223×
            .max(cutoff);
113148×
        for (i, (r, op)) in self.op_log()?.into_iter().enumerate() {
114148×
            keep.insert(r);
115148×
            if i == 0 || op.hlc.wall_ms >= cutoff {
116110×
                states.extend(op.view.bookmarks.values().copied());
117110×
                states.extend(op.view.remotes.values().flat_map(|b| b.values().copied()));
118110×
                policies.extend(op.view.policy);
11938×
            }
120148×
            if i == 0 || (self.config.snapshot_retention_days > 0 && op.hlc.wall_ms >= wc_cutoff) {
121107×
                changes.extend(op.view.workspaces.values().copied());
122107×
            }
123
        }
124
        // Checkpoints: the object, its payload blob, and the blob's chunks.
12523×
        for r in self.checkpoint_refs()? {
1262×
            if let Ok(bytes) = self.store.get_typed(&r, ObjectType::Checkpoint) {
1272×
                keep.insert(r);
1282×
                let cp = crate::objects::Checkpoint::decode(&bytes)?;
1292×
                keep.insert(cp.payload);
1302×
                if let Ok(b) = self.store.get_typed(&cp.payload, ObjectType::Blob) {
1312×
                    keep.extend(Blob::decode(&b)?.chunks);
1320×
                }
133
                // A version 2 payload's graph blobs and their chunks.
1342×
                for g in self.checkpoint_graph_blobs(&cp).unwrap_or_default() {
1351×
                    keep.insert(g);
1361×
                    if let Ok(b) = self.store.get_typed(&g, ObjectType::Blob) {
1371×
                        keep.extend(Blob::decode(&b)?.chunks);
1380×
                    }
139
                }
1400×
            }
141
        }
142
        // Tags: their states and attestations.
14323×
        let view_now = self.view()?;
14423×
        states.extend(view_now.tags.values().copied());
14523×
        for name in view_now.tags.keys() {
1463×
            if let Some((r, _)) = self.tag_attest(name)? {
1473×
                attests.push(r);
1483×
            }
149
        }
150
        // Reference attestations.
15123×
        for name in self.view()?.bookmarks.keys() {
15223×
            if let Some((r, _)) = self.latest_ref_attest(name)? {
153
                // With a host's acceptance of it (spec §14.7).
1541×
                if let Some(acc) = self.acceptance_of(&r)? {
1551×
                    attests.push(acc.attest.hash());
1561×
                }
1571×
                attests.push(r);
15822×
            }
159
        }
160
        // A historical view may name objects pruned under an earlier, shorter
161
        // retention; there is nothing to keep for those.
162129×
        for st in states {
163129×
            if keep.insert(st) {
16476×
                match self.store.get_state(&st) {
16573×
                    Ok(s) => changes.extend(s.heads),
1663×
                    Err(StoreError::NotFound(_)) => continue,
1670×
                    Err(e) => return Err(e.into()),
168
                }
16953×
            }
170
        }
17123×
        for p in policies {
1729×
            if keep.insert(p) {
1733×
                let bytes = match self.store.get_typed(&p, ObjectType::Policy) {
1743×
                    Ok(b) => b,
1750×
                    Err(StoreError::NotFound(_)) => continue,
1760×
                    Err(e) => return Err(e.into()),
177
                };
1783×
                let policy = crate::policy::Policy::decode(&bytes)?;
1794×
                for id in &policy.identities {
1804×
                    keep.insert(id.hash());
1814×
                }
1823×
                for sig in self.store.signatures(&p)? {
1833×
                    keep.insert(sig.key);
1843×
                }
1856×
            }
186
        }
187
        // Changes: their closure, identities, blobs, chunks, seals.
18823×
        let mut stack = changes;
189386×
        while let Some(h) = stack.pop() {
190363×
            if !keep.insert(h) {
191203×
                continue;
192160×
            }
193
            // Beyond the shallow boundary, or pruned under an earlier
194
            // retention, there is nothing to keep.
195160×
            let c = match self.store.get_change_parts(&h) {
196150×
                Ok((c, texts)) => {
197150×
                    keep.extend(texts);
198150×
                    c
199
                }
20010×
                Err(StoreError::NotFound(_)) => continue,
2010×
                Err(e) => return Err(e.into()),
202
            };
203150×
            stack.extend(c.deps.iter().copied());
204150×
            if !c.author.is_zero() {
20532×
                keep.insert(c.author);
206118×
            }
207150×
            for sig in self.store.signatures(&h)? {
20813×
                self.keep_signer(&mut keep, sig.key)?;
209
            }
210150×
            for e in &c.edits {
211133×
                if let Edit::Replace { old, new, .. } = e {
21218×
                    for b in [old, new].into_iter().flatten() {
21318×
                        if keep.insert(*b) {
21418×
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
21518×
                                keep.extend(Blob::decode(&bytes)?.chunks);
2160×
                            }
2170×
                        }
218
                    }
219115×
                }
220
            }
221150×
            attests.extend(self.store.seals_for(&h)?);
222
        }
22323×
        self.reachable_receipts(&mut keep)?;
22423×
        self.reachable_approvals(&mut keep)?;
22523×
        for a in attests {
2269×
            if keep.insert(a) {
2278×
                for sig in self.store.signatures(&a)? {
2288×
                    self.keep_signer(&mut keep, sig.key)?;
229
                }
2301×
            }
231
        }
23223×
        Ok(keep)
23323×
    }
234
235
    /// Keep a signer's identity and, for a short-lived key, its
236
    /// certificate and the certificate's issuer (spec §14.7).
23723×
    pub(crate) fn keep_signer(&self, keep: &mut HashSet<ObjectRef>, key: ObjectRef) -> Result<()> {
23823×
        keep.insert(key);
23923×
        if let Some(c) = self.store.certificate_of(&key)? {
2403×
            keep.insert(c);
2413×
            if let Ok(cert) = self.store.get_certificate(&c) {
2423×
                keep.insert(cert.cert.issuer);
2433×
            }
24420×
        }
24523×
        Ok(())
24623×
    }
247
}