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-coord/tests/identity.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-coord / tests / identity.rs` 299 lines ยท 10955 bytes Raw Blame History 1 //! Store identity marker (issue #15): creation, races, expecting-open refusals, crash 2 //! safety, and the split-coordination-root negative control. 3 4 use std::fs; 5 use std::path::{Path, PathBuf}; 6 use std::process::Command; 7 use std::sync::atomic::{AtomicU32, Ordering}; 8 use synapse_coord::{ 9 ClaimOutcome, CoordError, CoordStore, Holder, NoOracle, StoreId, Workspace, STORE_ID_FILE, 10 }; 11 12 static N: AtomicU32 = AtomicU32::new(0); 13 14 struct Scratch(PathBuf); 15 impl Scratch { 16 fn new(tag: &str) -> Scratch { 17 let p = std::env::temp_dir().join(format!( 18 "synapse-coord-id-{tag}-{}-{}", 19 std::process::id(), 20 N.fetch_add(1, Ordering::SeqCst) 21 )); 22 let _ = fs::remove_dir_all(&p); 23 fs::create_dir_all(&p).unwrap(); 24 Scratch(p) 25 } 26 } 27 impl Drop for Scratch { 28 fn drop(&mut self) { 29 let _ = fs::remove_dir_all(&self.0); 30 } 31 } 32 33 fn ws(agent: &str) -> Workspace { 34 let mut h = Holder::synapse("lane/main", &"ab".repeat(32), &"cd".repeat(32)); 35 h.session = Some(format!("{agent}-sess")); 36 Workspace::with_oracle(format!("/synapse/ws/{agent}"), h, Box::new(NoOracle)) 37 } 38 39 fn claim(cs: &CoordStore, agent: &str, target: &str) -> Result { 40 cs.claim(&ws(agent), agent, ".", target, "edit", None) 41 } 42 43 fn cli(store: &Path, args: &[&str]) -> Command { 44 let mut c = Command::new(env!("CARGO_BIN_EXE_synapse-coord")); 45 c.arg("--store").arg(store).args(args); 46 c 47 } 48 49 fn marker(root: &Path) -> Vec { 50 fs::read(root.join(STORE_ID_FILE)).unwrap() 51 } 52 53 #[test] 54 fn first_mutation_creates_marker_and_sniff_shows_it() { 55 let s = Scratch::new("first"); 56 let root = s.0.join("crumb/v1"); 57 let cs = CoordStore::open(&root); 58 assert_eq!(cs.store_id().unwrap(), None, "opening creates nothing"); 59 let sn = cs.sniff(&ws("a"), "a", ".").unwrap(); 60 assert_eq!(sn.store_id, None, "a read never creates the marker"); 61 assert!(sn.render(&ws("a"), "a").contains("store id: (none yet)")); 62 assert!(!root.exists(), "sniff wrote nothing"); 63 64 assert!(matches!( 65 claim(&cs, "a", "src/x.c").unwrap(), 66 ClaimOutcome::Claimed { .. } 67 )); 68 let id = cs 69 .store_id() 70 .unwrap() 71 .expect("first mutation created the marker"); 72 assert_eq!(marker(&root), id.encode()); 73 assert_eq!(cs.ensure_store_id().unwrap(), id, "idempotent"); 74 let sn = cs.sniff(&ws("a"), "a", ".").unwrap(); 75 assert_eq!(sn.store_id, Some(id)); 76 assert!(sn 77 .render(&ws("a"), "a") 78 .contains(&format!(" store id: {id}\n"))); 79 } 80 81 #[test] 82 fn concurrent_first_opens_agree_on_one_id_threads_and_processes() { 83 for round in 0..5 { 84 let s = Scratch::new(&format!("race{round}")); 85 let root = s.0.join("crumb/v1"); 86 let kids: Vec<_> = (0..8) 87 .map(|_| { 88 cli(&root, &["id"]) 89 .stdout(std::process::Stdio::piped()) 90 .spawn() 91 .unwrap() 92 }) 93 .collect(); 94 let thread_ids: Vec = std::thread::scope(|sc| { 95 let hs: Vec<_> = (0..16) 96 .map(|i| { 97 let root = &root; 98 sc.spawn(move || { 99 let cs = CoordStore::open(root); 100 if i % 2 == 0 { 101 cs.ensure_store_id().unwrap() 102 } else { 103 claim(&cs, &format!("t{i}"), &format!("f{i}.c")).unwrap(); 104 cs.store_id().unwrap().unwrap() 105 } 106 }) 107 }) 108 .collect(); 109 hs.into_iter().map(|h| h.join().unwrap()).collect() 110 }); 111 let proc_ids: Vec = kids 112 .into_iter() 113 .map(|k| { 114 let o = k.wait_with_output().unwrap(); 115 assert!(o.status.success()); 116 StoreId::parse_hex(String::from_utf8(o.stdout).unwrap().trim()).unwrap() 117 }) 118 .collect(); 119 let on_disk = StoreId::decode(&marker(&root)).unwrap(); 120 for id in thread_ids.iter().chain(&proc_ids) { 121 assert_eq!(*id, on_disk, "round {round}: every opener sees one id"); 122 } 123 let stray: Vec<_> = fs::read_dir(&root) 124 .unwrap() 125 .filter_map(|e| e.ok()) 126 .map(|e| e.file_name().into_string().unwrap()) 127 .filter(|n| n.starts_with("STORE_ID.tmp")) 128 .collect(); 129 assert!(stray.is_empty(), "temporary markers cleaned up: {stray:?}"); 130 } 131 } 132 133 #[test] 134 fn expecting_open_refuses_missing_marker_and_creates_nothing() { 135 let s = Scratch::new("missing"); 136 let root = s.0.join("crumb/v1"); 137 // A store crumb.c has used but no Synapse opener has marked: layout without STORE_ID. 138 for d in ["dirs", "agents", "continuations", "ledger"] { 139 fs::create_dir_all(root.join(d)).unwrap(); 140 } 141 let id = StoreId::random().unwrap(); 142 match CoordStore::open_expecting(&root, id) { 143 Err(CoordError::StoreIdMissing { root: r }) => assert_eq!(r, root), 144 other => panic!("expected StoreIdMissing, got {other:?}"), 145 } 146 let empty = s.0.join("never/used"); 147 assert!(matches!( 148 CoordStore::open_expecting(&empty, id), 149 Err(CoordError::StoreIdMissing { .. }) 150 )); 151 assert!(!empty.exists(), "refusal creates nothing"); 152 assert!(!root.join(STORE_ID_FILE).exists()); 153 } 154 155 #[test] 156 fn expecting_open_refuses_mismatch_and_writes_nothing() { 157 let s = Scratch::new("mismatch"); 158 let a = s.0.join("a/crumb/v1"); 159 let b = s.0.join("b/crumb/v1"); 160 let id_a = CoordStore::open(&a).ensure_store_id().unwrap(); 161 let id_b = CoordStore::open(&b).ensure_store_id().unwrap(); 162 assert_ne!(id_a, id_b, "two stores, two ids"); 163 match CoordStore::open_expecting(&b, id_a) { 164 Err(CoordError::StoreIdMismatch { 165 expected, found, .. 166 }) => assert_eq!((expected, found), (id_a, id_b)), 167 other => panic!("expected StoreIdMismatch, got {other:?}"), 168 } 169 let ok = CoordStore::open_expecting(&a, id_a).unwrap(); 170 assert_eq!(ok.expected_store_id(), Some(id_a)); 171 assert!(matches!( 172 claim(&ok, "a", "x.c").unwrap(), 173 ClaimOutcome::Claimed { .. } 174 )); 175 assert!(!b.join("dirs/_root.json").exists()); 176 } 177 178 #[test] 179 fn expectation_is_rechecked_inside_every_transaction() { 180 let s = Scratch::new("recheck"); 181 let root = s.0.join("crumb/v1"); 182 let id = CoordStore::open(&root).ensure_store_id().unwrap(); 183 let cs = CoordStore::open_expecting(&root, id).unwrap(); 184 assert!(matches!( 185 claim(&cs, "a", "x.c").unwrap(), 186 ClaimOutcome::Claimed { .. } 187 )); 188 // The root is repointed / replaced after the handle was opened. 189 let other = StoreId::random().unwrap(); 190 fs::write(root.join(STORE_ID_FILE), other.encode()).unwrap(); 191 assert!(matches!( 192 claim(&cs, "a", "y.c"), 193 Err(CoordError::StoreIdMismatch { .. }) 194 )); 195 assert!(matches!( 196 cs.sniff(&ws("a"), "a", "."), 197 Err(CoordError::StoreIdMismatch { .. }) 198 )); 199 fs::remove_file(root.join(STORE_ID_FILE)).unwrap(); 200 assert!(matches!( 201 cs.ensure_store_id(), 202 Err(CoordError::StoreIdMissing { .. }) 203 )); 204 assert!( 205 !root.join(STORE_ID_FILE).exists(), 206 "an expecting handle never creates a marker" 207 ); 208 } 209 210 #[test] 211 fn unreadable_marker_is_refused_not_rewritten() { 212 let s = Scratch::new("unreadable"); 213 let root = s.0.join("crumb/v1"); 214 fs::create_dir_all(&root).unwrap(); 215 let junk = b"crumb-coord-store-id/9 0123\n"; 216 fs::write(root.join(STORE_ID_FILE), junk).unwrap(); 217 let cs = CoordStore::open(&root); 218 assert!(matches!( 219 claim(&cs, "a", "x.c"), 220 Err(CoordError::StoreIdUnreadable { .. }) 221 )); 222 assert_eq!(marker(&root), junk); 223 } 224 225 #[test] 226 fn crash_before_marker_link_leaves_no_marker_then_recovers() { 227 let s = Scratch::new("crash"); 228 let root = s.0.join("crumb/v1"); 229 let st = cli(&root, &["id"]) 230 .env("SYNAPSE_COORD_FAULT", "storeid-before-link") 231 .stderr(std::process::Stdio::null()) 232 .status() 233 .unwrap(); 234 assert!(!st.success(), "process aborted at the fault point"); 235 assert!(!root.join(STORE_ID_FILE).exists(), "no torn marker"); 236 assert!(fs::read_dir(&root).unwrap().any(|e| e 237 .unwrap() 238 .file_name() 239 .to_string_lossy() 240 .starts_with("STORE_ID.tmp"))); 241 let o = cli(&root, &["id"]).output().unwrap(); 242 assert!(o.status.success()); 243 let id = StoreId::parse_hex(String::from_utf8(o.stdout).unwrap().trim()).unwrap(); 244 assert_eq!(StoreId::decode(&marker(&root)).unwrap(), id); 245 } 246 247 #[test] 248 fn marker_survives_pruning_expiry_and_close() { 249 let s = Scratch::new("survive"); 250 let root = s.0.join("crumb/v1"); 251 let t0 = 1_800_000_000; 252 let cs = CoordStore::open(&root).with_clock(move || t0); 253 claim(&cs, "a", "x.c").unwrap(); 254 let before = marker(&root); 255 cs.close(&ws("a"), "a", ".", "x.c", "modify", Some("done")) 256 .unwrap(); 257 claim(&cs, "b", "y.c").unwrap(); 258 // Two days later: every lock, agent and whisper is pruned on the next mutation. 259 let later = CoordStore::open(&root).with_clock(move || t0 + 2 * 86_400); 260 claim(&later, "c", "z.c").unwrap(); 261 assert_eq!(marker(&root), before); 262 } 263 264 /// Negative control for the split-brain finding: two tools configured with different 265 /// roots both grant a claim on one file. Without an expectation nothing notices; the 266 /// expecting open refuses the wrong root. 267 #[test] 268 fn split_roots_are_silent_without_expectation_and_refused_with_it() { 269 let s = Scratch::new("split"); 270 let right = s.0.join("repo/.git/crumb/v1"); 271 let wrong = s.0.join("elsewhere/crumb/v1"); 272 let registered = CoordStore::open(&right).ensure_store_id().unwrap(); 273 274 let git_side = CoordStore::open(&right); 275 let synapse_misconfigured = CoordStore::open(&wrong); 276 let a = claim(&git_side, "git-agent", "src/runtime.c").unwrap(); 277 let b = claim(&synapse_misconfigured, "syn-agent", "src/runtime.c").unwrap(); 278 assert!( 279 matches!(a, ClaimOutcome::Claimed { .. }) && matches!(b, ClaimOutcome::Claimed { .. }), 280 "the old failure: both agents own src/runtime.c" 281 ); 282 283 // Same misconfiguration, opened as Synapse now does: refused. 284 assert!(matches!( 285 CoordStore::open_expecting(&wrong, registered), 286 Err(CoordError::StoreIdMismatch { .. }) 287 )); 288 let fresh_wrong = s.0.join("fresh/crumb/v1"); 289 assert!(matches!( 290 CoordStore::open_expecting(&fresh_wrong, registered), 291 Err(CoordError::StoreIdMissing { .. }) 292 )); 293 // Correctly configured: the claim is blocked as it should be. 294 let good = CoordStore::open_expecting(&right, registered).unwrap(); 295 assert!(matches!( 296 claim(&good, "syn-agent", "src/runtime.c").unwrap(), 297 ClaimOutcome::Blocked { .. } 298 )); 299 }