1use crate::commit::{Author, CommitId, Delta};
6use crate::error::{GraphError, Result};
7use crate::store::CommitStore;
8use serde::{Deserialize, Serialize};
9use std::collections::HashSet;
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct MaterializedMessage {
15 pub commit_id: CommitId,
16 pub author: Author,
17 pub delta: Delta,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct MaterializedContext {
27 pub head: CommitId,
28 pub messages: Vec<MaterializedMessage>,
29 pub manifest: Vec<CommitId>,
30}
31
32pub async fn materialize<S: CommitStore + ?Sized>(
40 store: &S,
41 head: CommitId,
42) -> Result<MaterializedContext> {
43 let mut chain = Vec::new();
44 let mut current = Some(head);
45 while let Some(id) = current {
46 let commit = store
47 .get(&id)
48 .await?
49 .ok_or(GraphError::CommitNotFound(id))?;
50 current = commit.parent_ids.first().copied();
51 chain.push(commit);
52 }
53 chain.reverse();
54
55 let mut messages: Vec<MaterializedMessage> = Vec::new();
56 let mut manifest: Vec<CommitId> = Vec::new();
57
58 for commit in chain {
59 let commit_id = commit.id;
60 let author = commit.author;
61 match commit.delta {
62 Delta::Compaction { replaces, summary } => {
63 let replaced: HashSet<CommitId> = replaces.iter().copied().collect();
64 messages.retain(|m| !replaced.contains(&m.commit_id));
65 manifest.retain(|id| !replaced.contains(id));
66 messages.push(MaterializedMessage {
67 commit_id,
68 author,
69 delta: Delta::Compaction { replaces, summary },
70 });
71 manifest.push(commit_id);
72 }
73 Delta::Merge { .. } => {
80 manifest.push(commit_id);
81 }
82 other => {
83 messages.push(MaterializedMessage {
84 commit_id,
85 author,
86 delta: other,
87 });
88 manifest.push(commit_id);
89 }
90 }
91 }
92
93 Ok(MaterializedContext {
94 head,
95 messages,
96 manifest,
97 })
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103 use crate::commit::{Author, Commit, Metadata};
104 use crate::mem::InMemoryCommitStore;
105 use chrono::Utc;
106
107 fn msg(parents: Vec<CommitId>, author: Author, text: &str) -> Commit {
108 Commit::new(
109 parents,
110 author,
111 Delta::Message {
112 content: text.to_string(),
113 },
114 Metadata::new(Utc::now()),
115 )
116 }
117
118 #[tokio::test]
119 async fn materializing_a_single_root_commit_yields_one_message() {
120 let store = InMemoryCommitStore::new();
121 let root = msg(vec![], Author::System, "root");
122 store.put(root.clone()).await.unwrap();
123
124 let ctx = materialize(&store, root.id).await.unwrap();
125 assert_eq!(ctx.messages.len(), 1);
126 assert_eq!(ctx.manifest, vec![root.id]);
127 assert_eq!(ctx.messages[0].delta, root.delta);
128 }
129
130 #[tokio::test]
131 async fn materializing_a_chain_preserves_root_to_head_order() {
132 let store = InMemoryCommitStore::new();
133 let root = msg(vec![], Author::User, "one");
134 store.put(root.clone()).await.unwrap();
135 let second = msg(vec![root.id], Author::Assistant, "two");
136 store.put(second.clone()).await.unwrap();
137 let third = msg(vec![second.id], Author::User, "three");
138 store.put(third.clone()).await.unwrap();
139
140 let ctx = materialize(&store, third.id).await.unwrap();
141 let texts: Vec<String> = ctx
142 .messages
143 .iter()
144 .map(|m| match &m.delta {
145 Delta::Message { content } => content.clone(),
146 _ => unreachable!(),
147 })
148 .collect();
149 assert_eq!(texts, vec!["one", "two", "three"]);
150 assert_eq!(ctx.manifest, vec![root.id, second.id, third.id]);
151 }
152
153 #[tokio::test]
154 async fn materializing_nonexistent_commit_fails() {
155 let store = InMemoryCommitStore::new();
156 let err = materialize(&store, CommitId::from_bytes([1; 32])).await.unwrap_err();
157 assert!(matches!(err, GraphError::CommitNotFound(_)));
158 }
159
160 fn compaction(parents: Vec<CommitId>, replaces: Vec<CommitId>, summary: &str) -> Commit {
161 Commit::new(
162 parents,
163 Author::System,
164 Delta::Compaction {
165 replaces,
166 summary: summary.to_string(),
167 },
168 Metadata::new(Utc::now()),
169 )
170 }
171
172 #[tokio::test]
173 async fn compaction_replaces_prior_turns_with_a_single_condensed_message() {
174 let store = InMemoryCommitStore::new();
175 let a = msg(vec![], Author::User, "one");
176 store.put(a.clone()).await.unwrap();
177 let b = msg(vec![a.id], Author::Assistant, "two");
178 store.put(b.clone()).await.unwrap();
179 let c = msg(vec![b.id], Author::User, "three");
180 store.put(c.clone()).await.unwrap();
181
182 let condensed = compaction(vec![c.id], vec![a.id, b.id], "one and two, condensed");
183 store.put(condensed.clone()).await.unwrap();
184
185 let ctx = materialize(&store, condensed.id).await.unwrap();
186 assert_eq!(ctx.manifest, vec![c.id, condensed.id]);
188 assert_eq!(ctx.messages.len(), 2);
189 assert!(matches!(ctx.messages[1].delta, Delta::Compaction { .. }));
190 }
191
192 #[tokio::test]
193 async fn compaction_does_not_delete_replaced_commits_from_the_store() {
194 let store = InMemoryCommitStore::new();
195 let a = msg(vec![], Author::User, "one");
196 store.put(a.clone()).await.unwrap();
197 let condensed = compaction(vec![a.id], vec![a.id], "condensed");
198 store.put(condensed.clone()).await.unwrap();
199
200 materialize(&store, condensed.id).await.unwrap();
201 assert!(store.get(&a.id).await.unwrap().is_some());
204 assert_eq!(store.len().await.unwrap(), 2);
205 }
206
207 #[tokio::test]
208 async fn compaction_referencing_an_id_not_in_the_current_window_is_a_harmless_noop() {
209 let store = InMemoryCommitStore::new();
214 let a = msg(vec![], Author::User, "one");
215 store.put(a.clone()).await.unwrap();
216 let stray = CommitId::from_bytes([77; 32]);
217 let condensed = compaction(vec![a.id], vec![stray], "condensed");
218 store.put(condensed.clone()).await.unwrap();
219
220 let ctx = materialize(&store, condensed.id).await.unwrap();
221 assert_eq!(ctx.manifest, vec![a.id, condensed.id]);
222 }
223
224 #[tokio::test]
225 async fn double_compaction_folds_an_already_compacted_region_cleanly() {
226 let store = InMemoryCommitStore::new();
227 let a = msg(vec![], Author::User, "one");
228 store.put(a.clone()).await.unwrap();
229 let b = msg(vec![a.id], Author::Assistant, "two");
230 store.put(b.clone()).await.unwrap();
231 let first = compaction(vec![b.id], vec![a.id], "a condensed");
232 store.put(first.clone()).await.unwrap();
233 let c = msg(vec![first.id], Author::User, "three");
234 store.put(c.clone()).await.unwrap();
235 let second = compaction(vec![c.id], vec![b.id, first.id], "everything condensed");
238 store.put(second.clone()).await.unwrap();
239
240 let ctx = materialize(&store, second.id).await.unwrap();
241 assert_eq!(ctx.manifest, vec![c.id, second.id]);
242 }
243
244 #[tokio::test]
245 async fn materializing_through_compaction_is_deterministic_and_idempotent() {
246 let store = InMemoryCommitStore::new();
247 let a = msg(vec![], Author::User, "one");
248 store.put(a.clone()).await.unwrap();
249 let b = msg(vec![a.id], Author::Assistant, "two");
250 store.put(b.clone()).await.unwrap();
251 let condensed = compaction(vec![b.id], vec![a.id], "condensed");
252 store.put(condensed.clone()).await.unwrap();
253
254 let first = materialize(&store, condensed.id).await.unwrap();
255 let second = materialize(&store, condensed.id).await.unwrap();
256 assert_eq!(first, second);
257 }
258
259 #[tokio::test]
260 async fn compaction_with_empty_replaces_list_is_just_an_added_message() {
261 let store = InMemoryCommitStore::new();
262 let a = msg(vec![], Author::User, "one");
263 store.put(a.clone()).await.unwrap();
264 let condensed = compaction(vec![a.id], vec![], "note");
265 store.put(condensed.clone()).await.unwrap();
266
267 let ctx = materialize(&store, condensed.id).await.unwrap();
268 assert_eq!(ctx.manifest, vec![a.id, condensed.id]);
269 assert_eq!(ctx.messages.len(), 2);
270 }
271}