Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 28.4 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Ancestry: first-parent chains and merge bases.
5//!
6//! The free functions walk history one changeset at a time, reading only
7//! objects, so they cost time proportional to the part of history they
8//! cover. The methods of [`History`] of the same names give the same answers
9//! with commit graph data, derived data stored per changeset:
10//!
11//! - the **generation**, 1 for a changeset without parents and otherwise 1
12//! more than the largest generation of its parents, so that an ancestor
13//! always has a smaller generation than its descendants and walks stop as
14//! soon as they go below the one they look for;
15//! - the **height**, the number of first parents down to a changeset
16//! without parents, and a **skip pointer** to the first-parent ancestor at
17//! height [`skip_height`]`(height)`, the rule of Bitcoin's block index:
18//! following skip pointers reaches any first-parent ancestor in a number of
19//! steps that grows with the logarithm of the distance.
20//!
21//! The derived function `graph`, version 1, of a changeset is:
22//!
23//! ```text
24//! uv n, n × [32] parents, in order
25//! uv generation
26//! uv height
27//! [32] skip pointer, when the height is not 0
28//! ```
29//!
30//! It depends on the parents' values, so computing it for a changeset
31//! computes it for every ancestor that lacks it, once; afterwards a query
32//! reads only the records it needs.
33
34use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
35use std::rc::Rc;
36
37use braid_format::codec::{Reader, put_id, put_uv};
38use braid_format::{DecodeError, Kind, ObjectId, Objects};
39
40use crate::access::read_changeset;
41use crate::derived::{DerivedIndex, DerivedKey};
42use crate::error::{Error, store_error};
43use crate::history::History;
44
45/// Whether `base` is `head` or one of its first-parent ancestors no more than
46/// `limit` steps away. Walking stops at the limit, so `false` also means "not
47/// within `limit` steps".
48pub fn first_parent_chain_contains<O: Objects>(
49 objects: &O,
50 head: ObjectId,
51 base: ObjectId,
52 limit: usize,
53) -> Result<bool, Error> {
54 let mut current = head;
55 let mut steps = 0;
56 loop {
57 if current == base {
58 return Ok(true);
59 }
60 if steps == limit {
61 return Ok(false);
62 }
63 match read_changeset(objects, current)?.parents.first() {
64 Some(parent) => current = *parent,
65 None => return Ok(false),
66 }
67 steps += 1;
68 }
69}
70
71/// The best common ancestors of `a` and `b`: the common ancestors (a
72/// changeset counts as its own ancestor) that are not ancestors of another
73/// common ancestor. There are several after criss-cross merges, and none when
74/// the histories are unrelated. Sorted by id.
75pub fn merge_bases<O: Objects>(
76 objects: &O,
77 a: ObjectId,
78 b: ObjectId,
79) -> Result<Vec<ObjectId>, Error> {
80 let mut graph = Graph {
81 objects,
82 parents: HashMap::new(),
83 };
84 let from_a = graph.ancestors(vec![a])?;
85
86 // Walk back from `b`, stopping on each path at the first common ancestor.
87 // Every common ancestor is one of these or an ancestor of one of them.
88 let mut candidates = Vec::new();
89 let mut seen = HashSet::from([b]);
90 let mut queue = VecDeque::from([b]);
91 while let Some(id) = queue.pop_front() {
92 if from_a.contains(&id) {
93 candidates.push(id);
94 continue;
95 }
96 for parent in graph.parents(id)? {
97 if seen.insert(parent) {
98 queue.push_back(parent);
99 }
100 }
101 }
102
103 // Drop the candidates that are ancestors of other candidates.
104 if candidates.len() > 1 {
105 let mut starts = Vec::new();
106 for candidate in &candidates {
107 starts.extend(graph.parents(*candidate)?);
108 }
109 let below = graph.ancestors(starts)?;
110 candidates.retain(|candidate| !below.contains(candidate));
111 }
112 candidates.sort();
113 Ok(candidates)
114}
115
116/// One best common ancestor of `a` and `b`, or `None` if their histories are
117/// unrelated. When there are several (see [`merge_bases`]), the one with the
118/// smallest id, so the answer does not depend on how history was walked.
119pub fn merge_base<O: Objects>(
120 objects: &O,
121 a: ObjectId,
122 b: ObjectId,
123) -> Result<Option<ObjectId>, Error> {
124 Ok(merge_bases(objects, a, b)?.into_iter().next())
125}
126
127/// Whether `ancestor` is `descendant` or one of its ancestors, through any
128/// parents. The walk goes back from `descendant` and stops when it finds
129/// `ancestor`, so a "no" covers the whole history behind `descendant`.
130pub fn is_ancestor<O: Objects>(
131 objects: &O,
132 ancestor: ObjectId,
133 descendant: ObjectId,
134) -> Result<bool, Error> {
135 all_ancestors(objects, &[ancestor], descendant)
136}
137
138/// Whether each of `ids` is `head` or one of its ancestors: one walk back
139/// from `head`, which stops as soon as all of them are found.
140pub(crate) fn all_ancestors<O: Objects>(
141 objects: &O,
142 ids: &[ObjectId],
143 head: ObjectId,
144) -> Result<bool, Error> {
145 let mut wanted: HashSet<ObjectId> = ids.iter().copied().collect();
146 if wanted.is_empty() {
147 return Ok(true);
148 }
149 let mut graph = Graph {
150 objects,
151 parents: HashMap::new(),
152 };
153 let mut seen = HashSet::from([head]);
154 let mut queue = VecDeque::from([head]);
155 while let Some(id) = queue.pop_front() {
156 if wanted.remove(&id) && wanted.is_empty() {
157 return Ok(true);
158 }
159 for parent in graph.parents(id)? {
160 if seen.insert(parent) {
161 queue.push_back(parent);
162 }
163 }
164 }
165 Ok(false)
166}
167
168/// Parents of changesets, read once each.
169struct Graph<'o, O> {
170 objects: &'o O,
171 parents: HashMap<ObjectId, Vec<ObjectId>>,
172}
173
174impl<O: Objects> Graph<'_, O> {
175 fn parents(&mut self, id: ObjectId) -> Result<Vec<ObjectId>, Error> {
176 if let Some(parents) = self.parents.get(&id) {
177 return Ok(parents.clone());
178 }
179 let parents = read_changeset(self.objects, id)?.parents;
180 self.parents.insert(id, parents.clone());
181 Ok(parents)
182 }
183
184 /// `starts` and all their ancestors.
185 fn ancestors(&mut self, starts: Vec<ObjectId>) -> Result<HashSet<ObjectId>, Error> {
186 let mut seen: HashSet<ObjectId> = starts.iter().copied().collect();
187 let mut queue: VecDeque<ObjectId> = starts.into();
188 while let Some(id) = queue.pop_front() {
189 for parent in self.parents(id)? {
190 if seen.insert(parent) {
191 queue.push_back(parent);
192 }
193 }
194 }
195 Ok(seen)
196 }
197}
198
199/// The derived function of commit graph data.
200const GRAPH: &str = "graph";
201
202/// The version of its encoding.
203const GRAPH_VERSION: u64 = 1;
204
205/// What the commit graph records of a changeset: the value of the derived
206/// function `graph`, version 1 (section 8 of the format spec).
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct GraphNode {
209 /// The parents, in order.
210 pub parents: Vec<ObjectId>,
211 /// 1 without parents, otherwise 1 more than the largest generation of
212 /// the parents.
213 pub generation: u64,
214 /// The number of first parents down to a changeset without parents.
215 pub height: u64,
216 /// The first-parent ancestor at height [`skip_height`]`(height)`; `None`
217 /// exactly when the height is 0.
218 pub skip: Option<ObjectId>,
219}
220
221impl GraphNode {
222 fn encode(&self) -> Vec<u8> {
223 let mut out = Vec::with_capacity(16 + 32 * (self.parents.len() + 1));
224 put_uv(&mut out, self.parents.len() as u64);
225 for parent in &self.parents {
226 put_id(&mut out, parent);
227 }
228 put_uv(&mut out, self.generation);
229 put_uv(&mut out, self.height);
230 if let Some(skip) = &self.skip {
231 put_id(&mut out, skip);
232 }
233 out
234 }
235
236 /// Decodes a value, checking what it can without other records.
237 fn decode(value: &[u8]) -> Option<GraphNode> {
238 let read = || -> Result<GraphNode, DecodeError> {
239 let mut reader = Reader::new(value);
240 let count = reader.count(ObjectId::LEN)?;
241 let mut parents = Vec::with_capacity(count);
242 for _ in 0..count {
243 parents.push(reader.id()?);
244 }
245 let generation = reader.uv()?;
246 let height = reader.uv()?;
247 let skip = if height == 0 {
248 None
249 } else {
250 Some(reader.id()?)
251 };
252 reader.finish()?;
253 Ok(GraphNode {
254 parents,
255 generation,
256 height,
257 skip,
258 })
259 };
260 let node = read().ok()?;
261 let consistent = if node.parents.is_empty() {
262 node.generation == 1 && node.height == 0
263 } else {
264 node.generation >= 2 && node.height >= 1
265 };
266 consistent.then_some(node)
267 }
268}
269
270/// The height the skip pointer of a changeset at `height` points to, by the
271/// rule of Bitcoin's block index: 0 below 2; for an even height, the height
272/// with its lowest set bit cleared; for an odd one, 1 more than `height - 1`
273/// with its two lowest set bits cleared. Always below `height` when `height`
274/// is not 0.
275pub fn skip_height(height: u64) -> u64 {
276 fn clear_lowest_bit(n: u64) -> u64 {
277 n & n.wrapping_sub(1)
278 }
279 if height < 2 {
280 0
281 } else if height & 1 == 1 {
282 clear_lowest_bit(clear_lowest_bit(height - 1)) + 1
283 } else {
284 clear_lowest_bit(height)
285 }
286}
287
288/// Flags of the walk that finds merge bases.
289const FROM_A: u8 = 1;
290const FROM_B: u8 = 2;
291const FROM_BOTH: u8 = FROM_A | FROM_B;
292/// Below a merge base already found, so not a best one.
293const STALE: u8 = 4;
294
295impl<O: Objects, I: DerivedIndex> History<'_, O, I> {
296 /// The commit graph data of a changeset, computed for it and for its
297 /// ancestors when missing.
298 pub fn graph(&mut self, id: ObjectId) -> Result<GraphNode, Error> {
299 let node = self.node(id)?;
300 Ok(GraphNode::clone(&node))
301 }
302
303 /// The generation of a changeset (see [`GraphNode::generation`]).
304 pub fn generation(&mut self, id: ObjectId) -> Result<u64, Error> {
305 Ok(self.node(id)?.generation)
306 }
307
308 /// The changeset `steps` first parents below `id` (`id` itself for 0), or
309 /// `None` when the chain is shorter. Logarithmic in `steps`.
310 pub fn first_parent_ancestor(
311 &mut self,
312 id: ObjectId,
313 steps: u64,
314 ) -> Result<Option<ObjectId>, Error> {
315 let height = self.node(id)?.height;
316 if steps > height {
317 return Ok(None);
318 }
319 Ok(Some(self.ancestor_at(id, height - steps)?))
320 }
321
322 /// Whether `base` is `head` or one of its first-parent ancestors no more
323 /// than `limit` steps away, as [`first_parent_chain_contains`] says, with
324 /// skip pointers: logarithmic in the distance.
325 pub fn first_parent_chain_contains(
326 &mut self,
327 head: ObjectId,
328 base: ObjectId,
329 limit: usize,
330 ) -> Result<bool, Error> {
331 if head == base {
332 return Ok(true);
333 }
334 if limit == 0 {
335 return Ok(false);
336 }
337 let top = self.node(head)?;
338 if !self.is_changeset(base)? {
339 return Ok(false);
340 }
341 let target = self.node(base)?;
342 if target.height >= top.height || top.height - target.height > limit as u64 {
343 return Ok(false);
344 }
345 Ok(self.ancestor_at(head, target.height)? == base)
346 }
347
348 /// Whether `ancestor` is `descendant` or one of its ancestors, as
349 /// [`is_ancestor`] says. A first-parent ancestor is found through skip
350 /// pointers; otherwise the walk back from `descendant` never goes below
351 /// the generation of `ancestor`.
352 pub fn is_ancestor(&mut self, ancestor: ObjectId, descendant: ObjectId) -> Result<bool, Error> {
353 self.all_ancestors(&[ancestor], descendant)
354 }
355
356 /// Whether each of `ids` is `head` or one of its ancestors: the answer of
357 /// [`is_ancestor`] for all of them at once. The walk back from `head`
358 /// never goes below the smallest generation among them.
359 pub fn all_ancestors(&mut self, ids: &[ObjectId], head: ObjectId) -> Result<bool, Error> {
360 let mut wanted: HashSet<ObjectId> = ids.iter().copied().collect();
361 wanted.remove(&head);
362 if wanted.is_empty() {
363 return Ok(true);
364 }
365 let top = self.node(head)?;
366 let mut floor = u64::MAX;
367 let mut off_chain = HashSet::new();
368 for id in wanted {
369 if !self.is_changeset(id)? {
370 return Ok(false);
371 }
372 let node = self.node(id)?;
373 if node.generation >= top.generation {
374 return Ok(false);
375 }
376 if node.height < top.height && self.ancestor_at(head, node.height)? == id {
377 continue;
378 }
379 floor = floor.min(node.generation);
380 off_chain.insert(id);
381 }
382 if off_chain.is_empty() {
383 return Ok(true);
384 }
385 let mut seen = HashSet::from([head]);
386 let mut stack = vec![head];
387 while let Some(id) = stack.pop() {
388 let node = self.node(id)?;
389 for &parent in &node.parents {
390 if !seen.insert(parent) {
391 continue;
392 }
393 if off_chain.remove(&parent) && off_chain.is_empty() {
394 return Ok(true);
395 }
396 if self.node(parent)?.generation > floor {
397 stack.push(parent);
398 }
399 }
400 }
401 Ok(false)
402 }
403
404 /// The best common ancestors of `a` and `b`, sorted by id, as
405 /// [`merge_bases`] says.
406 ///
407 /// When one is a first-parent ancestor of the other, skip pointers find
408 /// it. Otherwise the walk goes down from both in order of generation,
409 /// marking what it reaches from each side; a changeset reached from both
410 /// is a best common ancestor unless it is below one already found, and
411 /// the walk stops when everything left to visit is below one. It visits
412 /// the changesets between `a`, `b` and their merge bases, never all of
413 /// history unless the histories are unrelated.
414 pub fn merge_bases(&mut self, a: ObjectId, b: ObjectId) -> Result<Vec<ObjectId>, Error> {
415 let (top_a, top_b) = (self.node(a)?, self.node(b)?);
416 if a == b {
417 return Ok(vec![a]);
418 }
419 if top_b.height < top_a.height && self.ancestor_at(a, top_b.height)? == b {
420 return Ok(vec![b]);
421 }
422 if top_a.height < top_b.height && self.ancestor_at(b, top_a.height)? == a {
423 return Ok(vec![a]);
424 }
425
426 let mut flags: HashMap<ObjectId, u8> = HashMap::from([(a, FROM_A), (b, FROM_B)]);
427 let mut queue = BinaryHeap::from([(top_a.generation, a), (top_b.generation, b)]);
428 // Queued changesets, and those of them that are not stale.
429 let mut queued = HashSet::from([a, b]);
430 let mut live = HashSet::from([a, b]);
431 let mut bases = Vec::new();
432 while !live.is_empty() {
433 let Some((_, id)) = queue.pop() else {
434 break;
435 };
436 queued.remove(&id);
437 live.remove(&id);
438 let mut mark = flags[&id];
439 if mark & (FROM_BOTH | STALE) == FROM_BOTH {
440 bases.push(id);
441 mark |= STALE;
442 flags.insert(id, mark);
443 }
444 let node = self.node(id)?;
445 for &parent in &node.parents {
446 let old = flags.get(&parent).copied().unwrap_or(0);
447 let new = old | mark;
448 if new == old {
449 continue;
450 }
451 flags.insert(parent, new);
452 if queued.insert(parent) {
453 let generation = self.node(parent)?.generation;
454 queue.push((generation, parent));
455 }
456 if new & STALE == 0 {
457 live.insert(parent);
458 } else {
459 live.remove(&parent);
460 }
461 }
462 }
463 bases.sort();
464 Ok(bases)
465 }
466
467 /// One best common ancestor of `a` and `b`, the one with the smallest id,
468 /// as [`merge_base`] says.
469 pub fn merge_base(&mut self, a: ObjectId, b: ObjectId) -> Result<Option<ObjectId>, Error> {
470 Ok(self.merge_bases(a, b)?.into_iter().next())
471 }
472
473 /// Whether `id` is stored as a changeset.
474 fn is_changeset(&mut self, id: ObjectId) -> Result<bool, Error> {
475 if self.nodes.contains_key(&id) {
476 return Ok(true);
477 }
478 Ok(matches!(
479 self.objects.stat(&id).map_err(store_error)?,
480 Some((Kind::Changeset, _))
481 ))
482 }
483
484 /// The first-parent ancestor of `id` at `height`, which must not be above
485 /// the height of `id`, through skip pointers where they get closer.
486 fn ancestor_at(&mut self, id: ObjectId, height: u64) -> Result<ObjectId, Error> {
487 let mut at = id;
488 let mut node = self.node(id)?;
489 while node.height > height {
490 let current = node.height;
491 let skip = skip_height(current);
492 let skip_below = skip_height(current - 1);
493 // Take the skip pointer when it lands on the target, or above it
494 // where the parent's own pointer would not land closer.
495 let jump = skip == height
496 || (skip > height && !(skip_below + 2 < skip && skip_below >= height));
497 let (next, expected) = match (node.skip, node.parents.first()) {
498 (Some(skip_to), _) if jump => (skip_to, skip),
499 (_, Some(parent)) => (*parent, current - 1),
500 (_, None) => return Err(Error::DerivedData { id: at }),
501 };
502 at = next;
503 node = self.node(at)?;
504 if node.height != expected {
505 return Err(Error::DerivedData { id: at });
506 }
507 }
508 Ok(at)
509 }
510
511 /// The commit graph data of `id`, from memory, from its record, or
512 /// computed with that of every ancestor that lacks it.
513 pub(crate) fn node(&mut self, id: ObjectId) -> Result<Rc<GraphNode>, Error> {
514 if let Some(node) = self.nodes.get(&id) {
515 return Ok(Rc::clone(node));
516 }
517 if let Some(node) = self.load_node(id)? {
518 return Ok(node);
519 }
520 // Depth first, parents before children, with an explicit stack: a
521 // history can be far longer than a thread's stack is deep.
522 let mut parents_of: HashMap<ObjectId, Vec<ObjectId>> = HashMap::new();
523 let mut stack = vec![(id, false)];
524 while let Some((top, expanded)) = stack.pop() {
525 if self.nodes.contains_key(&top) {
526 continue;
527 }
528 if expanded {
529 let parents = parents_of.remove(&top).unwrap_or_default();
530 self.compute_node(top, parents)?;
531 continue;
532 }
533 if top != id && self.load_node(top)?.is_some() {
534 continue;
535 }
536 let parents = read_changeset(self.objects, top)?.parents;
537 stack.push((top, true));
538 for parent in &parents {
539 if !self.nodes.contains_key(parent) {
540 stack.push((*parent, false));
541 }
542 }
543 parents_of.insert(top, parents);
544 }
545 self.nodes
546 .get(&id)
547 .cloned()
548 .ok_or(Error::DerivedData { id })
549 }
550
551 /// The commit graph data of `id` from its record, remembered.
552 fn load_node(&mut self, id: ObjectId) -> Result<Option<Rc<GraphNode>>, Error> {
553 let key = DerivedKey::new(GRAPH, GRAPH_VERSION, &[id], b"");
554 let Some(node) = self.load(&key, GraphNode::decode)? else {
555 return Ok(None);
556 };
557 let node = Rc::new(node);
558 self.nodes.insert(id, Rc::clone(&node));
559 Ok(Some(node))
560 }
561
562 /// Computes and stores the commit graph data of `id`, whose parents have
563 /// theirs.
564 fn compute_node(&mut self, id: ObjectId, parents: Vec<ObjectId>) -> Result<(), Error> {
565 let mut generation = 0;
566 for parent in &parents {
567 generation = generation.max(self.node(*parent)?.generation);
568 }
569 let (height, skip) = match parents.first() {
570 None => (0, None),
571 Some(first) => {
572 let height = self.node(*first)?.height + 1;
573 (height, Some(self.ancestor_at(*first, skip_height(height))?))
574 }
575 };
576 let node = GraphNode {
577 parents,
578 generation: generation + 1,
579 height,
580 skip,
581 };
582 let key = DerivedKey::new(GRAPH, GRAPH_VERSION, &[id], b"");
583 self.save(key, &node.encode())?;
584 self.nodes.insert(id, Rc::new(node));
585 Ok(())
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592 use crate::derived::MemoryIndex;
593 use crate::testing::Repo;
594
595 /// A changeset with these parents, distinguished by a file named `name`.
596 fn node(repo: &Repo, parents: &[ObjectId], name: &str) -> ObjectId {
597 repo.commit(parents, vec![repo.set(&format!("{name}.txt"), name)])
598 }
599
600 #[test]
601 fn first_parent_chain() {
602 let repo = Repo::new();
603 let root = node(&repo, &[], "root");
604 let a = node(&repo, &[root], "a");
605 let side = node(&repo, &[root], "side");
606 let merge = node(&repo, &[a, side], "merge");
607 let head = node(&repo, &[merge], "head");
608 let objects = &repo.objects;
609 for ancestor in [head, merge, a, root] {
610 assert!(first_parent_chain_contains(objects, head, ancestor, usize::MAX).unwrap());
611 }
612 // Reachable, but only through a second parent.
613 assert!(!first_parent_chain_contains(objects, head, side, usize::MAX).unwrap());
614 // Not an ancestor at all.
615 assert!(!first_parent_chain_contains(objects, root, head, usize::MAX).unwrap());
616 // The limit counts steps.
617 assert!(first_parent_chain_contains(objects, head, a, 2).unwrap());
618 assert!(!first_parent_chain_contains(objects, head, a, 1).unwrap());
619 assert!(first_parent_chain_contains(objects, head, head, 0).unwrap());
620 }
621
622 #[test]
623 fn merge_base_of_a_fork() {
624 let repo = Repo::new();
625 let root = node(&repo, &[], "root");
626 let base = node(&repo, &[root], "base");
627 let left = node(&repo, &[base], "left");
628 let left2 = node(&repo, &[left], "left2");
629 let right = node(&repo, &[base], "right");
630 let objects = &repo.objects;
631 assert_eq!(merge_base(objects, left2, right).unwrap(), Some(base));
632 assert_eq!(merge_base(objects, right, left2).unwrap(), Some(base));
633 // An ancestor is its own merge base with a descendant.
634 assert_eq!(merge_base(objects, left2, base).unwrap(), Some(base));
635 assert_eq!(merge_base(objects, left, left).unwrap(), Some(left));
636 }
637
638 #[test]
639 fn merge_base_skips_ancestors_of_better_candidates() {
640 // `b` reaches `root` directly and `mid` through `d`; `mid` is better.
641 let repo = Repo::new();
642 let root = node(&repo, &[], "root");
643 let mid = node(&repo, &[root], "mid");
644 let a = node(&repo, &[mid], "a");
645 let d = node(&repo, &[mid], "d");
646 let b = node(&repo, &[root, d], "b");
647 assert_eq!(merge_bases(&repo.objects, a, b).unwrap(), [mid]);
648 }
649
650 #[test]
651 fn criss_cross_has_two_merge_bases() {
652 let repo = Repo::new();
653 let root = node(&repo, &[], "root");
654 let x = node(&repo, &[root], "x");
655 let y = node(&repo, &[root], "y");
656 let m1 = node(&repo, &[x, y], "m1");
657 let m2 = node(&repo, &[y, x], "m2");
658 let mut expected = vec![x, y];
659 expected.sort();
660 assert_eq!(merge_bases(&repo.objects, m1, m2).unwrap(), expected);
661 assert_eq!(
662 merge_base(&repo.objects, m1, m2).unwrap(),
663 Some(expected[0])
664 );
665 }
666
667 #[test]
668 fn ancestors_through_any_parent() {
669 let repo = Repo::new();
670 let root = node(&repo, &[], "root");
671 let side = node(&repo, &[root], "side");
672 let main = node(&repo, &[root], "main");
673 let merge = node(&repo, &[main, side], "merge");
674 let objects = &repo.objects;
675 for ancestor in [merge, main, side, root] {
676 assert!(is_ancestor(objects, ancestor, merge).unwrap());
677 }
678 assert!(!is_ancestor(objects, merge, main).unwrap());
679 assert!(!is_ancestor(objects, side, main).unwrap());
680 assert!(all_ancestors(objects, &[side, main, root], merge).unwrap());
681 assert!(!all_ancestors(objects, &[side, merge], main).unwrap());
682 assert!(all_ancestors(objects, &[], main).unwrap());
683 }
684
685 #[test]
686 fn unrelated_histories_have_no_merge_base() {
687 let repo = Repo::new();
688 let one = node(&repo, &[], "one");
689 let two = node(&repo, &[], "two");
690 assert_eq!(merge_base(&repo.objects, one, two).unwrap(), None);
691 let index = MemoryIndex::new();
692 let mut history = History::new(&repo.objects, &index);
693 assert_eq!(history.merge_bases(one, two).unwrap(), []);
694 assert!(!history.is_ancestor(one, two).unwrap());
695 }
696
697 #[test]
698 fn graph_data_counts_generations_and_heights() {
699 let repo = Repo::new();
700 let root = node(&repo, &[], "root");
701 let a = node(&repo, &[root], "a");
702 let b = node(&repo, &[a], "b");
703 let side = node(&repo, &[root], "side");
704 let merge = node(&repo, &[side, b], "merge");
705 let index = MemoryIndex::new();
706 let mut history = History::new(&repo.objects, &index);
707 let graph = history.graph(merge).unwrap();
708 // The merge is one above its highest parent, b, but its first
709 // parent is the side branch: height 2.
710 assert_eq!(graph.generation, 4);
711 assert_eq!(graph.height, 2);
712 assert_eq!(graph.parents, [side, b]);
713 assert_eq!(graph.skip, Some(root));
714 assert_eq!(history.graph(root).unwrap().skip, None);
715 assert_eq!(history.generation(b).unwrap(), 3);
716 assert_eq!(history.first_parent_ancestor(merge, 1).unwrap(), Some(side));
717 assert_eq!(history.first_parent_ancestor(merge, 2).unwrap(), Some(root));
718 assert_eq!(history.first_parent_ancestor(merge, 3).unwrap(), None);
719 // One record per changeset, recorded on flush.
720 assert_eq!(history.computed(), 5);
721 history.flush().unwrap();
722 assert_eq!(index.len(), 5);
723 let decoded = GraphNode::decode(&graph.encode()).unwrap();
724 assert_eq!(decoded, graph);
725 // Values that contradict themselves are refused.
726 let mut bad = graph.clone();
727 bad.generation = 1;
728 assert_eq!(GraphNode::decode(&bad.encode()), None);
729 }
730
731 #[test]
732 fn history_answers_what_the_walks_answer() {
733 let repo = Repo::new();
734 let root = node(&repo, &[], "root");
735 let mid = node(&repo, &[root], "mid");
736 let a = node(&repo, &[mid], "a");
737 let d = node(&repo, &[mid], "d");
738 let b = node(&repo, &[root, d], "b");
739 let x = node(&repo, &[a], "x");
740 let y = node(&repo, &[b], "y");
741 let m1 = node(&repo, &[x, y], "m1");
742 let m2 = node(&repo, &[y, x], "m2");
743 let octopus = node(&repo, &[m1, a, d, b], "octopus");
744 let all = [root, mid, a, d, b, x, y, m1, m2, octopus];
745 let index = MemoryIndex::new();
746 let mut history = History::new(&repo.objects, &index);
747 let objects = &repo.objects;
748 for p in all {
749 for q in all {
750 assert_eq!(
751 history.merge_bases(p, q).unwrap(),
752 merge_bases(objects, p, q).unwrap()
753 );
754 assert_eq!(
755 history.is_ancestor(p, q).unwrap(),
756 is_ancestor(objects, p, q).unwrap()
757 );
758 for limit in [0, 1, 2, usize::MAX] {
759 assert_eq!(
760 history.first_parent_chain_contains(p, q, limit).unwrap(),
761 first_parent_chain_contains(objects, p, q, limit).unwrap()
762 );
763 }
764 }
765 }
766 let mut expected = vec![x, y];
767 expected.sort();
768 assert_eq!(history.merge_bases(m1, m2).unwrap(), expected);
769 assert_eq!(history.merge_bases(a, b).unwrap(), [mid]);
770 assert!(history.all_ancestors(&[a, d, root], octopus).unwrap());
771 assert!(!history.all_ancestors(&[m2, a], octopus).unwrap());
772 assert!(history.all_ancestors(&[], root).unwrap());
773 }
774}