Version control for agents

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):
    1. 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.
    2. 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).
    3. 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-parent link_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-run is identical to main (clean, fork H). The loopback remote review now certifies fork X where 0.103.0 reported none. Hosted oak/oak branch review --remote --merge-preview for both open branches: candidate = main 501ecca4 (fork 501ecca4, clean, same file counts).

Limitations / follow-ups

  • A pull whose backfill reports incomplete still 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

@@ -13,6 +13,9 @@
1313 use crate::output;
1414 use crate::workdir_lock::WorkdirLock;
1515
16+#[cfg(test)]
17+pub(crate) mod merge_base_fixtures;
18+
1619 /// Merge the current branch into its parent branch.
1720 ///
1821 /// When the parent is `main` the merge can't happen locally — `main` only
@@ -545,16 +548,28 @@
545548
546549 #[derive(Debug, Clone)]
547550 pub(crate) enum MergeBaseUnavailable {
548- IncompleteAncestry { missing: Vec<Hash> },
549- IncompleteManifestData { missing: Vec<Hash> },
550- IncompleteBlobData { missing: Vec<Hash> },
551+ /// `missing`: the gaps that prevent certification (what an error names).
552+ /// `link_gaps`: when a local candidate exists, the first-parent gap below
553+ /// it. Fetching it never certifies anything by itself; a hydrating caller
554+ /// may add it so later rounds can link deep blocking gaps into the
555+ /// candidate's ancestry instead of walking them to the root.
556+ IncompleteAncestry {
557+ missing: Vec<Hash>,
558+ link_gaps: Vec<Hash>,
559+ },
560+ IncompleteManifestData {
561+ missing: Vec<Hash>,
562+ },
563+ IncompleteBlobData {
564+ missing: Vec<Hash>,
565+ },
551566 NoVerifiedCommonAncestor,
552567 }
553568
554569 impl MergeBaseUnavailable {
555570 pub(crate) fn to_error(&self, left: &str, right: &str) -> OakError {
556571 match self {
557- MergeBaseUnavailable::IncompleteAncestry { missing } => {
572+ MergeBaseUnavailable::IncompleteAncestry { missing, .. } => {
558573 incomplete_ancestry_error(left, right, missing)
559574 }
560575 MergeBaseUnavailable::IncompleteManifestData { missing } => {
@@ -737,30 +752,24 @@
737752 // head is unavailable, never permission to consult a local ref.
738753 None => AncestorWalk::default(),
739754 };
740- let b_ancestor_set: HashSet<String> = b_walk.ancestors.iter().map(|h| h.to_string()).collect();
741-
742- // The first ancestor of branch_a that also appears in branch_b's history is the LCA.
743- for hash in &a_walk.ancestors {
744- if b_ancestor_set.contains(&hash.to_string()) {
745- let a_depth = a_walk.depth(hash).unwrap_or(usize::MAX);
746- let b_depth = b_walk.depth(hash).unwrap_or(usize::MAX);
747- let missing_edges = missing_edges_that_can_hide_lca(&a_walk, a_depth, &b_walk, b_depth);
748- if !missing_edges.is_empty() {
749- return Ok(MergeBaseIdentity::Unavailable(
750- MergeBaseUnavailable::IncompleteAncestry {
751- missing: missing_edges,
752- },
753- ));
754- }
755- if repo.get_commit(hash)?.is_none() {
755+ match certify_common_ancestor_from_walks(&a_walk, &b_walk) {
756+ CommonAncestorCertificate::Certified(hash) => {
757+ if repo.get_commit(&hash)?.is_none() {
756758 return Ok(MergeBaseIdentity::Unavailable(
757759 MergeBaseUnavailable::IncompleteAncestry {
758- missing: vec![hash.clone()],
760+ missing: vec![hash],
761+ link_gaps: Vec::new(),
759762 },
760763 ));
761764 }
762- return Ok(MergeBaseIdentity::Commit(hash.clone()));
765+ return Ok(MergeBaseIdentity::Commit(hash));
763766 }
767+ CommonAncestorCertificate::Uncertified { missing, link_gaps } => {
768+ return Ok(MergeBaseIdentity::Unavailable(
769+ MergeBaseUnavailable::IncompleteAncestry { missing, link_gaps },
770+ ));
771+ }
772+ CommonAncestorCertificate::NoCommonAncestor => {}
764773 }
765774
766775 // Oak can have a branch whose metadata says it is parented to `branch_b`,
@@ -779,6 +788,7 @@
779788 return Ok(MergeBaseIdentity::Unavailable(
780789 MergeBaseUnavailable::IncompleteAncestry {
781790 missing: missing_edges,
791+ link_gaps: Vec::new(),
782792 },
783793 ));
784794 }
@@ -931,43 +941,177 @@
931941 Ok(root_count == 1 && branch_owned_root_count == 1)
932942 }
933943
944+/// A breadth-first walk of the *local* ancestry of one head.
945+///
946+/// `ancestors` is in BFS order (parent before merge parent at each step);
947+/// `parents` records the parent edges of every present commit so the resolver
948+/// can reason about the local graph without re-reading rows; `missing_edges`
949+/// are parent hashes the walk reached whose commit rows are not local (shallow
950+/// boundaries, backfill holes, unfetched merge parents).
934951 #[derive(Debug, Default)]
935-struct AncestorWalk {
952+pub(crate) struct AncestorWalk {
936953 ancestors: Vec<Hash>,
937- depths: HashMap<String, usize>,
938- missing_edges: Vec<MissingEdge>,
954+ parents: HashMap<String, Vec<Hash>>,
955+ first_parents: HashMap<String, Hash>,
956+ missing_edges: Vec<Hash>,
939957 }
940958
941959 impl AncestorWalk {
942- fn depth(&self, hash: &Hash) -> Option<usize> {
943- self.depths.get(hash.as_str()).copied()
960+ pub(crate) fn missing_edges(&self) -> &[Hash] {
961+ &self.missing_edges
944962 }
945963 }
946964
947-#[derive(Debug)]
948-struct MissingEdge {
949- hash: Hash,
950- depth: usize,
965+/// Outcome of certifying a merge base / fork point on the local graph.
966+#[derive(Debug, Clone, PartialEq, Eq)]
967+pub(crate) enum CommonAncestorCertificate {
968+ /// The base the complete graph would select.
969+ Certified(Hash),
970+ /// A local candidate exists, but the gaps in `missing` could hide a
971+ /// better one. `link_gaps` is the candidate's first-parent gap: hydrating
972+ /// it (alongside `missing`) lets a retry link deep blocking gaps into the
973+ /// candidate's ancestry rather than walking them to the root.
974+ Uncertified {
975+ missing: Vec<Hash>,
976+ link_gaps: Vec<Hash>,
977+ },
978+ /// No common ancestor is visible locally.
979+ NoCommonAncestor,
951980 }
952981
953-fn missing_edges_that_can_hide_lca(
982+/// Certify the merge base of two local ancestry walks.
983+///
984+/// Selection (complete or partial graph): the common ancestors are
985+/// `A ∩ B`; a *best* common ancestor is one that is not a parent of another
986+/// common ancestor (no common descendant). The result is the first best common
987+/// ancestor in `a`'s BFS order — for criss-cross histories with several best
988+/// common ancestors that order is the deterministic tie-break.
989+///
990+/// Certification on a partial graph: let `C` be the local selection and
991+/// `gaps(C)` the missing edges reached walking `C`'s own local ancestry. `C`
992+/// is certified only when every missing edge of *both* walks is in `gaps(C)`.
993+/// Proof sketch (G = complete graph, L = local rows):
994+/// 1. Every commit reachable in G from `a`/`b` but not in L lies behind some
995+/// walk gap `m` (the first absent commit on any path), so it is an
996+/// ancestor of `m`, hence a proper ancestor of `C`, hence not a best
997+/// common ancestor in G (`C` is common and descends from it).
998+/// 2. If two local common ancestors are related in G but not in L, the G path
999+/// between them crosses a gap, so the older one is a proper ancestor of `C`.
1000+/// Therefore every best common ancestor of G is locally visible and locally
1001+/// best, `C` itself is best in G, and any locally-best-but-not-G-best
1002+/// commit is a proper ancestor of `C` (it would fail this check if chosen).
1003+/// 3. Commits that are not ancestors of a gap keep their BFS depth and
1004+/// discovery order in G, so G's first best common ancestor is `C`.
1005+///
1006+/// A depth filter is not sound here: a better base can hide behind a target
1007+/// gap at any depth (its BFS depth is bounded by the longest path, not the
1008+/// candidate's shortest one), so gaps are never dismissed as "too deep".
1009+/// Shallow checkouts stay certifiable because their boundary gaps are below
1010+/// the base: reached from the base's own walk.
1011+pub(crate) fn certify_common_ancestor_from_walks(
9541012 a_walk: &AncestorWalk,
955- a_candidate_depth: usize,
9561013 b_walk: &AncestorWalk,
957- b_candidate_depth: usize,
958-) -> Vec<Hash> {
959- a_walk
1014+) -> CommonAncestorCertificate {
1015+ let b_ancestor_set: HashSet<&str> = b_walk.ancestors.iter().map(|h| h.as_str()).collect();
1016+ let common: Vec<&Hash> = a_walk
1017+ .ancestors
1018+ .iter()
1019+ .filter(|hash| b_ancestor_set.contains(hash.as_str()))
1020+ .collect();
1021+ if common.is_empty() {
1022+ return CommonAncestorCertificate::NoCommonAncestor;
1023+ }
1024+ // Common ancestry is ancestor-closed within the local graph, so a common
1025+ // ancestor is dominated exactly when it is a parent of another one.
1026+ let common_set: HashSet<&str> = common.iter().map(|h| h.as_str()).collect();
1027+ let mut dominated: HashSet<&str> = HashSet::new();
1028+ for hash in &common {
1029+ for parent in a_walk
1030+ .parents
1031+ .get(hash.as_str())
1032+ .map(Vec::as_slice)
1033+ .unwrap_or(&[])
1034+ {
1035+ if common_set.contains(parent.as_str()) {
1036+ dominated.insert(parent.as_str());
1037+ }
1038+ }
1039+ }
1040+ let candidate = common
1041+ .iter()
1042+ .find(|hash| !dominated.contains(hash.as_str()))
1043+ .copied()
1044+ .expect("a finite DAG has an undominated common ancestor")
1045+ .clone();
1046+
1047+ if a_walk.missing_edges.is_empty() && b_walk.missing_edges.is_empty() {
1048+ return CommonAncestorCertificate::Certified(candidate);
1049+ }
1050+
1051+ // gaps(C): walk C's local ancestry over the edges already recorded by
1052+ // `a_walk` (C's ancestry is a subset of it).
1053+ let mut candidate_gap_set: HashSet<&str> = HashSet::new();
1054+ let mut seen: HashSet<&str> = HashSet::new();
1055+ let mut queue: VecDeque<&Hash> = VecDeque::from([&candidate]);
1056+ while let Some(hash) = queue.pop_front() {
1057+ if !seen.insert(hash.as_str()) {
1058+ continue;
1059+ }
1060+ match a_walk.parents.get(hash.as_str()) {
1061+ Some(parents) => queue.extend(parents.iter()),
1062+ None => {
1063+ candidate_gap_set.insert(hash.as_str());
1064+ }
1065+ }
1066+ }
1067+
1068+ let mut offending: Vec<Hash> = Vec::new();
1069+ let mut offending_set: HashSet<&str> = HashSet::new();
1070+ for gap in a_walk
9601071 .missing_edges
9611072 .iter()
962- .filter(|edge| edge.depth <= a_candidate_depth)
963- .chain(
964- b_walk
965- .missing_edges
966- .iter()
967- .filter(|edge| edge.depth <= b_candidate_depth),
968- )
969- .map(|edge| edge.hash.clone())
970- .collect()
1073+ .chain(b_walk.missing_edges.iter())
1074+ {
1075+ if !candidate_gap_set.contains(gap.as_str()) && offending_set.insert(gap.as_str()) {
1076+ offending.push(gap.clone());
1077+ }
1078+ }
1079+ if offending.is_empty() {
1080+ return CommonAncestorCertificate::Certified(candidate);
1081+ }
1082+ // First-parent gap below the candidate (main's history in Oak shapes).
1083+ let mut link_gaps = Vec::new();
1084+ let mut cursor = &candidate;
1085+ let mut first_parent_seen: HashSet<&str> = HashSet::new();
1086+ while first_parent_seen.insert(cursor.as_str()) {
1087+ match a_walk.first_parents.get(cursor.as_str()) {
1088+ Some(parent) if a_walk.parents.contains_key(parent.as_str()) => cursor = parent,
1089+ Some(parent) => {
1090+ link_gaps.push(parent.clone());
1091+ break;
1092+ }
1093+ None => break,
1094+ }
1095+ }
1096+ CommonAncestorCertificate::Uncertified {
1097+ missing: offending,
1098+ link_gaps,
1099+ }
1100+}
1101+
1102+/// Certify the merge base / fork point of two heads on the local graph.
1103+pub(crate) fn certify_common_ancestor(
1104+ repo: &dyn Repository,
1105+ a_head: &Hash,
1106+ b_head: &Hash,
1107+) -> Result<(CommonAncestorCertificate, AncestorWalk, AncestorWalk)> {
1108+ let a_walk = collect_ancestors_from_head(repo, a_head)?;
1109+ let b_walk = collect_ancestors_from_head(repo, b_head)?;
1110+ Ok((
1111+ certify_common_ancestor_from_walks(&a_walk, &b_walk),
1112+ a_walk,
1113+ b_walk,
1114+ ))
9711115 }
9721116
9731117 fn all_missing_edges(a_walk: &AncestorWalk, b_walk: &AncestorWalk) -> Vec<Hash> {
@@ -975,7 +1119,7 @@
9751119 .missing_edges
9761120 .iter()
9771121 .chain(b_walk.missing_edges.iter())
978- .map(|edge| edge.hash.clone())
1122+ .cloned()
9791123 .collect()
9801124 }
9811125
@@ -983,33 +1127,37 @@
9831127 /// Follows both parent_hash and merge_parent_hash to correctly traverse the DAG.
9841128 fn collect_ancestors_from_head(repo: &dyn Repository, head: &Hash) -> Result<AncestorWalk> {
9851129 let mut ancestors = Vec::new();
986- let mut depths = HashMap::new();
1130+ let mut parents = HashMap::new();
1131+ let mut first_parents = HashMap::new();
9871132 let mut missing_edges = Vec::new();
9881133 let mut queue = VecDeque::new();
9891134 let mut visited = HashSet::new();
990- queue.push_back((head.clone(), 0usize));
1135+ queue.push_back(head.clone());
9911136
992- while let Some((hash, depth)) = queue.pop_front() {
1137+ while let Some(hash) = queue.pop_front() {
9931138 if !visited.insert(hash.to_string()) {
9941139 continue;
9951140 }
9961141 let Some(commit) = repo.get_commit(&hash)? else {
997- missing_edges.push(MissingEdge { hash, depth });
1142+ missing_edges.push(hash);
9981143 continue;
9991144 };
1000- depths.insert(hash.to_string(), depth);
1001- ancestors.push(hash);
1002- if let Some(parent) = commit.parent_hash {
1003- queue.push_back((parent, depth + 1));
1145+ if let Some(parent) = &commit.parent_hash {
1146+ first_parents.insert(hash.to_string(), parent.clone());
10041147 }
1005- if let Some(merge_parent) = commit.merge_parent_hash {
1006- queue.push_back((merge_parent, depth + 1));
1007- }
1148+ let edges: Vec<Hash> = [commit.parent_hash, commit.merge_parent_hash]
1149+ .into_iter()
1150+ .flatten()
1151+ .collect();
1152+ queue.extend(edges.iter().cloned());
1153+ parents.insert(hash.to_string(), edges);
1154+ ancestors.push(hash);
10081155 }
10091156
10101157 Ok(AncestorWalk {
10111158 ancestors,
1012- depths,
1159+ parents,
1160+ first_parents,
10131161 missing_edges,
10141162 })
10151163 }
@@ -5143,4 +5291,180 @@
51435291 "pruned branch's head pointer should be deleted too"
51445292 );
51455293 }
5294+
5295+ // ---- merge-base certification on partial graphs -------------------------
5296+ //
5297+ // Invariant: a merge base computed on a partial local graph equals the
5298+ // complete-graph result, or is reported unavailable. Never a different
5299+ // (stale) base.
5300+
5301+ use super::merge_base_fixtures as fx;
5302+
5303+ fn identity(repo: &dyn Repository, a: &Hash, b: &Hash) -> MergeBaseIdentity {
5304+ resolve_merge_base_identity_from_heads(repo, "a", Some(a), None, "main", Some(b)).unwrap()
5305+ }
5306+
5307+ fn identity_label(identity: &MergeBaseIdentity) -> String {
5308+ match identity {
5309+ MergeBaseIdentity::Commit(hash) => format!("commit {}", hash.short()),
5310+ MergeBaseIdentity::DeclaredRoot => "declared-root".into(),
5311+ MergeBaseIdentity::Unavailable(reason) => format!("unavailable {reason:?}"),
5312+ }
5313+ }
5314+
5315+ #[test]
5316+ fn merge_base_squash_revert_full_graph_is_x() {
5317+ let s = fx::squash_revert();
5318+ let (_dir, full) = s.graph.materialize(|_| true);
5319+ match identity(&full, &s.a1, &s.h) {
5320+ MergeBaseIdentity::Commit(base) => assert_eq!(base, s.x, "full graph must resolve X"),
5321+ other => panic!("full graph must resolve X, got {}", identity_label(&other)),
5322+ }
5323+ }
5324+
5325+ /// Confirmed Blocker: with main's first-parent history above X missing,
5326+ /// C is reachable at depth 2 through H's merge parent Z1 while X is only
5327+ /// reachable through a missing edge at depth 3. The old depth filter
5328+ /// dismissed that gap and certified C, re-applying X's reverted change.
5329+ #[test]
5330+ fn merge_base_partial_graph_never_certifies_stale_base_behind_target_gap() {
5331+ let s = fx::squash_revert();
5332+ // Each partial shape drops a different slice of main's history.
5333+ let shapes: Vec<(&str, Vec<Hash>)> = vec![
5334+ ("M7 missing", vec![s.m[6].clone()]),
5335+ (
5336+ "R and M1..M7 missing",
5337+ std::iter::once(s.r.clone())
5338+ .chain(s.m[..7].iter().cloned())
5339+ .collect(),
5340+ ),
5341+ ("M1 missing", vec![s.m[0].clone()]),
5342+ ("M9 missing", vec![s.m[8].clone()]),
5343+ ];
5344+ for (label, dropped) in shapes {
5345+ let (_dir, partial) = s.graph.materialize(|c| !dropped.contains(&c.hash));
5346+ match identity(&partial, &s.a1, &s.h) {
5347+ MergeBaseIdentity::Commit(base) => {
5348+ assert_ne!(base, s.c, "{label}: certified stale base C");
5349+ assert_eq!(base, s.x, "{label}: certified a non-merge-base");
5350+ }
5351+ MergeBaseIdentity::Unavailable(MergeBaseUnavailable::IncompleteAncestry {
5352+ missing,
5353+ ..
5354+ }) => assert!(
5355+ dropped.iter().any(|d| missing.contains(d)),
5356+ "{label}: unavailable must name the gap that hides X, got {missing:?}"
5357+ ),
5358+ other => panic!("{label}: unexpected {}", identity_label(&other)),
5359+ }
5360+ }
5361+ }
5362+
5363+ /// Replays the review preparation loop (fetch exactly the reported gaps,
5364+ /// retry) from an empty local graph: it must converge on X, never C.
5365+ #[test]
5366+ fn merge_base_hydration_loop_converges_on_true_base() {
5367+ let s = fx::squash_revert();
5368+ let (_dir, partial) = s.graph.materialize(|c| c.hash == s.a1 || c.hash == s.h);
5369+ let mut rounds = 0;
5370+ let base = loop {
5371+ rounds += 1;
5372+ assert!(rounds < 32, "hydration did not converge");
5373+ match identity(&partial, &s.a1, &s.h) {
5374+ MergeBaseIdentity::Unavailable(MergeBaseUnavailable::IncompleteAncestry {
5375+ missing,
5376+ ..
5377+ }) => {
5378+ for hash in &missing {
5379+ partial
5380+ .store_commit(s.graph.get(hash).expect("reported gap exists"))
5381+ .unwrap();
5382+ }
5383+ }
5384+ MergeBaseIdentity::Commit(base) => break base,
5385+ other => panic!("unexpected {}", identity_label(&other)),
5386+ }
5387+ };
5388+ assert_eq!(
5389+ base,
5390+ s.x,
5391+ "hydration certified {} (C = {})",
5392+ base.short(),
5393+ s.c.short()
5394+ );
5395+ }
5396+
5397+ /// A merged branch forked far below the candidate leaves a blocking gap
5398+ /// that is really an old main ancestor. The review hydration policy must
5399+ /// link it into the candidate's first-parent history (bounded work) rather
5400+ /// than walk it to the root or give up.
5401+ #[test]
5402+ fn merge_base_hydration_links_deep_merged_branch_fork_into_candidate_history() {
5403+ let mut g = fx::Graph::new();
5404+ let mut main = vec![g.add("main", None, None)];
5405+ for _ in 1..300 {
5406+ let head = main.last().unwrap().clone();
5407+ main.push(g.add("main", Some(&head), None));
5408+ }
5409+ // Branch z forked at main[250], merged after the candidate main[280].
5410+ let z1 = g.add("z", Some(&main[250]), None);
5411+ let z2 = g.add("z", Some(&z1), None);
5412+ let a1 = g.add("a", Some(&main[280]), None);
5413+ let h = g.add("main", Some(&main[299]), Some(&z2));
5414+ // Shallow worker: main[270..] plus the heads' own rows.
5415+ let keep: std::collections::HashSet<Hash> = main[270..]
5416+ .iter()
5417+ .cloned()
5418+ .chain([z1.clone(), z2.clone(), a1.clone(), h.clone()])
5419+ .collect();
5420+ let (_dir, partial) = g.materialize(|c| keep.contains(&c.hash));
5421+ let before = partial.get_all_commits().unwrap().len();
5422+ let (identity, rounds) = fx::hydrate_like_review(&g, &partial, &a1, &h, 64).unwrap();
5423+ let MergeBaseIdentity::Commit(base) = identity else {
5424+ panic!("unexpected {}", identity_label(&identity));
5425+ };
5426+ assert_eq!(base, main[280]);
5427+ let fetched = partial.get_all_commits().unwrap().len() - before;
5428+ eprintln!("rounds={rounds} fetched={fetched}");
5429+ assert!(
5430+ fetched <= 64,
5431+ "linking must stay bounded, fetched {fetched}"
5432+ );
5433+ }
5434+
5435+ /// Shallow boundaries below the base stay certifiable (no over-blocking):
5436+ /// only R is missing, and R is below C/X on both sides.
5437+ #[test]
5438+ fn merge_base_shallow_boundary_below_base_is_certified() {
5439+ let s = fx::squash_revert();
5440+ let (_dir, partial) = s.graph.materialize(|c| c.hash != s.r);
5441+ match identity(&partial, &s.a1, &s.h) {
5442+ MergeBaseIdentity::Commit(base) => assert_eq!(base, s.x),
5443+ other => panic!(
5444+ "shallow boundary must not block: {}",
5445+ identity_label(&other)
5446+ ),
5447+ }
5448+ // A branch whose only gap is its fork point's own parent (the fresh
5449+ // shallow worker shape) is certified too.
5450+ let (_dir2, shallow) = s
5451+ .graph
5452+ .materialize(|c| c.hash != s.r && c.hash != s.c && c.hash != s.z1);
5453+ match resolve_merge_base_identity_from_heads(
5454+ &shallow,
5455+ "a",
5456+ Some(&s.a1),
5457+ None,
5458+ "main",
5459+ Some(&s.m[8]),
5460+ )
5461+ .unwrap()
5462+ {
5463+ MergeBaseIdentity::Commit(base) => assert_eq!(base, s.x),
5464+ other => panic!(
5465+ "fresh shallow shape must certify: {}",
5466+ identity_label(&other)
5467+ ),
5468+ }
5469+ }
51465470 }