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/advisory_snapshot_parity.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 / advisory_snapshot_parity.rs` 421 lines ยท 14564 bytes Raw Blame History 1 //! Issue #94 parity: advisory and Crumb context answers over a recorded corpus are 2 //! byte-identical (their `Debug` rendering, errors included) to the answers recorded on 3 //! `origin/main` before snapshot views were cached. 4 //! 5 //! The corpus: a base tree with nested `.crumb` files; every file, directory and two absent 6 //! paths, alone and all together; against the base, a changeset base, an explicit `latest`, 7 //! an older `snapshot_seq`, a promoted canonical head, with and without claims in the 8 //! coordination plane. It runs, then new proposals land (a new snapshot, a `.crumb` 9 //! rewrite, a promotion), and it runs again twice (the second time fully warm). The SHA-256 10 //! of the whole transcript, with the host part of each claim session masked, was 11 //! recorded on `origin/main` (`3d78efe`). 12 //! 13 //! Keys, nonces and grant ids are derived from labels and counters, never literals. 14 15 use `ed25519`_dalek::SigningKey; 16 use sha2::{Digest, Sha256}; 17 use std::fmt::Debug; 18 use std::fs; 19 use std::path::PathBuf; 20 use synapse_api::{ 21 ChangesetAdvisoryPayload, CrumbContextQueryPayload, SubmitChangesetPayload, SynapseService, 22 TreeTarget, 23 }; 24 use synapse_auth::{AgentCapabilityGrant, AuthenticatedRequest, Capability}; 25 use synapse_coord::{ClaimOutcome, CoordStore, Holder, NoOracle, Workspace}; 26 use synapse_core::{ 27 encode_did_key_`ed25519`, BlobDigest, ChangesetEnvelope, ChangesetId, FileMode, GitOid, 28 IdempotencyKey, MutationOp, PathMutation, RadicleCanonicalHead, RepoId, SynapseResult, WalSeq, 29 SYNAPSE_ENVELOPE_VERSION, 30 }; 31 use synapse_store::{FsyncPolicy, IngestOutcome, RecoveryPolicy, StoreLimits}; 32 33 /// SHA-256 of the host-neutral transcript (see [`host_neutral`]), recorded on `origin/main` 34 /// `3d78efe` (before #94). 35 const RECORDED_TRANSCRIPT_SHA256: &str = 36 "`36bfcc7b7ab1dc637555b17a8587662998c638fa0d4cbcff29ac54af89bc7e96`"; 37 38 /// The transcript with the host part of every claim session masked: `session: "carol@host"` 39 /// becomes `session: "carol@"`. A claim's session defaults to `agent@hostname`, so the 40 /// host differs between machines; the agent part is kept, so a claim whose session names the 41 /// wrong agent still changes the hash. Everything else is a function of the corpus alone. 42 fn host_neutral(transcript: &[u8]) -> Vec { 43 const FIELD: &[u8] = b"session: \""; 44 let mut out = Vec::with_capacity(transcript.len()); 45 let mut rest = transcript; 46 while let Some(at) = rest.windows(FIELD.len()).position(|w| w == FIELD) { 47 out.extend_from_slice(&rest[..at + FIELD.len()]); 48 rest = &rest[at + FIELD.len()..]; 49 let end = rest.iter().position(|&b| b == b'"').unwrap_or(rest.len()); 50 let value = &rest[..end]; 51 match value.iter().rposition(|&b| b == b'@') { 52 Some(host_at) => { 53 out.extend_from_slice(&value[..=host_at]); 54 out.extend_from_slice(b""); 55 } 56 None => out.extend_from_slice(value), 57 } 58 rest = &rest[end..]; 59 } 60 out.extend_from_slice(rest); 61 out 62 } 63 64 const T0: i64 = 1_800_000_000; 65 66 fn derived(label: &str, n: u64) -> [u8; 32] { 67 let mut h = Sha256::new(); 68 h.update(b"SYNAPSE_API_ADVISORY_PARITY_TEST_V1\0"); 69 h.update(label.as_bytes()); 70 h.update(n.to_le_bytes()); 71 h.finalize().into() 72 } 73 74 fn key(label: &str) -> SigningKey { 75 SigningKey::from_bytes(&derived(label, 0)) 76 } 77 78 fn did(k: &SigningKey) -> String { 79 encode_did_key_`ed25519`(&k.verifying_key().to_bytes()) 80 } 81 82 fn crumb(name: &str, rule: &str) -> Vec { 83 format!( 84 r#"{{"schema_version":"1.0.0","name":"{name}","purpose":"{name} purpose.","invariants":["{rule}"]}}"# 85 ) 86 .into_bytes() 87 } 88 89 struct Corpus { 90 svc: SynapseService, 91 authority: SigningKey, 92 repo: RepoId, 93 base_oid: GitOid, 94 counter: u64, 95 dir: PathBuf, 96 transcript: Vec, 97 } 98 99 impl Drop for Corpus { 100 fn drop(&mut self) { 101 let _ = fs::remove_dir_all(&self.dir); 102 } 103 } 104 105 impl Corpus { 106 fn new() -> Self { 107 let dir = std::env::temp_dir().join(format!( 108 "synapse-api-advisory-parity-{}-{}", 109 std::process::id(), 110 std::time::SystemTime::now() 111 .duration_since(std::time::UNIX_EPOCH) 112 .unwrap() 113 .as_nanos() 114 )); 115 let repo = RepoId::new("aien-spark/synapse").unwrap(); 116 let mut svc = SynapseService::open( 117 dir.join("svc"), 118 repo.clone(), 119 FsyncPolicy::EveryCommit, 120 RecoveryPolicy::StrictFailClosed, 121 StoreLimits::default(), 122 ) 123 .unwrap(); 124 let authority = key("authority"); 125 svc.register_authority(did(&authority)); 126 let base_oid = GitOid::compute_blob(b"advisory parity base"); 127 let files: Vec<(String, FileMode, Vec)> = [ 128 (".crumb", crumb("root", "root rule")), 129 ("README.md", b"# readme\n".to_vec()), 130 ("src/.crumb", crumb("src", "src rule")), 131 ("src/a.rs", b"fn a() {}\n".to_vec()), 132 ("src/b.rs", b"fn b() {}\n".to_vec()), 133 ("src/deep/z.rs", b"fn z() {}\n".to_vec()), 134 ("src/deep/x/.crumb", crumb("x", "x rule")), 135 ("src/deep/x/y.rs", b"fn y() {}\n".to_vec()), 136 ("docs/x.md", b"# x\n".to_vec()), 137 ("docs/guide/intro.md", b"# intro\n".to_vec()), 138 ] 139 .into_iter() 140 .map(|(p, b)| (p.to_string(), FileMode::Regular644, b)) 141 .collect(); 142 svc.register_base_tree(base_oid, files).unwrap(); 143 Self { 144 svc, 145 authority, 146 repo, 147 base_oid, 148 counter: 0, 149 dir, 150 transcript: Vec::new(), 151 } 152 } 153 154 fn next(&mut self) -> u64 { 155 self.counter += 1; 156 self.counter 157 } 158 159 fn grant(&mut self, agent: &SigningKey, caps: Vec) -> AgentCapabilityGrant { 160 let n = self.next(); 161 AgentCapabilityGrant::issue( 162 &self.authority, 163 derived("grant", n), 164 self.repo.clone(), 165 did(agent), 166 caps, 167 1024 * 1024, 168 1_000_000, 169 60_000, 170 10, 171 u64::MAX / 2, 172 ) 173 } 174 175 fn propose( 176 &mut self, 177 agent: &SigningKey, 178 label: &str, 179 path: &str, 180 bytes: &[u8], 181 ) -> ChangesetId { 182 let digest = BlobDigest::compute(bytes); 183 let mut env = ChangesetEnvelope { 184 version: SYNAPSE_ENVELOPE_VERSION, 185 repo_id: self.repo.clone(), 186 base_git_oid: self.base_oid, 187 parent_changesets: vec![], 188 author_did: String::new(), 189 idempotency_key: IdempotencyKey::from_label(label), 190 created_at_ms: 100, 191 intent_summary: label.to_string(), 192 mutations: vec![PathMutation { 193 path: path.to_string(), 194 op: MutationOp::Upsert { 195 mode: FileMode::Regular644, 196 blob_digest: digest, 197 size_bytes: bytes.len() as u64, 198 }, 199 }], 200 evidence_receipts: vec![], 201 signature: vec![], 202 }; 203 env.sign(agent); 204 let grant = self.grant(agent, vec![Capability::Propose]); 205 let n = self.next(); 206 let now = 1000 + n; 207 let req = AuthenticatedRequest::sign_new( 208 agent, 209 grant, 210 self.repo.clone(), 211 Capability::Propose, 212 derived("nonce", n), 213 now, 214 0, 215 SubmitChangesetPayload { 216 envelope: env, 217 blobs: vec![(digest, bytes.to_vec())], 218 }, 219 ) 220 .unwrap(); 221 match self.svc.submit(&req, now).unwrap() { 222 IngestOutcome::Committed { changeset_id, .. } => changeset_id, 223 other => panic!("unexpected {other:?}"), 224 } 225 } 226 227 fn promote(&mut self, cs: ChangesetId) { 228 self.svc 229 .store_mut() 230 .record_canonical_promotion(RadicleCanonicalHead { 231 repo_id: self.repo.clone(), 232 default_branch: "main".to_string(), 233 canonical_git_oid: GitOid::compute_blob(b"canonical"), 234 promoted_changeset_id: Some(cs), 235 rad_id_commit_oid: GitOid::compute_blob(b"rad id"), 236 threshold: 1, 237 verified_delegates: vec![], 238 verified_at_ms: 5, 239 }) 240 .unwrap(); 241 } 242 243 fn record(&mut self, what: &str, r: SynapseResult) { 244 let line = match r { 245 Ok(v) => format!("{what} => {v:?}\n"), 246 Err(e) => format!("{what} => ERR {:?} {}\n", e.code, e.message), 247 }; 248 self.transcript.extend_from_slice(line.as_bytes()); 249 } 250 251 fn advise( 252 &mut self, 253 base: TreeTarget, 254 latest: Option, 255 paths: &[&str], 256 snapshot_seq: Option, 257 coord: Option<&CoordStore>, 258 ) { 259 let reader = key("reader"); 260 let grant = self.grant(&reader, vec![Capability::Read]); 261 let n = self.next(); 262 let now = 1000 + n; 263 let r = AuthenticatedRequest::sign_new( 264 &reader, 265 grant, 266 self.repo.clone(), 267 Capability::Read, 268 derived("nonce", n), 269 now, 270 0, 271 ChangesetAdvisoryPayload { 272 base, 273 latest, 274 paths: paths.iter().map(|p| p.to_string()).collect(), 275 agent: "alice".to_string(), 276 snapshot_seq, 277 }, 278 ) 279 .and_then(|req| self.svc.changeset_advisory(&req, coord, now)); 280 let what = format!( 281 "advise base={base:?} latest={latest:?} seq={snapshot_seq:?} coord={} paths={paths:?}", 282 coord.is_some() 283 ); 284 self.record(&what, r); 285 } 286 287 fn crumb_context(&mut self, target: TreeTarget, path: &str, snapshot_seq: Option) { 288 let reader = key("reader"); 289 let grant = self.grant(&reader, vec![Capability::Read]); 290 let n = self.next(); 291 let now = 1000 + n; 292 let r = AuthenticatedRequest::sign_new( 293 &reader, 294 grant, 295 self.repo.clone(), 296 Capability::Read, 297 derived("nonce", n), 298 now, 299 0, 300 CrumbContextQueryPayload { 301 target, 302 path: path.to_string(), 303 snapshot_seq, 304 }, 305 ) 306 .and_then(|req| self.svc.crumb_context(&req, now)); 307 let what = format!("crumb target={target:?} seq={snapshot_seq:?} path={path}"); 308 self.record(&what, r); 309 } 310 311 /// One pass of the corpus over `targets`. 312 fn pass(&mut self, targets: &[TreeTarget], older: Option, coord: &CoordStore) { 313 const PATHS: &[&str] = &[ 314 ".crumb", 315 "README.md", 316 "src", 317 "src/.crumb", 318 "src/a.rs", 319 "src/b.rs", 320 "src/deep", 321 "src/deep/z.rs", 322 "src/deep/x", 323 "src/deep/x/.crumb", 324 "src/deep/x/y.rs", 325 "docs", 326 "docs/x.md", 327 "docs/guide", 328 "docs/guide/intro.md", 329 "src/new.rs", 330 "new/dir/f.rs", 331 ]; 332 for &base in targets { 333 for &p in PATHS { 334 self.advise(base, None, &[p], None, None); 335 self.advise(base, None, &[p], None, Some(coord)); 336 self.crumb_context(base, p, None); 337 } 338 self.crumb_context(base, ".", None); 339 self.advise(base, None, PATHS, None, Some(coord)); 340 for &latest in targets { 341 self.advise( 342 base, 343 Some(latest), 344 &["src/a.rs", "src/deep/x/y.rs"], 345 None, 346 None, 347 ); 348 } 349 self.advise(base, None, PATHS, older, Some(coord)); 350 self.crumb_context(base, "src/deep/x/y.rs", older); 351 } 352 } 353 } 354 355 fn claim(store: &CoordStore, agent: &str, target: &str) { 356 let ws = Workspace::with_oracle( 357 format!("/synapse/ws/{agent}"), 358 Holder::synapse("lane", "`00112233445566778899`", "`aabbccddeeff00112233`"), 359 Box::new(NoOracle), 360 ); 361 let out = store 362 .claim(&ws, agent, ".", target, "edit", Some(600)) 363 .unwrap(); 364 assert!(matches!(out, ClaimOutcome::Claimed { .. }), "{out:?}"); 365 } 366 367 #[test] 368 fn advisory_and_crumb_answers_match_the_transcript_recorded_on_main() { 369 assert!( 370 std::env::var_os("CRUMB_SESSION").is_none_or(|s| s.is_empty()), 371 "unset CRUMB_SESSION: it replaces the agent@host claim sessions the transcript records" 372 ); 373 let mut c = Corpus::new(); 374 let coord = CoordStore::open(c.dir.join("coord")).with_clock(|| T0); 375 claim(&coord, "carol", "src/deep"); 376 claim(&coord, "alice", "src/b.rs"); 377 claim(&coord, "dave", "docs/guide/intro.md"); 378 379 let bob = key("bob"); 380 let base = TreeTarget::BaseGitCommit(c.base_oid); 381 let cs1 = c.propose(&bob, "bob-a", "src/a.rs", b"fn a2() {}\n"); 382 let cs2 = c.propose(&bob, "bob-new", "src/deep/new.rs", b"fn n() {}\n"); 383 let older = Some(c.svc.store().committed_seq()); 384 let cs3 = c.propose( 385 &bob, 386 "bob-crumb", 387 "src/deep/x/.crumb", 388 &crumb("x", "x rule 2"), 389 ); 390 let targets = [ 391 base, 392 TreeTarget::Changeset(cs1), 393 TreeTarget::Changeset(cs2), 394 TreeTarget::Changeset(cs3), 395 ]; 396 c.pass(&targets, older, &coord); 397 398 // New snapshots: a root `.crumb` rewrite and a promotion, then two more passes. 399 let cs4 = c.propose(&bob, "bob-root", ".crumb", &crumb("root", "root rule 2")); 400 c.promote(cs1); 401 let older = Some(c.svc.store().committed_seq()); 402 let cs5 = c.propose(&bob, "bob-docs", "docs/guide/intro.md", b"# intro 2\n"); 403 let targets = [ 404 base, 405 TreeTarget::Changeset(cs1), 406 TreeTarget::Changeset(cs4), 407 TreeTarget::Changeset(cs5), 408 ]; 409 c.pass(&targets, older, &coord); 410 c.promote(cs4); 411 c.pass(&targets, older, &coord); 412 c.pass(&targets, older, &coord); 413 414 let digest = hex::encode(Sha256::digest(host_neutral(&c.transcript))); 415 println!( 416 "advisory parity transcript: {} bytes, {} answers, sha256 {digest}", 417 c.transcript.len(), 418 c.transcript.iter().filter(|&&b| b == b'\n').count() 419 ); 420 assert_eq!(digest, RECORDED_TRANSCRIPT_SHA256); 421 }