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-api/tests/d1_merge_tier_t1.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-api / tests / d1_merge_tier_t1.rs` 415 lines ยท 13805 bytes Raw Blame History 1 //! ADR 0003 step D1 through the service: tier T1 merges of revisions that write the same file, 2 //! derived by the server, admitted with the merged file, and recomputed by a replica. 3 //! 4 //! Base `B0` holds `src/lib.rs` (20 lines) and `README.md`. On `B0`: `ra` changes line 2, 5 //! `rb` changes line 15, `rc` changes line 3 (touching `ra`'s region), `rd` deletes 6 //! `src/lib.rs`, `re` changes line 15 exactly as `rb` does plus line 18, `rf` changes line 18 7 //! and makes the file executable. 8 9 use `ed25519`_dalek::SigningKey; 10 use sha2::{Digest, Sha256}; 11 use std::path::{Path, PathBuf}; 12 use synapse_api::{SynapseService, TreeTarget}; 13 use synapse_auth::{ 14 Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChangeScope, LinkCaveats, 15 OperationSet, PathScope, ReferenceScope, SignedStateMove, ROOT_PARENT, 16 }; 17 use synapse_core::{ 18 BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, ChangesetId, DerivationAttestation, 19 DerivationInput, DerivationRule, DerivedRevision, FileMode, GitOid, IdempotencyKey, MergeTier, 20 MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, RevisionState, TreeDigest, 21 WalSeq, 22 }; 23 use synapse_radicle::{ 24 IdentityDocumentDigest, IdentityEdit, IdentityLog, RepositoryIdentityDocument, 25 }; 26 use synapse_store::{ 27 AdmissionAuthority, FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits, 28 }; 29 30 const NOW: u64 = 5_000; 31 const T0: DerivationRule = DerivationRule::Merge { 32 tier: MergeTier::T0Path, 33 }; 34 const T1: DerivationRule = DerivationRule::Merge { 35 tier: MergeTier::T1Region, 36 }; 37 const B0: GitOid = GitOid([0xB0; 20]); 38 39 fn repo() -> RepoId { 40 RepoId::new("aien-spark/synapse").unwrap() 41 } 42 43 fn label(s: &str) -> [u8; 32] { 44 Sha256::digest(format!("synapse d1 test: {s}").as_bytes()).into() 45 } 46 47 fn key(s: &str) -> SigningKey { 48 SigningKey::from_bytes(&label(&format!("key {s}"))) 49 } 50 51 fn pk(k: &SigningKey) -> [u8; 32] { 52 k.verifying_key().to_bytes() 53 } 54 55 fn change(s: &str) -> ChangeId { 56 let mut id = [0u8; 16]; 57 id.copy_from_slice(&label(&format!("change {s}"))[..16]); 58 ChangeId(id) 59 } 60 61 fn chain(s: &str) -> CapabilityChain { 62 let caveats = LinkCaveats { 63 operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), 64 paths: PathScope::whole_repository(), 65 references: ReferenceScope::from_kinds(&[]), 66 changes: ChangeScope::any(), 67 quotas: ChainQuotas { 68 max_ops_per_window: 1_000, 69 window_duration_ms: 60_000, 70 storage_bytes: 1 << 30, 71 footprint_paths: 1 << 20, 72 max_bytes_per_op: 1 << 20, 73 }, 74 issued_at_ms: 0, 75 expires_at_ms: u64::MAX, 76 }; 77 CapabilityChain::new(vec![CapabilityLink::issue( 78 &key("authority"), 79 ROOT_PARENT, 80 label(&format!("nonce {s}")), 81 repo(), 82 pk(&key(&format!("chain {s}"))), 83 caveats, 84 )]) 85 } 86 87 fn authority(s: &str) -> AdmissionAuthority { 88 let links = chain(s).link_digests().iter().map(|d| d.0).collect(); 89 AdmissionAuthority { 90 chain: ChainPath::new(links).unwrap(), 91 change_scope: vec![], 92 } 93 } 94 95 fn base_lib() -> String { 96 (0..20).map(|i| format!("fn line_{i}() {{}}\n")).collect() 97 } 98 99 /// `base_lib` with each `(line, text)` replaced. 100 fn edited(edits: &[(usize, &str)]) -> Vec { 101 base_lib() 102 .split_inclusive('\n') 103 .enumerate() 104 .map(|(i, l)| match edits.iter().find(|(n, _)| *n == i) { 105 Some((_, t)) => format!("{t}\n"), 106 None => l.to_string(), 107 }) 108 .collect::() 109 .into_bytes() 110 } 111 112 fn open(dir: &Path) -> SynapseService { 113 let mut svc = SynapseService::open( 114 dir, 115 repo(), 116 FsyncPolicy::EveryCommit, 117 RecoveryPolicy::StrictFailClosed, 118 StoreLimits { 119 wal_prealloc_bytes: 64 * 1024, 120 ..Default::default() 121 }, 122 ) 123 .unwrap(); 124 svc.register_base_tree( 125 B0, 126 vec![ 127 ("README.md".into(), FileMode::Regular644, b"base\n".to_vec()), 128 ( 129 "src/lib.rs".into(), 130 FileMode::Regular644, 131 base_lib().into_bytes(), 132 ), 133 ], 134 ) 135 .unwrap(); 136 svc 137 } 138 139 struct Fx { 140 dir: PathBuf, 141 svc: SynapseService, 142 server: SigningKey, 143 keys: IdentityLog, 144 b0: TreeDigest, 145 revs: Vec<(String, ChangesetId)>, 146 } 147 148 impl Fx { 149 fn new(name: &str) -> Self { 150 let dir: PathBuf = std::env::temp_dir().join(format!( 151 "synapse-d1-{name}-{}-{}", 152 std::process::id(), 153 std::time::SystemTime::now() 154 .duration_since(std::time::UNIX_EPOCH) 155 .unwrap() 156 .as_nanos() 157 )); 158 let mut svc = open(&dir); 159 let b0 = svc 160 .tree_digest(TreeTarget::BaseGitCommit(B0), None) 161 .unwrap(); 162 let server = key("server"); 163 let delegates = [key("delegate 1"), key("delegate 2")]; 164 let mut ds = vec![pk(&delegates[0]), pk(&delegates[1])]; 165 ds.sort(); 166 let genesis = RepositoryIdentityDocument { 167 repo_id: repo(), 168 revision: 0, 169 prev: IdentityDocumentDigest::ZERO, 170 threshold: 2, 171 delegates: ds, 172 executors: vec![], 173 server_key: pk(&server), 174 }; 175 let edit = IdentityEdit::sign(genesis, &[&delegates[0], &delegates[1]]); 176 let keys = IdentityLog::genesis(&edit, WalSeq(0)).unwrap(); 177 let mut fx = Self { 178 dir, 179 svc, 180 server, 181 keys, 182 b0, 183 revs: Vec::new(), 184 }; 185 fx.admit_agent("a", Some(edited(&[(2, "fn a() {}")]))); 186 fx.admit_agent("b", Some(edited(&[(15, "fn b() {}")]))); 187 fx.admit_agent("c", Some(edited(&[(3, "fn c() {}")]))); 188 fx.admit_agent("d", None); 189 fx.admit_agent("e", Some(edited(&[(15, "fn b() {}"), (18, "fn e() {}")]))); 190 fx.admit_agent("f", Some(edited(&[(18, "fn f() {}")]))); 191 fx 192 } 193 194 /// Admit and publish agent `s`'s revision of `src/lib.rs` (`None`: delete it). 195 fn admit_agent(&mut self, s: &str, body: Option>) { 196 let op = match &body { 197 Some(b) => MutationOp::Upsert { 198 mode: if s == "f" { 199 FileMode::Executable755 200 } else { 201 FileMode::Regular644 202 }, 203 blob_digest: BlobDigest::compute(b), 204 size_bytes: b.len() as u64, 205 }, 206 None => MutationOp::Delete, 207 }; 208 let content = RevisionContent { 209 change_id: change(s), 210 base_tree: self.b0, 211 parents: vec![], 212 mutations: vec![PathMutation { 213 path: "src/lib.rs".into(), 214 op, 215 }], 216 intent_summary: format!("agent revision {s}"), 217 }; 218 let env = ChangesetEnvelopeV2::sign_new( 219 &key(&format!("agent {s}")), 220 repo(), 221 content, 222 IdempotencyKey(label(&format!("idempotency {s}"))), 223 NOW, 224 ); 225 let id = env.changeset_id(); 226 let blobs: Vec<(BlobDigest, Vec)> = body 227 .into_iter() 228 .map(|b| (BlobDigest::compute(&b), b)) 229 .collect(); 230 self.svc 231 .store_mut() 232 .admit_revision(env, &blobs, authority(s), NOW) 233 .unwrap(); 234 let mv = SignedStateMove::sign_new( 235 &key(&format!("chain {s}")), 236 repo(), 237 id, 238 RevisionState::Proposed, 239 &chain(s), 240 NOW, 241 ) 242 .unwrap(); 243 self.svc 244 .store_mut() 245 .advance_revision_state(mv, NOW) 246 .unwrap(); 247 self.revs.push((s.to_string(), id)); 248 } 249 250 fn id(&self, s: &str) -> ChangesetId { 251 self.revs.iter().find(|(n, _)| n == s).unwrap().1 252 } 253 254 /// Merge inputs for `names` in the canonical merge order. 255 fn inputs(&self, names: &[&str]) -> Vec { 256 let mut ids: Vec = names.iter().map(|n| self.id(n)).collect(); 257 ids.sort(); 258 let mut inputs = vec![DerivationInput::Tree(self.b0)]; 259 inputs.extend(ids.into_iter().map(DerivationInput::Revision)); 260 inputs 261 } 262 263 fn derive( 264 &mut self, 265 rule: DerivationRule, 266 names: &[&str], 267 ) -> Result { 268 let server = self.server.clone(); 269 let inputs = self.inputs(names); 270 self.svc 271 .derive_revision(&server, rule, inputs) 272 .map_err(|e| e.code) 273 } 274 275 fn admit(&mut self, derived: DerivedRevision) -> Result { 276 let keys = self.keys.clone(); 277 match self 278 .svc 279 .admit_derived_revision(derived, authority("a"), &keys, NOW) 280 { 281 Ok(RevisionOutcome::Admitted { wal_seq, .. }) => Ok(wal_seq), 282 Ok(other) => panic!("unexpected outcome {other:?}"), 283 Err(e) => Err(e.code), 284 } 285 } 286 287 fn verify(&mut self) -> Result { 288 let keys = self.keys.clone(); 289 self.svc.verify_revision_log(&keys).map_err(|e| e.code) 290 } 291 } 292 293 fn lib_blob(content: &RevisionContent) -> (BlobDigest, u64) { 294 match &content 295 .mutations 296 .iter() 297 .find(|m| m.path == "src/lib.rs") 298 .unwrap() 299 .op 300 { 301 MutationOp::Upsert { 302 blob_digest, 303 size_bytes, 304 .. 305 } => (*blob_digest, *size_bytes), 306 MutationOp::Delete => panic!("merged file deleted"), 307 } 308 } 309 310 /// Acceptance with the service: two revisions that change different regions of one file are 311 /// refused at T0 (path level) and merge at T1. The attestation records the tier and the merge 312 /// order, the merged file is written with the derived revision, and a replica recomputes the 313 /// same output (also after a reopen). 314 #[test] 315 fn d1_api_t1_merges_disjoint_regions_of_one_file_end_to_end() { 316 let mut fx = Fx::new("e2e"); 317 assert_eq!( 318 fx.derive(T0, &["a", "b"]).unwrap_err(), 319 RefusalCode::DerivationRecomputeMismatch 320 ); 321 let merged = fx.derive(T1, &["a", "b"]).unwrap(); 322 assert_eq!(merged.attestation.rule, T1); 323 assert_eq!(merged.attestation.inputs, fx.inputs(&["a", "b"])); 324 assert_eq!( 325 merged.content.intent_summary, 326 "merge tier T1 of 2 revisions" 327 ); 328 let want = edited(&[(2, "fn a() {}"), (15, "fn b() {}")]); 329 let (blob, size) = lib_blob(&merged.content); 330 assert_eq!(blob, BlobDigest::compute(&want)); 331 assert_eq!(size, want.len() as u64); 332 // Nothing is stored until admission. 333 assert!(fx.svc.read_blob_bytes(blob, None).is_err()); 334 fx.admit(merged.clone()).unwrap(); 335 assert_eq!(fx.svc.read_blob_bytes(blob, None).unwrap(), want); 336 let id = merged.content.changeset_id(); 337 let stored = fx.svc.store().get_revision(&repo(), id).unwrap(); 338 assert_eq!(stored.content, merged.content); 339 // 6 admissions, 6 state moves, 1 derived revision. 340 assert_eq!(fx.verify(), Ok(13)); 341 342 // `rb` and `re` make the same change to line 15, but `re` also changes line 18, so the 343 // files differ and their line 15 regions overlap: refused (identical edits inside 344 // different files are not merged). `ra` with `re` merges. 345 assert_eq!( 346 fx.derive(T1, &["b", "e"]).unwrap_err(), 347 RefusalCode::DerivationRecomputeMismatch 348 ); 349 let second = fx.derive(T1, &["a", "e"]).unwrap(); 350 fx.admit(second).unwrap(); 351 352 let dir = fx.dir.clone(); 353 drop(fx.svc); 354 fx.svc = open(&dir); 355 assert_eq!(fx.svc.read_blob_bytes(blob, None).unwrap(), want); 356 assert!(fx.verify().is_ok()); 357 fx.svc.checkpoint_compact_and_invalidate_index(NOW).unwrap(); 358 assert_eq!(fx.svc.read_blob_bytes(blob, None).unwrap(), want); 359 assert!(fx.verify().is_ok()); 360 let _ = std::fs::remove_dir_all(&dir); 361 } 362 363 /// Regions that touch, a delete against a change, and a mode change are conflicts at T1: 364 /// refused with 365 /// `DerivationRecomputeMismatch`, nothing derived. 366 #[test] 367 fn d1_api_t1_refuses_touching_regions_and_modify_delete() { 368 let mut fx = Fx::new("conflicts"); 369 for pair in [["a", "c"], ["a", "d"], ["b", "e"], ["a", "f"]] { 370 assert_eq!( 371 fx.derive(T1, &pair).unwrap_err(), 372 RefusalCode::DerivationRecomputeMismatch, 373 "{pair:?}" 374 ); 375 } 376 let _ = std::fs::remove_dir_all(&fx.dir); 377 } 378 379 /// A server that signs a T1 merge with different merged bytes than the rule produces is 380 /// refused at admission (the store recomputes) and at replay. 381 #[test] 382 fn d1_api_forged_t1_merge_output_is_refused() { 383 let mut fx = Fx::new("forged"); 384 let honest = fx.derive(T1, &["a", "b"]).unwrap(); 385 let mut content = honest.content.clone(); 386 let lie = edited(&[(2, "fn a() {}"), (15, "fn b() {}"), (19, "fn extra() {}")]); 387 for m in &mut content.mutations { 388 if m.path == "src/lib.rs" { 389 m.op = MutationOp::Upsert { 390 mode: FileMode::Regular644, 391 blob_digest: BlobDigest::compute(&lie), 392 size_bytes: lie.len() as u64, 393 }; 394 } 395 } 396 let attestation = DerivationAttestation::sign( 397 &fx.server, 398 repo(), 399 T1, 400 honest.attestation.inputs.clone(), 401 content.changeset_id(), 402 honest.attestation.output_tree, 403 ); 404 let forged = DerivedRevision { 405 content, 406 attestation, 407 }; 408 let before = fx.svc.store().committed_seq(); 409 assert_eq!( 410 fx.admit(forged).unwrap_err(), 411 RefusalCode::DerivationRecomputeMismatch 412 ); 413 assert_eq!(fx.svc.store().committed_seq(), before); 414 let _ = std::fs::remove_dir_all(&fx.dir); 415 }