Skip to main content

contextgraph_core/
log.rs

1//! History walks: `log` over a commit's ancestry (or a branch's full
2//! history, which is just the ancestry of its head), with metadata-tag
3//! filtering and pagination.
4
5use crate::commit::{Commit, CommitId};
6use crate::error::{GraphError, Result};
7use crate::store::CommitStore;
8use serde::{Deserialize, Serialize};
9use std::collections::BTreeMap;
10
11/// Filters commits by exact tag match. A commit must carry every listed
12/// key/value pair (in `metadata.tags`) to pass. An empty filter matches
13/// everything.
14#[derive(Debug, Clone, Default, PartialEq, Eq)]
15pub struct LogFilter {
16    pub tags: BTreeMap<String, String>,
17}
18
19impl LogFilter {
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
25        self.tags.insert(key.into(), value.into());
26        self
27    }
28
29    fn matches(&self, commit: &Commit) -> bool {
30        self.tags
31            .iter()
32            .all(|(k, v)| commit.metadata.tags.get(k) == Some(v))
33    }
34}
35
36/// A page of `log` results, newest (closest to the requested head) first.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct LogPage {
39    pub commits: Vec<Commit>,
40    /// Total commits matching the filter, before pagination.
41    pub total_matched: usize,
42    pub has_more: bool,
43}
44
45/// Walks the first-parent ancestry of `from` back to the root, newest
46/// (i.e. `from`) first, applying `filter` and then `offset`/`limit`
47/// pagination. This is a plain linear walk — `bisect` (milestone 7) is the
48/// log-n counterpart for narrowing to a single flip point, but `log` itself
49/// always has to visit every candidate commit to filter and count them.
50pub async fn log_ancestors<S: CommitStore + ?Sized>(
51    store: &S,
52    from: CommitId,
53    filter: &LogFilter,
54    offset: usize,
55    limit: usize,
56) -> Result<LogPage> {
57    let mut chain = Vec::new();
58    let mut current = Some(from);
59    while let Some(id) = current {
60        let commit = store
61            .get(&id)
62            .await?
63            .ok_or(GraphError::CommitNotFound(id))?;
64        current = commit.parent_ids.first().copied();
65        chain.push(commit);
66    }
67
68    let filtered: Vec<Commit> = chain.into_iter().filter(|c| filter.matches(c)).collect();
69    let total_matched = filtered.len();
70    let page: Vec<Commit> = filtered.into_iter().skip(offset).take(limit).collect();
71    let has_more = offset.saturating_add(page.len()) < total_matched;
72
73    Ok(LogPage {
74        commits: page,
75        total_matched,
76        has_more,
77    })
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use crate::commit::{Author, Commit, Delta, Metadata};
84    use crate::mem::InMemoryCommitStore;
85    use chrono::Utc;
86
87    async fn build_chain(
88        store: &InMemoryCommitStore,
89        n: usize,
90        tag_every: Option<&str>,
91    ) -> Vec<CommitId> {
92        let mut ids = Vec::new();
93        let mut parent = None;
94        for i in 0..n {
95            let mut meta = Metadata::new(Utc::now());
96            if let Some(tag_value) = tag_every {
97                if i % 2 == 0 {
98                    meta = meta.with_tag("step", tag_value);
99                }
100            }
101            let commit = Commit::new(
102                parent.into_iter().collect(),
103                Author::User,
104                Delta::Message {
105                    content: format!("msg-{i}"),
106                },
107                meta,
108            );
109            let id = store.put(commit).await.unwrap();
110            ids.push(id);
111            parent = Some(id);
112        }
113        ids
114    }
115
116    #[tokio::test]
117    async fn log_over_a_chain_returns_newest_first() {
118        let store = InMemoryCommitStore::new();
119        let ids = build_chain(&store, 3, None).await;
120        let page = log_ancestors(&store, *ids.last().unwrap(), &LogFilter::new(), 0, 10)
121            .await
122            .unwrap();
123        let returned: Vec<CommitId> = page.commits.iter().map(|c| c.id).collect();
124        assert_eq!(returned, vec![ids[2], ids[1], ids[0]]);
125        assert_eq!(page.total_matched, 3);
126        assert!(!page.has_more);
127    }
128
129    #[tokio::test]
130    async fn log_pagination_returns_correct_page_and_has_more_flag() {
131        let store = InMemoryCommitStore::new();
132        let ids = build_chain(&store, 5, None).await;
133        let page = log_ancestors(&store, *ids.last().unwrap(), &LogFilter::new(), 1, 2)
134            .await
135            .unwrap();
136        let returned: Vec<CommitId> = page.commits.iter().map(|c| c.id).collect();
137        assert_eq!(returned, vec![ids[3], ids[2]]);
138        assert_eq!(page.total_matched, 5);
139        assert!(page.has_more);
140    }
141
142    #[tokio::test]
143    async fn log_pagination_offset_beyond_range_yields_empty_page_without_more() {
144        let store = InMemoryCommitStore::new();
145        let ids = build_chain(&store, 3, None).await;
146        let page = log_ancestors(&store, *ids.last().unwrap(), &LogFilter::new(), 10, 5)
147            .await
148            .unwrap();
149        assert!(page.commits.is_empty());
150        assert!(!page.has_more);
151    }
152
153    #[tokio::test]
154    async fn log_with_tag_filter_returns_only_matching_commits_at_the_exact_boundary() {
155        let store = InMemoryCommitStore::new();
156        // commits 0, 2, 4 get tag step=planning; 1, 3 get none.
157        let ids = build_chain(&store, 5, Some("planning")).await;
158        let filter = LogFilter::new().with_tag("step", "planning");
159        let page = log_ancestors(&store, *ids.last().unwrap(), &filter, 0, 10)
160            .await
161            .unwrap();
162        let returned: Vec<CommitId> = page.commits.iter().map(|c| c.id).collect();
163        assert_eq!(returned, vec![ids[4], ids[2], ids[0]]);
164        assert_eq!(page.total_matched, 3);
165    }
166
167    #[tokio::test]
168    async fn log_with_tag_filter_that_matches_nothing_returns_empty_page() {
169        let store = InMemoryCommitStore::new();
170        let ids = build_chain(&store, 3, Some("planning")).await;
171        let filter = LogFilter::new().with_tag("step", "execution");
172        let page = log_ancestors(&store, *ids.last().unwrap(), &filter, 0, 10)
173            .await
174            .unwrap();
175        assert!(page.commits.is_empty());
176        assert_eq!(page.total_matched, 0);
177    }
178
179    #[tokio::test]
180    async fn log_over_single_commit_range_does_not_panic() {
181        let store = InMemoryCommitStore::new();
182        let ids = build_chain(&store, 1, None).await;
183        let page = log_ancestors(&store, ids[0], &LogFilter::new(), 0, 10)
184            .await
185            .unwrap();
186        assert_eq!(page.commits.len(), 1);
187    }
188
189    #[tokio::test]
190    async fn log_from_nonexistent_commit_fails() {
191        let store = InMemoryCommitStore::new();
192        let err = log_ancestors(&store, CommitId::from_bytes([9; 32]), &LogFilter::new(), 0, 10)
193            .await
194            .unwrap_err();
195        assert!(matches!(err, GraphError::CommitNotFound(_)));
196    }
197}