Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 12.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Property tests of the history queries on random histories: the ancestry
5//! of [`History`], with generation numbers and skip pointers, answers what
6//! the walking functions answer, on histories with octopus merges and
7//! criss-cross merges; skip pointers find every first-parent ancestor; and
8//! derived records are the same whatever order they are computed in.
9
10use std::collections::BTreeSet;
11
12use braid_engine::{
13 DerivedIndex, History, MemoryIndex, commit, first_parent_chain_contains, is_ancestor,
14 merge_base, merge_bases, read_changeset, skip_height,
15};
16use braid_format::{Change, ChangeOp, Kind, MemoryObjects, ObjectId, Objects, Signature};
17use proptest::prelude::*;
18use proptest::sample::Index;
19
20/// How the next changesets of a random history are made.
21#[derive(Clone, Debug)]
22enum Step {
23 /// A changeset without parents.
24 Root,
25 /// A changeset on one parent.
26 Child(Index),
27 /// A merge of two to five parents, which may repeat.
28 Merge(Vec<Index>),
29 /// Two merges of the same two parents, in both orders.
30 CrissCross(Index, Index),
31}
32
33fn step() -> impl Strategy<Value = Step> {
34 prop_oneof![
35 1 => Just(Step::Root),
36 6 => any::<Index>().prop_map(Step::Child),
37 3 => proptest::collection::vec(any::<Index>(), 2..=5).prop_map(Step::Merge),
38 2 => (any::<Index>(), any::<Index>()).prop_map(|(a, b)| Step::CrissCross(a, b)),
39 ]
40}
41
42fn signature() -> Signature {
43 Signature {
44 name: b"Ada".to_vec(),
45 email: b"ada@example.org".to_vec(),
46 seconds: 1_700_000_000,
47 offset_minutes: 0,
48 }
49}
50
51/// A changeset with these parents that adds a file of its own, and changes
52/// a shared one every third time.
53fn node(objects: &MemoryObjects, parents: Vec<ObjectId>, n: usize) -> ObjectId {
54 let mut changes = Vec::new();
55 let mut set = |path: String, content: String| {
56 let blob = objects.put(Kind::Blob, content.as_bytes()).unwrap();
57 changes.push(Change {
58 path: path.into_bytes(),
59 op: ChangeOp::File {
60 blob,
61 size: content.len() as u64,
62 },
63 });
64 };
65 set(format!("n/{n}"), format!("{n}\n"));
66 if n.is_multiple_of(3) {
67 set("shared".to_owned(), format!("{n}\n"));
68 }
69 commit(
70 objects,
71 parents,
72 changes,
73 signature(),
74 signature(),
75 format!("{n}\n").into_bytes(),
76 Vec::new(),
77 )
78 .unwrap()
79}
80
81/// Builds a history from `steps`; returns every changeset, oldest first.
82fn build(objects: &MemoryObjects, steps: &[Step]) -> Vec<ObjectId> {
83 let mut nodes: Vec<ObjectId> = Vec::new();
84 for step in steps {
85 let pick = |index: &Index| nodes[index.index(nodes.len())];
86 let made = match step {
87 _ if nodes.is_empty() => vec![node(objects, Vec::new(), 0)],
88 Step::Root => vec![node(objects, Vec::new(), nodes.len())],
89 Step::Child(parent) => vec![node(objects, vec![pick(parent)], nodes.len())],
90 Step::Merge(parents) => {
91 vec![node(
92 objects,
93 parents.iter().map(pick).collect(),
94 nodes.len(),
95 )]
96 }
97 Step::CrissCross(a, b) => {
98 let (a, b) = (pick(a), pick(b));
99 let first = node(objects, vec![a, b], nodes.len());
100 let second = node(objects, vec![b, a], nodes.len() + 1);
101 vec![first, second]
102 }
103 };
104 nodes.extend(made);
105 }
106 nodes
107}
108
109/// `head` and all its ancestors, by walking.
110fn all_ancestors_of(objects: &MemoryObjects, head: ObjectId) -> BTreeSet<ObjectId> {
111 let mut seen = BTreeSet::from([head]);
112 let mut stack = vec![head];
113 while let Some(id) = stack.pop() {
114 for parent in read_changeset(objects, id).unwrap().parents {
115 if seen.insert(parent) {
116 stack.push(parent);
117 }
118 }
119 }
120 seen
121}
122
123/// The first-parent ancestor `steps` below `id`, by walking.
124fn walk_first_parents(objects: &MemoryObjects, id: ObjectId, steps: u64) -> Option<ObjectId> {
125 let mut at = id;
126 for _ in 0..steps {
127 at = *read_changeset(objects, at).unwrap().parents.first()?;
128 }
129 Some(at)
130}
131
132/// Every pair of the history's changesets, or about 120 of them spread over
133/// all of it.
134fn pairs(nodes: &[ObjectId]) -> Vec<(ObjectId, ObjectId)> {
135 let every = (nodes.len() * nodes.len()).div_ceil(120);
136 let mut pairs = Vec::new();
137 for (i, a) in nodes.iter().enumerate() {
138 for (j, b) in nodes.iter().enumerate() {
139 if (i * nodes.len() + j) % every == (i + j) % every {
140 pairs.push((*a, *b));
141 }
142 }
143 }
144 pairs
145}
146
147fn check_ancestry(
148 objects: &MemoryObjects,
149 history: &mut History<'_, MemoryObjects, &MemoryIndex>,
150 nodes: &[ObjectId],
151) -> Result<(), TestCaseError> {
152 for (a, b) in pairs(nodes) {
153 prop_assert_eq!(
154 history.merge_bases(a, b).unwrap(),
155 merge_bases(objects, a, b).unwrap(),
156 "merge bases of {} and {}",
157 a.short(),
158 b.short()
159 );
160 prop_assert_eq!(
161 history.merge_base(a, b).unwrap(),
162 merge_base(objects, a, b).unwrap()
163 );
164 prop_assert_eq!(
165 history.is_ancestor(a, b).unwrap(),
166 is_ancestor(objects, a, b).unwrap(),
167 "is {} an ancestor of {}",
168 a.short(),
169 b.short()
170 );
171 for limit in [0, 1, 3, usize::MAX] {
172 prop_assert_eq!(
173 history.first_parent_chain_contains(a, b, limit).unwrap(),
174 first_parent_chain_contains(objects, a, b, limit).unwrap(),
175 "is {} on the chain of {} within {}",
176 b.short(),
177 a.short(),
178 limit
179 );
180 }
181 }
182 // Several at once, against every ancestor found by walking.
183 for (i, head) in nodes.iter().enumerate().step_by(3) {
184 let ancestors = all_ancestors_of(objects, *head);
185 for wanted in [
186 nodes
187 .iter()
188 .skip(i % 3)
189 .step_by(4)
190 .copied()
191 .collect::<Vec<_>>(),
192 nodes.iter().take(i).step_by(5).copied().collect(),
193 ] {
194 let expected = wanted.iter().all(|id| ancestors.contains(id));
195 prop_assert_eq!(history.all_ancestors(&wanted, *head).unwrap(), expected);
196 }
197 }
198 // Ids that are not changesets are nobody's ancestors.
199 let absent = ObjectId::hash(Kind::Changeset, b"absent");
200 let head = *nodes.last().unwrap();
201 prop_assert!(!history.is_ancestor(absent, head).unwrap());
202 prop_assert!(
203 !history
204 .first_parent_chain_contains(head, absent, usize::MAX)
205 .unwrap()
206 );
207 Ok(())
208}
209
210proptest! {
211 #![proptest_config(ProptestConfig::with_cases(32))]
212
213 #[test]
214 fn ancestry_with_derived_data_equals_the_walks(
215 steps in proptest::collection::vec(step(), 1..24),
216 ) {
217 let objects = MemoryObjects::new();
218 let nodes = build(&objects, &steps);
219 let index = MemoryIndex::new();
220
221 // With everything computed in this history.
222 let mut history = History::new(&objects, &index);
223 check_ancestry(&objects, &mut history, &nodes)?;
224 history.flush().unwrap();
225
226 // With everything read back from records.
227 let mut again = History::new(&objects, &index);
228 check_ancestry(&objects, &mut again, &nodes)?;
229 prop_assert_eq!(again.computed(), 0);
230 }
231
232 #[test]
233 fn skip_pointers_reach_every_first_parent_ancestor(
234 steps in proptest::collection::vec(step(), 1..60),
235 ) {
236 let objects = MemoryObjects::new();
237 let nodes = build(&objects, &steps);
238 let index = MemoryIndex::new();
239 let mut history = History::new(&objects, &index);
240 for id in &nodes {
241 let node = history.graph(*id).unwrap();
242 for steps in 0..=node.height + 1 {
243 prop_assert_eq!(
244 history.first_parent_ancestor(*id, steps).unwrap(),
245 walk_first_parents(&objects, *id, steps).filter(|_| steps <= node.height)
246 );
247 }
248 if let Some(skip) = node.skip {
249 prop_assert_eq!(history.graph(skip).unwrap().height, skip_height(node.height));
250 }
251 let parents = read_changeset(&objects, *id).unwrap().parents;
252 let mut generation = 0;
253 for parent in &parents {
254 generation = generation.max(history.generation(*parent).unwrap());
255 }
256 prop_assert_eq!(node.generation, generation + 1);
257 prop_assert_eq!(&node.parents, &parents);
258 }
259 }
260
261 #[test]
262 fn derived_records_do_not_depend_on_the_order_they_are_made_in(
263 steps in proptest::collection::vec(step(), 1..30),
264 order in any::<u64>(),
265 ) {
266 let objects = MemoryObjects::new();
267 let nodes = build(&objects, &steps);
268
269 // Oldest first, newest first, and in a shuffled order.
270 let mut shuffled = nodes.clone();
271 let mut state = order | 1;
272 for i in (1..shuffled.len()).rev() {
273 state ^= state << 13;
274 state ^= state >> 7;
275 state ^= state << 17;
276 shuffled.swap(i, (state % (i as u64 + 1)) as usize);
277 }
278 let mut orders = vec![nodes.clone(), nodes.iter().rev().copied().collect(), shuffled];
279 let mut results = Vec::new();
280 for order in orders.drain(..) {
281 let index = MemoryIndex::new();
282 let mut history = History::new(&objects, &index);
283 for id in &order {
284 history.derive(&[*id]).unwrap();
285 history.blame(*id, b"shared").unwrap();
286 }
287 history.flush().unwrap();
288 results.push(index.entries());
289 }
290 prop_assert_eq!(&results[0], &results[1]);
291 prop_assert_eq!(&results[0], &results[2]);
292 // Two records per changeset, plus blame records.
293 let changesets: BTreeSet<ObjectId> = nodes.iter().copied().collect();
294 prop_assert!(results[0].len() >= 2 * changesets.len());
295 }
296}
297
298#[test]
299fn skip_heights_follow_the_rule() {
300 let expected = [0, 0, 0, 1, 0, 1, 4, 1, 0, 1, 8, 1, 8, 1, 12, 9, 0, 1];
301 for (height, skip) in expected.iter().enumerate() {
302 assert_eq!(skip_height(height as u64), *skip, "height {height}");
303 }
304 for height in 1..10_000u64 {
305 assert!(skip_height(height) < height);
306 }
307 // Large heights land far away: following pointers takes few steps.
308 assert_eq!(skip_height(1 << 40), 0);
309 assert_eq!(skip_height((1 << 40) + 2), 1 << 40);
310}
311
312#[test]
313fn a_long_chain_is_walked_in_few_records() {
314 // A chain of 3000 changesets: once its graph data exists, reaching the
315 // root reads a few dozen records, not thousands.
316 let objects = MemoryObjects::new();
317 let edit = |parents: Vec<ObjectId>, n: usize| {
318 let content = format!("{n}\n");
319 let blob = objects.put(Kind::Blob, content.as_bytes()).unwrap();
320 let change = Change {
321 path: b"f".to_vec(),
322 op: ChangeOp::File {
323 blob,
324 size: content.len() as u64,
325 },
326 };
327 let message = content.clone().into_bytes();
328 commit(
329 &objects,
330 parents,
331 vec![change],
332 signature(),
333 signature(),
334 message,
335 Vec::new(),
336 )
337 .unwrap()
338 };
339 let mut at = edit(Vec::new(), 0);
340 let root = at;
341 for n in 1..3000 {
342 at = edit(vec![at], n);
343 }
344 let index = MemoryIndex::new();
345 let mut history = History::new(&objects, &index);
346 history.derive(&[at]).unwrap();
347
348 let counting = Counting {
349 inner: &index,
350 lookups: std::cell::Cell::new(0),
351 };
352 let mut fresh = History::new(&objects, &counting);
353 assert!(fresh.is_ancestor(root, at).unwrap());
354 assert!(
355 fresh
356 .first_parent_chain_contains(at, root, usize::MAX)
357 .unwrap()
358 );
359 assert_eq!(fresh.merge_bases(at, root).unwrap(), [root]);
360 assert_eq!(fresh.first_parent_ancestor(at, 2999).unwrap(), Some(root));
361 assert!(
362 counting.lookups.get() < 100,
363 "{} lookups",
364 counting.lookups.get()
365 );
366}
367
368/// An index that counts lookups.
369#[derive(Debug)]
370struct Counting<'i> {
371 inner: &'i MemoryIndex,
372 lookups: std::cell::Cell<usize>,
373}
374
375impl DerivedIndex for Counting<'_> {
376 type Error = std::convert::Infallible;
377
378 fn find(
379 &self,
380 key: &braid_engine::DerivedKey,
381 ) -> Result<Option<ObjectId>, std::convert::Infallible> {
382 self.lookups.set(self.lookups.get() + 1);
383 self.inner.find(key)
384 }
385
386 fn record(
387 &self,
388 entries: &[(braid_engine::DerivedKey, ObjectId)],
389 ) -> Result<(), std::convert::Infallible> {
390 self.inner.record(entries)
391 }
392}