Commit 5d2ee0fb
5d2ee0fb599dMergedfrom mrmrs-45f600
mrmrs · 1 month ago · 3 files · +1 added · ~2 modified
Description
Merge-base / fork-point soundness on partial graphs: never certify a stale base (Blocker)
Severity: Blocker (invalid merge / content loss). Reproduced on released 0.103.0 and on main 501ecca4. Repro credit: /Users/mrmrs/o/worker-mrmrs-20260926T051738-repro-mergebase/REPRO.md.
Bug
missing_edges_that_can_hide_lca (merge.rs) and its review twin missing_edges_that_can_hide_fork (review.rs, which feeds fork_point) ignored a missing edge whenever it was deeper than the candidate on the same side. That is unsound. A better common ancestor can sit behind a target-side gap at any depth. Shape: R-C-X-M1..M9-H, where M5 reverts X, H.merge_parent = Z1 (forked from C), and branch a = a1 on X. With M7 missing, C is at depth 2 via Z1 and M7 is at depth 3, so the gap was filtered and C was certified. Effects: merge --dry-run --json reported clean:true with f.txt re-applied and no caveat, and oak pull exited 0 after a transient 500 on M7, writing a sync commit that re-applied the reverted change.
Invariant
A merge base or fork point computed on a partial local graph equals the complete-graph result, or it is reported unavailable (IncompleteAncestry). It is never a different base. Shallow boundaries below the base stay certifiable.
Rule (one shared implementation: merge::certify_common_ancestor_from_walks; review's first_common_ancestor now calls it)
- Selection: take the local common ancestors A∩B. A best common ancestor is one that is not a parent of another common ancestor. The candidate C is the first best common ancestor in a's BFS order, which is also the deterministic criss-cross tie-break.
- Certification: let gaps(C) be the missing edges reached by walking C's own local ancestry. C is certified only if every missing edge of both walks is in gaps(C). Otherwise the result is IncompleteAncestry { missing: blocking gaps, link_gaps: C's first-parent gap }.
- Proof sketch (G = complete graph, L = local rows):
- Any commit in G but not in L that is reachable from a or b lies behind a walk gap m, so it is an ancestor of m, which is an ancestor of C. It is therefore a proper ancestor of a common commit and cannot be a best common ancestor.
- If two local common ancestors are related in G but not in L, their path crosses a gap, so the older one is a proper ancestor of C. So G's best common ancestors are exactly L's best common ancestors minus some proper ancestors of C. C is best in G, and a spurious local-best Z would itself fail the check (its gaps cannot contain a descendant gap).
- Commits that are not ancestors of a gap keep their BFS depth and discovery order, so G's first best common ancestor is C.
- Semantics change (complete graph): selection moved from "first a-BFS common ancestor" to "first a-BFS best common ancestor". The old rule could pick a proper ancestor of a better base when a side had a short path to an old commit, such as a stale sync merge_parent (the random property found this on main). That is the same stale-base defect class. Ordinary shapes, where the first common ancestor is already best, are unchanged.
- Hydration (review.rs
prepare_remote_review_ancestry): the loop fetches the blocking gaps. When the same candidate stays uncertified for a second round, it also fetches C's first-parentlink_gaps, so a deep blocking chain (a merged branch forked far below C) links into C's history instead of being walked to the root. The existing budgets (256 exact commits, deadline) and the no-progress check are unchanged. Error text now names only the blocking gaps.
Evidence
- RED on main 501ecca4 (evidence/red-main-501ecca4.log): repro tests for merge.rs and review.rs certify C, and the differential property finds 187 violations over 160 seeds (partial ≠ full, plus full-graph non-best bases).
- GREEN: 7 new tests (merge.rs: squash-revert full control, 4 partial shapes, hydration loop, deep merged-branch link bounded at 21 rounds / 39 fetches, shallow boundary certified; review.rs: fork-point repro, and a differential property over 64 seeds / 444 pairs / 2664 partial resolutions per resolver, 0 violations, about 8 s debug). A 2000-seed soak (13005 pairs) also found 0 violations. The property asserts: bounded ∈ {full, unavailable}; full ∈ best-CA oracle; review hydration converges on full.
- fmt; clippy --workspace --all-targets -D warnings;
cargo test -p oakvcs-cli --no-fail-fast: 1509 passed, 0 failed, 7 ignored. - Real-binary e2e (loopback depth-honouring serve plus fault proxy): S1 full control is unchanged (X, clean, pull l2). S2 partial dry-run: main says clean, fork C, f.txt changed; candidate says prediction unavailable, caveat names M7. S3 transient 500 on M7: main exits 0 and writes a re-applying commit; candidate exits 5 with "Incomplete ancestry … c371d336 (M7)", the head is unchanged, and a retry without the fault syncs with f.txt=l2. No over-blocking: fresh shallow
merge --dry-runis identical to main (clean, fork H). The loopback remote review now certifies fork X where 0.103.0 reported none. Hosted oak/oakbranch review --remote --merge-previewfor both open branches: candidate = main 501ecca4 (fork 501ecca4, clean, same file counts).
Limitations / follow-ups
- A pull whose backfill reports
incompletestill continues until the resolver fails closed. It no longer writes a wrong base here, but "pull should stop when backfill is incomplete" remains a separate follow-up (sync.rs, not touched). - In a shallow worker, when the merged-branch fork is far below the candidate, review hydration costs about 2× that distance in exact commits and rounds. Beyond the 256 budget it fails closed ("budget exceeded"), which is the correct direction but can be slow.
- Fresh shallow switch+pull on the loopback fixture fails with IncompleteManifestData on both main and candidate (pre-existing; the base manifest is not hydrated by pull). Not changed here.
Details
- Commit
- 5d2ee0fb599d
- Parent
- 501ecca41d16
- Merge parent
- e066e87367c4
cli/src/commands/merge.rsmodifiedView file
use crate::output;use crate::workdir_lock::WorkdirLock;#[cfg(test)]pub(crate) mod merge_base_fixtures;/// Merge the current branch into its parent branch.////// When the parent is `main` the merge can't happen locally — `main` only#[derive(Debug, Clone)]pub(crate) enum MergeBaseUnavailable { IncompleteAncestry { missing: Vec<Hash> }, IncompleteManifestData { missing: Vec<Hash> }, IncompleteBlobData { missing: Vec<Hash> }, /// `missing`: the gaps that prevent certification (what an error names). /// `link_gaps`: when a local candidate exists, the first-parent gap below /// it. Fetching it never certifies anything by itself; a hydrating caller /// may add it so later rounds can link deep blocking gaps into the /// candidate's ancestry instead of walking them to the root. IncompleteAncestry { missing: Vec<Hash>, link_gaps: Vec<Hash>, }, IncompleteManifestData { missing: Vec<Hash>, }, IncompleteBlobData { missing: Vec<Hash>, }, NoVerifiedCommonAncestor,}impl MergeBaseUnavailable { pub(crate) fn to_error(&self, left: &str, right: &str) -> OakError { match self { MergeBaseUnavailable::IncompleteAncestry { missing } => { MergeBaseUnavailable::IncompleteAncestry { missing, .. } => { incomplete_ancestry_error(left, right, missing) } MergeBaseUnavailable::IncompleteManifestData { missing } => { // head is unavailable, never permission to consult a local ref. None => AncestorWalk::default(), }; let b_ancestor_set: HashSet<String> = b_walk.ancestors.iter().map(|h| h.to_string()).collect(); // The first ancestor of branch_a that also appears in branch_b's history is the LCA. for hash in &a_walk.ancestors { if b_ancestor_set.contains(&hash.to_string()) { let a_depth = a_walk.depth(hash).unwrap_or(usize::MAX); let b_depth = b_walk.depth(hash).unwrap_or(usize::MAX); let missing_edges = missing_edges_that_can_hide_lca(&a_walk, a_depth, &b_walk, b_depth); if !missing_edges.is_empty() { return Ok(MergeBaseIdentity::Unavailable( MergeBaseUnavailable::IncompleteAncestry { missing: missing_edges, }, )); } if repo.get_commit(hash)?.is_none() { match certify_common_ancestor_from_walks(&a_walk, &b_walk) { CommonAncestorCertificate::Certified(hash) => { if repo.get_commit(&hash)?.is_none() { return Ok(MergeBaseIdentity::Unavailable( MergeBaseUnavailable::IncompleteAncestry { missing: vec![hash.clone()], missing: vec![hash], link_gaps: Vec::new(), }, )); } return Ok(MergeBaseIdentity::Commit(hash.clone())); return Ok(MergeBaseIdentity::Commit(hash)); } CommonAncestorCertificate::Uncertified { missing, link_gaps } => { return Ok(MergeBaseIdentity::Unavailable( MergeBaseUnavailable::IncompleteAncestry { missing, link_gaps }, )); } CommonAncestorCertificate::NoCommonAncestor => {} } // Oak can have a branch whose metadata says it is parented to `branch_b`, return Ok(MergeBaseIdentity::Unavailable( MergeBaseUnavailable::IncompleteAncestry { missing: missing_edges, link_gaps: Vec::new(), }, )); } Ok(root_count == 1 && branch_owned_root_count == 1)}/// A breadth-first walk of the *local* ancestry of one head.////// `ancestors` is in BFS order (parent before merge parent at each step);/// `parents` records the parent edges of every present commit so the resolver/// can reason about the local graph without re-reading rows; `missing_edges`/// are parent hashes the walk reached whose commit rows are not local (shallow/// boundaries, backfill holes, unfetched merge parents).#[derive(Debug, Default)]struct AncestorWalk {pub(crate) struct AncestorWalk { ancestors: Vec<Hash>, depths: HashMap<String, usize>, missing_edges: Vec<MissingEdge>, parents: HashMap<String, Vec<Hash>>, first_parents: HashMap<String, Hash>, missing_edges: Vec<Hash>,}impl AncestorWalk { fn depth(&self, hash: &Hash) -> Option<usize> { self.depths.get(hash.as_str()).copied() pub(crate) fn missing_edges(&self) -> &[Hash] { &self.missing_edges }}#[derive(Debug)]struct MissingEdge { hash: Hash, depth: usize,/// Outcome of certifying a merge base / fork point on the local graph.#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) enum CommonAncestorCertificate { /// The base the complete graph would select. Certified(Hash), /// A local candidate exists, but the gaps in `missing` could hide a /// better one. `link_gaps` is the candidate's first-parent gap: hydrating /// it (alongside `missing`) lets a retry link deep blocking gaps into the /// candidate's ancestry rather than walking them to the root. Uncertified { missing: Vec<Hash>, link_gaps: Vec<Hash>, }, /// No common ancestor is visible locally. NoCommonAncestor,}fn missing_edges_that_can_hide_lca(/// Certify the merge base of two local ancestry walks.////// Selection (complete or partial graph): the common ancestors are/// `A ∩ B`; a *best* common ancestor is one that is not a parent of another/// common ancestor (no common descendant). The result is the first best common/// ancestor in `a`'s BFS order — for criss-cross histories with several best/// common ancestors that order is the deterministic tie-break.////// Certification on a partial graph: let `C` be the local selection and/// `gaps(C)` the missing edges reached walking `C`'s own local ancestry. `C`/// is certified only when every missing edge of *both* walks is in `gaps(C)`./// Proof sketch (G = complete graph, L = local rows):/// 1. Every commit reachable in G from `a`/`b` but not in L lies behind some/// walk gap `m` (the first absent commit on any path), so it is an/// ancestor of `m`, hence a proper ancestor of `C`, hence not a best/// common ancestor in G (`C` is common and descends from it)./// 2. If two local common ancestors are related in G but not in L, the G path/// between them crosses a gap, so the older one is a proper ancestor of `C`./// Therefore every best common ancestor of G is locally visible and locally/// best, `C` itself is best in G, and any locally-best-but-not-G-best/// commit is a proper ancestor of `C` (it would fail this check if chosen)./// 3. Commits that are not ancestors of a gap keep their BFS depth and/// discovery order in G, so G's first best common ancestor is `C`.////// A depth filter is not sound here: a better base can hide behind a target/// gap at any depth (its BFS depth is bounded by the longest path, not the/// candidate's shortest one), so gaps are never dismissed as "too deep"./// Shallow checkouts stay certifiable because their boundary gaps are below/// the base: reached from the base's own walk.pub(crate) fn certify_common_ancestor_from_walks( a_walk: &AncestorWalk, a_candidate_depth: usize, b_walk: &AncestorWalk, b_candidate_depth: usize,) -> Vec<Hash> { a_walk) -> CommonAncestorCertificate { let b_ancestor_set: HashSet<&str> = b_walk.ancestors.iter().map(|h| h.as_str()).collect(); let common: Vec<&Hash> = a_walk .ancestors .iter() .filter(|hash| b_ancestor_set.contains(hash.as_str())) .collect(); if common.is_empty() { return CommonAncestorCertificate::NoCommonAncestor; } // Common ancestry is ancestor-closed within the local graph, so a common // ancestor is dominated exactly when it is a parent of another one. let common_set: HashSet<&str> = common.iter().map(|h| h.as_str()).collect(); let mut dominated: HashSet<&str> = HashSet::new(); for hash in &common { for parent in a_walk .parents .get(hash.as_str()) .map(Vec::as_slice) .unwrap_or(&[]) { if common_set.contains(parent.as_str()) { dominated.insert(parent.as_str()); } } } let candidate = common .iter() .find(|hash| !dominated.contains(hash.as_str())) .copied() .expect("a finite DAG has an undominated common ancestor") .clone(); if a_walk.missing_edges.is_empty() && b_walk.missing_edges.is_empty() { return CommonAncestorCertificate::Certified(candidate); } // gaps(C): walk C's local ancestry over the edges already recorded by // `a_walk` (C's ancestry is a subset of it). let mut candidate_gap_set: HashSet<&str> = HashSet::new(); let mut seen: HashSet<&str> = HashSet::new(); let mut queue: VecDeque<&Hash> = VecDeque::from([&candidate]); while let Some(hash) = queue.pop_front() { if !seen.insert(hash.as_str()) { continue; } match a_walk.parents.get(hash.as_str()) { Some(parents) => queue.extend(parents.iter()), None => { candidate_gap_set.insert(hash.as_str()); } } } let mut offending: Vec<Hash> = Vec::new(); let mut offending_set: HashSet<&str> = HashSet::new(); for gap in a_walk .missing_edges .iter() .filter(|edge| edge.depth <= a_candidate_depth) .chain( b_walk .missing_edges .iter() .filter(|edge| edge.depth <= b_candidate_depth), ) .map(|edge| edge.hash.clone()) .collect() .chain(b_walk.missing_edges.iter()) { if !candidate_gap_set.contains(gap.as_str()) && offending_set.insert(gap.as_str()) { offending.push(gap.clone()); } } if offending.is_empty() { return CommonAncestorCertificate::Certified(candidate); } // First-parent gap below the candidate (main's history in Oak shapes). let mut link_gaps = Vec::new(); let mut cursor = &candidate; let mut first_parent_seen: HashSet<&str> = HashSet::new(); while first_parent_seen.insert(cursor.as_str()) { match a_walk.first_parents.get(cursor.as_str()) { Some(parent) if a_walk.parents.contains_key(parent.as_str()) => cursor = parent, Some(parent) => { link_gaps.push(parent.clone()); break; } None => break, } } CommonAncestorCertificate::Uncertified { missing: offending, link_gaps, }}/// Certify the merge base / fork point of two heads on the local graph.pub(crate) fn certify_common_ancestor( repo: &dyn Repository, a_head: &Hash, b_head: &Hash,) -> Result<(CommonAncestorCertificate, AncestorWalk, AncestorWalk)> { let a_walk = collect_ancestors_from_head(repo, a_head)?; let b_walk = collect_ancestors_from_head(repo, b_head)?; Ok(( certify_common_ancestor_from_walks(&a_walk, &b_walk), a_walk, b_walk, ))}fn all_missing_edges(a_walk: &AncestorWalk, b_walk: &AncestorWalk) -> Vec<Hash> { .missing_edges .iter() .chain(b_walk.missing_edges.iter()) .map(|edge| edge.hash.clone()) .cloned() .collect()}/// Follows both parent_hash and merge_parent_hash to correctly traverse the DAG.fn collect_ancestors_from_head(repo: &dyn Repository, head: &Hash) -> Result<AncestorWalk> { let mut ancestors = Vec::new(); let mut depths = HashMap::new(); let mut parents = HashMap::new(); let mut first_parents = HashMap::new(); let mut missing_edges = Vec::new(); let mut queue = VecDeque::new(); let mut visited = HashSet::new(); queue.push_back((head.clone(), 0usize)); queue.push_back(head.clone()); while let Some((hash, depth)) = queue.pop_front() { while let Some(hash) = queue.pop_front() { if !visited.insert(hash.to_string()) { continue; } let Some(commit) = repo.get_commit(&hash)? else { missing_edges.push(MissingEdge { hash, depth }); missing_edges.push(hash); continue; }; depths.insert(hash.to_string(), depth); ancestors.push(hash); if let Some(parent) = commit.parent_hash { queue.push_back((parent, depth + 1)); if let Some(parent) = &commit.parent_hash { first_parents.insert(hash.to_string(), parent.clone()); } if let Some(merge_parent) = commit.merge_parent_hash { queue.push_back((merge_parent, depth + 1)); } let edges: Vec<Hash> = [commit.parent_hash, commit.merge_parent_hash] .into_iter() .flatten() .collect(); queue.extend(edges.iter().cloned()); parents.insert(hash.to_string(), edges); ancestors.push(hash); } Ok(AncestorWalk { ancestors, depths, parents, first_parents, missing_edges, })} "pruned branch's head pointer should be deleted too" ); } // ---- merge-base certification on partial graphs ------------------------- // // Invariant: a merge base computed on a partial local graph equals the // complete-graph result, or is reported unavailable. Never a different // (stale) base. use super::merge_base_fixtures as fx; fn identity(repo: &dyn Repository, a: &Hash, b: &Hash) -> MergeBaseIdentity { resolve_merge_base_identity_from_heads(repo, "a", Some(a), None, "main", Some(b)).unwrap() } fn identity_label(identity: &MergeBaseIdentity) -> String { match identity { MergeBaseIdentity::Commit(hash) => format!("commit {}", hash.short()), MergeBaseIdentity::DeclaredRoot => "declared-root".into(), MergeBaseIdentity::Unavailable(reason) => format!("unavailable {reason:?}"), } } #[test] fn merge_base_squash_revert_full_graph_is_x() { let s = fx::squash_revert(); let (_dir, full) = s.graph.materialize(|_| true); match identity(&full, &s.a1, &s.h) { MergeBaseIdentity::Commit(base) => assert_eq!(base, s.x, "full graph must resolve X"), other => panic!("full graph must resolve X, got {}", identity_label(&other)), } } /// Confirmed Blocker: with main's first-parent history above X missing, /// C is reachable at depth 2 through H's merge parent Z1 while X is only /// reachable through a missing edge at depth 3. The old depth filter /// dismissed that gap and certified C, re-applying X's reverted change. #[test] fn merge_base_partial_graph_never_certifies_stale_base_behind_target_gap() { let s = fx::squash_revert(); // Each partial shape drops a different slice of main's history. let shapes: Vec<(&str, Vec<Hash>)> = vec![ ("M7 missing", vec![s.m[6].clone()]), ( "R and M1..M7 missing", std::iter::once(s.r.clone()) .chain(s.m[..7].iter().cloned()) .collect(), ), ("M1 missing", vec![s.m[0].clone()]), ("M9 missing", vec![s.m[8].clone()]), ]; for (label, dropped) in shapes { let (_dir, partial) = s.graph.materialize(|c| !dropped.contains(&c.hash)); match identity(&partial, &s.a1, &s.h) { MergeBaseIdentity::Commit(base) => { assert_ne!(base, s.c, "{label}: certified stale base C"); assert_eq!(base, s.x, "{label}: certified a non-merge-base"); } MergeBaseIdentity::Unavailable(MergeBaseUnavailable::IncompleteAncestry { missing, .. }) => assert!( dropped.iter().any(|d| missing.contains(d)), "{label}: unavailable must name the gap that hides X, got {missing:?}" ), other => panic!("{label}: unexpected {}", identity_label(&other)), } } } /// Replays the review preparation loop (fetch exactly the reported gaps, /// retry) from an empty local graph: it must converge on X, never C. #[test] fn merge_base_hydration_loop_converges_on_true_base() { let s = fx::squash_revert(); let (_dir, partial) = s.graph.materialize(|c| c.hash == s.a1 || c.hash == s.h); let mut rounds = 0; let base = loop { rounds += 1; assert!(rounds < 32, "hydration did not converge"); match identity(&partial, &s.a1, &s.h) { MergeBaseIdentity::Unavailable(MergeBaseUnavailable::IncompleteAncestry { missing, .. }) => { for hash in &missing { partial .store_commit(s.graph.get(hash).expect("reported gap exists")) .unwrap(); } } MergeBaseIdentity::Commit(base) => break base, other => panic!("unexpected {}", identity_label(&other)), } }; assert_eq!( base, s.x, "hydration certified {} (C = {})", base.short(), s.c.short() ); } /// A merged branch forked far below the candidate leaves a blocking gap /// that is really an old main ancestor. The review hydration policy must /// link it into the candidate's first-parent history (bounded work) rather /// than walk it to the root or give up. #[test] fn merge_base_hydration_links_deep_merged_branch_fork_into_candidate_history() { let mut g = fx::Graph::new(); let mut main = vec![g.add("main", None, None)]; for _ in 1..300 { let head = main.last().unwrap().clone(); main.push(g.add("main", Some(&head), None)); } // Branch z forked at main[250], merged after the candidate main[280]. let z1 = g.add("z", Some(&main[250]), None); let z2 = g.add("z", Some(&z1), None); let a1 = g.add("a", Some(&main[280]), None); let h = g.add("main", Some(&main[299]), Some(&z2)); // Shallow worker: main[270..] plus the heads' own rows. let keep: std::collections::HashSet<Hash> = main[270..] .iter() .cloned() .chain([z1.clone(), z2.clone(), a1.clone(), h.clone()]) .collect(); let (_dir, partial) = g.materialize(|c| keep.contains(&c.hash)); let before = partial.get_all_commits().unwrap().len(); let (identity, rounds) = fx::hydrate_like_review(&g, &partial, &a1, &h, 64).unwrap(); let MergeBaseIdentity::Commit(base) = identity else { panic!("unexpected {}", identity_label(&identity)); }; assert_eq!(base, main[280]); let fetched = partial.get_all_commits().unwrap().len() - before; eprintln!("rounds={rounds} fetched={fetched}"); assert!( fetched <= 64, "linking must stay bounded, fetched {fetched}" ); } /// Shallow boundaries below the base stay certifiable (no over-blocking): /// only R is missing, and R is below C/X on both sides. #[test] fn merge_base_shallow_boundary_below_base_is_certified() { let s = fx::squash_revert(); let (_dir, partial) = s.graph.materialize(|c| c.hash != s.r); match identity(&partial, &s.a1, &s.h) { MergeBaseIdentity::Commit(base) => assert_eq!(base, s.x), other => panic!( "shallow boundary must not block: {}", identity_label(&other) ), } // A branch whose only gap is its fork point's own parent (the fresh // shallow worker shape) is certified too. let (_dir2, shallow) = s .graph .materialize(|c| c.hash != s.r && c.hash != s.c && c.hash != s.z1); match resolve_merge_base_identity_from_heads( &shallow, "a", Some(&s.a1), None, "main", Some(&s.m[8]), ) .unwrap() { MergeBaseIdentity::Commit(base) => assert_eq!(base, s.x), other => panic!( "fresh shallow shape must certify: {}", identity_label(&other) ), } }}cli/src/commands/merge/merge_base_fixtures.rsaddedView file
Loading diff…
cli/src/commands/review.rsmodifiedView file
Loading diff…