Skip to main content

contextgraph_core/
diff.rs

1//! Structural diff between two commits' materialized contexts: which turns
2//! were added, removed, or held in common — never a text diff. Messages are
3//! immutable, content-addressed atoms, so there is no "modify in place";
4//! a changed turn shows up as a `Removed` entry for the old commit paired
5//! with an `Added` entry for the new one, exactly as a line-level text diff
6//! represents an edited line.
7
8use crate::commit::CommitId;
9use crate::materialize::{materialize, MaterializedMessage};
10use crate::store::CommitStore;
11use crate::Result;
12use serde::{Deserialize, Serialize};
13
14/// One position in a structural diff.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16pub enum DiffOp {
17    /// Present, unchanged, in both sides (same commit id).
18    Common(MaterializedMessage),
19    /// Present only in `to` (the "new" side).
20    Added(MaterializedMessage),
21    /// Present only in `from` (the "old" side).
22    Removed(MaterializedMessage),
23}
24
25/// A structural diff between two materialized contexts.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct ContextDiff {
28    pub from: CommitId,
29    pub to: CommitId,
30    pub ops: Vec<DiffOp>,
31}
32
33impl ContextDiff {
34    pub fn added(&self) -> impl Iterator<Item = &MaterializedMessage> {
35        self.ops.iter().filter_map(|op| match op {
36            DiffOp::Added(m) => Some(m),
37            _ => None,
38        })
39    }
40
41    pub fn removed(&self) -> impl Iterator<Item = &MaterializedMessage> {
42        self.ops.iter().filter_map(|op| match op {
43            DiffOp::Removed(m) => Some(m),
44            _ => None,
45        })
46    }
47
48    pub fn is_identical(&self) -> bool {
49        self.ops.iter().all(|op| matches!(op, DiffOp::Common(_)))
50    }
51}
52
53/// Diffs the materialized contexts of two arbitrary commits.
54pub async fn diff<S: CommitStore + ?Sized>(
55    store: &S,
56    from: CommitId,
57    to: CommitId,
58) -> Result<ContextDiff> {
59    let from_ctx = materialize(store, from).await?;
60    let to_ctx = materialize(store, to).await?;
61    let ops = lcs_diff(&from_ctx.messages, &to_ctx.messages);
62    Ok(ContextDiff { from, to, ops })
63}
64
65/// Classic LCS-based sequence diff over commit ids, since two messages are
66/// "the same" iff they came from the same (immutable) commit.
67fn lcs_diff(a: &[MaterializedMessage], b: &[MaterializedMessage]) -> Vec<DiffOp> {
68    let n = a.len();
69    let m = b.len();
70    let mut dp = vec![vec![0usize; m + 1]; n + 1];
71    for i in (0..n).rev() {
72        for j in (0..m).rev() {
73            dp[i][j] = if a[i].commit_id == b[j].commit_id {
74                dp[i + 1][j + 1] + 1
75            } else {
76                dp[i + 1][j].max(dp[i][j + 1])
77            };
78        }
79    }
80
81    let mut ops = Vec::with_capacity(n + m);
82    let (mut i, mut j) = (0, 0);
83    while i < n && j < m {
84        if a[i].commit_id == b[j].commit_id {
85            ops.push(DiffOp::Common(a[i].clone()));
86            i += 1;
87            j += 1;
88        } else if dp[i + 1][j] >= dp[i][j + 1] {
89            ops.push(DiffOp::Removed(a[i].clone()));
90            i += 1;
91        } else {
92            ops.push(DiffOp::Added(b[j].clone()));
93            j += 1;
94        }
95    }
96    while i < n {
97        ops.push(DiffOp::Removed(a[i].clone()));
98        i += 1;
99    }
100    while j < m {
101        ops.push(DiffOp::Added(b[j].clone()));
102        j += 1;
103    }
104    ops
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::commit::{Author, Commit, Delta, Metadata};
111    use crate::mem::InMemoryCommitStore;
112    use chrono::Utc;
113
114    fn msg(parents: Vec<CommitId>, text: &str) -> Commit {
115        Commit::new(
116            parents,
117            Author::User,
118            Delta::Message {
119                content: text.to_string(),
120            },
121            Metadata::new(Utc::now()),
122        )
123    }
124
125    #[tokio::test]
126    async fn diffing_a_commit_against_itself_yields_no_added_or_removed() {
127        let store = InMemoryCommitStore::new();
128        let a = msg(vec![], "hi");
129        store.put(a.clone()).await.unwrap();
130        let d = diff(&store, a.id, a.id).await.unwrap();
131        assert!(d.is_identical());
132        assert_eq!(d.added().count(), 0);
133        assert_eq!(d.removed().count(), 0);
134    }
135
136    #[tokio::test]
137    async fn diffing_two_forked_branches_shows_shared_prefix_as_common() {
138        let store = InMemoryCommitStore::new();
139        let root = msg(vec![], "root");
140        store.put(root.clone()).await.unwrap();
141        let shared = msg(vec![root.id], "shared");
142        store.put(shared.clone()).await.unwrap();
143
144        let a = msg(vec![shared.id], "branch-a-turn");
145        store.put(a.clone()).await.unwrap();
146        let b = msg(vec![shared.id], "branch-b-turn");
147        store.put(b.clone()).await.unwrap();
148
149        let d = diff(&store, a.id, b.id).await.unwrap();
150        let commons: Vec<_> = d
151            .ops
152            .iter()
153            .filter(|op| matches!(op, DiffOp::Common(_)))
154            .collect();
155        assert_eq!(commons.len(), 2); // root, shared
156        assert_eq!(d.removed().count(), 1); // branch-a-turn
157        assert_eq!(d.added().count(), 1); // branch-b-turn
158    }
159
160    #[tokio::test]
161    async fn diffing_a_commit_against_its_own_child_shows_one_addition() {
162        let store = InMemoryCommitStore::new();
163        let root = msg(vec![], "root");
164        store.put(root.clone()).await.unwrap();
165        let child = msg(vec![root.id], "child");
166        store.put(child.clone()).await.unwrap();
167
168        let d = diff(&store, root.id, child.id).await.unwrap();
169        assert_eq!(d.added().count(), 1);
170        assert_eq!(d.removed().count(), 0);
171        assert!(!d.is_identical());
172    }
173
174    #[tokio::test]
175    async fn diffing_two_completely_unrelated_roots_shows_full_removal_and_addition() {
176        let store = InMemoryCommitStore::new();
177        let a = msg(vec![], "a-only");
178        store.put(a.clone()).await.unwrap();
179        let b = msg(vec![], "b-only");
180        store.put(b.clone()).await.unwrap();
181
182        let d = diff(&store, a.id, b.id).await.unwrap();
183        assert_eq!(d.removed().count(), 1);
184        assert_eq!(d.added().count(), 1);
185        assert_eq!(
186            d.ops
187                .iter()
188                .filter(|op| matches!(op, DiffOp::Common(_)))
189                .count(),
190            0
191        );
192    }
193
194    #[tokio::test]
195    async fn diffing_two_empty_equal_single_commits_is_identical() {
196        let store = InMemoryCommitStore::new();
197        let a = msg(vec![], "");
198        store.put(a.clone()).await.unwrap();
199        let d = diff(&store, a.id, a.id).await.unwrap();
200        assert!(d.is_identical());
201    }
202}