Skip to main content

contextgraph_core/
bisect.rs

1//! `bisect`: git-bisect-for-agent-runs. Given a `good` commit (predicate
2//! holds) and a `bad` commit (predicate has flipped), finds the exact
3//! commit along their ancestry path where the predicate first goes false.
4//!
5//! Building the candidate path from `bad` back to `good` is an unavoidable
6//! O(depth) pointer-chase (there's no way to know the range without
7//! visiting it, same as `git rev-list` before a real bisect). The actual
8//! search *within* that path — the part that matters, because evaluating
9//! the predicate is the expensive step (materializing + checking agent
10//! behavior) — is a proper binary search: O(log n) predicate calls, never
11//! a linear scan.
12
13use crate::commit::CommitId;
14use crate::error::{GraphError, Result};
15use crate::materialize::{materialize, MaterializedContext};
16use crate::store::CommitStore;
17use serde::{Deserialize, Serialize};
18
19/// The outcome of a bisect run.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21pub enum BisectOutcome {
22    /// The predicate flips somewhere strictly between `good` and `bad`.
23    Flip(BisectResult),
24    /// The predicate never flips across the given range (it's `true`
25    /// (still "good") at `bad` too, or already `false` at `good`). This is
26    /// a normal, clearly-reported outcome — not an error.
27    NoFlip,
28}
29
30/// The two adjacent commits straddling the flip point.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct BisectResult {
33    /// The last commit (closest to `bad`) where the predicate still held.
34    pub last_good: CommitId,
35    /// The first commit (closest to `good`) where the predicate no longer held.
36    pub first_bad: CommitId,
37    /// Number of predicate evaluations performed (for verifying O(log n)).
38    pub predicate_calls: usize,
39}
40
41/// Walks the first-parent ancestry from `bad` back to `good`, returning the
42/// path in root-to-descendant order (`good` first, `bad` last). Fails if
43/// `good` is not on `bad`'s first-parent ancestry path.
44async fn ancestry_path<S: CommitStore + ?Sized>(
45    store: &S,
46    good: CommitId,
47    bad: CommitId,
48) -> Result<Vec<CommitId>> {
49    let mut path = vec![bad];
50    let mut current = bad;
51    while current != good {
52        let commit = store
53            .get(&current)
54            .await?
55            .ok_or(GraphError::CommitNotFound(current))?;
56        match commit.parent_ids.first() {
57            Some(parent) => {
58                current = *parent;
59                path.push(current);
60            }
61            None => return Err(GraphError::InvalidBisectRange(good, bad)),
62        }
63    }
64    path.reverse();
65    Ok(path)
66}
67
68/// Binary-searches the ancestry path between `good` and `bad` for the exact
69/// commit where `predicate` flips from `true` to `false`.
70///
71/// Contract: `predicate` is expected to be monotonic along the path — true
72/// for a prefix starting at `good`, false for a suffix ending at `bad`.
73/// Constructed test DAGs uphold this by design; if it doesn't hold in
74/// practice (e.g. flaky predicate), the search still terminates in
75/// O(log n) calls but the reported boundary is only meaningful under the
76/// monotonicity assumption, exactly as with `git bisect`.
77pub async fn bisect<S, F>(
78    store: &S,
79    good: CommitId,
80    bad: CommitId,
81    mut predicate: F,
82) -> Result<BisectOutcome>
83where
84    S: CommitStore + ?Sized,
85    F: FnMut(&MaterializedContext) -> bool,
86{
87    let path = ancestry_path(store, good, bad).await?;
88
89    // Trivial range: a single commit has no boundary to find.
90    if path.len() == 1 {
91        return Ok(BisectOutcome::NoFlip);
92    }
93
94    let mut calls = 0usize;
95    let mut lo = 0usize;
96    let mut hi = path.len() - 1;
97
98    let good_ctx = materialize(store, path[lo]).await?;
99    calls += 1;
100    if !predicate(&good_ctx) {
101        return Ok(BisectOutcome::NoFlip);
102    }
103
104    let bad_ctx = materialize(store, path[hi]).await?;
105    calls += 1;
106    if predicate(&bad_ctx) {
107        return Ok(BisectOutcome::NoFlip);
108    }
109
110    while hi - lo > 1 {
111        let mid = lo + (hi - lo) / 2;
112        let mid_ctx = materialize(store, path[mid]).await?;
113        calls += 1;
114        if predicate(&mid_ctx) {
115            lo = mid;
116        } else {
117            hi = mid;
118        }
119    }
120
121    Ok(BisectOutcome::Flip(BisectResult {
122        last_good: path[lo],
123        first_bad: path[hi],
124        predicate_calls: calls,
125    }))
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use crate::commit::{Author, Commit, Delta, Metadata};
132    use crate::mem::InMemoryCommitStore;
133    use chrono::Utc;
134
135    /// Builds a linear chain of `n` commits, tagging each with its index so
136    /// tests can define a predicate purely in terms of position.
137    async fn build_chain(store: &InMemoryCommitStore, n: usize) -> Vec<CommitId> {
138        let mut ids = Vec::new();
139        let mut parent = None;
140        for i in 0..n {
141            let commit = Commit::new(
142                parent.into_iter().collect(),
143                Author::User,
144                Delta::Message {
145                    content: format!("turn-{i}"),
146                },
147                Metadata::new(Utc::now()).with_tag("index", i.to_string()),
148            );
149            let id = store.put(commit).await.unwrap();
150            ids.push(id);
151            parent = Some(id);
152        }
153        ids
154    }
155
156    fn index_of(ctx: &MaterializedContext) -> usize {
157        // The predicate operates on the tag of the *last* contributing
158        // commit's tag, which we look up via the manifest's tail — but tags
159        // live on Metadata, not on MaterializedMessage, so tests instead
160        // decode the index from the message content ("turn-N").
161        let last = ctx.messages.last().unwrap();
162        match &last.delta {
163            Delta::Message { content } => content
164                .strip_prefix("turn-")
165                .and_then(|s| s.parse().ok())
166                .unwrap(),
167            _ => unreachable!(),
168        }
169    }
170
171    async fn bisect_flip_at(n: usize, flip_at: usize) -> (BisectOutcome, usize) {
172        let store = InMemoryCommitStore::new();
173        let ids = build_chain(&store, n).await;
174        let good = ids[0];
175        let bad = *ids.last().unwrap();
176        let mut calls = 0usize;
177        let outcome = bisect(&store, good, bad, |ctx| {
178            calls += 1;
179            index_of(ctx) < flip_at
180        })
181        .await
182        .unwrap();
183        (outcome, calls)
184    }
185
186    #[tokio::test]
187    async fn bisect_finds_the_exact_known_flip_point_in_a_small_chain() {
188        let store = InMemoryCommitStore::new();
189        let ids = build_chain(&store, 10).await;
190        let flip_at = 6; // predicate true for indices 0..6, false for 6..10
191        let outcome = bisect(&store, ids[0], *ids.last().unwrap(), |ctx| {
192            index_of(ctx) < flip_at
193        })
194        .await
195        .unwrap();
196
197        match outcome {
198            BisectOutcome::Flip(r) => {
199                assert_eq!(r.last_good, ids[flip_at - 1]);
200                assert_eq!(r.first_bad, ids[flip_at]);
201            }
202            BisectOutcome::NoFlip => panic!("expected a flip"),
203        }
204    }
205
206    #[tokio::test]
207    async fn bisect_over_two_commit_range_resolves_without_looping() {
208        let store = InMemoryCommitStore::new();
209        let ids = build_chain(&store, 2).await;
210        let outcome = bisect(&store, ids[0], ids[1], |ctx| index_of(ctx) < 1)
211            .await
212            .unwrap();
213        match outcome {
214            BisectOutcome::Flip(r) => {
215                assert_eq!(r.last_good, ids[0]);
216                assert_eq!(r.first_bad, ids[1]);
217            }
218            BisectOutcome::NoFlip => panic!("expected a flip"),
219        }
220    }
221
222    #[tokio::test]
223    async fn bisect_over_a_single_commit_range_does_not_panic_or_underflow() {
224        let store = InMemoryCommitStore::new();
225        let ids = build_chain(&store, 1).await;
226        let outcome = bisect(&store, ids[0], ids[0], |_| true).await.unwrap();
227        assert_eq!(outcome, BisectOutcome::NoFlip);
228    }
229
230    #[tokio::test]
231    async fn bisect_with_a_predicate_that_never_flips_reports_no_flip_cleanly() {
232        let store = InMemoryCommitStore::new();
233        let ids = build_chain(&store, 8).await;
234        let outcome = bisect(&store, ids[0], *ids.last().unwrap(), |_| true)
235            .await
236            .unwrap();
237        assert_eq!(outcome, BisectOutcome::NoFlip);
238    }
239
240    #[tokio::test]
241    async fn bisect_where_good_already_exhibits_bad_behavior_reports_no_flip() {
242        let store = InMemoryCommitStore::new();
243        let ids = build_chain(&store, 5).await;
244        let outcome = bisect(&store, ids[0], *ids.last().unwrap(), |_| false)
245            .await
246            .unwrap();
247        assert_eq!(outcome, BisectOutcome::NoFlip);
248    }
249
250    #[tokio::test]
251    async fn bisect_from_a_commit_that_is_not_an_ancestor_fails() {
252        let store = InMemoryCommitStore::new();
253        let a = build_chain(&store, 3).await;
254        let unrelated = Commit::new(
255            vec![],
256            Author::User,
257            Delta::Message {
258                content: "unrelated".into(),
259            },
260            Metadata::new(Utc::now()),
261        );
262        let unrelated_id = store.put(unrelated).await.unwrap();
263
264        let err = bisect(&store, unrelated_id, *a.last().unwrap(), |_| true)
265            .await
266            .unwrap_err();
267        assert!(matches!(err, GraphError::InvalidBisectRange(_, _)));
268    }
269
270    #[tokio::test]
271    async fn bisect_performs_logarithmically_many_predicate_calls_across_sizes() {
272        // Power-of-two-adjacent sizes are where off-by-one bisect bugs
273        // cluster, so exercise a spread of them.
274        for &n in &[2usize, 3, 4, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65] {
275            let flip_at = n / 2;
276            let (outcome, calls) = bisect_flip_at(n, flip_at.max(1)).await;
277            assert!(matches!(outcome, BisectOutcome::Flip(_)), "n={n}");
278            let max_expected = (n as f64).log2().ceil() as usize + 2;
279            assert!(
280                calls <= max_expected,
281                "n={n} used {calls} predicate calls, expected <= {max_expected}"
282            );
283        }
284    }
285}