From 753df719e9ec24c23e41845faaf86f2179f14e08 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:37:21 +0100 Subject: [PATCH] feat(ancestry): find merge bases, merging criss-crossed ones A merge needs a base: the snapshot both sides started from. For a change's heads, that's the newest revision they all evolve from; for two targets that landed each other, the newest acceptance both histories share. Either history is a graph of immutable records, each with its parents and a snapshot. `Ancestry` walks such a history once, from its tips, and finds their best common ancestors: those every tip descends from, but no other shared ancestor descends from. The newest shared ancestor wins, however far it is. Histories that merged each other criss-cross and have several; as git's recursive strategy does, they're merged into one first, each from their own merge base. Merging bases uses `Store::merge_bases`, which leaves an entry no object has where they conflict, and never reads under it: the bases may have had a directory there. A merge from that base then conflicts at, and under, every such path unless both sides agree, rather than take what one side removed for what the other added. --- apps/origin-src/src/ancestry.rs | 195 ++++++++++++++++++++++++++++++++ apps/origin-src/src/lib.rs | 1 + apps/origin-src/src/tree.rs | 41 ++++++- 3 files changed, 233 insertions(+), 4 deletions(-) create mode 100644 apps/origin-src/src/ancestry.rs diff --git a/apps/origin-src/src/ancestry.rs b/apps/origin-src/src/ancestry.rs new file mode 100644 index 00000000..8278e72f --- /dev/null +++ b/apps/origin-src/src/ancestry.rs @@ -0,0 +1,195 @@ +//! Merge bases in a history of immutable records with snapshots: the +//! acceptances of targets, each after the one before it and the +//! acceptances it landed, or the revisions of a change, each after its +//! predecessors. + +use std::collections::{HashMap, HashSet}; +use std::hash::Hash; + +use origin_platform::Platform; +use origin_shared::TreeId; + +use crate::store::{Store, StoreError}; + +/// A history, as far as it was walked: the parents and the snapshot of +/// each record in it. +#[derive(Debug)] +pub struct Ancestry { + records: HashMap, TreeId)>, +} + +impl Ancestry { + /// Walks everything `tips` descend from, asking `read` for the parents + /// and the snapshot of each record, once. + /// + /// # Errors + /// + /// Fails as `read` does. + pub fn walk( + tips: &[I], + mut read: impl FnMut(I) -> Result<(Vec, TreeId), E>, + ) -> Result { + let mut records = HashMap::new(); + let mut next = tips.to_vec(); + while let Some(id) = next.pop() { + if records.contains_key(&id) { + continue; + } + let record = read(id)?; + next.extend(&record.0); + records.insert(id, record); + } + Ok(Self { records }) + } + + /// The snapshot to merge `tips` from, `None` if they share no ancestor: + /// that of their best common ancestor. Several, as histories that + /// merged each other criss-cross have, merge into one first, as git's + /// recursive strategy does: each from their own merge base, with what + /// [`Store::merge_bases`] leaves where they conflict, so a merge from + /// the result conflicts there, and under it, unless both sides agree. Writes the trees + /// that makes, which merging reads. + /// + /// # Errors + /// + /// Fails if a tree cannot be read or written. + pub fn merge_base( + &self, + store: &Store

, + tips: &[I], + ) -> Result, StoreError> { + let groups: Vec<_> = tips.iter().map(std::slice::from_ref).collect(); + self.merge_base_of(store, &groups) + } + + /// The snapshot to merge `groups` from, each standing for all it holds. + fn merge_base_of( + &self, + store: &Store

, + groups: &[&[I]], + ) -> Result, StoreError> { + let bases = self.best_common(groups); + let Some((&first, others)) = bases.split_first() else { + return Ok(None); + }; + let mut merged = vec![first]; + let mut tree = self.snapshot(first); + for &other in others { + let base = self.merge_base_of(store, &[&merged, &[other]])?; + let merge = store.merge_bases(base, tree, self.snapshot(other))?; + store.write_all(&merge.trees)?; + tree = merge.tree; + merged.push(other); + } + Ok(Some(tree)) + } + + /// The best common ancestors of `groups`: the records that every group + /// has one that is or descends from, but that none of the others + /// descends from, sorted. Each record is visited a bounded number of + /// times. + fn best_common(&self, groups: &[&[I]]) -> Vec { + let Some((first, others)) = groups.split_first() else { + return Vec::new(); + }; + let mut common = self.reachable(first.iter().copied()); + for group in others { + let reachable = self.reachable(group.iter().copied()); + common.retain(|id| reachable.contains(id)); + } + let parents = common.iter().flat_map(|&id| self.parents(id)); + let below = self.reachable(parents.copied()); + let mut bases: Vec<_> = common.difference(&below).copied().collect(); + bases.sort_unstable(); + bases + } + + /// The records `from` are or descend from. + fn reachable(&self, from: impl IntoIterator) -> HashSet { + let mut reached = HashSet::new(); + let mut next: Vec<_> = from.into_iter().collect(); + while let Some(id) = next.pop() { + if reached.insert(id) { + next.extend(self.parents(id)); + } + } + reached + } + + /// Whether `id` is or descends from `ancestor`, as far as the walk + /// read. + #[must_use] + pub fn descends(&self, id: I, ancestor: I) -> bool { + self.reachable([id]).contains(&ancestor) + } + + fn parents(&self, id: I) -> &[I] { + self.records.get(&id).map_or(&[], |(parents, _)| parents) + } + + fn snapshot(&self, id: I) -> TreeId { + self.records[&id].1 + } +} + +#[cfg(test)] +mod tests { + use origin_shared::{Record, Tree}; + + use super::*; + + /// The history of `edges`, each a record and its parents. + fn ancestry(edges: &[(u8, &[u8])]) -> Ancestry { + let tips: Vec<_> = edges.iter().map(|&(id, _)| id).collect(); + let empty = Tree::default().encode().id().into(); + Ancestry::walk(&tips, |id| { + let parents = edges.iter().find(|&&(of, _)| of == id).map(|&(_, p)| p); + Ok::<_, ()>((parents.unwrap_or_default().to_vec(), empty)) + }) + .unwrap() + } + + fn bases(history: &Ancestry, tips: &[u8]) -> Vec { + let groups: Vec<_> = tips.iter().map(std::slice::from_ref).collect(); + history.best_common(&groups) + } + + #[test] + fn the_newest_shared_ancestor_wins_however_far() { + // 2 follows 1; 3 to 6 and 7 to 10 grow apart from 2, then each + // lands a side line forked from 1: 1 is nearer, but 2 is newer. + let history = ancestry(&[ + (2, &[1]), + (3, &[2]), + (4, &[3]), + (5, &[4]), + (6, &[5]), + (7, &[2]), + (8, &[7]), + (9, &[8]), + (10, &[9]), + (11, &[1]), + (12, &[6, 11]), + (13, &[1]), + (14, &[10, 13]), + ]); + assert_eq!(bases(&history, &[12, 14]), [2]); + assert_eq!(bases(&history, &[12, 6]), [6], "an ancestor of the other"); + } + + #[test] + fn criss_cross_merges_have_two_bases() { + // 2 and 3 fork from 1, then each merges the other. + let history = ancestry(&[(2, &[1]), (3, &[1]), (4, &[2, 3]), (5, &[3, 2])]); + assert_eq!(bases(&history, &[4, 5]), [2, 3]); + assert_eq!(bases(&history, &[4, 5, 3]), [3]); + // Merging those two needs their own base. + assert_eq!(history.best_common(&[&[2], &[3]]), [1]); + } + + #[test] + fn unrelated_histories_have_none() { + let history = ancestry(&[(2, &[1]), (4, &[3])]); + assert_eq!(bases(&history, &[2, 4]), []); + } +} diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index e0c5c022..336d1f99 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -1,6 +1,7 @@ //! The origin command line and server. Both share the repository logic in //! this library; `main.rs` only parses arguments and dispatches. +pub mod ancestry; pub mod annotations; pub mod cli; pub mod config; diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index 16d5a6f3..cc59b90d 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -5,7 +5,8 @@ use std::collections::hash_map::Entry; use origin_platform::Platform; use origin_shared::{ - Digest, EncodedObject, EntryKind, EntryName, Inputs, Record, RepoPath, Tree, TreeEntry, TreeId, + Digest, EncodedObject, EntryKind, EntryName, Inputs, ObjectId, Record, RepoPath, Tree, + TreeEntry, TreeId, }; use crate::conflict::{Conflicted, Conflicts}; @@ -108,6 +109,8 @@ enum OnConflict<'l> { /// Both versions between conflict markers naming the sides with these /// labels, see [`Conflicts::mark`]. Mark([&'l str; 2]), + /// [`Store::UNKNOWN`], a version neither side can have. + Unknown, } impl Store

{ @@ -150,6 +153,32 @@ impl Store

{ self.merge_with(base, ours, theirs, OnConflict::Mark(labels)) } + /// The entry a merge of merge bases has where they conflict: an id no + /// object has, so it equals neither side of a merge from it. A merge + /// never reads under it either: the bases may have had a directory + /// there, so any change at or under its path conflicts. + const UNKNOWN: TreeEntry = TreeEntry { + kind: EntryKind::File, + id: ObjectId::from_bytes([0; ObjectId::LEN]), + }; + + /// Merges like [`Store::merge`], but where both sides changed a path, + /// the merged tree has [`Store::UNKNOWN`]: how merge bases are merged + /// into one, so a merge from it conflicts there unless both sides + /// agree. + /// + /// # Errors + /// + /// Fails if a tree that differs cannot be read. + pub fn merge_bases( + &self, + base: Option, + ours: TreeId, + theirs: TreeId, + ) -> Result { + self.merge_with(base, ours, theirs, OnConflict::Unknown) + } + fn merge_with( &self, base: Option, @@ -224,11 +253,14 @@ impl Store

{ ours } else if base == ours { theirs - } else if ours.is_none_or(|ours| ours.kind.is_tree()) + } else if base != Some(Self::UNKNOWN) + && ours.is_none_or(|ours| ours.kind.is_tree()) && theirs.is_none_or(|theirs| theirs.kind.is_tree()) { // Both sides changed a directory, or one changed it and the - // other removed it: merge it file by file. + // other removed it: merge it file by file, unless what it was + // is unknown, which would take what one side removed for + // what the other added. let subtree = |entry: Option| entry.and_then(TreeEntry::subtree); self.merge_dir( &dir.join(name), @@ -246,6 +278,7 @@ impl Store

{ let written = match on_conflict { OnConflict::KeepOurs => ours, OnConflict::Mark(labels) => self.mark(ours, theirs, labels, merge)?, + OnConflict::Unknown => Some(Self::UNKNOWN), }; // Paths come in order, each once. merge.conflicts.push(Conflicted { @@ -369,7 +402,7 @@ pub(crate) mod tests { use std::collections::BTreeMap; use origin_platform::Native; - use origin_shared::{EncodedObject, EntryKind, ObjectId, Record}; + use origin_shared::{EncodedObject, EntryKind, Record}; use super::*;