synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / tree_parity.rs
| 1 | //! Tree and diff parity between Synapse and Git (ADR 0003 section 9 step 4, C1). |
| 2 | //! |
| 3 | //! Every comparison is per entry, not a count: a Synapse tree listing is rendered in the |
| 4 | //! exact line shape of `git ls-tree -r --full-tree` (`<mode> blob <oid>\t<path>`), and a |
| 5 | //! Synapse diff in the exact shape of `git diff-tree -r --raw --no-renames --no-abbrev` |
| 6 | //! (`:<old mode> <new mode> <old oid> <new oid> <status>\t<path>`), and both sides are |
| 7 | //! compared line for line, in order. Synapse answers come from the public signed `tree` |
| 8 | //! and `diff` APIs (all pages, one pinned snapshot), so the check covers what a client sees. |
| 9 | //! |
| 10 | //! The module also builds the small synthetic Git repository the CI tests use (the Gate 4 |
| 11 | //! fixture is not available on CI runners) and applies [`Proposal`]s to both systems. |
| 12 | |
| 13 | use crate::fixture::{self, configure_bench_clone}; |
| 14 | use crate::git_arm; |
| 15 | use crate::gitcmd::{git_line, git_ok}; |
| 16 | use crate::synapse_arm::{self, AgentIdentity, BenchIdentities}; |
| 17 | use crate::workload::{EditOp, FileEdit, Proposal}; |
| 18 | use std::path::{Path, PathBuf}; |
| 19 | use synapse_api::{ |
| 20 | DiffEntry, DiffQueryPayload, PageRequest, PageResponse, SynapseService, TreeQueryPayload, |
| 21 | TreeTarget, VirtualTreeEntry, DEFAULT_MAX_PAGE_SIZE, |
| 22 | }; |
| 23 | use synapse_core::{ChangesetId, GitOid, WalSeq}; |
| 24 | use synapse_store::{FsyncPolicy, IngestOutcome, RecoveryPolicy}; |
| 25 | |
| 26 | const ZERO_MODE: &str = "000000"; |
| 27 | const ZERO_OID: &str = "0000000000000000000000000000000000000000"; |
| 28 | |
| 29 | /// First differing line of a parity comparison (or a length difference). |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub struct ParityMismatch { |
| 32 | pub index: usize, |
| 33 | pub git: Option<String>, |
| 34 | pub synapse: Option<String>, |
| 35 | } |
| 36 | |
| 37 | /// Compare two line lists in order; `None` when equal. |
| 38 | pub fn first_mismatch(git: &[String], synapse: &[String]) -> Option<ParityMismatch> { |
| 39 | let n = git.len().max(synapse.len()); |
| 40 | (0..n) |
| 41 | .find(|&i| git.get(i) != synapse.get(i)) |
| 42 | .map(|i| ParityMismatch { |
| 43 | index: i, |
| 44 | git: git.get(i).cloned(), |
| 45 | synapse: synapse.get(i).cloned(), |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | fn split_nul(bytes: &[u8]) -> Result<Vec<String>, String> { |
| 50 | bytes |
| 51 | .split(|&b| b == 0) |
| 52 | .filter(|s| !s.is_empty()) |
| 53 | .map(|s| String::from_utf8(s.to_vec()).map_err(|e| format!("non UTF-8 git output: {e}"))) |
| 54 | .collect() |
| 55 | } |
| 56 | |
| 57 | /// `git ls-tree -r -z --full-tree <rev>` as `<mode> <type> <oid>\t<path>` lines. |
| 58 | pub fn git_ls_tree_r(repo: &Path, rev: &str) -> Result<Vec<String>, String> { |
| 59 | let out = git_ok( |
| 60 | repo, |
| 61 | &[], |
| 62 | &[], |
| 63 | &["ls-tree", "-r", "-z", "--full-tree", rev], |
| 64 | None, |
| 65 | )?; |
| 66 | split_nul(&out) |
| 67 | } |
| 68 | |
| 69 | /// `git diff-tree -r -z --raw --no-renames --no-abbrev <old> <new>` as |
| 70 | /// `:<old mode> <new mode> <old oid> <new oid> <status>\t<path>` lines. |
| 71 | pub fn git_diff_tree_raw(repo: &Path, old: &str, new: &str) -> Result<Vec<String>, String> { |
| 72 | let out = git_ok( |
| 73 | repo, |
| 74 | &[], |
| 75 | &[], |
| 76 | &[ |
| 77 | "diff-tree", |
| 78 | "-r", |
| 79 | "-z", |
| 80 | "--raw", |
| 81 | "--no-renames", |
| 82 | "--no-abbrev", |
| 83 | old, |
| 84 | new, |
| 85 | ], |
| 86 | None, |
| 87 | )?; |
| 88 | // With -z each record is `:<meta>\0<path>\0`. |
| 89 | let fields = split_nul(&out)?; |
| 90 | if fields.len() % 2 != 0 { |
| 91 | return Err(format!("odd diff-tree -z field count {}", fields.len())); |
| 92 | } |
| 93 | Ok(fields |
| 94 | .chunks(2) |
| 95 | .map(|c| format!("{}\t{}", c[0], c[1])) |
| 96 | .collect()) |
| 97 | } |
| 98 | |
| 99 | /// One Synapse tree entry in `git ls-tree -r` line shape. |
| 100 | pub fn ls_tree_line(e: &VirtualTreeEntry) -> String { |
| 101 | format!( |
| 102 | "{} blob {}\t{}", |
| 103 | e.mode.git_octal_str(), |
| 104 | e.git_blob_oid.to_hex(), |
| 105 | e.path |
| 106 | ) |
| 107 | } |
| 108 | |
| 109 | /// One Synapse diff entry in `git diff-tree --raw` line shape. |
| 110 | pub fn diff_tree_line(d: &DiffEntry) -> String { |
| 111 | let side = |e: &Option<VirtualTreeEntry>| match e { |
| 112 | Some(e) => (e.mode.git_octal_str().to_string(), e.git_blob_oid.to_hex()), |
| 113 | None => (ZERO_MODE.to_string(), ZERO_OID.to_string()), |
| 114 | }; |
| 115 | let (om, oo) = side(&d.old_entry); |
| 116 | let (nm, no) = side(&d.new_entry); |
| 117 | format!( |
| 118 | ":{om} {nm} {oo} {no} {}\t{}", |
| 119 | d.status.git_status_char(), |
| 120 | d.path |
| 121 | ) |
| 122 | } |
| 123 | |
| 124 | /// A reader that issues signed `tree` and `diff` requests and collects every page. |
| 125 | pub struct ApiReader<'a> { |
| 126 | pub agent: &'a AgentIdentity, |
| 127 | pub ids: &'a BenchIdentities, |
| 128 | pub counter: u64, |
| 129 | } |
| 130 | |
| 131 | impl ApiReader<'_> { |
| 132 | fn pages<P, T>( |
| 133 | &mut self, |
| 134 | svc: &mut SynapseService, |
| 135 | make: impl Fn(PageRequest) -> P, |
| 136 | api: fn( |
| 137 | &mut SynapseService, |
| 138 | &synapse_auth::AuthenticatedRequest<P>, |
| 139 | u64, |
| 140 | ) -> synapse_core::SynapseResult<PageResponse<T>>, |
| 141 | ) -> Result<Vec<T>, String> |
| 142 | where |
| 143 | P: serde::Serialize, |
| 144 | { |
| 145 | let mut cursor: Option<String> = None; |
| 146 | let mut snapshot: Option<WalSeq> = None; |
| 147 | let mut items = Vec::new(); |
| 148 | loop { |
| 149 | self.counter += 1; |
| 150 | let now = crate::unix_now_ms(); |
| 151 | let page = PageRequest { |
| 152 | cursor: cursor.clone(), |
| 153 | limit: DEFAULT_MAX_PAGE_SIZE, |
| 154 | min_visible_seq: None, |
| 155 | snapshot_seq: snapshot, |
| 156 | }; |
| 157 | let req = synapse_arm::build_read_request( |
| 158 | self.agent, |
| 159 | &self.ids.repo_id, |
| 160 | make(page), |
| 161 | &format!("c1/parity/{}", self.counter), |
| 162 | now, |
| 163 | )?; |
| 164 | let resp = api(svc, &req, now).map_err(|e| e.to_string())?; |
| 165 | snapshot = Some(resp.snapshot_seq); |
| 166 | items.extend(resp.items); |
| 167 | match resp.next_cursor { |
| 168 | Some(next) => cursor = Some(next), |
| 169 | None => return Ok(items), |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// Every entry of `target` through the paginated `tree` API, as `ls-tree -r` lines. |
| 175 | pub fn ls_tree_r( |
| 176 | &mut self, |
| 177 | svc: &mut SynapseService, |
| 178 | target: TreeTarget, |
| 179 | ) -> Result<Vec<String>, String> { |
| 180 | let entries = self.pages( |
| 181 | svc, |
| 182 | |page| TreeQueryPayload { |
| 183 | target, |
| 184 | path_prefix: None, |
| 185 | page, |
| 186 | }, |
| 187 | |svc, req, now| svc.tree(req, now), |
| 188 | )?; |
| 189 | Ok(entries.iter().map(ls_tree_line).collect()) |
| 190 | } |
| 191 | |
| 192 | /// Every entry of `base -> target` through the paginated `diff` API, as raw diff lines. |
| 193 | pub fn diff_tree_raw( |
| 194 | &mut self, |
| 195 | svc: &mut SynapseService, |
| 196 | base: TreeTarget, |
| 197 | target: TreeTarget, |
| 198 | ) -> Result<Vec<String>, String> { |
| 199 | let entries = self.pages( |
| 200 | svc, |
| 201 | |page| DiffQueryPayload { base, target, page }, |
| 202 | |svc, req, now| svc.diff(req, now), |
| 203 | )?; |
| 204 | Ok(entries.iter().map(diff_tree_line).collect()) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | /// A Synapse service and a Git clone holding the same base commit and proposals. |
| 209 | pub struct ParityPair { |
| 210 | pub clone: PathBuf, |
| 211 | pub base_commit: String, |
| 212 | pub base_oid: GitOid, |
| 213 | pub ids: BenchIdentities, |
| 214 | pub svc: SynapseService, |
| 215 | plumbing: git_arm::PlumbingAgent, |
| 216 | work: PathBuf, |
| 217 | submitted: u64, |
| 218 | } |
| 219 | |
| 220 | impl ParityPair { |
| 221 | /// Open a fresh Synapse store under `work`, register `base_commit` of `clone` as the base |
| 222 | /// tree, and prepare the Git plumbing index used to commit proposals. |
| 223 | pub fn open( |
| 224 | clone: &Path, |
| 225 | base_commit: &str, |
| 226 | work: &Path, |
| 227 | seed: u64, |
| 228 | agents: usize, |
| 229 | ) -> Result<Self, String> { |
| 230 | let base = fixture::list_base_tree(clone, base_commit)?; |
| 231 | let full = fixture::load_full_base(clone, &base)?; |
| 232 | let ids = synapse_arm::issue_identities(seed, agents.max(1), crate::unix_now_ms())?; |
| 233 | let mut svc = synapse_arm::open_service( |
| 234 | &work.join("synapse-store"), |
| 235 | &ids, |
| 236 | FsyncPolicy::BatchWindow { max_records: 1024 }, |
| 237 | RecoveryPolicy::StrictFailClosed, |
| 238 | )?; |
| 239 | let base_oid = synapse_arm::register_base(&mut svc, base_commit, full)?; |
| 240 | let plumbing = git_arm::g3_setup_agent(clone, base_commit, &work.join("plumbing"), 0, &[])?; |
| 241 | Ok(Self { |
| 242 | clone: clone.to_path_buf(), |
| 243 | base_commit: base_commit.to_string(), |
| 244 | base_oid, |
| 245 | ids, |
| 246 | svc, |
| 247 | plumbing, |
| 248 | work: work.to_path_buf(), |
| 249 | submitted: 0, |
| 250 | }) |
| 251 | } |
| 252 | |
| 253 | /// Submit `p` to Synapse (agent `p.agent`) and commit it to Git on the base commit. |
| 254 | /// Returns the changeset id and the Git commit id. |
| 255 | pub fn apply(&mut self, p: &Proposal) -> Result<(ChangesetId, String), String> { |
| 256 | self.submitted += 1; |
| 257 | let label = format!( |
| 258 | "c1/parity/submit/{}/{}", |
| 259 | self.work.display(), |
| 260 | self.submitted |
| 261 | ); |
| 262 | let now = crate::unix_now_ms(); |
| 263 | let agent = &self.ids.agents[p.agent % self.ids.agents.len()]; |
| 264 | let req = synapse_arm::build_submit_request( |
| 265 | agent, |
| 266 | &self.ids.repo_id, |
| 267 | self.base_oid, |
| 268 | p, |
| 269 | &label, |
| 270 | now, |
| 271 | )?; |
| 272 | let cs = match self.svc.submit(&req, now).map_err(|e| e.to_string())? { |
| 273 | IngestOutcome::Committed { changeset_id, .. } |
| 274 | | IngestOutcome::IdempotentDuplicate { changeset_id, .. } => changeset_id, |
| 275 | }; |
| 276 | let commit = git_arm::g3_op(&self.clone, &self.base_commit, &self.plumbing, p, &[])?; |
| 277 | Ok((cs, commit)) |
| 278 | } |
| 279 | |
| 280 | /// `git ls-tree -r <commit>` and the Synapse `tree` listing of `target`. |
| 281 | pub fn tree_pair( |
| 282 | &mut self, |
| 283 | target: TreeTarget, |
| 284 | commit: &str, |
| 285 | ) -> Result<(Vec<String>, Vec<String>), String> { |
| 286 | let git = git_ls_tree_r(&self.clone, commit)?; |
| 287 | let mut reader = ApiReader { |
| 288 | agent: &self.ids.agents[0], |
| 289 | ids: &self.ids, |
| 290 | counter: self.submitted * 1_000_000, |
| 291 | }; |
| 292 | let syn = reader.ls_tree_r(&mut self.svc, target)?; |
| 293 | Ok((git, syn)) |
| 294 | } |
| 295 | |
| 296 | /// `git diff-tree -r --raw <base> <commit>` and the Synapse `diff` from the base tree. |
| 297 | pub fn diff_pair( |
| 298 | &mut self, |
| 299 | target: TreeTarget, |
| 300 | commit: &str, |
| 301 | ) -> Result<(Vec<String>, Vec<String>), String> { |
| 302 | let git = git_diff_tree_raw(&self.clone, &self.base_commit, commit)?; |
| 303 | let base = TreeTarget::BaseGitCommit(self.base_oid); |
| 304 | let mut reader = ApiReader { |
| 305 | agent: &self.ids.agents[0], |
| 306 | ids: &self.ids, |
| 307 | counter: self.submitted * 1_000_000 + 500_000, |
| 308 | }; |
| 309 | let syn = reader.diff_tree_raw(&mut self.svc, base, target)?; |
| 310 | Ok((git, syn)) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /// Build a synthetic repository at `<root>/fixture` with nested directories, an executable, |
| 315 | /// a symlink, names that test Git's directory ordering (`a-b`, `a.c`, `a/`), and `n_files` |
| 316 | /// text files of `lines` lines (each at least the Gate 4 editable size). Returns the commit. |
| 317 | pub fn synthetic_fixture(root: &Path, n_files: usize, lines: usize) -> Result<String, String> { |
| 318 | let repo = root.join("fixture"); |
| 319 | let mkdir = |p: &Path| std::fs::create_dir_all(p).map_err(|e| format!("mkdir: {e}")); |
| 320 | let write = |p: &Path, b: &[u8]| std::fs::write(p, b).map_err(|e| format!("write: {e}")); |
| 321 | for d in ["src/nested/deep", "docs", "a"] { |
| 322 | mkdir(&repo.join(d))?; |
| 323 | } |
| 324 | git_ok(&repo, &[], &[], &["init", "-q", "-b", "main"], None)?; |
| 325 | configure_bench_clone(&repo)?; |
| 326 | for i in 0..n_files { |
| 327 | let mut body = String::new(); |
| 328 | for l in 0..lines { |
| 329 | body.push_str(&format!("synthetic file {i} line {l} with padding text\n")); |
| 330 | } |
| 331 | let path = match i % 4 { |
| 332 | 0 => repo.join(format!("src/nested/file{i:03}.txt")), |
| 333 | 1 => repo.join(format!("src/nested/deep/file{i:03}.txt")), |
| 334 | 2 => repo.join(format!("docs/page{i:03}.md")), |
| 335 | _ => repo.join(format!("src/file{i:03}.txt")), |
| 336 | }; |
| 337 | write(&path, body.as_bytes())?; |
| 338 | } |
| 339 | write(&repo.join("a/inner.txt"), b"inside a/\n")?; |
| 340 | write(&repo.join("a-b"), b"dash sorts before slash\n")?; |
| 341 | write(&repo.join("a.c"), b"dot sorts before slash\n")?; |
| 342 | write(&repo.join("run.sh"), b"#!/bin/sh\necho synthetic\n")?; |
| 343 | let mut perm = std::fs::metadata(repo.join("run.sh")) |
| 344 | .map_err(|e| e.to_string())? |
| 345 | .permissions(); |
| 346 | std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755); |
| 347 | std::fs::set_permissions(repo.join("run.sh"), perm).map_err(|e| e.to_string())?; |
| 348 | std::os::unix::fs::symlink("run.sh", repo.join("link")).map_err(|e| e.to_string())?; |
| 349 | git_ok(&repo, &[], &[], &["add", "-A"], None)?; |
| 350 | git_ok( |
| 351 | &repo, |
| 352 | &[], |
| 353 | &[], |
| 354 | &["commit", "-q", "-m", "synthetic C1 base"], |
| 355 | None, |
| 356 | )?; |
| 357 | git_line(&repo, &["rev-parse", "HEAD"]) |
| 358 | } |
| 359 | |
| 360 | /// A unique temporary directory for one test. |
| 361 | pub fn temp_dir(label: &str) -> PathBuf { |
| 362 | let dir = std::env::temp_dir().join(format!( |
| 363 | "synapse-c1-{label}-{}-{}", |
| 364 | std::process::id(), |
| 365 | crate::unix_now_ms() |
| 366 | )); |
| 367 | let _ = std::fs::remove_dir_all(&dir); |
| 368 | let _ = std::fs::create_dir_all(&dir); |
| 369 | dir |
| 370 | } |
| 371 | |
| 372 | fn upsert(path: &str, mode: synapse_core::FileMode, content: &[u8]) -> FileEdit { |
| 373 | FileEdit { |
| 374 | path: path.to_string(), |
| 375 | op: EditOp::Upsert { |
| 376 | mode, |
| 377 | content: std::sync::Arc::new(content.to_vec()), |
| 378 | }, |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | fn delete(path: &str) -> FileEdit { |
| 383 | FileEdit { |
| 384 | path: path.to_string(), |
| 385 | op: EditOp::Delete, |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | /// Hand-written proposals that cover every raw diff status Git can produce without rename |
| 390 | /// detection, against [`synthetic_fixture`]: add, modify, delete, mode change (`M`), |
| 391 | /// symlink to file and file to symlink (`T`), file replaced by a directory and directory |
| 392 | /// replaced by a file (`D` plus `A`), and new nested directories. |
| 393 | pub fn edge_case_proposals() -> Vec<Proposal> { |
| 394 | use synapse_core::FileMode::{Regular644, Symlink120000}; |
| 395 | let p = |index: usize, summary: &str, mut edits: Vec<FileEdit>| { |
| 396 | edits.sort_by(|a, b| a.path.cmp(&b.path)); |
| 397 | Proposal { |
| 398 | agent: index % 2, |
| 399 | index, |
| 400 | summary: summary.to_string(), |
| 401 | edits, |
| 402 | } |
| 403 | }; |
| 404 | vec![ |
| 405 | p( |
| 406 | 0, |
| 407 | "add modify delete", |
| 408 | vec![ |
| 409 | upsert("new/dir/file.txt", Regular644, b"brand new\n"), |
| 410 | upsert("a-b", Regular644, b"modified dash file\n"), |
| 411 | delete("a.c"), |
| 412 | ], |
| 413 | ), |
| 414 | p( |
| 415 | 1, |
| 416 | "mode change only (run.sh is executable in the base)", |
| 417 | vec![upsert("run.sh", Regular644, b"#!/bin/sh\necho synthetic\n")], |
| 418 | ), |
| 419 | p( |
| 420 | 2, |
| 421 | "symlink becomes a regular file", |
| 422 | vec![upsert("link", Regular644, b"run.sh")], |
| 423 | ), |
| 424 | p( |
| 425 | 3, |
| 426 | "regular file becomes a symlink", |
| 427 | vec![upsert("a-b", Symlink120000, b"a.c")], |
| 428 | ), |
| 429 | p( |
| 430 | 4, |
| 431 | "file replaced by a directory", |
| 432 | vec![ |
| 433 | delete("a.c"), |
| 434 | upsert("a.c/child.txt", Regular644, b"child\n"), |
| 435 | ], |
| 436 | ), |
| 437 | p( |
| 438 | 5, |
| 439 | "directory replaced by a file", |
| 440 | vec![ |
| 441 | delete("a/inner.txt"), |
| 442 | upsert("a", Regular644, b"a is a file now\n"), |
| 443 | ], |
| 444 | ), |
| 445 | p( |
| 446 | 6, |
| 447 | "upsert below an existing file", |
| 448 | vec![upsert( |
| 449 | "a-b/under.txt", |
| 450 | Regular644, |
| 451 | b"git replaces the file\n", |
| 452 | )], |
| 453 | ), |
| 454 | p( |
| 455 | 7, |
| 456 | "upsert over an existing directory", |
| 457 | vec![upsert("docs", Regular644, b"git replaces the directory\n")], |
| 458 | ), |
| 459 | ] |
| 460 | } |