1use crate::commit::CommitId;
14use crate::error::{GraphError, Result};
15use crate::materialize::{materialize, MaterializedContext};
16use crate::store::CommitStore;
17use serde::{Deserialize, Serialize};
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21pub enum BisectOutcome {
22 Flip(BisectResult),
24 NoFlip,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct BisectResult {
33 pub last_good: CommitId,
35 pub first_bad: CommitId,
37 pub predicate_calls: usize,
39}
40
41async 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(¤t)
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
68pub 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 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 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 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; 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 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}