synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / conformance.rs
| 1 | //! Neutral conformance suites with recorded pass/fail per case. |
| 2 | //! |
| 3 | //! * `wal`: crash and torn-write recovery of `SynapseStore` (fault injection hooks). |
| 4 | //! * `git`: deterministic Git materialization, `git fsck`, fetch/checkout byte parity, |
| 5 | //! and human-branch fast-forward enforcement (`synapse-git`). |
| 6 | //! * `radicle`: delegate-threshold canonical promotion and refusals (`synapse-radicle`), |
| 7 | //! plus an optional read-only check of a live Radicle storage repository. |
| 8 | //! |
| 9 | //! Each case compares observed behaviour with its documented expectation and records |
| 10 | //! the outcome. A harness error inside a case marks that case failed; it never aborts |
| 11 | //! the suite, and no outcome is hard-coded. |
| 12 | |
| 13 | use crate::fixture::configure_bench_clone; |
| 14 | use crate::gitcmd::{git_line, git_ok, run_git}; |
| 15 | use crate::path_str; |
| 16 | use crate::synapse_arm::{self, BenchIdentities}; |
| 17 | use crate::workload::{EditOp, FileEdit, Proposal}; |
| 18 | use ed25519_dalek::SigningKey; |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | use std::collections::BTreeMap; |
| 21 | use std::path::{Path, PathBuf}; |
| 22 | use std::sync::Arc; |
| 23 | use synapse_api::{SynapseService, TreeTarget}; |
| 24 | use synapse_auth::{AgentCapabilityGrant, AuthenticatedRequest, Capability}; |
| 25 | use synapse_core::{ |
| 26 | encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, ChangesetId, FileMode, GitOid, |
| 27 | IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, WalSeq, |
| 28 | SYNAPSE_ENVELOPE_VERSION, |
| 29 | }; |
| 30 | use synapse_git::{ |
| 31 | advance_human_branch_fast_forward, materialize_changeset_to_git, GitProjectionIndex, |
| 32 | HumanBranchAdvanceRequest, |
| 33 | }; |
| 34 | use synapse_radicle::{ |
| 35 | load_radicle_state_from_bare_repo, CanonicalPromotionEngine, DelegateSigrefs, |
| 36 | PromotionCandidate, RadicleIdentityDoc, RadiclePayloadMap, RadicleProjectPayload, |
| 37 | ReconciliationState, |
| 38 | }; |
| 39 | use synapse_store::{ |
| 40 | FaultInjection, FsyncPolicy, IngestOutcome, RecoveryPolicy, StoreLimits, SynapseStore, |
| 41 | }; |
| 42 | |
| 43 | /// Outcome of one case. |
| 44 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 45 | pub enum CaseOutcome { |
| 46 | Pass, |
| 47 | Fail, |
| 48 | Skipped, |
| 49 | } |
| 50 | |
| 51 | /// One recorded conformance case. |
| 52 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 53 | pub struct CaseResult { |
| 54 | pub suite: String, |
| 55 | pub case: String, |
| 56 | pub expected: String, |
| 57 | pub observed: String, |
| 58 | pub outcome: CaseOutcome, |
| 59 | } |
| 60 | |
| 61 | /// All cases of one suite. |
| 62 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 63 | pub struct SuiteResult { |
| 64 | pub suite: String, |
| 65 | pub cases: Vec<CaseResult>, |
| 66 | pub passed: usize, |
| 67 | pub failed: usize, |
| 68 | pub skipped: usize, |
| 69 | } |
| 70 | |
| 71 | impl SuiteResult { |
| 72 | fn from_cases(suite: &str, cases: Vec<CaseResult>) -> Self { |
| 73 | let count = |o: CaseOutcome| cases.iter().filter(|c| c.outcome == o).count(); |
| 74 | Self { |
| 75 | suite: suite.to_string(), |
| 76 | passed: count(CaseOutcome::Pass), |
| 77 | failed: count(CaseOutcome::Fail), |
| 78 | skipped: count(CaseOutcome::Skipped), |
| 79 | cases, |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | /// Observation returned by a case body: `(passed, observed description)`. |
| 85 | type Observation = Result<(bool, String), String>; |
| 86 | |
| 87 | fn record( |
| 88 | suite: &str, |
| 89 | case: &str, |
| 90 | expected: &str, |
| 91 | body: impl FnOnce() -> Observation, |
| 92 | ) -> CaseResult { |
| 93 | let (outcome, observed) = match body() { |
| 94 | Ok((true, obs)) => (CaseOutcome::Pass, obs), |
| 95 | Ok((false, obs)) => (CaseOutcome::Fail, obs), |
| 96 | Err(e) => (CaseOutcome::Fail, format!("harness error: {e}")), |
| 97 | }; |
| 98 | CaseResult { |
| 99 | suite: suite.to_string(), |
| 100 | case: case.to_string(), |
| 101 | expected: expected.to_string(), |
| 102 | observed, |
| 103 | outcome, |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | fn skipped(suite: &str, case: &str, expected: &str, reason: &str) -> CaseResult { |
| 108 | CaseResult { |
| 109 | suite: suite.to_string(), |
| 110 | case: case.to_string(), |
| 111 | expected: expected.to_string(), |
| 112 | observed: reason.to_string(), |
| 113 | outcome: CaseOutcome::Skipped, |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | fn code_of<T>(r: &Result<T, synapse_core::SynapseError>) -> Option<RefusalCode> { |
| 118 | r.as_ref().err().map(|e| e.code) |
| 119 | } |
| 120 | |
| 121 | // --------------------------------------------------------------------------------------- |
| 122 | // WAL suite |
| 123 | // --------------------------------------------------------------------------------------- |
| 124 | |
| 125 | const WAL: &str = "wal"; |
| 126 | |
| 127 | fn wal_key() -> SigningKey { |
| 128 | synapse_arm::deterministic_key(0x57A1, "wal-conformance", 0) |
| 129 | } |
| 130 | |
| 131 | /// Content-addressed blobs supplied with an envelope. |
| 132 | type BlobSet = Vec<(BlobDigest, Vec<u8>)>; |
| 133 | |
| 134 | fn wal_envelope(i: u64) -> Result<(ChangesetEnvelope, BlobSet), String> { |
| 135 | let key = wal_key(); |
| 136 | let content = format!("wal conformance changeset {i}\n").into_bytes(); |
| 137 | let digest = BlobDigest::compute(&content); |
| 138 | let mut env = ChangesetEnvelope { |
| 139 | version: SYNAPSE_ENVELOPE_VERSION, |
| 140 | repo_id: RepoId::new("aien-spark/wal-conformance").map_err(|e| e.to_string())?, |
| 141 | base_git_oid: GitOid::compute_blob(b"wal conformance base"), |
| 142 | parent_changesets: Vec::new(), |
| 143 | author_did: String::new(), |
| 144 | idempotency_key: IdempotencyKey::from_label(&format!("wal-conformance-{i}")), |
| 145 | created_at_ms: 1_700_000_000_000 + i, |
| 146 | intent_summary: format!("wal conformance {i}"), |
| 147 | mutations: vec![PathMutation { |
| 148 | path: format!("conformance/file-{i}.txt"), |
| 149 | op: MutationOp::Upsert { |
| 150 | mode: FileMode::Regular644, |
| 151 | blob_digest: digest, |
| 152 | size_bytes: content.len() as u64, |
| 153 | }, |
| 154 | }], |
| 155 | evidence_receipts: Vec::new(), |
| 156 | signature: Vec::new(), |
| 157 | }; |
| 158 | env.sign(&key); |
| 159 | Ok((env, vec![(digest, content)])) |
| 160 | } |
| 161 | |
| 162 | fn open_store(dir: &Path, policy: RecoveryPolicy) -> synapse_core::SynapseResult<SynapseStore> { |
| 163 | SynapseStore::open( |
| 164 | dir, |
| 165 | FsyncPolicy::EveryCommit, |
| 166 | policy, |
| 167 | StoreLimits::default(), |
| 168 | ) |
| 169 | } |
| 170 | |
| 171 | /// State acknowledged before a fault is injected. |
| 172 | struct Acked { |
| 173 | ids: Vec<ChangesetId>, |
| 174 | blobs: BlobSet, |
| 175 | state_root: [u8; 32], |
| 176 | committed: WalSeq, |
| 177 | wal_bytes: Vec<u8>, |
| 178 | } |
| 179 | |
| 180 | fn seed_store(dir: &Path) -> Result<Acked, String> { |
| 181 | let _ = std::fs::remove_dir_all(dir); |
| 182 | let mut store = open_store(dir, RecoveryPolicy::StrictFailClosed).map_err(|e| e.to_string())?; |
| 183 | let mut ids = Vec::new(); |
| 184 | let mut all_blobs = Vec::new(); |
| 185 | for i in 0..3 { |
| 186 | let (env, blobs) = wal_envelope(i)?; |
| 187 | match store |
| 188 | .ingest_changeset(env, &blobs) |
| 189 | .map_err(|e| e.to_string())? |
| 190 | { |
| 191 | IngestOutcome::Committed { changeset_id, .. } => ids.push(changeset_id), |
| 192 | IngestOutcome::IdempotentDuplicate { .. } => { |
| 193 | return Err("unexpected idempotent duplicate while seeding".into()) |
| 194 | } |
| 195 | } |
| 196 | all_blobs.extend(blobs); |
| 197 | } |
| 198 | let state_root = store.state_root_digest(None).map_err(|e| e.to_string())?; |
| 199 | let committed = store.committed_seq(); |
| 200 | drop(store); |
| 201 | let wal_bytes = std::fs::read(dir.join("wal.log")).map_err(|e| format!("read wal.log: {e}"))?; |
| 202 | Ok(Acked { |
| 203 | ids, |
| 204 | blobs: all_blobs, |
| 205 | state_root, |
| 206 | committed, |
| 207 | wal_bytes, |
| 208 | }) |
| 209 | } |
| 210 | |
| 211 | fn acked_intact(store: &SynapseStore, acked: &Acked) -> Result<bool, String> { |
| 212 | if store.committed_seq() != acked.committed { |
| 213 | return Ok(false); |
| 214 | } |
| 215 | for id in &acked.ids { |
| 216 | if store.get_changeset(*id, None, None).is_err() { |
| 217 | return Ok(false); |
| 218 | } |
| 219 | } |
| 220 | for (d, bytes) in &acked.blobs { |
| 221 | match store.get_blob_visible(*d, None, None) { |
| 222 | Ok(b) if &b == bytes => {} |
| 223 | _ => return Ok(false), |
| 224 | } |
| 225 | } |
| 226 | Ok(store.state_root_digest(None).map_err(|e| e.to_string())? == acked.state_root) |
| 227 | } |
| 228 | |
| 229 | fn wal_prefix_unchanged(dir: &Path, acked: &Acked) -> Result<bool, String> { |
| 230 | let now = std::fs::read(dir.join("wal.log")).map_err(|e| format!("read wal.log: {e}"))?; |
| 231 | Ok(now.len() >= acked.wal_bytes.len() && now[..acked.wal_bytes.len()] == acked.wal_bytes[..]) |
| 232 | } |
| 233 | |
| 234 | /// Seed, inject `fault` on the next ingest, and return (ingest refusal code, acked state). |
| 235 | fn inject( |
| 236 | dir: &Path, |
| 237 | fault: FaultInjection, |
| 238 | ) -> Result<(Option<RefusalCode>, Acked, ChangesetId), String> { |
| 239 | let acked = seed_store(dir)?; |
| 240 | let mut store = open_store(dir, RecoveryPolicy::StrictFailClosed).map_err(|e| e.to_string())?; |
| 241 | store.set_fault_injection(fault); |
| 242 | let (env, blobs) = wal_envelope(10)?; |
| 243 | let id = env.compute_id(); |
| 244 | let r = store.ingest_changeset(env, &blobs); |
| 245 | Ok((code_of(&r), acked, id)) |
| 246 | } |
| 247 | |
| 248 | fn torn_refusal_case(work: &Path, name: &str, fault: FaultInjection) -> CaseResult { |
| 249 | record( |
| 250 | WAL, |
| 251 | name, |
| 252 | "faulted append refused with WalTornFrame; StrictFailClosed reopen refuses with WalTornFrame; acknowledged WAL prefix unchanged", |
| 253 | || { |
| 254 | let dir = work.join(name); |
| 255 | let (ingest_code, acked, _) = inject(&dir, fault)?; |
| 256 | let strict = open_store(&dir, RecoveryPolicy::StrictFailClosed); |
| 257 | let strict_code = code_of(&strict); |
| 258 | drop(strict); |
| 259 | let prefix = wal_prefix_unchanged(&dir, &acked)?; |
| 260 | Ok(( |
| 261 | ingest_code == Some(RefusalCode::WalTornFrame) |
| 262 | && strict_code == Some(RefusalCode::WalTornFrame) |
| 263 | && prefix, |
| 264 | format!( |
| 265 | "ingest refusal {ingest_code:?}; strict reopen {strict_code:?}; acknowledged prefix unchanged: {prefix}" |
| 266 | ), |
| 267 | )) |
| 268 | }, |
| 269 | ) |
| 270 | } |
| 271 | |
| 272 | fn torn_recovery_case(work: &Path, name: &str, fault: FaultInjection) -> CaseResult { |
| 273 | record( |
| 274 | WAL, |
| 275 | name, |
| 276 | "TruncateTornTail reopen succeeds, truncates exactly 1 torn frame, acknowledged changesets/blobs/state root intact, unacknowledged changeset absent, next append and strict reopen succeed", |
| 277 | || { |
| 278 | let dir = work.join(name); |
| 279 | let (_, acked, unacked_id) = inject(&dir, fault)?; |
| 280 | let mut store = |
| 281 | open_store(&dir, RecoveryPolicy::TruncateTornTail).map_err(|e| e.to_string())?; |
| 282 | let truncated = store.torn_frames_truncated_on_open(); |
| 283 | let intact = acked_intact(&store, &acked)?; |
| 284 | let absent = store.get_changeset(unacked_id, None, None).is_err(); |
| 285 | let (env, blobs) = wal_envelope(11)?; |
| 286 | let next_ok = store.ingest_changeset(env, &blobs).is_ok(); |
| 287 | drop(store); |
| 288 | let strict = open_store(&dir, RecoveryPolicy::StrictFailClosed); |
| 289 | let strict_ok = strict |
| 290 | .as_ref() |
| 291 | .map(|s| s.committed_seq() == acked.committed.next()) |
| 292 | .unwrap_or(false); |
| 293 | Ok(( |
| 294 | truncated == 1 && intact && absent && next_ok && strict_ok, |
| 295 | format!( |
| 296 | "truncated frames {truncated}; acknowledged intact {intact}; unacknowledged absent {absent}; next append ok {next_ok}; strict reopen at seq+1 ok {strict_ok}" |
| 297 | ), |
| 298 | )) |
| 299 | }, |
| 300 | ) |
| 301 | } |
| 302 | |
| 303 | fn corruption_case( |
| 304 | work: &Path, |
| 305 | name: &str, |
| 306 | fault: FaultInjection, |
| 307 | code: RefusalCode, |
| 308 | ) -> CaseResult { |
| 309 | let expected = format!( |
| 310 | "both StrictFailClosed and TruncateTornTail reopens refuse with {code:?} (corruption is never truncated away); acknowledged WAL prefix unchanged" |
| 311 | ); |
| 312 | record(WAL, name, &expected, || { |
| 313 | let dir = work.join(name); |
| 314 | let (ingest_code, acked, _) = inject(&dir, fault)?; |
| 315 | let strict = code_of(&open_store(&dir, RecoveryPolicy::StrictFailClosed)); |
| 316 | let lenient = code_of(&open_store(&dir, RecoveryPolicy::TruncateTornTail)); |
| 317 | let prefix = wal_prefix_unchanged(&dir, &acked)?; |
| 318 | Ok(( |
| 319 | strict == Some(code) && lenient == Some(code) && prefix, |
| 320 | format!( |
| 321 | "faulted ingest result {ingest_code:?} (None = acknowledged); strict reopen {strict:?}; truncate-tail reopen {lenient:?}; acknowledged prefix unchanged {prefix}" |
| 322 | ), |
| 323 | )) |
| 324 | }) |
| 325 | } |
| 326 | |
| 327 | /// Run the WAL crash and torn-write recovery suite under `work`. |
| 328 | pub fn run_wal_suite(work: &Path) -> SuiteResult { |
| 329 | let mut cases = Vec::new(); |
| 330 | cases.push(record( |
| 331 | WAL, |
| 332 | "clean_reopen_baseline", |
| 333 | "StrictFailClosed reopen of an undamaged store succeeds with all acknowledged state intact (positive control)", |
| 334 | || { |
| 335 | let dir = work.join("clean_reopen_baseline"); |
| 336 | let acked = seed_store(&dir)?; |
| 337 | let store = |
| 338 | open_store(&dir, RecoveryPolicy::StrictFailClosed).map_err(|e| e.to_string())?; |
| 339 | let intact = acked_intact(&store, &acked)?; |
| 340 | Ok((intact, format!("reopen ok; acknowledged intact {intact}"))) |
| 341 | }, |
| 342 | )); |
| 343 | cases.push(record( |
| 344 | WAL, |
| 345 | "crash_after_blob_write_before_wal_append", |
| 346 | "append refused with IoFailure; StrictFailClosed reopen succeeds; unacknowledged changeset absent; acknowledged state intact", |
| 347 | || { |
| 348 | let dir = work.join("crash_after_blob_write_before_wal_append"); |
| 349 | let (code, acked, id) = inject(&dir, FaultInjection::CrashAfterBlobWriteBeforeWalAppend)?; |
| 350 | let store = |
| 351 | open_store(&dir, RecoveryPolicy::StrictFailClosed).map_err(|e| e.to_string())?; |
| 352 | let absent = store.get_changeset(id, None, None).is_err(); |
| 353 | let intact = acked_intact(&store, &acked)?; |
| 354 | Ok(( |
| 355 | code == Some(RefusalCode::IoFailure) && absent && intact, |
| 356 | format!("ingest refusal {code:?}; unacknowledged absent {absent}; acknowledged intact {intact}"), |
| 357 | )) |
| 358 | }, |
| 359 | )); |
| 360 | let header = FaultInjection::TornWalHeaderWrite { bytes_written: 40 }; |
| 361 | let payload = FaultInjection::TornWalPayloadWrite { bytes_written: 10 }; |
| 362 | cases.push(torn_refusal_case( |
| 363 | work, |
| 364 | "torn_header_strict_refuses", |
| 365 | header, |
| 366 | )); |
| 367 | cases.push(torn_recovery_case( |
| 368 | work, |
| 369 | "torn_header_truncate_recovers", |
| 370 | header, |
| 371 | )); |
| 372 | cases.push(torn_refusal_case( |
| 373 | work, |
| 374 | "torn_payload_strict_refuses", |
| 375 | payload, |
| 376 | )); |
| 377 | cases.push(torn_recovery_case( |
| 378 | work, |
| 379 | "torn_payload_truncate_recovers", |
| 380 | payload, |
| 381 | )); |
| 382 | cases.push(corruption_case( |
| 383 | work, |
| 384 | "crc_corruption_refused", |
| 385 | FaultInjection::CorruptNextWalCrc, |
| 386 | RefusalCode::WalCrcMismatch, |
| 387 | )); |
| 388 | cases.push(corruption_case( |
| 389 | work, |
| 390 | "chain_corruption_refused", |
| 391 | FaultInjection::CorruptNextWalChain, |
| 392 | RefusalCode::WalChainMismatch, |
| 393 | )); |
| 394 | cases.push(corruption_case( |
| 395 | work, |
| 396 | "sequence_gap_refused", |
| 397 | FaultInjection::InjectNextWalSequenceGap, |
| 398 | RefusalCode::WalSequenceGap, |
| 399 | )); |
| 400 | cases.push(corruption_case( |
| 401 | work, |
| 402 | "duplicate_sequence_refused", |
| 403 | FaultInjection::InjectDuplicateWalSequence, |
| 404 | RefusalCode::WalSequenceGap, |
| 405 | )); |
| 406 | cases.push(record( |
| 407 | WAL, |
| 408 | "committed_blob_bitflip_refused", |
| 409 | "flipping one byte of a committed blob file makes StrictFailClosed reopen refuse with BlobDigestMismatch", |
| 410 | || { |
| 411 | let dir = work.join("committed_blob_bitflip_refused"); |
| 412 | let acked = seed_store(&dir)?; |
| 413 | let (digest, _) = acked.blobs.first().ok_or("no seeded blob")?; |
| 414 | let hex = digest.to_hex(); |
| 415 | let path = dir.join("blobs").join(&hex[0..2]).join(&hex); |
| 416 | let mut bytes = std::fs::read(&path).map_err(|e| format!("read blob: {e}"))?; |
| 417 | bytes[0] ^= 0x01; |
| 418 | std::fs::write(&path, bytes).map_err(|e| format!("write blob: {e}"))?; |
| 419 | let code = code_of(&open_store(&dir, RecoveryPolicy::StrictFailClosed)); |
| 420 | Ok(( |
| 421 | code == Some(RefusalCode::BlobDigestMismatch), |
| 422 | format!("strict reopen {code:?}"), |
| 423 | )) |
| 424 | }, |
| 425 | )); |
| 426 | SuiteResult::from_cases(WAL, cases) |
| 427 | } |
| 428 | |
| 429 | // --------------------------------------------------------------------------------------- |
| 430 | // Git suite |
| 431 | // --------------------------------------------------------------------------------------- |
| 432 | |
| 433 | const GIT: &str = "git"; |
| 434 | |
| 435 | struct GitFixture { |
| 436 | base_repo: PathBuf, |
| 437 | base_commit: String, |
| 438 | svc: SynapseService, |
| 439 | ids: BenchIdentities, |
| 440 | c1: ChangesetId, |
| 441 | c2: ChangesetId, |
| 442 | c3: ChangesetId, |
| 443 | } |
| 444 | |
| 445 | fn sign_publish_advance( |
| 446 | ids: &BenchIdentities, |
| 447 | label: &str, |
| 448 | branch: &str, |
| 449 | new_commit_oid: GitOid, |
| 450 | now_ms: u64, |
| 451 | ) -> Result<AuthenticatedRequest<HumanBranchAdvanceRequest>, String> { |
| 452 | let agent = &ids.agents[0]; |
| 453 | let grant = AgentCapabilityGrant::issue( |
| 454 | &ids.authority_key, |
| 455 | synapse_arm::label_bytes(&format!("publish-grant-{label}")), |
| 456 | ids.repo_id.clone(), |
| 457 | agent.did.clone(), |
| 458 | vec![Capability::Publish], |
| 459 | synapse_arm::BENCH_MAX_BYTES_PER_OP, |
| 460 | u32::MAX, |
| 461 | synapse_arm::BENCH_RATE_WINDOW_MS, |
| 462 | now_ms.saturating_sub(3_600_000), |
| 463 | now_ms + 7 * 24 * 3_600_000, |
| 464 | ); |
| 465 | AuthenticatedRequest::sign_new( |
| 466 | &agent.key, |
| 467 | grant, |
| 468 | ids.repo_id.clone(), |
| 469 | Capability::Publish, |
| 470 | synapse_arm::label_bytes(&format!("publish-nonce-{label}")), |
| 471 | now_ms, |
| 472 | 0, |
| 473 | HumanBranchAdvanceRequest { |
| 474 | branch: branch.to_string(), |
| 475 | new_commit_oid, |
| 476 | }, |
| 477 | ) |
| 478 | .map_err(|e| e.to_string()) |
| 479 | } |
| 480 | |
| 481 | fn upsert(path: &str, body: &str, mode: FileMode) -> FileEdit { |
| 482 | FileEdit { |
| 483 | path: path.to_string(), |
| 484 | op: EditOp::Upsert { |
| 485 | mode, |
| 486 | content: Arc::new(body.as_bytes().to_vec()), |
| 487 | }, |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | fn proposal(index: usize, mut edits: Vec<FileEdit>) -> Proposal { |
| 492 | edits.sort_by(|a, b| a.path.cmp(&b.path)); |
| 493 | Proposal { |
| 494 | agent: 0, |
| 495 | index, |
| 496 | summary: format!("git conformance changeset {index}"), |
| 497 | edits, |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | fn submit( |
| 502 | svc: &mut SynapseService, |
| 503 | ids: &BenchIdentities, |
| 504 | base: GitOid, |
| 505 | parents: Vec<ChangesetId>, |
| 506 | p: &Proposal, |
| 507 | ) -> Result<ChangesetId, String> { |
| 508 | let now = crate::unix_now_ms(); |
| 509 | let req = synapse_arm::build_submit_request_with_parents( |
| 510 | &ids.agents[0], |
| 511 | &ids.repo_id, |
| 512 | base, |
| 513 | parents, |
| 514 | p, |
| 515 | &format!("git-conformance-{}", p.index), |
| 516 | now, |
| 517 | )?; |
| 518 | match svc.submit(&req, now).map_err(|e| e.to_string())? { |
| 519 | IngestOutcome::Committed { changeset_id, .. } |
| 520 | | IngestOutcome::IdempotentDuplicate { changeset_id, .. } => Ok(changeset_id), |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | fn git_fixture(work: &Path) -> Result<GitFixture, String> { |
| 525 | let base_repo = work.join("git-base"); |
| 526 | let _ = std::fs::remove_dir_all(&base_repo); |
| 527 | std::fs::create_dir_all(base_repo.join("src/net")).map_err(|e| e.to_string())?; |
| 528 | std::fs::create_dir_all(base_repo.join("docs")).map_err(|e| e.to_string())?; |
| 529 | std::fs::create_dir_all(base_repo.join("scripts")).map_err(|e| e.to_string())?; |
| 530 | git_ok(&base_repo, &[], &[], &["init", "-q", "-b", "main"], None)?; |
| 531 | configure_bench_clone(&base_repo)?; |
| 532 | let files = [ |
| 533 | ("README.md", "# conformance base\n"), |
| 534 | ("src/lib.rs", "pub mod net;\n"), |
| 535 | ("src/net/http.rs", "pub fn serve() {}\n"), |
| 536 | ("docs/a.md", "doc a\n"), |
| 537 | ("scripts/run.sh", "#!/bin/sh\necho base\n"), |
| 538 | ]; |
| 539 | for (p, body) in files { |
| 540 | std::fs::write(base_repo.join(p), body).map_err(|e| e.to_string())?; |
| 541 | } |
| 542 | let script = base_repo.join("scripts/run.sh"); |
| 543 | let mut perm = std::fs::metadata(&script) |
| 544 | .map_err(|e| e.to_string())? |
| 545 | .permissions(); |
| 546 | std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755); |
| 547 | std::fs::set_permissions(&script, perm).map_err(|e| e.to_string())?; |
| 548 | git_ok(&base_repo, &[], &[], &["add", "-A"], None)?; |
| 549 | git_ok( |
| 550 | &base_repo, |
| 551 | &[], |
| 552 | &[], |
| 553 | &["commit", "-q", "-m", "conformance base"], |
| 554 | None, |
| 555 | )?; |
| 556 | let base_commit = git_line(&base_repo, &["rev-parse", "HEAD"])?; |
| 557 | |
| 558 | let ids = synapse_arm::issue_identities(0x617, 1, crate::unix_now_ms())?; |
| 559 | let mut svc = synapse_arm::open_service( |
| 560 | &work.join("git-svc"), |
| 561 | &ids, |
| 562 | FsyncPolicy::EveryCommit, |
| 563 | RecoveryPolicy::StrictFailClosed, |
| 564 | )?; |
| 565 | let base_oid = svc |
| 566 | .import_base_tree_from_git_repo(&base_repo, "HEAD") |
| 567 | .map_err(|e| e.to_string())?; |
| 568 | let p1 = proposal( |
| 569 | 1, |
| 570 | vec![ |
| 571 | upsert( |
| 572 | "src/lib.rs", |
| 573 | "pub mod net;\npub mod store;\n", |
| 574 | FileMode::Regular644, |
| 575 | ), |
| 576 | upsert("src/store.rs", "pub struct Wal;\n", FileMode::Regular644), |
| 577 | FileEdit { |
| 578 | path: "docs/a.md".into(), |
| 579 | op: EditOp::Delete, |
| 580 | }, |
| 581 | ], |
| 582 | ); |
| 583 | let p2 = proposal( |
| 584 | 2, |
| 585 | vec![ |
| 586 | upsert("README.md", "# conformance stacked\n", FileMode::Regular644), |
| 587 | upsert( |
| 588 | "scripts/new.sh", |
| 589 | "#!/bin/sh\necho new\n", |
| 590 | FileMode::Executable755, |
| 591 | ), |
| 592 | ], |
| 593 | ); |
| 594 | let p3 = proposal( |
| 595 | 3, |
| 596 | vec![upsert( |
| 597 | "src/lib.rs", |
| 598 | "pub mod net;\npub mod other;\n", |
| 599 | FileMode::Regular644, |
| 600 | )], |
| 601 | ); |
| 602 | let c1 = submit(&mut svc, &ids, base_oid, Vec::new(), &p1)?; |
| 603 | let c2 = submit(&mut svc, &ids, base_oid, vec![c1], &p2)?; |
| 604 | let c3 = submit(&mut svc, &ids, base_oid, Vec::new(), &p3)?; |
| 605 | Ok(GitFixture { |
| 606 | base_repo, |
| 607 | base_commit, |
| 608 | svc, |
| 609 | ids, |
| 610 | c1, |
| 611 | c2, |
| 612 | c3, |
| 613 | }) |
| 614 | } |
| 615 | |
| 616 | fn bare_clone(src: &Path, dest: &Path) -> Result<(), String> { |
| 617 | let _ = std::fs::remove_dir_all(dest); |
| 618 | let parent = dest.parent().ok_or("destination has no parent")?; |
| 619 | git_ok( |
| 620 | parent, |
| 621 | &[], |
| 622 | &[], |
| 623 | &["clone", "--bare", "-q", path_str(src)?, path_str(dest)?], |
| 624 | None, |
| 625 | )?; |
| 626 | Ok(()) |
| 627 | } |
| 628 | |
| 629 | fn copy_dir(src: &Path, dst: &Path) -> Result<(), String> { |
| 630 | std::fs::create_dir_all(dst).map_err(|e| format!("mkdir {}: {e}", dst.display()))?; |
| 631 | for entry in std::fs::read_dir(src).map_err(|e| format!("read_dir {}: {e}", src.display()))? { |
| 632 | let entry = entry.map_err(|e| e.to_string())?; |
| 633 | let ty = entry.file_type().map_err(|e| e.to_string())?; |
| 634 | let target = dst.join(entry.file_name()); |
| 635 | if ty.is_dir() { |
| 636 | copy_dir(&entry.path(), &target)?; |
| 637 | } else if ty.is_file() { |
| 638 | std::fs::copy(entry.path(), &target) |
| 639 | .map_err(|e| format!("copy {}: {e}", entry.path().display()))?; |
| 640 | } |
| 641 | } |
| 642 | Ok(()) |
| 643 | } |
| 644 | |
| 645 | fn walk_files( |
| 646 | root: &Path, |
| 647 | rel: &str, |
| 648 | out: &mut BTreeMap<String, (bool, Vec<u8>)>, |
| 649 | ) -> Result<(), String> { |
| 650 | let dir = if rel.is_empty() { |
| 651 | root.to_path_buf() |
| 652 | } else { |
| 653 | root.join(rel) |
| 654 | }; |
| 655 | for entry in std::fs::read_dir(&dir).map_err(|e| format!("read_dir {}: {e}", dir.display()))? { |
| 656 | let entry = entry.map_err(|e| e.to_string())?; |
| 657 | let name = entry.file_name().to_string_lossy().to_string(); |
| 658 | if rel.is_empty() && name == ".git" { |
| 659 | continue; |
| 660 | } |
| 661 | let path = if rel.is_empty() { |
| 662 | name |
| 663 | } else { |
| 664 | format!("{rel}/{name}") |
| 665 | }; |
| 666 | let ty = entry.file_type().map_err(|e| e.to_string())?; |
| 667 | if ty.is_dir() { |
| 668 | walk_files(root, &path, out)?; |
| 669 | } else { |
| 670 | let meta = entry.metadata().map_err(|e| e.to_string())?; |
| 671 | let exec = std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o111 != 0; |
| 672 | let bytes = std::fs::read(entry.path()).map_err(|e| e.to_string())?; |
| 673 | out.insert(path, (exec, bytes)); |
| 674 | } |
| 675 | } |
| 676 | Ok(()) |
| 677 | } |
| 678 | |
| 679 | /// Run the Git materialization suite under `work`. |
| 680 | pub fn run_git_suite(work: &Path) -> SuiteResult { |
| 681 | let mut cases = Vec::new(); |
| 682 | let mut fx = match git_fixture(work) { |
| 683 | Ok(fx) => fx, |
| 684 | Err(e) => { |
| 685 | cases.push(record(GIT, "fixture_setup", "fixture builds", || { |
| 686 | Err(e.clone()) |
| 687 | })); |
| 688 | return SuiteResult::from_cases(GIT, cases); |
| 689 | } |
| 690 | }; |
| 691 | let t1 = work.join("target-1.git"); |
| 692 | let t2 = work.join("target-2.git"); |
| 693 | let mut index = GitProjectionIndex::new(); |
| 694 | let mut c2_commit: Option<GitOid> = None; |
| 695 | let mut c1_commit: Option<GitOid> = None; |
| 696 | |
| 697 | cases.push(record( |
| 698 | GIT, |
| 699 | "deterministic_rematerialization", |
| 700 | "materializing the same stacked changeset into two fresh repositories yields identical commit and tree OIDs", |
| 701 | || { |
| 702 | bare_clone(&fx.base_repo, &t1)?; |
| 703 | bare_clone(&fx.base_repo, &t2)?; |
| 704 | let m1 = materialize_changeset_to_git(&mut fx.svc, &mut index, &t1, fx.c2, Some("conformance"), None) |
| 705 | .map_err(|e| e.to_string())?; |
| 706 | let mut index2 = GitProjectionIndex::new(); |
| 707 | let m2 = materialize_changeset_to_git(&mut fx.svc, &mut index2, &t2, fx.c2, None, None) |
| 708 | .map_err(|e| e.to_string())?; |
| 709 | c2_commit = Some(m1.commit_oid); |
| 710 | c1_commit = index.commit_for_changeset(fx.c1); |
| 711 | Ok(( |
| 712 | m1.commit_oid == m2.commit_oid && m1.tree_oid == m2.tree_oid, |
| 713 | format!("commit {} vs {}; tree {} vs {}", m1.commit_oid, m2.commit_oid, m1.tree_oid, m2.tree_oid), |
| 714 | )) |
| 715 | }, |
| 716 | )); |
| 717 | |
| 718 | cases.push(record( |
| 719 | GIT, |
| 720 | "fsck_full_strict_clean", |
| 721 | "`git fsck --full --strict` exits 0 on the materialized repository", |
| 722 | || { |
| 723 | let run = run_git(&t1, &[], &[], &["fsck", "--full", "--strict"], None)?; |
| 724 | Ok(( |
| 725 | run.code == Some(0), |
| 726 | format!("exit {:?} {}", run.code, run.stderr_tail()), |
| 727 | )) |
| 728 | }, |
| 729 | )); |
| 730 | |
| 731 | cases.push(record( |
| 732 | GIT, |
| 733 | "fsck_detects_corrupted_object", |
| 734 | "negative control: overwriting one materialized loose object makes `git fsck --full --strict` exit non-zero", |
| 735 | || { |
| 736 | let commit = c2_commit.ok_or("no materialized commit")?; |
| 737 | let t3 = work.join("target-3-corrupt.git"); |
| 738 | let _ = std::fs::remove_dir_all(&t3); |
| 739 | copy_dir(&t1, &t3)?; |
| 740 | let hex = commit.to_hex(); |
| 741 | let obj = t3.join("objects").join(&hex[0..2]).join(&hex[2..]); |
| 742 | let mut perm = std::fs::metadata(&obj).map_err(|e| format!("stat {}: {e}", obj.display()))?.permissions(); |
| 743 | std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o644); |
| 744 | std::fs::set_permissions(&obj, perm).map_err(|e| e.to_string())?; |
| 745 | std::fs::write(&obj, b"not a zlib stream").map_err(|e| e.to_string())?; |
| 746 | let run = run_git(&t3, &[], &[], &["fsck", "--full", "--strict"], None)?; |
| 747 | Ok((run.code.is_some_and(|c| c != 0), format!("exit {:?}", run.code))) |
| 748 | }, |
| 749 | )); |
| 750 | |
| 751 | cases.push(record( |
| 752 | GIT, |
| 753 | "fetch_checkout_byte_parity", |
| 754 | "fetching the changeset ref into a new repository and checking it out yields exactly the Synapse virtual tree (paths, bytes, executable bits)", |
| 755 | || { |
| 756 | let commit = c2_commit.ok_or("no materialized commit")?; |
| 757 | let dst = work.join("fetch-check"); |
| 758 | let _ = std::fs::remove_dir_all(&dst); |
| 759 | std::fs::create_dir_all(&dst).map_err(|e| e.to_string())?; |
| 760 | git_ok(&dst, &[], &[], &["init", "-q"], None)?; |
| 761 | let refspec = format!("{}:refs/heads/check", synapse_git::changeset_git_ref(fx.c2)); |
| 762 | git_ok(&dst, &[], &[], &["fetch", "-q", path_str(&t1)?, &refspec], None)?; |
| 763 | git_ok(&dst, &[], &[], &["checkout", "-q", "check"], None)?; |
| 764 | let head = git_line(&dst, &["rev-parse", "HEAD"])?; |
| 765 | let mut on_disk = BTreeMap::new(); |
| 766 | walk_files(&dst, "", &mut on_disk)?; |
| 767 | let vt = fx |
| 768 | .svc |
| 769 | .materialize_virtual_tree(TreeTarget::Changeset(fx.c2), None) |
| 770 | .map_err(|e| e.to_string())?; |
| 771 | let mut expected = BTreeMap::new(); |
| 772 | for (path, entry) in &vt { |
| 773 | let bytes = fx.svc.read_blob_bytes(entry.blob_digest, None).map_err(|e| e.to_string())?; |
| 774 | expected.insert(path.clone(), (entry.mode == FileMode::Executable755, bytes)); |
| 775 | } |
| 776 | Ok(( |
| 777 | head == commit.to_hex() && on_disk == expected, |
| 778 | format!("checked out {head}; {} files on disk vs {} in virtual tree; identical {}", on_disk.len(), expected.len(), on_disk == expected), |
| 779 | )) |
| 780 | }, |
| 781 | )); |
| 782 | |
| 783 | cases.push(record( |
| 784 | GIT, |
| 785 | "materialized_diff_matches_changeset_paths", |
| 786 | "`git diff-tree -r --name-status <base> <C1>` lists exactly the changeset's mutations (unchanged paths reproduce identical tree objects)", |
| 787 | || { |
| 788 | let c1 = c1_commit.ok_or("no materialized parent commit")?; |
| 789 | let out = git_ok(&t1, &[], &[], &["diff-tree", "-r", "--name-status", &fx.base_commit, &c1.to_hex()], None)?; |
| 790 | let got: Vec<String> = String::from_utf8_lossy(&out).lines().map(|l| l.replace('\t', " ")).collect(); |
| 791 | let want = vec!["D docs/a.md".to_string(), "M src/lib.rs".to_string(), "A src/store.rs".to_string()]; |
| 792 | Ok((got == want, format!("{got:?}"))) |
| 793 | }, |
| 794 | )); |
| 795 | |
| 796 | cases.push(record( |
| 797 | GIT, |
| 798 | "fast_forward_human_branch_allowed", |
| 799 | "advancing refs/heads/main from the base to the stacked descendant succeeds (positive control)", |
| 800 | || { |
| 801 | let commit = c2_commit.ok_or("no materialized commit")?; |
| 802 | let now = crate::unix_now_ms(); |
| 803 | let req = sign_publish_advance(&fx.ids, "ff", "main", commit, now)?; |
| 804 | let r = advance_human_branch_fast_forward(&mut fx.svc, &t1, &req, now); |
| 805 | let head = git_line(&t1, &["rev-parse", "refs/heads/main"])?; |
| 806 | Ok((r.is_ok() && head == commit.to_hex(), format!("result {:?}; main at {head}", code_of(&r)))) |
| 807 | }, |
| 808 | )); |
| 809 | |
| 810 | cases.push(record( |
| 811 | GIT, |
| 812 | "non_fast_forward_human_branch_refused", |
| 813 | "advancing refs/heads/main to a sibling changeset commit is refused with GitRefNonFastForward and main is unchanged", |
| 814 | || { |
| 815 | let before = git_line(&t1, &["rev-parse", "refs/heads/main"])?; |
| 816 | let m3 = materialize_changeset_to_git(&mut fx.svc, &mut index, &t1, fx.c3, None, None) |
| 817 | .map_err(|e| e.to_string())?; |
| 818 | let now = crate::unix_now_ms(); |
| 819 | let req = sign_publish_advance(&fx.ids, "non-ff", "main", m3.commit_oid, now)?; |
| 820 | let r = advance_human_branch_fast_forward(&mut fx.svc, &t1, &req, now); |
| 821 | let after = git_line(&t1, &["rev-parse", "refs/heads/main"])?; |
| 822 | Ok(( |
| 823 | code_of(&r) == Some(RefusalCode::GitRefNonFastForward) && before == after, |
| 824 | format!("result {:?}; main before {before} after {after}", code_of(&r)), |
| 825 | )) |
| 826 | }, |
| 827 | )); |
| 828 | SuiteResult::from_cases(GIT, cases) |
| 829 | } |
| 830 | |
| 831 | // --------------------------------------------------------------------------------------- |
| 832 | // Radicle suite |
| 833 | // --------------------------------------------------------------------------------------- |
| 834 | |
| 835 | const RAD: &str = "radicle"; |
| 836 | |
| 837 | fn rad_doc(delegates: &[SigningKey], threshold: usize) -> RadicleIdentityDoc { |
| 838 | RadicleIdentityDoc { |
| 839 | delegates: delegates |
| 840 | .iter() |
| 841 | .map(|k| encode_did_key_ed25519(&k.verifying_key().to_bytes())) |
| 842 | .collect(), |
| 843 | payload: RadiclePayloadMap { |
| 844 | project: RadicleProjectPayload { |
| 845 | default_branch: "main".into(), |
| 846 | description: String::new(), |
| 847 | name: "gate4-conformance".into(), |
| 848 | }, |
| 849 | }, |
| 850 | threshold, |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | fn signed(key: &SigningKey, oid: GitOid) -> DelegateSigrefs { |
| 855 | let mut refs = BTreeMap::new(); |
| 856 | refs.insert("refs/heads/main".to_string(), oid); |
| 857 | DelegateSigrefs::sign_refs(key, &refs) |
| 858 | } |
| 859 | |
| 860 | fn cand(base: GitOid, oid: GitOid, merged: bool) -> Result<PromotionCandidate, String> { |
| 861 | Ok(PromotionCandidate { |
| 862 | repo_id: RepoId::new("aien-spark/radicle-conformance").map_err(|e| e.to_string())?, |
| 863 | changeset_id: None, |
| 864 | proposal_base_git_oid: base, |
| 865 | candidate_git_oid: oid, |
| 866 | github_pr_merged: merged, |
| 867 | verified_at_ms: 1_700_000_000_000, |
| 868 | }) |
| 869 | } |
| 870 | |
| 871 | /// Run the Radicle canonicality suite; `live_repo` is an optional bare Radicle storage repo. |
| 872 | pub fn run_radicle_suite(live_repo: Option<&Path>) -> SuiteResult { |
| 873 | let keys: Vec<SigningKey> = (0..3) |
| 874 | .map(|i| synapse_arm::deterministic_key(0x4AD, "delegate", i)) |
| 875 | .collect(); |
| 876 | let outsider = synapse_arm::deterministic_key(0x4AD, "outsider", 0); |
| 877 | let base = GitOid::compute_git_object("commit", b"radicle conformance base"); |
| 878 | let x = GitOid::compute_git_object("commit", b"radicle conformance candidate x"); |
| 879 | let y = GitOid::compute_git_object("commit", b"radicle conformance candidate y"); |
| 880 | let doc = rad_doc(&keys, 2); |
| 881 | let engine = |
| 882 | || CanonicalPromotionEngine::new(doc.clone(), None, None).map_err(|e| e.to_string()); |
| 883 | let mut cases = Vec::new(); |
| 884 | |
| 885 | cases.push(record( |
| 886 | RAD, |
| 887 | "threshold_met_promotes", |
| 888 | "2 of 3 delegate signatures on X promote X with 2 verified delegates", |
| 889 | || { |
| 890 | let mut e = engine()?; |
| 891 | let r = e.verify_and_promote( |
| 892 | &cand(base, x, false)?, |
| 893 | &[signed(&keys[0], x), signed(&keys[1], x)], |
| 894 | ); |
| 895 | let ok = r |
| 896 | .as_ref() |
| 897 | .is_ok_and(|h| h.canonical_git_oid == x && h.verified_delegates.len() == 2); |
| 898 | Ok(( |
| 899 | ok, |
| 900 | format!( |
| 901 | "result {:?}", |
| 902 | r.map(|h| (h.canonical_git_oid, h.verified_delegates.len())) |
| 903 | .map_err(|e| e.code) |
| 904 | ), |
| 905 | )) |
| 906 | }, |
| 907 | )); |
| 908 | cases.push(record( |
| 909 | RAD, |
| 910 | "below_threshold_refused", |
| 911 | "1 of 3 signatures (threshold 2) is refused with RadicleQuorumInsufficient", |
| 912 | || { |
| 913 | let mut e = engine()?; |
| 914 | let r = e.verify_and_promote(&cand(base, x, false)?, &[signed(&keys[0], x)]); |
| 915 | Ok(( |
| 916 | code_of(&r) == Some(RefusalCode::RadicleQuorumInsufficient), |
| 917 | format!("result {:?}", code_of(&r)), |
| 918 | )) |
| 919 | }, |
| 920 | )); |
| 921 | cases.push(record(RAD, "vote_for_other_oid_not_counted", "a delegate signature over Y does not count toward X; promotion of X refused with RadicleQuorumInsufficient", || { |
| 922 | let mut e = engine()?; |
| 923 | let r = e.verify_and_promote(&cand(base, x, false)?, &[signed(&keys[0], x), signed(&keys[1], y)]); |
| 924 | Ok((code_of(&r) == Some(RefusalCode::RadicleQuorumInsufficient), format!("result {:?}", code_of(&r)))) |
| 925 | })); |
| 926 | cases.push(record( |
| 927 | RAD, |
| 928 | "tampered_refs_blob_refused", |
| 929 | "a sigrefs blob edited after signing (OID swapped) is refused with RadicleSignatureInvalid", |
| 930 | || { |
| 931 | let mut e = engine()?; |
| 932 | let mut forged = signed(&keys[1], y); |
| 933 | let text = String::from_utf8(forged.refs_blob.clone()).map_err(|e| e.to_string())?; |
| 934 | forged.refs_blob = text.replace(&y.to_hex(), &x.to_hex()).into_bytes(); |
| 935 | let r = e.verify_and_promote(&cand(base, x, false)?, &[signed(&keys[0], x), forged]); |
| 936 | Ok(( |
| 937 | code_of(&r) == Some(RefusalCode::RadicleSignatureInvalid), |
| 938 | format!("result {:?}", code_of(&r)), |
| 939 | )) |
| 940 | }, |
| 941 | )); |
| 942 | cases.push(record(RAD, "non_delegate_signer_refused", "a valid signature from a key not listed in the identity document is refused with RadicleIdentityInvalid", || { |
| 943 | let mut e = engine()?; |
| 944 | let r = e.verify_and_promote(&cand(base, x, false)?, &[signed(&keys[0], x), signed(&outsider, x)]); |
| 945 | Ok((code_of(&r) == Some(RefusalCode::RadicleIdentityInvalid), format!("result {:?}", code_of(&r)))) |
| 946 | })); |
| 947 | cases.push(record(RAD, "forged_delegate_signature_refused", "a sigrefs claiming a delegate DID but signed by another key is refused with RadicleSignatureInvalid", || { |
| 948 | let mut e = engine()?; |
| 949 | let mut forged = signed(&outsider, x); |
| 950 | forged.delegate_did = encode_did_key_ed25519(&keys[1].verifying_key().to_bytes()); |
| 951 | let r = e.verify_and_promote(&cand(base, x, false)?, &[signed(&keys[0], x), forged]); |
| 952 | Ok((code_of(&r) == Some(RefusalCode::RadicleSignatureInvalid), format!("result {:?}", code_of(&r)))) |
| 953 | })); |
| 954 | cases.push(record(RAD, "stale_base_refused", "after X is canonical, a candidate whose proposal base is not X is refused with StaleBaseHead", || { |
| 955 | let mut e = engine()?; |
| 956 | e.verify_and_promote(&cand(base, x, false)?, &[signed(&keys[0], x), signed(&keys[1], x)]) |
| 957 | .map_err(|e| e.to_string())?; |
| 958 | let r = e.verify_and_promote(&cand(base, y, false)?, &[signed(&keys[0], y), signed(&keys[1], y)]); |
| 959 | let still_x = e.current_canonical().is_some_and(|h| h.canonical_git_oid == x); |
| 960 | Ok((code_of(&r) == Some(RefusalCode::StaleBaseHead) && still_x, format!("result {:?}; canonical still X {still_x}", code_of(&r)))) |
| 961 | })); |
| 962 | cases.push(record(RAD, "github_merged_without_quorum_refused", "a GitHub-merged candidate with 1 of 2 required signatures classifies as SplitBrainGithubMergedWithoutRadicleQuorum and promotion is refused with RadicleQuorumInsufficient", || { |
| 963 | let mut e = engine()?; |
| 964 | let c = cand(base, x, true)?; |
| 965 | let sigs = [signed(&keys[0], x)]; |
| 966 | let state = e.classify_reconciliation(&c, &sigs).map_err(|e| e.to_string())?; |
| 967 | let classified = matches!(state, ReconciliationState::SplitBrainGithubMergedWithoutRadicleQuorum { .. }); |
| 968 | let r = e.verify_and_promote(&c, &sigs); |
| 969 | Ok((classified && code_of(&r) == Some(RefusalCode::RadicleQuorumInsufficient), format!("state {state:?}; result {:?}", code_of(&r)))) |
| 970 | })); |
| 971 | cases.push(record( |
| 972 | RAD, |
| 973 | "diverged_quorum_refused", |
| 974 | "when the delegate quorum signs Y, promoting X is refused with SplitBrainDivergence", |
| 975 | || { |
| 976 | let mut e = engine()?; |
| 977 | let r = e.verify_and_promote( |
| 978 | &cand(base, x, false)?, |
| 979 | &[signed(&keys[0], y), signed(&keys[1], y)], |
| 980 | ); |
| 981 | Ok(( |
| 982 | code_of(&r) == Some(RefusalCode::SplitBrainDivergence), |
| 983 | format!("result {:?}", code_of(&r)), |
| 984 | )) |
| 985 | }, |
| 986 | )); |
| 987 | cases.push(record(RAD, "invalid_threshold_identity_refused", "an identity document with threshold 4 of 3 delegates is refused with RadicleIdentityInvalid", || { |
| 988 | let r = CanonicalPromotionEngine::new(rad_doc(&keys, 4), None, None); |
| 989 | let code = r.as_ref().err().map(|e| e.code); |
| 990 | Ok((code == Some(RefusalCode::RadicleIdentityInvalid), format!("result {code:?}"))) |
| 991 | })); |
| 992 | |
| 993 | let live_expected = "read-only: load refs/rad/id and every delegate's sigrefs from the given bare Radicle storage repository, verify signatures, and classify the delegate-signed default-branch head as CanonicalQuorumSatisfied"; |
| 994 | match live_repo { |
| 995 | None => cases.push(skipped(RAD, "live_repository_load_and_classify", live_expected, "skipped: no --radicle-repo given")), |
| 996 | Some(p) if !p.exists() => cases.push(skipped(RAD, "live_repository_load_and_classify", live_expected, &format!("skipped: {} does not exist", p.display()))), |
| 997 | Some(p) => cases.push(record(RAD, "live_repository_load_and_classify", live_expected, || { |
| 998 | let (doc, id_oid, sigrefs) = load_radicle_state_from_bare_repo(p).map_err(|e| e.to_string())?; |
| 999 | let default_ref = doc.default_branch_ref(); |
| 1000 | let mut votes: BTreeMap<GitOid, usize> = BTreeMap::new(); |
| 1001 | for s in &sigrefs { |
| 1002 | let (_, refs) = s.verify_and_parse().map_err(|e| e.to_string())?; |
| 1003 | if let Some(oid) = refs.get(&default_ref) { |
| 1004 | *votes.entry(*oid).or_default() += 1; |
| 1005 | } |
| 1006 | } |
| 1007 | let (head, count) = votes.iter().max_by_key(|(_, c)| **c).map(|(o, c)| (*o, *c)).ok_or("no delegate signed the default branch")?; |
| 1008 | let engine = CanonicalPromotionEngine::new(doc.clone(), Some(id_oid), None).map_err(|e| e.to_string())?; |
| 1009 | let state = engine.classify_reconciliation(&cand(head, head, false)?, &sigrefs).map_err(|e| e.to_string())?; |
| 1010 | let ok = matches!(state, ReconciliationState::CanonicalQuorumSatisfied { .. }); |
| 1011 | Ok((ok, format!( |
| 1012 | "project {:?}; delegates {}; threshold {}; sigrefs loaded {}; default branch {default_ref} head {head} signed by {count}; state {}", |
| 1013 | doc.payload.project.name, doc.delegates.len(), doc.threshold, sigrefs.len(), |
| 1014 | match state { ReconciliationState::CanonicalQuorumSatisfied { .. } => "CanonicalQuorumSatisfied".to_string(), other => format!("{other:?}") } |
| 1015 | ))) |
| 1016 | })), |
| 1017 | } |
| 1018 | SuiteResult::from_cases(RAD, cases) |
| 1019 | } |
| 1020 | |
| 1021 | /// Run one suite by name (`wal`, `git`, or `radicle`). |
| 1022 | pub fn run_suite( |
| 1023 | name: &str, |
| 1024 | work: &Path, |
| 1025 | radicle_repo: Option<&Path>, |
| 1026 | ) -> Result<SuiteResult, String> { |
| 1027 | std::fs::create_dir_all(work).map_err(|e| format!("mkdir {}: {e}", work.display()))?; |
| 1028 | match name { |
| 1029 | WAL => Ok(run_wal_suite(work)), |
| 1030 | GIT => Ok(run_git_suite(work)), |
| 1031 | RAD => Ok(run_radicle_suite(radicle_repo)), |
| 1032 | other => Err(format!("unknown conformance suite {other}")), |
| 1033 | } |
| 1034 | } |
| 1035 | |
| 1036 | #[cfg(test)] |
| 1037 | mod tests { |
| 1038 | use super::*; |
| 1039 | use crate::fixture::test_support::temp_dir; |
| 1040 | |
| 1041 | fn assert_all_pass(s: &SuiteResult) { |
| 1042 | for c in &s.cases { |
| 1043 | assert_eq!( |
| 1044 | c.outcome, |
| 1045 | CaseOutcome::Pass, |
| 1046 | "{}::{} observed {}", |
| 1047 | c.suite, |
| 1048 | c.case, |
| 1049 | c.observed |
| 1050 | ); |
| 1051 | } |
| 1052 | } |
| 1053 | |
| 1054 | #[test] |
| 1055 | fn wal_suite_cases_pass() { |
| 1056 | let dir = temp_dir("conf-wal"); |
| 1057 | let s = run_wal_suite(&dir); |
| 1058 | assert_eq!(s.cases.len(), 11); |
| 1059 | assert_all_pass(&s); |
| 1060 | let _ = std::fs::remove_dir_all(&dir); |
| 1061 | } |
| 1062 | |
| 1063 | /// ADR 0003 A1: the WAL suite's stores hold binary codec v2 frames, so its 11 cases |
| 1064 | /// qualify the binary codec, not the v1 JSON one. |
| 1065 | #[test] |
| 1066 | fn wal_suite_stores_write_binary_codec_frames() { |
| 1067 | let dir = temp_dir("conf-wal-codec"); |
| 1068 | let acked = seed_store(&dir).unwrap(); |
| 1069 | let log = acked.wal_bytes; |
| 1070 | let mut at = 0; |
| 1071 | let mut frames = 0; |
| 1072 | while at < log.len() { |
| 1073 | assert_eq!( |
| 1074 | log[at + 7], |
| 1075 | synapse_store::codec::WAL_FLAG_CODEC_V2, |
| 1076 | "frame {frames} flags" |
| 1077 | ); |
| 1078 | let len = u32::from_le_bytes(log[at + 48..at + 52].try_into().unwrap()) as usize; |
| 1079 | at += synapse_store::WAL_HEADER_LEN + len; |
| 1080 | frames += 1; |
| 1081 | } |
| 1082 | assert_eq!(frames, 3); |
| 1083 | let _ = std::fs::remove_dir_all(&dir); |
| 1084 | } |
| 1085 | |
| 1086 | #[test] |
| 1087 | fn git_suite_cases_pass() { |
| 1088 | let dir = temp_dir("conf-git"); |
| 1089 | let s = run_git_suite(&dir); |
| 1090 | assert_eq!(s.cases.len(), 7); |
| 1091 | assert_all_pass(&s); |
| 1092 | let _ = std::fs::remove_dir_all(&dir); |
| 1093 | } |
| 1094 | |
| 1095 | #[test] |
| 1096 | fn radicle_suite_cases_pass_and_live_case_skips_without_path() { |
| 1097 | let s = run_radicle_suite(None); |
| 1098 | assert_eq!(s.skipped, 1); |
| 1099 | assert_eq!(s.failed, 0); |
| 1100 | assert_eq!(s.passed, s.cases.len() - 1); |
| 1101 | } |
| 1102 | } |