synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-store / src / a1_tests.rs
| 1 | //! ADR 0003 section 9 step A1 acceptance tests: binary canonical codec v2 for WAL records |
| 2 | //! and checkpoints. |
| 3 | //! |
| 4 | //! The v1 fixtures under `tests/fixtures/a1-v1` were written by the merged main-branch |
| 5 | //! store (`b04ad31`, JSON codec), so "the v1 JSON form" here is real v1 output, not a |
| 6 | //! re-serialization by the code under test. The generator is kept in |
| 7 | //! `evidence/a1-binary-codec/fixture-generator`. |
| 8 | |
| 9 | use super::tests::{make_signed_changeset, temp_store_dir}; |
| 10 | use super::*; |
| 11 | use crate::codec::*; |
| 12 | use ed25519_dalek::SigningKey; |
| 13 | use synapse_core::{FileMode, GitOid, PathMutation, SYNAPSE_ENVELOPE_VERSION}; |
| 14 | |
| 15 | const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; |
| 16 | |
| 17 | pub(super) fn fixture_dir(name: &str) -> PathBuf { |
| 18 | Path::new(env!("CARGO_MANIFEST_DIR")) |
| 19 | .join("tests/fixtures/a1-v1") |
| 20 | .join(name) |
| 21 | } |
| 22 | |
| 23 | pub(super) fn copy_tree(src: &Path, dst: &Path) { |
| 24 | fs::create_dir_all(dst).unwrap(); |
| 25 | for e in fs::read_dir(src).unwrap() { |
| 26 | let e = e.unwrap(); |
| 27 | let to = dst.join(e.file_name()); |
| 28 | if e.file_type().unwrap().is_dir() { |
| 29 | copy_tree(&e.path(), &to); |
| 30 | } else { |
| 31 | fs::copy(e.path(), &to).unwrap(); |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /// Copy a fixture store into a fresh temporary directory (opening a store writes to it). |
| 37 | pub(super) fn copy_fixture(name: &str) -> PathBuf { |
| 38 | let dir = temp_store_dir(&format!("a1-{name}")); |
| 39 | copy_tree(&fixture_dir(name), &dir); |
| 40 | let _ = fs::remove_file(dir.join("EXPECT")); |
| 41 | dir |
| 42 | } |
| 43 | |
| 44 | pub(super) struct Expect { |
| 45 | pub(super) committed_seq: u64, |
| 46 | pub(super) state_root: [u8; 32], |
| 47 | } |
| 48 | |
| 49 | pub(super) fn expect(name: &str) -> Expect { |
| 50 | let text = fs::read_to_string(fixture_dir(name).join("EXPECT")).unwrap(); |
| 51 | let field = |k: &str| { |
| 52 | text.lines() |
| 53 | .find_map(|l| l.strip_prefix(k).map(|v| v.trim().to_string())) |
| 54 | .unwrap() |
| 55 | }; |
| 56 | Expect { |
| 57 | committed_seq: field("committed_seq ").parse().unwrap(), |
| 58 | state_root: hex::decode(field("state_root ")) |
| 59 | .unwrap() |
| 60 | .try_into() |
| 61 | .unwrap(), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// `(kind, flags, payload)` of every frame in a `wal.log` (the v2 marker excluded). |
| 66 | fn v1_log_frames(bytes: &[u8]) -> Vec<(u8, u8, Vec<u8>)> { |
| 67 | let mut out = Vec::new(); |
| 68 | let mut at = 0; |
| 69 | while at < bytes.len() { |
| 70 | let h = &bytes[at..at + WAL_HEADER_LEN]; |
| 71 | let len = u32::from_le_bytes(h[48..52].try_into().unwrap()) as usize; |
| 72 | if h[6] != 0xFF { |
| 73 | out.push(( |
| 74 | h[6], |
| 75 | h[7], |
| 76 | bytes[at + WAL_HEADER_LEN..at + WAL_HEADER_LEN + len].to_vec(), |
| 77 | )); |
| 78 | } |
| 79 | at += WAL_HEADER_LEN + len; |
| 80 | } |
| 81 | out |
| 82 | } |
| 83 | |
| 84 | /// `(kind, flags, record bytes)` of every frame in a `wal.v2.log` (the record bytes are |
| 85 | /// the payload's metadata part, without inline blobs). |
| 86 | fn v2_log_frames(bytes: &[u8]) -> Vec<(u8, u8, Vec<u8>)> { |
| 87 | let mut out = Vec::new(); |
| 88 | let mut off = 0usize; |
| 89 | while off + wal2::WAL_V2_BATCH_HEADER_LEN <= bytes.len() |
| 90 | && bytes[off..off + 4] == wal2::WAL_V2_BATCH_MAGIC |
| 91 | { |
| 92 | let count = u32::from_le_bytes(bytes[off + 8..off + 12].try_into().unwrap()); |
| 93 | let body = u64::from_le_bytes(bytes[off + 16..off + 24].try_into().unwrap()) as usize; |
| 94 | let mut at = off + wal2::WAL_V2_BATCH_HEADER_LEN; |
| 95 | for _ in 0..count { |
| 96 | let h = &bytes[at..at + WAL_HEADER_LEN]; |
| 97 | let len = u32::from_le_bytes(h[48..52].try_into().unwrap()) as usize; |
| 98 | let p = &bytes[at + WAL_HEADER_LEN..at + WAL_HEADER_LEN + len]; |
| 99 | let meta_len = u32::from_le_bytes(p[0..4].try_into().unwrap()) as usize; |
| 100 | out.push((h[6], h[7], p[4..4 + meta_len].to_vec())); |
| 101 | at += WAL_HEADER_LEN + len; |
| 102 | } |
| 103 | off = wal2::align_up((off + wal2::WAL_V2_BATCH_HEADER_LEN + body) as u64) as usize; |
| 104 | } |
| 105 | out |
| 106 | } |
| 107 | |
| 108 | fn v1_flags(dir: &Path) -> Vec<u8> { |
| 109 | v1_log_frames(&fs::read(dir.join("wal.log")).unwrap()) |
| 110 | .into_iter() |
| 111 | .map(|(_, f, _)| f) |
| 112 | .collect() |
| 113 | } |
| 114 | |
| 115 | /// Flags of the frames written after the current checkpoint. With the segment store |
| 116 | /// (ADR 0003 A2) a checkpoint keeps the segments whole, so these are the frames from the |
| 117 | /// replay position of the checkpoint's segment index on. |
| 118 | fn v2_flags(dir: &Path) -> Vec<u8> { |
| 119 | let binding = segment::checkpoint_binding(dir).unwrap(); |
| 120 | let (first, off) = segment::SegmentIndex::load(dir, &binding) |
| 121 | .map(|i| (i.replay_segment, i.replay_offset as usize)) |
| 122 | .unwrap_or((1, 0)); |
| 123 | let last = segment::list_segments(dir) |
| 124 | .unwrap() |
| 125 | .last() |
| 126 | .copied() |
| 127 | .unwrap_or(1); |
| 128 | let mut out = Vec::new(); |
| 129 | for id in first..=last { |
| 130 | let bytes = fs::read(dir.join(segment::segment_file_name(id))).unwrap(); |
| 131 | let from = if id == first { off } else { 0 }; |
| 132 | out.extend(v2_log_frames(&bytes[from..]).into_iter().map(|(_, f, _)| f)); |
| 133 | } |
| 134 | out |
| 135 | } |
| 136 | |
| 137 | /// Every v1 JSON record payload in both fixtures. |
| 138 | pub(super) fn fixture_json_records() -> Vec<Vec<u8>> { |
| 139 | let mut out = Vec::new(); |
| 140 | for (kind, flags, json) in |
| 141 | v1_log_frames(&fs::read(fixture_dir("v1-wal-log").join("wal.log")).unwrap()) |
| 142 | { |
| 143 | assert_eq!(flags, 0, "fixture frames are v1 JSON"); |
| 144 | assert_ne!(kind, 0); |
| 145 | out.push(json); |
| 146 | } |
| 147 | for (_, flags, json) in |
| 148 | v2_log_frames(&fs::read(fixture_dir("v1-wal-v2-log").join(wal2::WAL_V2_FILE)).unwrap()) |
| 149 | { |
| 150 | assert_eq!(flags, 0, "fixture frames are v1 JSON"); |
| 151 | out.push(json); |
| 152 | } |
| 153 | out |
| 154 | } |
| 155 | |
| 156 | const CAP: u64 = 128 * 1024 * 1024; |
| 157 | |
| 158 | /// Both directions for one record, starting from its v1 JSON bytes. |
| 159 | fn assert_both_directions(json: &[u8]) -> u8 { |
| 160 | let record: WalRecord = serde_json::from_slice(json).unwrap(); |
| 161 | // JSON -> binary -> the same logical record, whose JSON form is the original bytes. |
| 162 | let bin = encode_record(&record).unwrap(); |
| 163 | assert_eq!(bin.first(), Some(&CODEC_V2), "codec version byte"); |
| 164 | assert_eq!(bin.get(1), Some(&record.kind_byte()), "record kind byte"); |
| 165 | let from_bin = decode_record(&bin, CAP).unwrap(); |
| 166 | assert_eq!(from_bin, record); |
| 167 | assert_eq!(serde_json::to_vec(&from_bin).unwrap(), json); |
| 168 | // binary -> JSON -> the same logical record, whose binary form is the original bytes. |
| 169 | let via_json: WalRecord = |
| 170 | serde_json::from_slice(&serde_json::to_vec(&from_bin).unwrap()).unwrap(); |
| 171 | assert_eq!(via_json, from_bin); |
| 172 | assert_eq!(encode_record(&via_json).unwrap(), bin); |
| 173 | record.kind_byte() |
| 174 | } |
| 175 | |
| 176 | #[test] |
| 177 | fn a1_every_record_kind_matches_its_v1_json_form_in_both_directions() { |
| 178 | let mut kinds = BTreeSet::new(); |
| 179 | let records = fixture_json_records(); |
| 180 | // 8 frames left in the v1 wal.log after its checkpoint, 8 in the group-commit log. |
| 181 | assert_eq!(records.len(), 16, "fixture record count"); |
| 182 | for json in &records { |
| 183 | kinds.insert(assert_both_directions(json)); |
| 184 | } |
| 185 | assert_eq!( |
| 186 | kinds, |
| 187 | (1u8..=6).collect::<BTreeSet<_>>(), |
| 188 | "every WalRecord kind is covered" |
| 189 | ); |
| 190 | } |
| 191 | |
| 192 | pub(super) fn edge_records() -> Vec<WalRecord> { |
| 193 | let key = SigningKey::from_bytes(&[0xE1; 32]); |
| 194 | let a = BlobDigest::compute(b"a"); |
| 195 | let mut env = ChangesetEnvelope { |
| 196 | version: SYNAPSE_ENVELOPE_VERSION, |
| 197 | repo_id: RepoId::new("a/b.c_d-e").unwrap(), |
| 198 | base_git_oid: GitOid::ZERO, |
| 199 | parent_changesets: vec![ChangesetId([0u8; 32]), ChangesetId([0xFF; 32])], |
| 200 | author_did: String::new(), |
| 201 | idempotency_key: IdempotencyKey([0xAB; 32]), |
| 202 | created_at_ms: u64::MAX, |
| 203 | intent_summary: "\u{0}\u{7f}\u{10FFFF} edge".into(), |
| 204 | mutations: vec![ |
| 205 | PathMutation { |
| 206 | path: "a".into(), |
| 207 | op: MutationOp::Upsert { |
| 208 | mode: FileMode::Regular644, |
| 209 | blob_digest: a, |
| 210 | size_bytes: 0, |
| 211 | }, |
| 212 | }, |
| 213 | PathMutation { |
| 214 | path: "b/c".into(), |
| 215 | op: MutationOp::Upsert { |
| 216 | mode: FileMode::Symlink120000, |
| 217 | blob_digest: a, |
| 218 | size_bytes: u64::MAX, |
| 219 | }, |
| 220 | }, |
| 221 | PathMutation { |
| 222 | path: "d".into(), |
| 223 | op: MutationOp::Delete, |
| 224 | }, |
| 225 | ], |
| 226 | evidence_receipts: vec![ |
| 227 | EvidenceAttachment { |
| 228 | gate_name: String::new(), |
| 229 | passed: false, |
| 230 | artifact_digest: [0u8; 32], |
| 231 | summary: String::new(), |
| 232 | }, |
| 233 | EvidenceAttachment { |
| 234 | gate_name: "g".into(), |
| 235 | passed: true, |
| 236 | artifact_digest: [1u8; 32], |
| 237 | summary: "s".repeat(300), |
| 238 | }, |
| 239 | ], |
| 240 | signature: vec![], |
| 241 | }; |
| 242 | env.sign(&key); |
| 243 | let id = env.compute_id(); |
| 244 | vec![ |
| 245 | WalRecord::ChangesetIngest { |
| 246 | envelope: env.clone(), |
| 247 | changeset_id: id, |
| 248 | new_blobs: vec![], |
| 249 | }, |
| 250 | WalRecord::ChangesetIngest { |
| 251 | envelope: ChangesetEnvelope { |
| 252 | signature: vec![], |
| 253 | parent_changesets: vec![], |
| 254 | evidence_receipts: vec![], |
| 255 | ..env |
| 256 | }, |
| 257 | changeset_id: id, |
| 258 | new_blobs: vec![a, BlobDigest([0u8; 32])], |
| 259 | }, |
| 260 | WalRecord::EvaluationAttached { |
| 261 | changeset_id: id, |
| 262 | attachment: EvidenceAttachment { |
| 263 | gate_name: "\u{1F600}".into(), |
| 264 | passed: true, |
| 265 | artifact_digest: [2u8; 32], |
| 266 | summary: "x\ty".into(), |
| 267 | }, |
| 268 | }, |
| 269 | WalRecord::ReviewRecorded { |
| 270 | changeset_id: id, |
| 271 | review: ReviewRecord { |
| 272 | reviewer_did: String::new(), |
| 273 | approved: false, |
| 274 | comment: String::new(), |
| 275 | recorded_at_ms: 0, |
| 276 | }, |
| 277 | }, |
| 278 | WalRecord::GitProjected { |
| 279 | projection: GitHubPullRequestProjection { |
| 280 | repo_id: RepoId::new("x").unwrap(), |
| 281 | pr_number: u64::MAX, |
| 282 | changeset_id: id, |
| 283 | head_git_oid: GitOid([0xFF; 20]), |
| 284 | base_git_oid: GitOid::ZERO, |
| 285 | pr_branch_ref: String::new(), |
| 286 | title: String::new(), |
| 287 | body_markdown: "\r\n".into(), |
| 288 | evidence_summary_digest: [0u8; 32], |
| 289 | github_merged: true, |
| 290 | }, |
| 291 | }, |
| 292 | WalRecord::CanonicalPromoted { |
| 293 | canonical: RadicleCanonicalHead { |
| 294 | repo_id: RepoId::new("x/y").unwrap(), |
| 295 | default_branch: String::new(), |
| 296 | canonical_git_oid: GitOid::ZERO, |
| 297 | promoted_changeset_id: None, |
| 298 | rad_id_commit_oid: GitOid([1u8; 20]), |
| 299 | threshold: usize::MAX, |
| 300 | verified_delegates: vec![String::new(), "d".into()], |
| 301 | verified_at_ms: u64::MAX, |
| 302 | }, |
| 303 | }, |
| 304 | WalRecord::LeaseUpdated { |
| 305 | changeset_id: id, |
| 306 | lease_expires_at_ms: 0, |
| 307 | }, |
| 308 | ] |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn a1_edge_records_match_their_json_form_in_both_directions() { |
| 313 | for r in edge_records() { |
| 314 | let json = serde_json::to_vec(&r).unwrap(); |
| 315 | assert_both_directions(&json); |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn a1_encoder_refuses_a_repository_id_that_rejects_validation() { |
| 321 | // `RepoId`'s serde derive accepts any string; the binary decoder validates, so the |
| 322 | // encoder must refuse what the decoder would refuse. |
| 323 | let bad: RepoId = serde_json::from_str("\"a//b\"").unwrap(); |
| 324 | let r = WalRecord::CanonicalPromoted { |
| 325 | canonical: RadicleCanonicalHead { |
| 326 | repo_id: bad, |
| 327 | default_branch: "main".into(), |
| 328 | canonical_git_oid: GitOid::ZERO, |
| 329 | promoted_changeset_id: None, |
| 330 | rad_id_commit_oid: GitOid::ZERO, |
| 331 | threshold: 1, |
| 332 | verified_delegates: vec![], |
| 333 | verified_at_ms: 0, |
| 334 | }, |
| 335 | }; |
| 336 | assert_eq!( |
| 337 | encode_record(&r).unwrap_err().code, |
| 338 | RefusalCode::RepoIdInvalid |
| 339 | ); |
| 340 | } |
| 341 | |
| 342 | fn put_str(b: &mut Vec<u8>, s: &[u8]) { |
| 343 | b.extend_from_slice(&(s.len() as u32).to_le_bytes()); |
| 344 | b.extend_from_slice(s); |
| 345 | } |
| 346 | |
| 347 | /// `ReviewRecorded` written by hand from the documented layout. |
| 348 | fn review_bytes(did: &[u8], approved: u8, comment: &[u8]) -> Vec<u8> { |
| 349 | let mut b = vec![CODEC_V2, 3]; |
| 350 | b.extend_from_slice(&[9u8; 32]); |
| 351 | put_str(&mut b, did); |
| 352 | b.push(approved); |
| 353 | put_str(&mut b, comment); |
| 354 | b.extend_from_slice(&7u64.to_le_bytes()); |
| 355 | b |
| 356 | } |
| 357 | |
| 358 | /// `CanonicalPromoted` written by hand with option tag `tag` and repository id `repo`. |
| 359 | fn canonical_bytes(repo: &[u8], tag: u8) -> Vec<u8> { |
| 360 | let mut b = vec![CODEC_V2, 5]; |
| 361 | put_str(&mut b, repo); |
| 362 | put_str(&mut b, b"main"); |
| 363 | b.extend_from_slice(&[1u8; 20]); |
| 364 | b.push(tag); |
| 365 | if tag == 1 { |
| 366 | b.extend_from_slice(&[2u8; 32]); |
| 367 | } |
| 368 | b.extend_from_slice(&[3u8; 20]); |
| 369 | b.extend_from_slice(&2u64.to_le_bytes()); |
| 370 | b.extend_from_slice(&0u32.to_le_bytes()); |
| 371 | b.extend_from_slice(&5u64.to_le_bytes()); |
| 372 | b |
| 373 | } |
| 374 | |
| 375 | #[test] |
| 376 | fn a1_documented_layout_decodes_and_every_non_canonical_form_is_refused() { |
| 377 | // Positive controls: the hand-written layout is what the codec reads and writes. |
| 378 | let review = review_bytes(b"did:key:z", 1, b"ok"); |
| 379 | let r = decode_record(&review, CAP).unwrap(); |
| 380 | assert_eq!( |
| 381 | r, |
| 382 | WalRecord::ReviewRecorded { |
| 383 | changeset_id: ChangesetId([9u8; 32]), |
| 384 | review: ReviewRecord { |
| 385 | reviewer_did: "did:key:z".into(), |
| 386 | approved: true, |
| 387 | comment: "ok".into(), |
| 388 | recorded_at_ms: 7, |
| 389 | }, |
| 390 | } |
| 391 | ); |
| 392 | assert_eq!(encode_record(&r).unwrap(), review); |
| 393 | let canon = canonical_bytes(b"a/b", 1); |
| 394 | let c = decode_record(&canon, CAP).unwrap(); |
| 395 | assert_eq!(encode_record(&c).unwrap(), canon); |
| 396 | assert_eq!( |
| 397 | decode_record(&canonical_bytes(b"a/b", 0), CAP) |
| 398 | .map(|r| matches!(r, WalRecord::CanonicalPromoted { canonical } if canonical.promoted_changeset_id.is_none())), |
| 399 | Ok(true) |
| 400 | ); |
| 401 | |
| 402 | let kind = |r: Result<WalRecord, CodecRefusal>| r.unwrap_err().kind(); |
| 403 | let mut v1 = review.clone(); |
| 404 | v1[0] = 1; |
| 405 | assert_eq!( |
| 406 | decode_record(&v1, CAP), |
| 407 | Err(CodecRefusal::VersionUnsupported { found: 1 }) |
| 408 | ); |
| 409 | let mut k = review.clone(); |
| 410 | k[1] = 12; // first unused kind (7, 8, 9 and 11 are revision records, 10 the H1 Git bridge) |
| 411 | assert_eq!(kind(decode_record(&k, CAP)), "UnknownTag"); |
| 412 | let mut k0 = review.clone(); |
| 413 | k0[1] = 0; |
| 414 | assert_eq!(kind(decode_record(&k0, CAP)), "UnknownTag"); |
| 415 | let mut trailing = review.clone(); |
| 416 | trailing.push(0); |
| 417 | assert_eq!(kind(decode_record(&trailing, CAP)), "TrailingBytes"); |
| 418 | assert_eq!( |
| 419 | kind(decode_record(&review[..review.len() - 1], CAP)), |
| 420 | "Truncated" |
| 421 | ); |
| 422 | assert_eq!(kind(decode_record(&[], CAP)), "Truncated"); |
| 423 | assert_eq!( |
| 424 | kind(decode_record(&review_bytes(b"d", 2, b""), CAP)), |
| 425 | "UnknownTag" |
| 426 | ); |
| 427 | assert_eq!( |
| 428 | kind(decode_record(&review_bytes(b"\xff\xfe", 1, b""), CAP)), |
| 429 | "InvalidUtf8" |
| 430 | ); |
| 431 | assert_eq!( |
| 432 | kind(decode_record(&canonical_bytes(b"a/b", 2), CAP)), |
| 433 | "UnknownTag" |
| 434 | ); |
| 435 | assert_eq!( |
| 436 | kind(decode_record(&canonical_bytes(b"a//b", 0), CAP)), |
| 437 | "InvalidRepoId" |
| 438 | ); |
| 439 | // A declared length longer than what remains, and one longer than the cap. |
| 440 | let mut long = review.clone(); |
| 441 | long[34..38].copy_from_slice(&1000u32.to_le_bytes()); |
| 442 | assert_eq!(kind(decode_record(&long, CAP)), "Truncated"); |
| 443 | let mut huge = review.clone(); |
| 444 | huge[34..38].copy_from_slice(&u32::MAX.to_le_bytes()); |
| 445 | assert_eq!( |
| 446 | decode_record(&huge, 4096), |
| 447 | Err(CodecRefusal::LengthOverCap { |
| 448 | at: 34, |
| 449 | declared: u64::from(u32::MAX), |
| 450 | cap: 4096 |
| 451 | }) |
| 452 | ); |
| 453 | // Malformed binary records surface as WalRecordMalformed. |
| 454 | assert_eq!( |
| 455 | decode_record_with(&trailing, RecordCodec::BinaryV2, CAP) |
| 456 | .unwrap_err() |
| 457 | .code, |
| 458 | RefusalCode::WalRecordMalformed |
| 459 | ); |
| 460 | } |
| 461 | |
| 462 | #[test] |
| 463 | fn a1_checkpoint_state_matches_its_v1_json_form_in_both_directions() { |
| 464 | let v1_bytes = fs::read(fixture_dir("v1-wal-log").join("checkpoint.v1")).unwrap(); |
| 465 | let manifest: CheckpointManifest = serde_json::from_slice(&v1_bytes).unwrap(); |
| 466 | let state = CheckpointState::from_v1_manifest(manifest.clone()).unwrap(); |
| 467 | assert!(!state.changesets.is_empty() && !state.github_projections.is_empty()); |
| 468 | assert_eq!(state.to_v1_manifest(), manifest); |
| 469 | assert_eq!( |
| 470 | serde_json::to_vec(&state.to_v1_manifest()).unwrap(), |
| 471 | v1_bytes |
| 472 | ); |
| 473 | |
| 474 | let (bytes, chain) = encode_checkpoint_v2(&state, [1u8; 32], [2u8; 32]).unwrap(); |
| 475 | assert_eq!(bytes[0..4], CHECKPOINT_V2_MAGIC); |
| 476 | let (back, back_chain) = decode_checkpoint_v2(&bytes).unwrap(); |
| 477 | assert_eq!(back, state); |
| 478 | assert_eq!(back_chain, chain); |
| 479 | assert_eq!( |
| 480 | serde_json::to_vec(&back.to_v1_manifest()).unwrap(), |
| 481 | v1_bytes |
| 482 | ); |
| 483 | // Canonical: the decoded state encodes to the same bytes. |
| 484 | assert_eq!( |
| 485 | encode_checkpoint_v2(&back, [1u8; 32], [2u8; 32]).unwrap().0, |
| 486 | bytes |
| 487 | ); |
| 488 | assert_eq!(chain.v1_state_root, [1u8; 32]); |
| 489 | assert_eq!(chain.prev_checkpoint_root, [2u8; 32]); |
| 490 | assert_eq!(chain.state_root, state.state_root()); |
| 491 | assert_eq!( |
| 492 | chain.checkpoint_root, |
| 493 | checkpoint_root( |
| 494 | &[1u8; 32], |
| 495 | &[2u8; 32], |
| 496 | state.checkpoint_seq, |
| 497 | &state.anchor_frame_sha256, |
| 498 | &chain.state_root, |
| 499 | &chain.content_sha256 |
| 500 | ) |
| 501 | ); |
| 502 | } |
| 503 | |
| 504 | #[test] |
| 505 | fn a1_state_root_helpers_match_the_store() { |
| 506 | let empty = temp_store_dir("a1-empty-root"); |
| 507 | let s = SynapseStore::open( |
| 508 | &empty, |
| 509 | FsyncPolicy::EveryCommit, |
| 510 | STRICT, |
| 511 | StoreLimits::default(), |
| 512 | ) |
| 513 | .unwrap(); |
| 514 | assert_eq!(s.state_root_digest(None).unwrap(), empty_state_root()); |
| 515 | let dir = copy_fixture("v1-wal-log"); |
| 516 | let s = SynapseStore::open( |
| 517 | &dir, |
| 518 | FsyncPolicy::EveryCommit, |
| 519 | STRICT, |
| 520 | StoreLimits::default(), |
| 521 | ) |
| 522 | .unwrap(); |
| 523 | assert_eq!( |
| 524 | state_root_of(&s.changesets, &[], s.committed_seq), |
| 525 | s.state_root_digest(None).unwrap() |
| 526 | ); |
| 527 | assert_eq!( |
| 528 | state_root_of(&s.changesets, &[], WalSeq(3)), |
| 529 | s.state_root_digest(Some(WalSeq(3))).unwrap() |
| 530 | ); |
| 531 | } |
| 532 | |
| 533 | fn first_changeset(s: &SynapseStore) -> ChangesetId { |
| 534 | *s.changesets.keys().next().unwrap() |
| 535 | } |
| 536 | |
| 537 | /// Legacy v1 store: replay unchanged, keeps writing v1 until its first v2 checkpoint, |
| 538 | /// which records the last v1 state root and chains its own root to it. |
| 539 | fn migration_case(name: &str, policy: FsyncPolicy, flags: fn(&Path) -> Vec<u8>) { |
| 540 | let limits = StoreLimits { |
| 541 | wal_prealloc_bytes: 64 * 1024, |
| 542 | ..Default::default() |
| 543 | }; |
| 544 | let dir = copy_fixture(name); |
| 545 | let ex = expect(name); |
| 546 | let mut s = SynapseStore::open(&dir, policy, STRICT, limits.clone()).unwrap(); |
| 547 | assert_eq!(s.committed_seq(), WalSeq(ex.committed_seq), "{name}"); |
| 548 | assert_eq!(s.state_root_digest(None).unwrap(), ex.state_root, "{name}"); |
| 549 | assert_eq!( |
| 550 | s.record_codec(), |
| 551 | RecordCodec::JsonV1, |
| 552 | "{name}: legacy store" |
| 553 | ); |
| 554 | assert_eq!(s.checkpoint_chain(), None); |
| 555 | let cs = first_changeset(&s); |
| 556 | s.update_lease(cs, 7).unwrap(); |
| 557 | assert!(flags(&dir).iter().all(|f| *f == 0), "{name}: still v1"); |
| 558 | |
| 559 | let last_v1_root = s.state_root_digest(None).unwrap(); |
| 560 | s.checkpoint_and_compact(2_000).unwrap(); |
| 561 | let chain = s.checkpoint_chain().expect("first v2 checkpoint"); |
| 562 | assert_eq!(chain.v1_state_root, last_v1_root, "{name}"); |
| 563 | assert_eq!(chain.prev_checkpoint_root, last_v1_root, "{name}"); |
| 564 | assert_eq!(chain.checkpoint_seq, s.committed_seq()); |
| 565 | assert_eq!(chain.anchor_frame_sha256, s.last_frame_sha256()); |
| 566 | assert_eq!(chain.state_root, s.state_root_digest(None).unwrap()); |
| 567 | assert_eq!( |
| 568 | chain.checkpoint_root, |
| 569 | checkpoint_root( |
| 570 | &last_v1_root, |
| 571 | &last_v1_root, |
| 572 | chain.checkpoint_seq, |
| 573 | &chain.anchor_frame_sha256, |
| 574 | &chain.state_root, |
| 575 | &chain.content_sha256 |
| 576 | ) |
| 577 | ); |
| 578 | let file = fs::read(dir.join(CHECKPOINT_V2_FILE)).unwrap(); |
| 579 | assert_eq!(decode_checkpoint_v2(&file).unwrap().1, chain); |
| 580 | assert_eq!( |
| 581 | fs::read(dir.join("checkpoint.v1")).unwrap(), |
| 582 | v1_tombstone_bytes() |
| 583 | ); |
| 584 | assert_eq!(s.record_codec(), RecordCodec::BinaryV2, "{name}"); |
| 585 | |
| 586 | s.update_lease(cs, 8).unwrap(); |
| 587 | s.update_lease(cs, 9).unwrap(); |
| 588 | let f = flags(&dir); |
| 589 | assert!( |
| 590 | !f.is_empty() && f.iter().all(|f| *f == WAL_FLAG_CODEC_V2), |
| 591 | "{name}: frames after the migration are binary: {f:?}" |
| 592 | ); |
| 593 | let root = s.state_root_digest(None).unwrap(); |
| 594 | drop(s); |
| 595 | |
| 596 | let mut s = SynapseStore::open(&dir, policy, STRICT, limits).unwrap(); |
| 597 | assert_eq!(s.state_root_digest(None).unwrap(), root, "{name}: reopen"); |
| 598 | assert_eq!(s.checkpoint_chain(), Some(chain)); |
| 599 | assert_eq!(s.record_codec(), RecordCodec::BinaryV2); |
| 600 | s.checkpoint_and_compact(3_000).unwrap(); |
| 601 | let next = s.checkpoint_chain().unwrap(); |
| 602 | assert_eq!(next.prev_checkpoint_root, chain.checkpoint_root, "{name}"); |
| 603 | assert_eq!(next.v1_state_root, last_v1_root, "{name}"); |
| 604 | assert_eq!( |
| 605 | next.checkpoint_root, |
| 606 | checkpoint_root( |
| 607 | &last_v1_root, |
| 608 | &chain.checkpoint_root, |
| 609 | next.checkpoint_seq, |
| 610 | &next.anchor_frame_sha256, |
| 611 | &next.state_root, |
| 612 | &next.content_sha256 |
| 613 | ) |
| 614 | ); |
| 615 | } |
| 616 | |
| 617 | #[test] |
| 618 | fn a1_first_v2_checkpoint_records_last_v1_root_and_chains_wal_log() { |
| 619 | migration_case("v1-wal-log", FsyncPolicy::EveryCommit, v1_flags); |
| 620 | } |
| 621 | |
| 622 | #[test] |
| 623 | fn a1_first_v2_checkpoint_records_last_v1_root_and_chains_wal_v2_log() { |
| 624 | migration_case("v1-wal-v2-log", FsyncPolicy::GROUP_COMMIT_DEFAULT, v2_flags); |
| 625 | } |
| 626 | |
| 627 | #[test] |
| 628 | fn a1_v1_readers_refuse_the_tombstone() { |
| 629 | // A binary that only knows v1 parses checkpoint.v1 and refuses any version but 1. |
| 630 | let m: CheckpointManifest = serde_json::from_slice(&v1_tombstone_bytes()).unwrap(); |
| 631 | assert_eq!(m.version, CHECKPOINT_V2_VERSION); |
| 632 | assert_ne!(m.version, CHECKPOINT_VERSION); |
| 633 | // This binary refuses a tombstone whose checkpoint.v2 is missing. |
| 634 | let dir = temp_store_dir("a1-tombstone-alone"); |
| 635 | fs::write(dir.join("checkpoint.v1"), v1_tombstone_bytes()).unwrap(); |
| 636 | let r = SynapseStore::open( |
| 637 | &dir, |
| 638 | FsyncPolicy::EveryCommit, |
| 639 | STRICT, |
| 640 | StoreLimits::default(), |
| 641 | ); |
| 642 | assert_eq!( |
| 643 | r.err().map(|e| e.code), |
| 644 | Some(RefusalCode::CheckpointCorrupt) |
| 645 | ); |
| 646 | } |
| 647 | |
| 648 | fn fresh_case(policy: FsyncPolicy, flags: fn(&Path) -> Vec<u8>) { |
| 649 | let dir = temp_store_dir("a1-fresh"); |
| 650 | let key = SigningKey::from_bytes(&[0xF1; 32]); |
| 651 | let mut s = SynapseStore::open(&dir, policy, STRICT, StoreLimits::default()).unwrap(); |
| 652 | assert_eq!(s.record_codec(), RecordCodec::BinaryV2); |
| 653 | for i in 0..3u64 { |
| 654 | let (env, blobs) = make_signed_changeset( |
| 655 | &key, |
| 656 | &format!("fresh-{i}"), |
| 657 | &format!("f{i}.rs"), |
| 658 | format!("{i}").as_bytes(), |
| 659 | vec![], |
| 660 | 1, |
| 661 | ); |
| 662 | s.ingest_changeset(env, &blobs).unwrap(); |
| 663 | } |
| 664 | let f = flags(&dir); |
| 665 | assert_eq!(f, vec![WAL_FLAG_CODEC_V2; 3]); |
| 666 | s.checkpoint_and_compact(2).unwrap(); |
| 667 | let chain = s.checkpoint_chain().unwrap(); |
| 668 | assert_eq!(chain.v1_state_root, empty_state_root()); |
| 669 | assert_eq!(chain.prev_checkpoint_root, empty_state_root()); |
| 670 | let root = s.state_root_digest(None).unwrap(); |
| 671 | drop(s); |
| 672 | let s = SynapseStore::open(&dir, policy, STRICT, StoreLimits::default()).unwrap(); |
| 673 | assert_eq!(s.state_root_digest(None).unwrap(), root); |
| 674 | assert_eq!(s.committed_seq(), WalSeq(3)); |
| 675 | } |
| 676 | |
| 677 | #[test] |
| 678 | fn a1_fresh_store_writes_binary_frames_and_records_the_empty_v1_root() { |
| 679 | fresh_case(FsyncPolicy::EveryCommit, v1_flags); |
| 680 | fresh_case(FsyncPolicy::GROUP_COMMIT_DEFAULT, v2_flags); |
| 681 | } |
| 682 | |
| 683 | /// Append a correctly chained frame with `codec` to `wal.log`. |
| 684 | fn append_frame(dir: &Path, s: &SynapseStore, record: &WalRecord, codec: RecordCodec) { |
| 685 | let payload = encode_record_with(record, codec).unwrap(); |
| 686 | let (frame, _) = wal_frame_from_payload( |
| 687 | s.committed_seq().next(), |
| 688 | s.last_frame_sha256(), |
| 689 | record.kind_byte(), |
| 690 | codec.frame_flags(), |
| 691 | &payload, |
| 692 | ); |
| 693 | let mut f = OpenOptions::new() |
| 694 | .append(true) |
| 695 | .open(dir.join("wal.log")) |
| 696 | .unwrap(); |
| 697 | f.write_all(&frame).unwrap(); |
| 698 | } |
| 699 | |
| 700 | #[test] |
| 701 | fn a1_codec_never_goes_back_and_never_runs_ahead_of_the_migration() { |
| 702 | // A v1 JSON frame after binary frames is refused. |
| 703 | let dir = temp_store_dir("a1-downgrade"); |
| 704 | let key = SigningKey::from_bytes(&[0xD1; 32]); |
| 705 | let mut s = SynapseStore::open( |
| 706 | &dir, |
| 707 | FsyncPolicy::EveryCommit, |
| 708 | STRICT, |
| 709 | StoreLimits::default(), |
| 710 | ) |
| 711 | .unwrap(); |
| 712 | let (env, blobs) = make_signed_changeset(&key, "d", "d.rs", b"d", vec![], 1); |
| 713 | s.ingest_changeset(env, &blobs).unwrap(); |
| 714 | let lease = WalRecord::LeaseUpdated { |
| 715 | changeset_id: first_changeset(&s), |
| 716 | lease_expires_at_ms: 5, |
| 717 | }; |
| 718 | append_frame(&dir, &s, &lease, RecordCodec::JsonV1); |
| 719 | drop(s); |
| 720 | let r = SynapseStore::open( |
| 721 | &dir, |
| 722 | FsyncPolicy::EveryCommit, |
| 723 | STRICT, |
| 724 | StoreLimits::default(), |
| 725 | ); |
| 726 | assert_eq!( |
| 727 | r.err().map(|e| e.code), |
| 728 | Some(RefusalCode::WalVersionUnsupported) |
| 729 | ); |
| 730 | |
| 731 | // A binary frame in a v1 store before its migration checkpoint is refused. |
| 732 | let dir = copy_fixture("v1-wal-log"); |
| 733 | let s = SynapseStore::open( |
| 734 | &dir, |
| 735 | FsyncPolicy::EveryCommit, |
| 736 | STRICT, |
| 737 | StoreLimits::default(), |
| 738 | ) |
| 739 | .unwrap(); |
| 740 | let lease = WalRecord::LeaseUpdated { |
| 741 | changeset_id: first_changeset(&s), |
| 742 | lease_expires_at_ms: 5, |
| 743 | }; |
| 744 | append_frame(&dir, &s, &lease, RecordCodec::BinaryV2); |
| 745 | drop(s); |
| 746 | let r = SynapseStore::open( |
| 747 | &dir, |
| 748 | FsyncPolicy::EveryCommit, |
| 749 | STRICT, |
| 750 | StoreLimits::default(), |
| 751 | ); |
| 752 | assert_eq!( |
| 753 | r.err().map(|e| e.code), |
| 754 | Some(RefusalCode::WalVersionUnsupported) |
| 755 | ); |
| 756 | } |
| 757 | |
| 758 | #[test] |
| 759 | fn a1_damaged_checkpoint_v2_is_refused() { |
| 760 | let dir = temp_store_dir("a1-ckpt-damage"); |
| 761 | let key = SigningKey::from_bytes(&[0xC1; 32]); |
| 762 | { |
| 763 | let mut s = SynapseStore::open( |
| 764 | &dir, |
| 765 | FsyncPolicy::EveryCommit, |
| 766 | STRICT, |
| 767 | StoreLimits::default(), |
| 768 | ) |
| 769 | .unwrap(); |
| 770 | let (env, blobs) = make_signed_changeset(&key, "c", "c.rs", b"c", vec![], 1); |
| 771 | s.ingest_changeset(env, &blobs).unwrap(); |
| 772 | s.checkpoint_and_compact(2).unwrap(); |
| 773 | } |
| 774 | let path = dir.join(CHECKPOINT_V2_FILE); |
| 775 | let good = fs::read(&path).unwrap(); |
| 776 | for damaged in [ |
| 777 | { |
| 778 | let mut b = good.clone(); |
| 779 | let last = b.len() - 1; |
| 780 | b[last] ^= 0x01; |
| 781 | b |
| 782 | }, |
| 783 | { |
| 784 | let mut b = good.clone(); |
| 785 | b[20] ^= 0x80; |
| 786 | b |
| 787 | }, |
| 788 | good[..good.len() - 1].to_vec(), |
| 789 | good[..CHECKPOINT_V2_HEADER_LEN - 1].to_vec(), |
| 790 | ] { |
| 791 | fs::write(&path, &damaged).unwrap(); |
| 792 | for policy in [STRICT, RecoveryPolicy::TruncateTornTail] { |
| 793 | let r = SynapseStore::open( |
| 794 | &dir, |
| 795 | FsyncPolicy::EveryCommit, |
| 796 | policy, |
| 797 | StoreLimits::default(), |
| 798 | ); |
| 799 | assert_eq!( |
| 800 | r.err().map(|e| e.code), |
| 801 | Some(RefusalCode::CheckpointCorrupt) |
| 802 | ); |
| 803 | } |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | #[test] |
| 808 | fn a1_frame_length_cap_is_enforced_on_write_and_on_replay() { |
| 809 | let key = SigningKey::from_bytes(&[0xCA; 32]); |
| 810 | let small = StoreLimits { |
| 811 | max_wal_record_bytes: 64, |
| 812 | ..Default::default() |
| 813 | }; |
| 814 | // Writer: a record above the cap is refused and nothing is logged. |
| 815 | let dir = temp_store_dir("a1-cap-write"); |
| 816 | let mut s = SynapseStore::open(&dir, FsyncPolicy::EveryCommit, STRICT, small.clone()).unwrap(); |
| 817 | let (env, blobs) = make_signed_changeset(&key, "w", "w.rs", b"w", vec![], 1); |
| 818 | assert_eq!( |
| 819 | s.ingest_changeset(env, &blobs).unwrap_err().code, |
| 820 | RefusalCode::QuotaPayloadTooLarge |
| 821 | ); |
| 822 | assert_eq!(s.committed_seq(), WalSeq::ZERO); |
| 823 | assert_eq!(fs::read(dir.join("wal.log")).unwrap_or_default().len(), 0); |
| 824 | drop(s); |
| 825 | |
| 826 | // Replay: a frame declaring more than the cap is refused under both policies (never |
| 827 | // truncated away as a torn tail) before its payload is read. |
| 828 | let dir = temp_store_dir("a1-cap-replay"); |
| 829 | { |
| 830 | let mut s = SynapseStore::open( |
| 831 | &dir, |
| 832 | FsyncPolicy::EveryCommit, |
| 833 | STRICT, |
| 834 | StoreLimits::default(), |
| 835 | ) |
| 836 | .unwrap(); |
| 837 | let (env, blobs) = make_signed_changeset(&key, "r", "r.rs", b"r", vec![], 1); |
| 838 | s.ingest_changeset(env, &blobs).unwrap(); |
| 839 | } |
| 840 | for policy in [STRICT, RecoveryPolicy::TruncateTornTail] { |
| 841 | let r = SynapseStore::open(&dir, FsyncPolicy::EveryCommit, policy, small.clone()); |
| 842 | assert_eq!( |
| 843 | r.err().map(|e| e.code), |
| 844 | Some(RefusalCode::QuotaPayloadTooLarge) |
| 845 | ); |
| 846 | } |
| 847 | // The same log opens under the default cap. |
| 848 | assert!(SynapseStore::open( |
| 849 | &dir, |
| 850 | FsyncPolicy::EveryCommit, |
| 851 | STRICT, |
| 852 | StoreLimits::default() |
| 853 | ) |
| 854 | .is_ok()); |
| 855 | } |
| 856 | |
| 857 | #[test] |
| 858 | fn a1_record_prepared_before_the_migration_commits_in_the_new_codec() { |
| 859 | // Group commit prepares records outside the store lock; the migration checkpoint can |
| 860 | // land between prepare and commit. The record must then be written as binary v2 with |
| 861 | // its inline blob still readable after reopen. |
| 862 | let limits = StoreLimits { |
| 863 | wal_prealloc_bytes: 64 * 1024, |
| 864 | ..Default::default() |
| 865 | }; |
| 866 | let policy = FsyncPolicy::GROUP_COMMIT_DEFAULT; |
| 867 | let dir = copy_fixture("v1-wal-v2-log"); |
| 868 | let mut s = SynapseStore::open(&dir, policy, STRICT, limits.clone()).unwrap(); |
| 869 | assert_eq!(s.record_codec(), RecordCodec::JsonV1); |
| 870 | let key = SigningKey::from_bytes(&[0x5E; 32]); |
| 871 | let content = b"prepared before the migration checkpoint"; |
| 872 | let (env, blobs) = make_signed_changeset(&key, "late", "late.rs", content, vec![], 9); |
| 873 | let digest = blobs[0].0; |
| 874 | let prepared = |
| 875 | SynapseStore::prepare_ingest(&limits, env, &blobs, Some(RecordCodec::JsonV1)).unwrap(); |
| 876 | s.checkpoint_and_compact(10).unwrap(); |
| 877 | assert_eq!(s.record_codec(), RecordCodec::BinaryV2); |
| 878 | let IngestOutcome::Committed { wal_seq, .. } = s.ingest_prepared(prepared).unwrap() else { |
| 879 | panic!("expected a commit"); |
| 880 | }; |
| 881 | assert_eq!(v2_flags(&dir), vec![WAL_FLAG_CODEC_V2]); |
| 882 | assert_eq!( |
| 883 | s.get_blob_visible(digest, None, None).unwrap(), |
| 884 | content.to_vec() |
| 885 | ); |
| 886 | let root = s.state_root_digest(None).unwrap(); |
| 887 | drop(s); |
| 888 | let s = SynapseStore::open(&dir, policy, STRICT, limits).unwrap(); |
| 889 | assert_eq!(s.committed_seq(), wal_seq); |
| 890 | assert_eq!(s.state_root_digest(None).unwrap(), root); |
| 891 | assert_eq!( |
| 892 | s.get_blob_visible(digest, None, None).unwrap(), |
| 893 | content.to_vec() |
| 894 | ); |
| 895 | } |
| 896 | |
| 897 | /// Where a migration checkpoint of a main-written v1 store was interrupted. |
| 898 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 899 | enum Crash { |
| 900 | /// `checkpoint.v2` renamed into place; the tombstone and log compaction never ran |
| 901 | /// (`checkpoint.v1` is the stale v1 checkpoint, every v1 JSON frame is still logged). |
| 902 | BeforeTombstone, |
| 903 | /// `checkpoint.v2` and the tombstone written; log compaction never ran (the logs |
| 904 | /// still hold the v1 JSON frames the checkpoint covers). |
| 905 | BeforeCompaction, |
| 906 | /// Logs compacted, but `checkpoint.v1` is the stale v1 checkpoint (tombstone lost). |
| 907 | StaleV1Only, |
| 908 | } |
| 909 | |
| 910 | /// Build the on-disk state of `crash` from the main-written fixture `name`, reopen it, |
| 911 | /// and check it recovers the migrated state, rewrites the tombstone, accepts a new |
| 912 | /// binary commit after the v1 frames (a mixed log), and reopens again. |
| 913 | fn crash_case(name: &str, policy: FsyncPolicy, flags: fn(&Path) -> Vec<u8>, crash: Crash) { |
| 914 | let limits = StoreLimits { |
| 915 | wal_prealloc_bytes: 64 * 1024, |
| 916 | ..Default::default() |
| 917 | }; |
| 918 | let pre = copy_fixture(name); |
| 919 | let post = copy_fixture(name); |
| 920 | let (root, seq, chain) = { |
| 921 | let mut s = SynapseStore::open(&post, policy, STRICT, limits.clone()).unwrap(); |
| 922 | s.checkpoint_and_compact(2_000).unwrap(); |
| 923 | ( |
| 924 | s.state_root_digest(None).unwrap(), |
| 925 | s.committed_seq(), |
| 926 | s.checkpoint_chain().unwrap(), |
| 927 | ) |
| 928 | }; |
| 929 | let dir = match crash { |
| 930 | Crash::StaleV1Only => { |
| 931 | fs::copy(pre.join("checkpoint.v1"), post.join("checkpoint.v1")).unwrap(); |
| 932 | post.clone() |
| 933 | } |
| 934 | Crash::BeforeTombstone | Crash::BeforeCompaction => { |
| 935 | // Blob files and checkpoint.v2 were durable before the crash point. |
| 936 | copy_tree(&post.join("blobs"), &pre.join("blobs")); |
| 937 | fs::copy(post.join(CHECKPOINT_V2_FILE), pre.join(CHECKPOINT_V2_FILE)).unwrap(); |
| 938 | if crash == Crash::BeforeCompaction { |
| 939 | fs::copy(post.join("checkpoint.v1"), pre.join("checkpoint.v1")).unwrap(); |
| 940 | } |
| 941 | assert!( |
| 942 | flags(&pre).contains(&0), |
| 943 | "{name} {crash:?}: v1 JSON frames remain" |
| 944 | ); |
| 945 | pre.clone() |
| 946 | } |
| 947 | }; |
| 948 | |
| 949 | let mut s = SynapseStore::open(&dir, policy, STRICT, limits.clone()) |
| 950 | .unwrap_or_else(|e| panic!("{name} {crash:?}: reopen refused: {e:?}")); |
| 951 | assert_eq!(s.committed_seq(), seq, "{name} {crash:?}"); |
| 952 | assert_eq!(s.state_root_digest(None).unwrap(), root, "{name} {crash:?}"); |
| 953 | assert_eq!(s.checkpoint_chain(), Some(chain), "{name} {crash:?}"); |
| 954 | assert_eq!(s.record_codec(), RecordCodec::BinaryV2, "{name} {crash:?}"); |
| 955 | assert_eq!( |
| 956 | fs::read(dir.join("checkpoint.v1")).unwrap(), |
| 957 | v1_tombstone_bytes(), |
| 958 | "{name} {crash:?}: tombstone written on open" |
| 959 | ); |
| 960 | |
| 961 | let key = SigningKey::from_bytes(&[0xC7; 32]); |
| 962 | let (env, blobs) = make_signed_changeset(&key, "after-crash", "after.rs", b"after", vec![], 3); |
| 963 | let IngestOutcome::Committed { wal_seq, .. } = s.ingest_changeset(env, &blobs).unwrap() else { |
| 964 | panic!("{name} {crash:?}: expected a commit"); |
| 965 | }; |
| 966 | assert_eq!(wal_seq, seq.next()); |
| 967 | let f = flags(&dir); |
| 968 | assert_eq!(f.last(), Some(&WAL_FLAG_CODEC_V2), "{name} {crash:?}"); |
| 969 | if crash != Crash::StaleV1Only { |
| 970 | assert!(f.contains(&0), "{name} {crash:?}: mixed log"); |
| 971 | } |
| 972 | let root_after = s.state_root_digest(None).unwrap(); |
| 973 | drop(s); |
| 974 | let s = SynapseStore::open(&dir, policy, STRICT, limits) |
| 975 | .unwrap_or_else(|e| panic!("{name} {crash:?}: second reopen refused: {e:?}")); |
| 976 | assert_eq!(s.committed_seq(), wal_seq, "{name} {crash:?}"); |
| 977 | assert_eq!( |
| 978 | s.state_root_digest(None).unwrap(), |
| 979 | root_after, |
| 980 | "{name} {crash:?}" |
| 981 | ); |
| 982 | } |
| 983 | |
| 984 | #[test] |
| 985 | fn a1_crash_before_tombstone_recovers_wal_log() { |
| 986 | crash_case( |
| 987 | "v1-wal-log", |
| 988 | FsyncPolicy::EveryCommit, |
| 989 | v1_flags, |
| 990 | Crash::BeforeTombstone, |
| 991 | ); |
| 992 | } |
| 993 | |
| 994 | #[test] |
| 995 | fn a1_crash_before_tombstone_recovers_wal_v2_log() { |
| 996 | crash_case( |
| 997 | "v1-wal-v2-log", |
| 998 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 999 | v2_flags, |
| 1000 | Crash::BeforeTombstone, |
| 1001 | ); |
| 1002 | } |
| 1003 | |
| 1004 | #[test] |
| 1005 | fn a1_covered_json_frames_then_binary_frames_recover_wal_log() { |
| 1006 | crash_case( |
| 1007 | "v1-wal-log", |
| 1008 | FsyncPolicy::EveryCommit, |
| 1009 | v1_flags, |
| 1010 | Crash::BeforeCompaction, |
| 1011 | ); |
| 1012 | } |
| 1013 | |
| 1014 | #[test] |
| 1015 | fn a1_covered_json_frames_then_binary_frames_recover_wal_v2_log() { |
| 1016 | crash_case( |
| 1017 | "v1-wal-v2-log", |
| 1018 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 1019 | v2_flags, |
| 1020 | Crash::BeforeCompaction, |
| 1021 | ); |
| 1022 | } |
| 1023 | |
| 1024 | #[test] |
| 1025 | fn a1_stale_checkpoint_v1_beside_checkpoint_v2_recovers_wal_log() { |
| 1026 | crash_case( |
| 1027 | "v1-wal-log", |
| 1028 | FsyncPolicy::EveryCommit, |
| 1029 | v1_flags, |
| 1030 | Crash::StaleV1Only, |
| 1031 | ); |
| 1032 | } |
| 1033 | |
| 1034 | #[test] |
| 1035 | fn a1_v1_checkpoint_ahead_of_checkpoint_v2_is_refused() { |
| 1036 | // If a v1-only binary opened the store in the crash window and checkpointed it, its |
| 1037 | // checkpoint.v1 is ahead of checkpoint.v2: refused, never silently mixed. |
| 1038 | let dir = copy_fixture("v1-wal-log"); |
| 1039 | let stale = fs::read(dir.join("checkpoint.v1")).unwrap(); |
| 1040 | { |
| 1041 | let mut s = SynapseStore::open( |
| 1042 | &dir, |
| 1043 | FsyncPolicy::EveryCommit, |
| 1044 | STRICT, |
| 1045 | StoreLimits::default(), |
| 1046 | ) |
| 1047 | .unwrap(); |
| 1048 | s.checkpoint_and_compact(2_000).unwrap(); |
| 1049 | } |
| 1050 | let mut m: CheckpointManifest = serde_json::from_slice(&stale).unwrap(); |
| 1051 | m.checkpoint_seq = WalSeq(m.checkpoint_seq.0 + 100); |
| 1052 | fs::write(dir.join("checkpoint.v1"), serde_json::to_vec(&m).unwrap()).unwrap(); |
| 1053 | let r = SynapseStore::open( |
| 1054 | &dir, |
| 1055 | FsyncPolicy::EveryCommit, |
| 1056 | STRICT, |
| 1057 | StoreLimits::default(), |
| 1058 | ); |
| 1059 | assert_eq!( |
| 1060 | r.err().map(|e| e.code), |
| 1061 | Some(RefusalCode::CheckpointCorrupt) |
| 1062 | ); |
| 1063 | } |
| 1064 | |
| 1065 | #[test] |
| 1066 | fn a1_v1_records_appended_in_the_crash_window_are_refused() { |
| 1067 | // A v1-only binary that opens the store between the checkpoint.v2 rename and the |
| 1068 | // tombstone sees the old checkpoint.v1 and the JSON log, and may append JSON records |
| 1069 | // after the checkpoint's seq. Simulated by this build writing the pre-migration copy |
| 1070 | // (a v1-history store without checkpoint.v2 still writes JSON frames, as main does). |
| 1071 | // checkpoint.v2 makes the store binary, so the JSON record after it is refused. |
| 1072 | let limits = StoreLimits { |
| 1073 | wal_prealloc_bytes: 64 * 1024, |
| 1074 | ..Default::default() |
| 1075 | }; |
| 1076 | let policy = FsyncPolicy::EveryCommit; |
| 1077 | let pre = copy_fixture("v1-wal-log"); |
| 1078 | let post = copy_fixture("v1-wal-log"); |
| 1079 | { |
| 1080 | let mut s = SynapseStore::open(&post, policy, STRICT, limits.clone()).unwrap(); |
| 1081 | s.checkpoint_and_compact(2_000).unwrap(); |
| 1082 | } |
| 1083 | let key = SigningKey::from_bytes(&[0xC8; 32]); |
| 1084 | { |
| 1085 | let mut s = SynapseStore::open(&pre, policy, STRICT, limits.clone()).unwrap(); |
| 1086 | assert_eq!(s.record_codec(), RecordCodec::JsonV1); |
| 1087 | let (env, blobs) = make_signed_changeset(&key, "v1-window", "w.rs", b"w", vec![], 3); |
| 1088 | s.ingest_changeset(env, &blobs).unwrap(); |
| 1089 | } |
| 1090 | assert_eq!( |
| 1091 | v1_flags(&pre).last(), |
| 1092 | Some(&0), |
| 1093 | "JSON frame after the checkpoint seq" |
| 1094 | ); |
| 1095 | copy_tree(&post.join("blobs"), &pre.join("blobs")); |
| 1096 | fs::copy(post.join(CHECKPOINT_V2_FILE), pre.join(CHECKPOINT_V2_FILE)).unwrap(); |
| 1097 | let r = SynapseStore::open(&pre, policy, STRICT, limits); |
| 1098 | assert_eq!( |
| 1099 | r.err().map(|e| e.code), |
| 1100 | Some(RefusalCode::WalVersionUnsupported) |
| 1101 | ); |
| 1102 | } |