Skip to main content

contextgraph_core/
gc.rs

1//! `gc`: explicit, opt-in garbage collection. Never runs as a side effect of
2//! normal use — commits are only ever removed when a caller deliberately
3//! invokes this.
4
5use crate::commit::CommitId;
6use crate::error::Result;
7use crate::store::{CommitStore, RefStore};
8use std::collections::HashSet;
9
10/// All commit ids reachable from any branch pointer, following *every*
11/// parent edge (not just first-parent) — a merge commit's second parent
12/// must stay reachable too.
13pub async fn reachable_from_branches<S: CommitStore + RefStore + ?Sized>(
14    store: &S,
15) -> Result<HashSet<CommitId>> {
16    let branches = store.list_branches().await?;
17    let mut visited = HashSet::new();
18    let mut stack: Vec<CommitId> = branches.into_iter().map(|(_, id)| id).collect();
19
20    while let Some(id) = stack.pop() {
21        if !visited.insert(id) {
22            continue;
23        }
24        if let Some(commit) = store.get(&id).await? {
25            stack.extend(commit.parent_ids);
26        }
27    }
28    Ok(visited)
29}
30
31/// Removes every commit not reachable from any branch, returning the ids
32/// that were removed. A commit dropped from every branch (e.g. via
33/// `rollback`) but still hash-reachable from nowhere else becomes eligible
34/// here — until `gc` runs, it stays in storage.
35pub async fn gc<S: CommitStore + RefStore + ?Sized>(store: &S) -> Result<Vec<CommitId>> {
36    let reachable = reachable_from_branches(store).await?;
37    let all = store.all_ids().await?;
38    let unreachable: Vec<CommitId> = all
39        .into_iter()
40        .filter(|id| !reachable.contains(id))
41        .collect();
42    store.remove_many(&unreachable).await?;
43    Ok(unreachable)
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49    use crate::commit::{Author, Commit, Delta, Metadata};
50    use crate::mem::InMemoryGraphStore;
51    use crate::store::{CommitStore, RefStore};
52    use chrono::Utc;
53
54    fn msg(parents: Vec<CommitId>, text: &str) -> Commit {
55        Commit::new(
56            parents,
57            Author::User,
58            Delta::Message {
59                content: text.to_string(),
60            },
61            Metadata::new(Utc::now()),
62        )
63    }
64
65    #[tokio::test]
66    async fn gc_removes_commits_unreachable_from_every_branch() {
67        let store = InMemoryGraphStore::new();
68        let root = msg(vec![], "root");
69        store.put(root.clone()).await.unwrap();
70        store.set_branch("main", root.id).await.unwrap();
71
72        // A commit built on root but never referenced by any branch.
73        let orphan = msg(vec![root.id], "orphan");
74        store.put(orphan.clone()).await.unwrap();
75
76        let removed = gc(&store).await.unwrap();
77        assert_eq!(removed, vec![orphan.id]);
78        assert!(!store.contains(&orphan.id).await.unwrap());
79        assert!(store.contains(&root.id).await.unwrap());
80    }
81
82    #[tokio::test]
83    async fn gc_never_removes_commits_reachable_from_any_branch() {
84        let store = InMemoryGraphStore::new();
85        let root = msg(vec![], "root");
86        store.put(root.clone()).await.unwrap();
87        store.set_branch("main", root.id).await.unwrap();
88        let child = msg(vec![root.id], "child");
89        store.put(child.clone()).await.unwrap();
90        store.set_branch("feature", child.id).await.unwrap();
91
92        let removed = gc(&store).await.unwrap();
93        assert!(removed.is_empty());
94        assert!(store.contains(&root.id).await.unwrap());
95        assert!(store.contains(&child.id).await.unwrap());
96    }
97
98    #[tokio::test]
99    async fn gc_keeps_both_parents_of_a_reachable_merge_commit() {
100        let store = InMemoryGraphStore::new();
101        let root = msg(vec![], "root");
102        store.put(root.clone()).await.unwrap();
103        let a = msg(vec![root.id], "a");
104        store.put(a.clone()).await.unwrap();
105        let b = msg(vec![root.id], "b");
106        store.put(b.clone()).await.unwrap();
107        // A "merge" commit with two parents, reachable only via `main`.
108        let merged = Commit::new(
109            vec![a.id, b.id],
110            Author::System,
111            Delta::Message {
112                content: "merge".into(),
113            },
114            Metadata::new(Utc::now()),
115        );
116        store.put(merged.clone()).await.unwrap();
117        store.set_branch("main", merged.id).await.unwrap();
118
119        let removed = gc(&store).await.unwrap();
120        assert!(removed.is_empty());
121        assert!(store.contains(&a.id).await.unwrap());
122        assert!(store.contains(&b.id).await.unwrap());
123    }
124
125    #[tokio::test]
126    async fn gc_with_no_branches_removes_everything() {
127        let store = InMemoryGraphStore::new();
128        let root = msg(vec![], "root");
129        store.put(root.clone()).await.unwrap();
130
131        let removed = gc(&store).await.unwrap();
132        assert_eq!(removed, vec![root.id]);
133        assert_eq!(store.len().await.unwrap(), 0);
134    }
135
136    #[tokio::test]
137    async fn gc_is_a_no_op_on_an_empty_store() {
138        let store = InMemoryGraphStore::new();
139        let removed = gc(&store).await.unwrap();
140        assert!(removed.is_empty());
141    }
142}