Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-core/src/merge.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-core / src / merge.rs` 348 lines ยท 14216 bytes Raw Blame History 1 //! Merge tier T1 (region): line-level three-way merge of one file (ADR 0003 section 5.5, 2 //! section 9 step D1). See `docs/D1_MERGE_TIER_T1.md`. 3 //! 4 //! [`region_merge`] merges the versions of one file that several revisions wrote against the 5 //! same base version. The rule does not depend on which line diff is chosen: 6 //! 7 //! 1. **Anchors.** For each version, a base line is *forced* when every minimal line 8 //! alignment (every longest common subsequence) between the base and that version matches 9 //! it, and always to the same line of the version. The anchors are the base lines forced 10 //! for every version. 11 //! 2. **Segments.** The anchors cut the base and every version into matching segments (the 12 //! lines between two consecutive anchors). In each segment at most one version may differ 13 //! from the base; the merged file takes that version's segment (or the base's when none 14 //! differs). Two versions that change one segment are a conflict, also when they changed 15 //! it identically (callers take byte-identical whole-file mutations once, before calling 16 //! this). 17 //! 18 //! Why this agrees with Git: any minimal diff matches every anchor, so its changed regions for 19 //! one version stay inside that version's changed segments, and the regions of two versions 20 //! are always separated by at least one anchor line, which is the condition Git's three-way 21 //! merge needs for a clean result; the clean result is then the same file. `synapse-bench` 22 //! checks it against `git merge-file` and `git merge-tree`. The argument covers diffs that are 23 //! minimal; Git's histogram diff and its cost-limited Myers diff on very large inputs are not 24 //! always minimal, which is why the bench comparison is part of the acceptance. 25 //! 26 //! Refused as well: binary content (any NUL byte), a version that does not end with a newline, 27 //! and a base and version too long to align within [`MAX_ALIGNMENT_CELLS`]. 28 29 use std::collections::HashMap; 30 31 /// Largest `(base lines + 1) * (version lines + 1)` [`region_merge`] aligns (two `u32` tables 32 /// of this many cells per version, 16 MiB each at the limit). 33 pub const MAX_ALIGNMENT_CELLS: usize = 1 << 22; 34 35 /// Why a region merge is refused. 36 #[derive(Debug, Clone, PartialEq, Eq)] 37 pub enum RegionConflict { 38 /// A version contains a NUL byte. 39 Binary, 40 /// A non-empty version does not end with a newline. 41 NoFinalNewline, 42 /// The base and a version are too long to align within [`MAX_ALIGNMENT_CELLS`]. 43 TooLarge, 44 /// Versions `a` and `b` both change the base lines between two anchors, starting at base 45 /// line `line` (0-based). 46 Overlap { a: usize, b: usize, line: usize }, 47 } 48 49 impl std::fmt::Display for RegionConflict { 50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 51 match self { 52 RegionConflict::Binary => write!(f, "binary content"), 53 RegionConflict::NoFinalNewline => write!(f, "a version does not end with a newline"), 54 RegionConflict::TooLarge => write!( 55 f, 56 "the file is too long to align (more than {MAX_ALIGNMENT_CELLS} cells)" 57 ), 58 RegionConflict::Overlap { a, b, line } => write!( 59 f, 60 "versions {a} and {b} both change the region starting at base line {}", 61 line + 1 62 ), 63 } 64 } 65 } 66 67 fn split_lines(bytes: &[u8]) -> Vec<&[u8]> { 68 bytes.split_inclusive(|b| *b == b'\n').collect() 69 } 70 71 fn check_text(bytes: &[u8]) -> Result<(), RegionConflict> { 72 if bytes.contains(&0) { 73 return Err(RegionConflict::Binary); 74 } 75 if !bytes.is_empty() && bytes.last() != Some(&b'\n') { 76 return Err(RegionConflict::NoFinalNewline); 77 } 78 Ok(()) 79 } 80 81 /// For each line of `a`, the line of `b` it is matched to in every longest common subsequence 82 /// of `a` and `b`, or `None` when some longest common subsequence leaves it unmatched or 83 /// matches it elsewhere. 84 fn forced_matches(a: &[u32], b: &[u32]) -> Result>, RegionConflict> { 85 let (n, m) = (a.len(), b.len()); 86 let w = m + 1; 87 if (n + 1).saturating_mul(w) > MAX_ALIGNMENT_CELLS { 88 return Err(RegionConflict::TooLarge); 89 } 90 // f[i * w + j] = LCS(a[..i], b[..j]); s[i * w + j] = LCS(a[i..], b[j..]). 91 let mut f = vec![0u32; (n + 1) * w]; 92 for i in 1..=n { 93 for j in 1..=m { 94 f[i * w + j] = if a[i - 1] == b[j - 1] { 95 f[(i - 1) * w + j - 1] + 1 96 } else { 97 f[(i - 1) * w + j].max(f[i * w + j - 1]) 98 }; 99 } 100 } 101 let mut s = vec![0u32; (n + 1) * w]; 102 for i in (0..n).rev() { 103 for j in (0..m).rev() { 104 s[i * w + j] = if a[i] == b[j] { 105 s[(i + 1) * w + j + 1] + 1 106 } else { 107 s[(i + 1) * w + j].max(s[i * w + j + 1]) 108 }; 109 } 110 } 111 let total = f[n * w + m]; 112 let mut out = vec![None; n]; 113 for (i, slot) in out.iter_mut().enumerate() { 114 // Some optimal alignment leaves line i unmatched: not forced. 115 if (0..=m).any(|j| f[i * w + j] + s[(i + 1) * w + j] == total) { 116 continue; 117 } 118 let mut partners = 119 (0..m).filter(|&j| a[i] == b[j] && f[i * w + j] + 1 + s[(i + 1) * w + j + 1] == total); 120 if let (Some(j), None) = (partners.next(), partners.next()) { 121 *slot = Some(j); 122 } 123 } 124 Ok(out) 125 } 126 127 /// Line-level three-way merge of `versions` of one file against `base` (see the module 128 /// documentation). `Ok` holds the merged bytes. 129 pub fn region_merge<'a>(base: &'a [u8], versions: &[&'a [u8]]) -> Result, RegionConflict> { 130 check_text(base)?; 131 for v in versions { 132 check_text(v)?; 133 } 134 let mut ids: HashMap<&[u8], u32> = HashMap::new(); 135 let mut text: Vec<&[u8]> = Vec::new(); 136 let mut intern = |bytes: &'a [u8]| -> Vec { 137 split_lines(bytes) 138 .into_iter() 139 .map(|line| { 140 *ids.entry(line).or_insert_with(|| { 141 text.push(line); 142 (text.len() - 1) as u32 143 }) 144 }) 145 .collect() 146 }; 147 let base_ids = intern(base); 148 let version_ids: Vec> = versions.iter().map(|v| intern(v)).collect(); 149 let forced: Vec>> = version_ids 150 .iter() 151 .map(|v| forced_matches(&base_ids, v)) 152 .collect::>()?; 153 // Anchors: base lines forced in every version, with their partner in each version. The 154 // partners increase with the base line (an alignment never crosses), and the end of the 155 // files closes the last segment. 156 let mut cuts: Vec<(usize, Vec)> = Vec::new(); 157 for i in 0..base_ids.len() { 158 let partners: Option> = forced.iter().map(|f| f[i]).collect(); 159 if let Some(p) = partners { 160 cuts.push((i, p)); 161 } 162 } 163 let anchors = cuts.len(); 164 cuts.push((base_ids.len(), version_ids.iter().map(Vec::len).collect())); 165 let mut out: Vec = Vec::with_capacity(base_ids.len()); 166 let mut base_at = 0; 167 let mut ver_at = vec![0usize; versions.len()]; 168 for (k, (cut, partners)) in cuts.iter().enumerate() { 169 let base_seg = &base_ids[base_at..*cut]; 170 let mut changed: Option<(usize, &[u32])> = None; 171 for (v, ids) in version_ids.iter().enumerate() { 172 let seg = &ids[ver_at[v]..partners[v]]; 173 if seg != base_seg { 174 if let Some((first, _)) = changed { 175 return Err(RegionConflict::Overlap { 176 a: first, 177 b: v, 178 line: base_at, 179 }); 180 } 181 changed = Some((v, seg)); 182 } 183 } 184 out.extend_from_slice(changed.map_or(base_seg, |(_, seg)| seg)); 185 if k < anchors { 186 out.push(base_ids[*cut]); 187 } 188 base_at = cut + 1; 189 for (v, p) in partners.iter().enumerate() { 190 ver_at[v] = p + 1; 191 } 192 } 193 Ok(out 194 .into_iter() 195 .flat_map(|id| text[id as usize].iter().copied()) 196 .collect()) 197 } 198 199 #[cfg(test)] 200 mod tests { 201 use super::*; 202 use std::collections::BTreeSet; 203 204 fn lines(n: usize, tag: &str) -> String { 205 (0..n).map(|i| format!("{tag} {i}\n")).collect() 206 } 207 208 fn edit(base: &str, line: usize, new: &str) -> String { 209 base.split_inclusive('\n') 210 .enumerate() 211 .map(|(i, l)| { 212 if i == line { 213 format!("{new}\n") 214 } else { 215 l.to_string() 216 } 217 }) 218 .collect() 219 } 220 221 /// Every longest-common-subsequence alignment of `a` and `b`, as sets of matched pairs. 222 fn all_optimal(a: &[u32], b: &[u32]) -> Vec> { 223 fn go( 224 a: &[u32], 225 b: &[u32], 226 i: usize, 227 j: usize, 228 cur: &mut Vec<(usize, usize)>, 229 out: &mut Vec>, 230 ) { 231 if i == a.len() || j == b.len() { 232 out.push(cur.clone()); 233 return; 234 } 235 if a[i] == b[j] { 236 cur.push((i, j)); 237 go(a, b, i + 1, j + 1, cur, out); 238 cur.pop(); 239 } 240 go(a, b, i + 1, j, cur, out); 241 go(a, b, i, j + 1, cur, out); 242 } 243 let mut all = Vec::new(); 244 go(a, b, 0, 0, &mut Vec::new(), &mut all); 245 let best = all.iter().map(Vec::len).max().unwrap_or(0); 246 all.into_iter() 247 .filter(|x| x.len() == best) 248 .map(|x| x.into_iter().collect()) 249 .collect() 250 } 251 252 /// The forced matches equal the intersection of every optimal alignment, on random small 253 /// inputs over small alphabets (many repeated lines), checked by brute force. 254 #[test] 255 fn d1_forced_matches_are_exactly_the_pairs_every_optimal_alignment_shares() { 256 let mut s = 0x0D1_u64; 257 let mut next = || { 258 s = s 259 .wrapping_mul(`6364136223846793005`) 260 .wrapping_add(`1442695040888963407`); 261 s >> 33 262 }; 263 for _ in 0..2_000 { 264 let n = (next() % 7) as usize; 265 let m = (next() % 7) as usize; 266 let alpha = 1 + next() % 3; 267 let a: Vec = (0..n).map(|_| (next() % alpha) as u32).collect(); 268 let b: Vec = (0..m).map(|_| (next() % alpha) as u32).collect(); 269 let all = all_optimal(&a, &b); 270 let mut common = all[0].clone(); 271 for x in &all[1..] { 272 common = common.intersection(x).copied().collect(); 273 } 274 let want: Vec> = (0..n) 275 .map(|i| common.iter().find(|(x, _)| *x == i).map(|(_, j)| *j)) 276 .collect(); 277 assert_eq!(forced_matches(&a, &b).unwrap(), want, "{a:?} {b:?}"); 278 } 279 } 280 281 #[test] 282 fn d1_disjoint_single_line_edits_merge_and_touching_edits_conflict() { 283 let base = lines(60, "line"); 284 let a = edit(&base, 10, "alpha"); 285 let b = edit(&base, 30, "beta"); 286 let c = edit(&base, 50, "gamma"); 287 let merged = 288 region_merge(base.as_bytes(), &[a.as_bytes(), b.as_bytes(), c.as_bytes()]).unwrap(); 289 let want = edit(&edit(&edit(&base, 10, "alpha"), 30, "beta"), 50, "gamma"); 290 assert_eq!(String::from_utf8(merged).unwrap(), want); 291 // One unchanged line between: clean. Adjacent lines: conflict (as Git). 292 let near = edit(&base, 12, "near"); 293 assert!(region_merge(base.as_bytes(), &[a.as_bytes(), near.as_bytes()]).is_ok()); 294 let touch = edit(&base, 11, "touch"); 295 assert!(matches!( 296 region_merge(base.as_bytes(), &[a.as_bytes(), touch.as_bytes()]), 297 Err(RegionConflict::Overlap { .. }) 298 )); 299 // Identical edits are refused here (callers take identical whole files once). 300 assert!(region_merge(base.as_bytes(), &[a.as_bytes(), a.as_bytes()]).is_err()); 301 } 302 303 /// A version whose edit some minimal diff places next to the other version's edit is a 304 /// conflict, even when one particular alignment would separate them. 305 #[test] 306 fn d1_edits_that_some_minimal_diff_places_together_conflict() { 307 // An inserted `x` in a run of `x` lines may sit right before the `b` line. 308 let base = "a\nx\nx\nx\nb\nc\nd\n"; 309 let ins = "a\nx\nx\nx\nx\nb\nc\nd\n"; 310 let after = "a\nx\nx\nx\nB\nc\nd\n"; 311 assert!(matches!( 312 region_merge(base.as_bytes(), &[ins.as_bytes(), after.as_bytes()]), 313 Err(RegionConflict::Overlap { .. }) 314 )); 315 let far = "a\nx\nx\nx\nb\nc\nD\n"; 316 assert_eq!( 317 region_merge(base.as_bytes(), &[ins.as_bytes(), far.as_bytes()]).unwrap(), 318 b"a\nx\nx\nx\nx\nb\nc\nD\n" 319 ); 320 // Found by the `git merge-file` differential: version b moves an `x` across a `}`, 321 // which one minimal diff reads as an insertion before the `}` and another as a 322 // deletion of the `}` right where version a inserts `{`. 323 let base = "}\n}\nline 2\nx\nx\n}\nx\n}\nx\n}\n}\nline 11\n}\n"; 324 let a = "}\n}\nline 2\nx\nx\n}\n{\nx\n}\nx\n}\n}\nline 11\n}\n"; 325 let b = "}\n}\nline 2\nx\nx\nx\n}\nx\n}\nx\n}\nB 0\n}\n"; 326 assert!(region_merge(base.as_bytes(), &[a.as_bytes(), b.as_bytes()]).is_err()); 327 } 328 329 #[test] 330 fn d1_binary_missing_final_newline_and_oversized_files_are_refused() { 331 assert_eq!( 332 region_merge(b"a\0\n", &[b"a\n", b"b\n"]), 333 Err(RegionConflict::Binary) 334 ); 335 assert_eq!( 336 region_merge(b"a\nb\n", &[b"a\nb", b"a\nb\n"]), 337 Err(RegionConflict::NoFinalNewline) 338 ); 339 // Empty base: two versions that both add text conflict. 340 assert!(region_merge(b"", &[b"a\n", b"b\n"]).is_err()); 341 let big = lines(3_000, "l"); 342 let big2 = edit(&big, 5, "x"); 343 assert_eq!( 344 region_merge(big.as_bytes(), &[big2.as_bytes(), big.as_bytes()]), 345 Err(RegionConflict::TooLarge) 346 ); 347 } 348 }