synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-store / src / group_tests.rs
| 1 | //! Group commit (WAL v2 and [`SharedStore`]) tests. |
| 2 | //! |
| 3 | //! Durability rule under test: blobs, directories and the WAL are synced before any |
| 4 | //! acknowledgment. In WAL v2 blobs live inside the batch, so the one `fdatasync` per |
| 5 | //! batch covers them. These tests never assert a speed-up; they check correctness only. |
| 6 | |
| 7 | use super::tests::{make_signed_changeset, temp_store_dir}; |
| 8 | use super::*; |
| 9 | use ed25519_dalek::SigningKey; |
| 10 | use std::collections::BTreeSet; |
| 11 | use std::process::Command; |
| 12 | use std::sync::{Barrier, Mutex}; |
| 13 | use std::time::Duration; |
| 14 | |
| 15 | fn group(max_batch_records: u32, max_batch_delay_us: u32) -> FsyncPolicy { |
| 16 | FsyncPolicy::GroupCommit { |
| 17 | max_batch_records, |
| 18 | max_batch_delay_us, |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | fn open_shared(dir: &Path, policy: FsyncPolicy) -> SharedStore { |
| 23 | SharedStore::open( |
| 24 | dir, |
| 25 | policy, |
| 26 | RecoveryPolicy::StrictFailClosed, |
| 27 | StoreLimits::default(), |
| 28 | ) |
| 29 | .unwrap() |
| 30 | } |
| 31 | |
| 32 | fn reopen(dir: &Path, policy: FsyncPolicy, recovery: RecoveryPolicy) -> SynapseStore { |
| 33 | SynapseStore::open(dir, policy, recovery, StoreLimits::default()).unwrap() |
| 34 | } |
| 35 | |
| 36 | /// A signed single-file changeset with a distinct key, path and content per label. |
| 37 | fn cs( |
| 38 | key: &SigningKey, |
| 39 | label: &str, |
| 40 | blob_len: usize, |
| 41 | ) -> (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>) { |
| 42 | let mut content = format!("// {label}\n").into_bytes(); |
| 43 | let mut x: u8 = label |
| 44 | .bytes() |
| 45 | .fold(7u8, |a, b| a.wrapping_mul(31).wrapping_add(b)); |
| 46 | while content.len() < blob_len { |
| 47 | x = x.wrapping_mul(13).wrapping_add(1); |
| 48 | content.push(b'a' + x % 26); |
| 49 | } |
| 50 | make_signed_changeset( |
| 51 | key, |
| 52 | label, |
| 53 | &format!("src/{label}.rs"), |
| 54 | &content, |
| 55 | vec![], |
| 56 | 1000, |
| 57 | ) |
| 58 | } |
| 59 | |
| 60 | fn committed_seq_of(out: &IngestOutcome) -> WalSeq { |
| 61 | match out { |
| 62 | IngestOutcome::Committed { |
| 63 | wal_seq, |
| 64 | durability, |
| 65 | .. |
| 66 | } => { |
| 67 | assert_eq!(*durability, DurabilityGuarantee::FsyncBeforeAck); |
| 68 | *wal_seq |
| 69 | } |
| 70 | other => panic!("expected Committed, got {other:?}"), |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// Every changeset and its blobs are readable at the latest snapshot. |
| 75 | fn assert_all_readable(store: &SynapseStore, expected: usize) { |
| 76 | let all = store.list_changesets(None, None, None).unwrap(); |
| 77 | assert_eq!(all.len(), expected, "changeset count"); |
| 78 | for c in &all { |
| 79 | for m in &c.envelope.mutations { |
| 80 | if let MutationOp::Upsert { |
| 81 | blob_digest, |
| 82 | size_bytes, |
| 83 | .. |
| 84 | } = &m.op |
| 85 | { |
| 86 | let bytes = store.get_blob_visible(*blob_digest, None, None).unwrap(); |
| 87 | assert_eq!(bytes.len() as u64, *size_bytes); |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | #[test] |
| 94 | fn test_crc32c_hardware_matches_portable() { |
| 95 | assert_eq!(crc32c_portable(b"123456789"), 0xe306_9283); |
| 96 | let mut data = vec![0u8; 70_000]; |
| 97 | let mut s: u64 = 0x9e37_79b9_7f4a_7c15; |
| 98 | for b in data.iter_mut() { |
| 99 | s ^= s << 13; |
| 100 | s ^= s >> 7; |
| 101 | s ^= s << 17; |
| 102 | *b = s as u8; |
| 103 | } |
| 104 | let mut sizes: Vec<usize> = (0..=1100).collect(); |
| 105 | sizes.extend([4095, 4096, 4097, 65_535, 65_536, 65_537]); |
| 106 | for &n in &sizes { |
| 107 | for start in [0usize, 1, 3, 7] { |
| 108 | let slice = &data[start..start + n]; |
| 109 | assert_eq!( |
| 110 | crc32c(slice), |
| 111 | crc32c_portable(slice), |
| 112 | "size {n} start {start}" |
| 113 | ); |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | #[test] |
| 119 | fn test_group_commit_roundtrip_reopen_and_legacy_policy_refusal() { |
| 120 | let dir = temp_store_dir("gc-roundtrip"); |
| 121 | let key = SigningKey::from_bytes(&[61u8; 32]); |
| 122 | let root; |
| 123 | { |
| 124 | let shared = open_shared(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT); |
| 125 | assert!(shared.read().is_wal_v2()); |
| 126 | for i in 1..=4u64 { |
| 127 | let (env, blobs) = cs(&key, &format!("rt-{i}"), 300); |
| 128 | assert_eq!( |
| 129 | committed_seq_of(&shared.submit(env, &blobs).unwrap()), |
| 130 | WalSeq(i) |
| 131 | ); |
| 132 | } |
| 133 | // The single-store path writes WAL v2 too. |
| 134 | let mut store = shared.into_inner(); |
| 135 | let (env, blobs) = cs(&key, "rt-5", 300); |
| 136 | let out = store.ingest_changeset(env.clone(), &blobs).unwrap(); |
| 137 | assert_eq!(committed_seq_of(&out), WalSeq(5)); |
| 138 | let dup = store.ingest_changeset(env, &blobs).unwrap(); |
| 139 | assert!( |
| 140 | matches!(dup, IngestOutcome::IdempotentDuplicate { wal_seq, .. } if wal_seq == WalSeq(5)) |
| 141 | ); |
| 142 | root = store.state_root_digest(None).unwrap(); |
| 143 | assert_all_readable(&store, 5); |
| 144 | } |
| 145 | let store = reopen( |
| 146 | &dir, |
| 147 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 148 | RecoveryPolicy::StrictFailClosed, |
| 149 | ); |
| 150 | assert_eq!(store.committed_seq(), WalSeq(5)); |
| 151 | assert_eq!(store.state_root_digest(None).unwrap(), root); |
| 152 | assert_all_readable(&store, 5); |
| 153 | drop(store); |
| 154 | |
| 155 | for legacy in [ |
| 156 | FsyncPolicy::EveryCommit, |
| 157 | FsyncPolicy::BatchWindow { max_records: 8 }, |
| 158 | ] { |
| 159 | let err = SynapseStore::open( |
| 160 | &dir, |
| 161 | legacy, |
| 162 | RecoveryPolicy::StrictFailClosed, |
| 163 | StoreLimits::default(), |
| 164 | ) |
| 165 | .err() |
| 166 | .expect("legacy policy must refuse a WAL v2 store"); |
| 167 | assert_eq!(err.code, RefusalCode::WalVersionUnsupported); |
| 168 | } |
| 169 | let _ = fs::remove_dir_all(&dir); |
| 170 | } |
| 171 | |
| 172 | #[test] |
| 173 | fn test_v1_store_upgrades_to_v2_with_continuous_chain() { |
| 174 | let dir = temp_store_dir("gc-upgrade"); |
| 175 | let key = SigningKey::from_bytes(&[62u8; 32]); |
| 176 | { |
| 177 | let mut v1 = reopen( |
| 178 | &dir, |
| 179 | FsyncPolicy::EveryCommit, |
| 180 | RecoveryPolicy::StrictFailClosed, |
| 181 | ); |
| 182 | for i in 1..=3u64 { |
| 183 | let (env, blobs) = cs(&key, &format!("up-{i}"), 200); |
| 184 | assert_eq!( |
| 185 | committed_seq_of(&v1.ingest_changeset(env, &blobs).unwrap()), |
| 186 | WalSeq(i) |
| 187 | ); |
| 188 | } |
| 189 | assert!(!v1.is_wal_v2()); |
| 190 | } |
| 191 | let root; |
| 192 | { |
| 193 | let shared = open_shared(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT); |
| 194 | assert!(shared.read().is_wal_v2()); |
| 195 | assert_eq!(shared.read().committed_seq(), WalSeq(3)); |
| 196 | let v1_tip = shared.read().last_frame_sha256(); |
| 197 | let (env, blobs) = cs(&key, "up-4", 200); |
| 198 | assert_eq!( |
| 199 | committed_seq_of(&shared.submit(env, &blobs).unwrap()), |
| 200 | WalSeq(4) |
| 201 | ); |
| 202 | assert_ne!(shared.read().last_frame_sha256(), v1_tip); |
| 203 | // A v2 changeset that reuses a v1 blob file (not provided again). |
| 204 | let (_, v1_blobs) = cs(&key, "up-1", 200); |
| 205 | let (mut env5, _) = cs(&key, "up-5", 200); |
| 206 | if let MutationOp::Upsert { |
| 207 | blob_digest, |
| 208 | size_bytes, |
| 209 | .. |
| 210 | } = &mut env5.mutations[0].op |
| 211 | { |
| 212 | *blob_digest = v1_blobs[0].0; |
| 213 | *size_bytes = v1_blobs[0].1.len() as u64; |
| 214 | } |
| 215 | env5.sign(&key); |
| 216 | assert_eq!( |
| 217 | committed_seq_of(&shared.submit(env5, &[]).unwrap()), |
| 218 | WalSeq(5) |
| 219 | ); |
| 220 | root = shared.read().state_root_digest(None).unwrap(); |
| 221 | } |
| 222 | // Reopen replays v1 frames, the marker, then v2 batches: same chain and state. |
| 223 | let store = reopen( |
| 224 | &dir, |
| 225 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 226 | RecoveryPolicy::StrictFailClosed, |
| 227 | ); |
| 228 | assert_eq!(store.committed_seq(), WalSeq(5)); |
| 229 | assert_eq!(store.state_root_digest(None).unwrap(), root); |
| 230 | assert_all_readable(&store, 5); |
| 231 | let _ = fs::remove_dir_all(&dir); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn test_concurrent_submitters_acks_unique_contiguous_and_durable_before_ack() { |
| 236 | const THREADS: usize = 16; |
| 237 | const PER_THREAD: usize = 8; |
| 238 | let dir = temp_store_dir("gc-concurrent"); |
| 239 | let shared = open_shared(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT); |
| 240 | let barrier = Barrier::new(THREADS); |
| 241 | // (acked seq, committed watermark observed right after the ack) |
| 242 | let acks: Mutex<Vec<(WalSeq, WalSeq)>> = Mutex::new(Vec::new()); |
| 243 | std::thread::scope(|s| { |
| 244 | for t in 0..THREADS { |
| 245 | let (shared, barrier, acks) = (&shared, &barrier, &acks); |
| 246 | s.spawn(move || { |
| 247 | let key = SigningKey::from_bytes(&[t as u8 + 100; 32]); |
| 248 | let work: Vec<_> = (0..PER_THREAD) |
| 249 | .map(|i| cs(&key, &format!("t{t}-{i}"), 256)) |
| 250 | .collect(); |
| 251 | barrier.wait(); |
| 252 | for (env, blobs) in work { |
| 253 | let seq = committed_seq_of(&shared.submit(env, &blobs).unwrap()); |
| 254 | let watermark = shared.read().committed_seq(); |
| 255 | acks.lock().unwrap().push((seq, watermark)); |
| 256 | } |
| 257 | }); |
| 258 | } |
| 259 | }); |
| 260 | let acks = acks.into_inner().unwrap(); |
| 261 | let total = (THREADS * PER_THREAD) as u64; |
| 262 | for (seq, watermark) in &acks { |
| 263 | assert!( |
| 264 | watermark >= seq, |
| 265 | "acknowledged {seq} while the durable watermark was {watermark}" |
| 266 | ); |
| 267 | } |
| 268 | let seqs: BTreeSet<u64> = acks.iter().map(|(s, _)| s.0).collect(); |
| 269 | assert_eq!(seqs.len() as u64, total, "acks are unique"); |
| 270 | assert_eq!( |
| 271 | seqs, |
| 272 | (1..=total).collect::<BTreeSet<_>>(), |
| 273 | "acks are contiguous" |
| 274 | ); |
| 275 | // Release order equals WAL order. |
| 276 | let released: Vec<u64> = shared.ack_log().iter().map(|s| s.0).collect(); |
| 277 | assert_eq!(released, (1..=total).collect::<Vec<_>>()); |
| 278 | let stats = shared.stats(); |
| 279 | assert_eq!(stats.records, total); |
| 280 | assert_eq!(stats.failed_batches, 0); |
| 281 | let root = shared.read().state_root_digest(None).unwrap(); |
| 282 | drop(shared); |
| 283 | |
| 284 | let store = reopen( |
| 285 | &dir, |
| 286 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 287 | RecoveryPolicy::StrictFailClosed, |
| 288 | ); |
| 289 | assert_eq!(store.committed_seq(), WalSeq(total)); |
| 290 | assert_eq!(store.state_root_digest(None).unwrap(), root); |
| 291 | assert_all_readable(&store, total as usize); |
| 292 | let _ = fs::remove_dir_all(&dir); |
| 293 | } |
| 294 | |
| 295 | #[test] |
| 296 | fn test_duplicate_idempotency_keys_inside_one_batch() { |
| 297 | let dir = temp_store_dir("gc-dup-batch"); |
| 298 | let key = SigningKey::from_bytes(&[63u8; 32]); |
| 299 | // The leader waits (up to 5 s) until all four submissions are queued: one batch. |
| 300 | let shared = open_shared(&dir, group(4, 5_000_000)); |
| 301 | let (same, same_blobs) = cs(&key, "dup", 128); |
| 302 | // Same idempotency key, different content: a different changeset id. |
| 303 | let (conflict, conflict_blobs) = |
| 304 | make_signed_changeset(&key, "dup", "src/other.rs", b"other\n", vec![], 1000); |
| 305 | let inputs = vec![ |
| 306 | (same.clone(), same_blobs.clone()), |
| 307 | (same.clone(), same_blobs.clone()), |
| 308 | (same, same_blobs), |
| 309 | (conflict, conflict_blobs), |
| 310 | ]; |
| 311 | let barrier = Barrier::new(inputs.len()); |
| 312 | let results: Vec<SynapseResult<IngestOutcome>> = std::thread::scope(|s| { |
| 313 | let handles: Vec<_> = inputs |
| 314 | .into_iter() |
| 315 | .map(|(env, blobs)| { |
| 316 | let (shared, barrier) = (&shared, &barrier); |
| 317 | s.spawn(move || { |
| 318 | barrier.wait(); |
| 319 | shared.submit(env, &blobs) |
| 320 | }) |
| 321 | }) |
| 322 | .collect(); |
| 323 | handles.into_iter().map(|h| h.join().unwrap()).collect() |
| 324 | }); |
| 325 | let committed: Vec<_> = results |
| 326 | .iter() |
| 327 | .filter(|r| matches!(r, Ok(IngestOutcome::Committed { .. }))) |
| 328 | .collect(); |
| 329 | assert_eq!(committed.len(), 1, "exactly one Committed: {results:?}"); |
| 330 | for r in &results { |
| 331 | match r { |
| 332 | Ok(IngestOutcome::Committed { wal_seq, .. }) |
| 333 | | Ok(IngestOutcome::IdempotentDuplicate { wal_seq, .. }) => { |
| 334 | assert_eq!(*wal_seq, WalSeq(1)) |
| 335 | } |
| 336 | Err(e) => assert_eq!(e.code, RefusalCode::IdempotencyKeyConflict), |
| 337 | } |
| 338 | } |
| 339 | let stats = shared.stats(); |
| 340 | assert_eq!((stats.batches, stats.records), (1, 1)); |
| 341 | drop(shared); |
| 342 | let store = reopen( |
| 343 | &dir, |
| 344 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 345 | RecoveryPolicy::StrictFailClosed, |
| 346 | ); |
| 347 | assert_eq!(store.committed_seq(), WalSeq(1)); |
| 348 | assert_all_readable(&store, 1); |
| 349 | let _ = fs::remove_dir_all(&dir); |
| 350 | } |
| 351 | |
| 352 | /// Inject `fault`, submit a batch of four concurrently, and check: no waiter acked, |
| 353 | /// nothing visible (also after reopen), the retry commits, exactly one copy after reopen. |
| 354 | fn failed_batch_case(label: &str, fault: FaultInjection) { |
| 355 | let dir = temp_store_dir(label); |
| 356 | let key = SigningKey::from_bytes(&[64u8; 32]); |
| 357 | let work: Vec<_> = (0..4) |
| 358 | .map(|i| cs(&key, &format!("{label}-{i}"), 700)) |
| 359 | .collect(); |
| 360 | { |
| 361 | let shared = open_shared(&dir, group(4, 5_000_000)); |
| 362 | let (env0, blobs0) = cs(&key, &format!("{label}-base"), 100); |
| 363 | let out0 = shared |
| 364 | .with_exclusive(|s| s.ingest_changeset(env0, &blobs0)) |
| 365 | .unwrap(); |
| 366 | assert_eq!(committed_seq_of(&out0), WalSeq(1)); |
| 367 | let root_before = shared.read().state_root_digest(None).unwrap(); |
| 368 | shared.with_exclusive(|s| s.set_fault_injection(fault)); |
| 369 | |
| 370 | let barrier = Barrier::new(work.len()); |
| 371 | let results: Vec<_> = std::thread::scope(|s| { |
| 372 | let handles: Vec<_> = work |
| 373 | .iter() |
| 374 | .map(|(env, blobs)| { |
| 375 | let (shared, barrier) = (&shared, &barrier); |
| 376 | s.spawn(move || { |
| 377 | barrier.wait(); |
| 378 | shared.submit(env.clone(), blobs) |
| 379 | }) |
| 380 | }) |
| 381 | .collect(); |
| 382 | handles.into_iter().map(|h| h.join().unwrap()).collect() |
| 383 | }); |
| 384 | for r in &results { |
| 385 | let e = r |
| 386 | .as_ref() |
| 387 | .expect_err("no waiter of a failed batch is acknowledged"); |
| 388 | assert_eq!(e.code, RefusalCode::IoFailure); |
| 389 | } |
| 390 | assert_eq!(shared.stats().failed_batches, 1); |
| 391 | assert_eq!(shared.read().committed_seq(), WalSeq(1)); |
| 392 | assert_eq!(shared.read().state_root_digest(None).unwrap(), root_before); |
| 393 | assert!(shared.read().poisoned().is_none()); |
| 394 | } |
| 395 | // Nothing of the failed batch survives a reopen. |
| 396 | { |
| 397 | let store = reopen( |
| 398 | &dir, |
| 399 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 400 | RecoveryPolicy::StrictFailClosed, |
| 401 | ); |
| 402 | assert_eq!( |
| 403 | store.committed_seq(), |
| 404 | WalSeq(1), |
| 405 | "failed batch visible after reopen" |
| 406 | ); |
| 407 | assert_all_readable(&store, 1); |
| 408 | } |
| 409 | // Retry succeeds; then a reopen shows exactly one copy of each. |
| 410 | { |
| 411 | let shared = open_shared(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT); |
| 412 | for (env, blobs) in &work { |
| 413 | committed_seq_of(&shared.submit(env.clone(), blobs).unwrap()); |
| 414 | } |
| 415 | for (env, blobs) in &work { |
| 416 | assert!(matches!( |
| 417 | shared.submit(env.clone(), blobs).unwrap(), |
| 418 | IngestOutcome::IdempotentDuplicate { .. } |
| 419 | )); |
| 420 | } |
| 421 | } |
| 422 | let store = reopen( |
| 423 | &dir, |
| 424 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 425 | RecoveryPolicy::StrictFailClosed, |
| 426 | ); |
| 427 | assert_eq!(store.committed_seq(), WalSeq(5)); |
| 428 | assert_all_readable(&store, 5); |
| 429 | let _ = fs::remove_dir_all(&dir); |
| 430 | } |
| 431 | |
| 432 | #[test] |
| 433 | fn test_injected_sync_failure_acks_nothing_and_retry_commits_once() { |
| 434 | failed_batch_case("gc-fail-sync", FaultInjection::FailNextBatchSync); |
| 435 | } |
| 436 | |
| 437 | #[test] |
| 438 | fn test_injected_write_failure_acks_nothing_and_retry_commits_once() { |
| 439 | failed_batch_case( |
| 440 | "gc-fail-write", |
| 441 | FaultInjection::FailNextBatchWrite { |
| 442 | bytes_written: 1500, |
| 443 | }, |
| 444 | ); |
| 445 | } |
| 446 | |
| 447 | #[test] |
| 448 | fn test_rollback_failure_poisons_store_until_reopen() { |
| 449 | let dir = temp_store_dir("gc-poison"); |
| 450 | let key = SigningKey::from_bytes(&[65u8; 32]); |
| 451 | let (env1, blobs1) = cs(&key, "poison-1", 100); |
| 452 | let (env2, blobs2) = cs(&key, "poison-2", 100); |
| 453 | { |
| 454 | let shared = open_shared(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT); |
| 455 | shared.with_exclusive(|s| { |
| 456 | s.set_fault_injection(FaultInjection::FailNextBatchSyncAndRollback) |
| 457 | }); |
| 458 | let e = shared.submit(env1.clone(), &blobs1).unwrap_err(); |
| 459 | assert_eq!(e.code, RefusalCode::IoFailure); |
| 460 | assert!(shared.read().poisoned().is_some()); |
| 461 | // Every later write is refused, including through the single-store path. |
| 462 | let e = shared.submit(env2.clone(), &blobs2).unwrap_err(); |
| 463 | assert_eq!(e.code, RefusalCode::IoFailure); |
| 464 | let mut store = shared.into_inner(); |
| 465 | assert_eq!( |
| 466 | store |
| 467 | .ingest_changeset(env2.clone(), &blobs2) |
| 468 | .unwrap_err() |
| 469 | .code, |
| 470 | RefusalCode::IoFailure |
| 471 | ); |
| 472 | assert_eq!( |
| 473 | store.checkpoint_and_compact(0).unwrap_err().code, |
| 474 | RefusalCode::IoFailure |
| 475 | ); |
| 476 | assert_eq!(store.committed_seq(), WalSeq::ZERO); |
| 477 | } |
| 478 | // Reopen recovers. The refusal was not proof of non-commit: the batch bytes reached the |
| 479 | // file (only the sync and the rollback "failed"), so after reopen the record is there, |
| 480 | // and the client's retry with the same idempotency key resolves to that one copy. |
| 481 | let shared = open_shared(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT); |
| 482 | assert!(shared.read().poisoned().is_none()); |
| 483 | assert_eq!(shared.read().committed_seq(), WalSeq(1)); |
| 484 | let r1 = shared.submit(env1, &blobs1).unwrap(); |
| 485 | assert!( |
| 486 | matches!(r1, IngestOutcome::IdempotentDuplicate { wal_seq, .. } if wal_seq == WalSeq(1)), |
| 487 | "retry after a refused-but-durable batch must be an idempotent duplicate: {r1:?}" |
| 488 | ); |
| 489 | assert_eq!( |
| 490 | committed_seq_of(&shared.submit(env2, &blobs2).unwrap()), |
| 491 | WalSeq(2) |
| 492 | ); |
| 493 | drop(shared); |
| 494 | let store = reopen( |
| 495 | &dir, |
| 496 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 497 | RecoveryPolicy::StrictFailClosed, |
| 498 | ); |
| 499 | assert_eq!(store.committed_seq(), WalSeq(2)); |
| 500 | assert_all_readable(&store, 2); |
| 501 | let _ = fs::remove_dir_all(&dir); |
| 502 | } |
| 503 | |
| 504 | #[test] |
| 505 | fn test_shutdown_drains_queued_submissions_and_refuses_new_ones() { |
| 506 | const THREADS: usize = 8; |
| 507 | let dir = temp_store_dir("gc-shutdown"); |
| 508 | // A long linger keeps submissions queued until shutdown releases the leader. |
| 509 | let shared = open_shared(&dir, group(64, 2_000_000)); |
| 510 | let barrier = Barrier::new(THREADS + 1); |
| 511 | let mut committed_at_shutdown = WalSeq::ZERO; |
| 512 | let results: Vec<SynapseResult<IngestOutcome>> = std::thread::scope(|s| { |
| 513 | let handles: Vec<_> = (0..THREADS) |
| 514 | .map(|t| { |
| 515 | let (shared, barrier) = (&shared, &barrier); |
| 516 | s.spawn(move || { |
| 517 | let key = SigningKey::from_bytes(&[t as u8 + 150; 32]); |
| 518 | let (env, blobs) = cs(&key, &format!("sd-{t}"), 64); |
| 519 | barrier.wait(); |
| 520 | shared.submit(env, &blobs) |
| 521 | }) |
| 522 | }) |
| 523 | .collect(); |
| 524 | barrier.wait(); |
| 525 | std::thread::sleep(Duration::from_millis(50)); |
| 526 | shared.shutdown(); |
| 527 | committed_at_shutdown = shared.read().committed_seq(); |
| 528 | handles.into_iter().map(|h| h.join().unwrap()).collect() |
| 529 | }); |
| 530 | let mut ok = 0u64; |
| 531 | for r in &results { |
| 532 | match r { |
| 533 | Ok(out) => { |
| 534 | committed_seq_of(out); |
| 535 | ok += 1; |
| 536 | } |
| 537 | Err(e) => assert_eq!(e.code, RefusalCode::BackpressureOverCapacity), |
| 538 | } |
| 539 | } |
| 540 | assert!(ok > 0, "queued submissions were committed"); |
| 541 | // Everything admitted was durable before shutdown() returned. |
| 542 | assert_eq!(committed_at_shutdown, WalSeq(ok)); |
| 543 | let key = SigningKey::from_bytes(&[66u8; 32]); |
| 544 | let (env, blobs) = cs(&key, "after-shutdown", 64); |
| 545 | assert_eq!( |
| 546 | shared.submit(env, &blobs).unwrap_err().code, |
| 547 | RefusalCode::BackpressureOverCapacity |
| 548 | ); |
| 549 | drop(shared); |
| 550 | let store = reopen( |
| 551 | &dir, |
| 552 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 553 | RecoveryPolicy::StrictFailClosed, |
| 554 | ); |
| 555 | assert_eq!(store.committed_seq(), WalSeq(ok)); |
| 556 | assert_all_readable(&store, ok as usize); |
| 557 | let _ = fs::remove_dir_all(&dir); |
| 558 | } |
| 559 | |
| 560 | const CRASH_CHILD_ENV: &str = "SYNAPSE_GC_CRASH_CHILD_DIR"; |
| 561 | const CRASH_BATCH: usize = 4; |
| 562 | |
| 563 | #[test] |
| 564 | fn test_subprocess_crash_mid_batch_no_lost_ack_no_phantom() { |
| 565 | if let Ok(child_dir) = std::env::var(CRASH_CHILD_ENV) { |
| 566 | let dir = PathBuf::from(child_dir); |
| 567 | let ack_file = dir.join("acks.txt"); |
| 568 | let key = SigningKey::from_bytes(&[67u8; 32]); |
| 569 | let shared = open_shared(&dir, group(CRASH_BATCH as u32, 5_000_000)); |
| 570 | let ack = |seq: WalSeq| { |
| 571 | let mut f = OpenOptions::new() |
| 572 | .create(true) |
| 573 | .append(true) |
| 574 | .open(&ack_file) |
| 575 | .unwrap(); |
| 576 | // One write per line: O_APPEND keeps concurrent lines whole. |
| 577 | f.write_all(format!("{}\n", seq.0).as_bytes()).unwrap(); |
| 578 | }; |
| 579 | // Phase 1 commits one acknowledged batch of four; phase 2 crashes mid-batch. |
| 580 | let acked: Vec<_> = (0..CRASH_BATCH) |
| 581 | .map(|i| cs(&key, &format!("acked-{i}"), 1500)) |
| 582 | .collect(); |
| 583 | let crash: Vec<_> = (0..CRASH_BATCH) |
| 584 | .map(|i| cs(&key, &format!("crash-{i}"), 1500)) |
| 585 | .collect(); |
| 586 | // Crash after the first frame of the batch is complete and the second is torn. |
| 587 | let lens: Vec<usize> = crash |
| 588 | .iter() |
| 589 | .map(|(env, blobs)| { |
| 590 | SynapseStore::prepare_ingest( |
| 591 | &StoreLimits::default(), |
| 592 | env.clone(), |
| 593 | blobs, |
| 594 | Some(RecordCodec::BinaryV2), |
| 595 | ) |
| 596 | .unwrap() |
| 597 | .encoded |
| 598 | .unwrap() |
| 599 | .payload |
| 600 | .len() |
| 601 | }) |
| 602 | .collect(); |
| 603 | let frame = |len: usize| WAL_HEADER_LEN + len; |
| 604 | let max = lens.iter().copied().max().unwrap(); |
| 605 | let min = lens.iter().copied().min().unwrap(); |
| 606 | let cut = wal2::WAL_V2_BATCH_HEADER_LEN + frame(max) + 100; |
| 607 | assert!(cut < wal2::WAL_V2_BATCH_HEADER_LEN + 2 * frame(min) - 600); |
| 608 | |
| 609 | for (n, phase) in [&acked, &crash].into_iter().enumerate() { |
| 610 | if n == 1 { |
| 611 | shared.with_exclusive(|s| { |
| 612 | s.set_fault_injection(FaultInjection::CrashMidBatchWrite { bytes_written: cut }) |
| 613 | }); |
| 614 | } |
| 615 | let barrier = Barrier::new(CRASH_BATCH); |
| 616 | std::thread::scope(|s| { |
| 617 | for (env, blobs) in phase.iter() { |
| 618 | let (shared, barrier, ack) = (&shared, &barrier, &ack); |
| 619 | s.spawn(move || { |
| 620 | barrier.wait(); |
| 621 | if let Ok(out) = shared.submit(env.clone(), blobs) { |
| 622 | ack(committed_seq_of(&out)); |
| 623 | } |
| 624 | }); |
| 625 | } |
| 626 | }); |
| 627 | } |
| 628 | // Unreachable when the fault fires. |
| 629 | std::process::exit(0); |
| 630 | } |
| 631 | |
| 632 | let dir = temp_store_dir("gc-subprocess-crash"); |
| 633 | let exe = std::env::current_exe().expect("test binary path"); |
| 634 | let status = Command::new(exe) |
| 635 | .arg("--exact") |
| 636 | .arg("group_tests::test_subprocess_crash_mid_batch_no_lost_ack_no_phantom") |
| 637 | .arg("--nocapture") |
| 638 | .env(CRASH_CHILD_ENV, &dir) |
| 639 | .status() |
| 640 | .expect("spawn child process"); |
| 641 | assert_eq!(status.code(), Some(FAULT_CRASH_EXIT_CODE)); |
| 642 | |
| 643 | let acked: BTreeSet<u64> = fs::read_to_string(dir.join("acks.txt")) |
| 644 | .unwrap_or_default() |
| 645 | .lines() |
| 646 | .map(|l| l.parse().unwrap()) |
| 647 | .collect(); |
| 648 | assert_eq!(acked, (1..=CRASH_BATCH as u64).collect::<BTreeSet<_>>()); |
| 649 | |
| 650 | // Strict recovery refuses the torn tail; truncating recovery drops it. |
| 651 | let strict = SynapseStore::open( |
| 652 | &dir, |
| 653 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 654 | RecoveryPolicy::StrictFailClosed, |
| 655 | StoreLimits::default(), |
| 656 | ); |
| 657 | match strict { |
| 658 | Ok(s) => panic!( |
| 659 | "strict recovery accepted the torn batch: committed_seq {} with {} acknowledged", |
| 660 | s.committed_seq(), |
| 661 | CRASH_BATCH |
| 662 | ), |
| 663 | Err(e) => assert_eq!(e.code, RefusalCode::WalTornFrame), |
| 664 | } |
| 665 | let store = reopen( |
| 666 | &dir, |
| 667 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 668 | RecoveryPolicy::TruncateTornTail, |
| 669 | ); |
| 670 | assert_eq!(store.torn_frames_truncated_on_open(), 1); |
| 671 | // No lost ack: every acknowledged record is there. No phantom: nothing else is. |
| 672 | assert_eq!(store.committed_seq(), WalSeq(CRASH_BATCH as u64)); |
| 673 | assert_all_readable(&store, CRASH_BATCH); |
| 674 | drop(store); |
| 675 | // The truncated store accepts new batches and reopens strictly. |
| 676 | { |
| 677 | let shared = open_shared(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT); |
| 678 | let key = SigningKey::from_bytes(&[68u8; 32]); |
| 679 | let (env, blobs) = cs(&key, "post-crash", 100); |
| 680 | assert_eq!( |
| 681 | committed_seq_of(&shared.submit(env, &blobs).unwrap()), |
| 682 | WalSeq(CRASH_BATCH as u64 + 1) |
| 683 | ); |
| 684 | } |
| 685 | let store = reopen( |
| 686 | &dir, |
| 687 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 688 | RecoveryPolicy::StrictFailClosed, |
| 689 | ); |
| 690 | assert_eq!(store.committed_seq(), WalSeq(CRASH_BATCH as u64 + 1)); |
| 691 | let _ = fs::remove_dir_all(&dir); |
| 692 | } |
| 693 | |
| 694 | // --------------------------------------------------------------------------- |
| 695 | // Review fixes: checkpoint crash window, torn-tail rule, atomic upgrade marker. |
| 696 | // --------------------------------------------------------------------------- |
| 697 | |
| 698 | fn read_file(dir: &Path, name: &str) -> Vec<u8> { |
| 699 | fs::read(dir.join(name)).unwrap() |
| 700 | } |
| 701 | |
| 702 | fn write_file(dir: &Path, name: &str, bytes: &[u8]) { |
| 703 | fs::write(dir.join(name), bytes).unwrap(); |
| 704 | } |
| 705 | |
| 706 | fn try_open( |
| 707 | dir: &Path, |
| 708 | policy: FsyncPolicy, |
| 709 | recovery: RecoveryPolicy, |
| 710 | ) -> SynapseResult<SynapseStore> { |
| 711 | SynapseStore::open(dir, policy, recovery, StoreLimits::default()) |
| 712 | } |
| 713 | |
| 714 | /// Crash after the checkpoint is renamed into place but before `wal.log` is replaced by |
| 715 | /// the marker. With the segment store (ADR 0003 A2) the checkpoint no longer empties the |
| 716 | /// segments: replay starts at the position its segment index names, and the index |
| 717 | /// vouches for the covered bytes before it. Reconstructed by putting the pre-checkpoint |
| 718 | /// `wal.log` back next to the new checkpoint. |
| 719 | #[test] |
| 720 | fn test_v2_checkpoint_crash_window_reopens_and_skips_covered_frames() { |
| 721 | let dir = temp_store_dir("gc-ckpt-window"); |
| 722 | let key = SigningKey::from_bytes(&[71u8; 32]); |
| 723 | let gc = FsyncPolicy::GROUP_COMMIT_DEFAULT; |
| 724 | let strict = RecoveryPolicy::StrictFailClosed; |
| 725 | { |
| 726 | let mut v1 = reopen(&dir, FsyncPolicy::EveryCommit, strict); |
| 727 | for i in 1..=2u64 { |
| 728 | let (env, blobs) = cs(&key, &format!("cw-{i}"), 300); |
| 729 | assert_eq!( |
| 730 | committed_seq_of(&v1.ingest_changeset(env, &blobs).unwrap()), |
| 731 | WalSeq(i) |
| 732 | ); |
| 733 | } |
| 734 | } |
| 735 | let (old_wal, old_v2, new_wal, root, covered_digest); |
| 736 | { |
| 737 | let mut store = reopen(&dir, gc, strict); |
| 738 | for i in 3..=5u64 { |
| 739 | let (env, blobs) = cs(&key, &format!("cw-{i}"), 300); |
| 740 | assert_eq!( |
| 741 | committed_seq_of(&store.ingest_changeset(env, &blobs).unwrap()), |
| 742 | WalSeq(i) |
| 743 | ); |
| 744 | } |
| 745 | old_wal = read_file(&dir, "wal.log"); |
| 746 | old_v2 = read_file(&dir, wal2::WAL_V2_FILE); |
| 747 | root = store.state_root_digest(None).unwrap(); |
| 748 | let report = store.checkpoint_and_compact(1000).unwrap(); |
| 749 | assert_eq!(report.checkpoint_seq, WalSeq(5)); |
| 750 | new_wal = read_file(&dir, "wal.log"); |
| 751 | } |
| 752 | // The checkpoint keeps the segment bytes (no reset, no blob files). |
| 753 | let new_v2 = read_file(&dir, wal2::WAL_V2_FILE); |
| 754 | assert_eq!( |
| 755 | new_v2[..old_v2.len()], |
| 756 | old_v2[..], |
| 757 | "segment 1 is kept whole" |
| 758 | ); |
| 759 | |
| 760 | // Window 1: checkpoint renamed, wal.log not yet replaced by the marker. |
| 761 | // Window 2: wal.log replaced by the marker (the state after the checkpoint). |
| 762 | for (label, wal_bytes) in [ |
| 763 | ("before marker replace", &old_wal), |
| 764 | ("after marker replace", &new_wal), |
| 765 | ] { |
| 766 | write_file(&dir, "wal.log", wal_bytes); |
| 767 | let store = try_open(&dir, gc, strict).unwrap_or_else(|e| { |
| 768 | panic!("{label}: store must reopen after a checkpoint crash: {e:?}") |
| 769 | }); |
| 770 | assert_eq!(store.committed_seq(), WalSeq(5), "{label}"); |
| 771 | assert_eq!(store.state_root_digest(None).unwrap(), root, "{label}"); |
| 772 | assert_all_readable(&store, 5); |
| 773 | } |
| 774 | |
| 775 | // New commits land after the covered batches; the next reopen applies only them. |
| 776 | { |
| 777 | let mut store = reopen(&dir, gc, strict); |
| 778 | let (env, blobs) = cs(&key, "cw-6", 300); |
| 779 | assert_eq!( |
| 780 | committed_seq_of(&store.ingest_changeset(env, &blobs).unwrap()), |
| 781 | WalSeq(6) |
| 782 | ); |
| 783 | } |
| 784 | let store = reopen(&dir, gc, strict); |
| 785 | assert_eq!(store.committed_seq(), WalSeq(6)); |
| 786 | assert_all_readable(&store, 6); |
| 787 | drop(store); |
| 788 | |
| 789 | // Negative control: covered bytes are not trusted on read. Damage one byte of the |
| 790 | // inline blob of the first covered batch: the store opens (replay starts after the |
| 791 | // checkpoint) but reading that blob is refused. |
| 792 | let good_v2 = read_file(&dir, wal2::WAL_V2_FILE); |
| 793 | let mut bad = good_v2.clone(); |
| 794 | let p = wal2::WAL_V2_BATCH_HEADER_LEN + WAL_HEADER_LEN; |
| 795 | let meta_len = u32::from_le_bytes(bad[p..p + 4].try_into().unwrap()) as usize; |
| 796 | let d_at = p + 4 + meta_len + 4; |
| 797 | covered_digest = BlobDigest(bad[d_at..d_at + 32].try_into().unwrap()); |
| 798 | bad[d_at + 36 + 7] ^= 0x01; |
| 799 | write_file(&dir, wal2::WAL_V2_FILE, &bad); |
| 800 | let store = try_open(&dir, gc, strict).unwrap(); |
| 801 | assert_eq!( |
| 802 | store |
| 803 | .get_blob_visible(covered_digest, None, None) |
| 804 | .unwrap_err() |
| 805 | .code, |
| 806 | RefusalCode::BlobDigestMismatch, |
| 807 | "damaged covered blob must be refused on read" |
| 808 | ); |
| 809 | drop(store); |
| 810 | write_file(&dir, wal2::WAL_V2_FILE, &good_v2); |
| 811 | // Negative control: without the segment index bound to the checkpoint on disk the |
| 812 | // store refuses to open (it cannot know where replay starts). |
| 813 | let index_name = segment::SegmentIndex::file_name(&segment::checkpoint_binding(&dir).unwrap()); |
| 814 | let index = read_file(&dir, &index_name); |
| 815 | fs::remove_file(dir.join(&index_name)).unwrap(); |
| 816 | let err = try_open(&dir, gc, strict) |
| 817 | .err() |
| 818 | .expect("missing segment index must be refused"); |
| 819 | assert_eq!(err.code, RefusalCode::CheckpointCorrupt, "{err:?}"); |
| 820 | write_file(&dir, &index_name, &index); |
| 821 | assert_eq!( |
| 822 | try_open(&dir, gc, strict).unwrap().committed_seq(), |
| 823 | WalSeq(6) |
| 824 | ); |
| 825 | let _ = fs::remove_dir_all(&dir); |
| 826 | } |
| 827 | |
| 828 | /// Same crash window for a v1 store: checkpoint renamed, `wal.log` not yet truncated. |
| 829 | #[test] |
| 830 | fn test_v1_checkpoint_crash_window_reopens_and_skips_covered_frames() { |
| 831 | let dir = temp_store_dir("v1-ckpt-window"); |
| 832 | let key = SigningKey::from_bytes(&[72u8; 32]); |
| 833 | let strict = RecoveryPolicy::StrictFailClosed; |
| 834 | let (old_wal, root); |
| 835 | { |
| 836 | let mut store = reopen(&dir, FsyncPolicy::EveryCommit, strict); |
| 837 | for i in 1..=3u64 { |
| 838 | let (env, blobs) = cs(&key, &format!("v1cw-{i}"), 300); |
| 839 | assert_eq!( |
| 840 | committed_seq_of(&store.ingest_changeset(env, &blobs).unwrap()), |
| 841 | WalSeq(i) |
| 842 | ); |
| 843 | } |
| 844 | old_wal = read_file(&dir, "wal.log"); |
| 845 | root = store.state_root_digest(None).unwrap(); |
| 846 | store.checkpoint_and_compact(1000).unwrap(); |
| 847 | } |
| 848 | write_file(&dir, "wal.log", &old_wal); |
| 849 | { |
| 850 | let mut store = try_open(&dir, FsyncPolicy::EveryCommit, strict) |
| 851 | .unwrap_or_else(|e| panic!("v1 store must reopen after a checkpoint crash: {e:?}")); |
| 852 | assert_eq!(store.committed_seq(), WalSeq(3)); |
| 853 | assert_eq!(store.state_root_digest(None).unwrap(), root); |
| 854 | assert_all_readable(&store, 3); |
| 855 | let (env, blobs) = cs(&key, "v1cw-4", 300); |
| 856 | assert_eq!( |
| 857 | committed_seq_of(&store.ingest_changeset(env, &blobs).unwrap()), |
| 858 | WalSeq(4) |
| 859 | ); |
| 860 | } |
| 861 | let store = reopen(&dir, FsyncPolicy::EveryCommit, strict); |
| 862 | assert_eq!(store.committed_seq(), WalSeq(4)); |
| 863 | assert_all_readable(&store, 4); |
| 864 | drop(store); |
| 865 | // Negative control: a damaged covered frame is refused. |
| 866 | let mut bad = old_wal.clone(); |
| 867 | bad[WAL_HEADER_LEN + 10] ^= 0x01; |
| 868 | write_file(&dir, "wal.log", &bad); |
| 869 | assert!(try_open(&dir, FsyncPolicy::EveryCommit, strict).is_err()); |
| 870 | let _ = fs::remove_dir_all(&dir); |
| 871 | } |
| 872 | |
| 873 | /// (offset, declared end) of the WAL v2 batch at `off`. |
| 874 | fn batch_extent(v2: &[u8], off: usize) -> (usize, usize) { |
| 875 | let (_, body, _) = wal2::parse_batch_header(&v2[off..off + wal2::WAL_V2_BATCH_HEADER_LEN]) |
| 876 | .expect("valid batch header"); |
| 877 | (off, off + wal2::WAL_V2_BATCH_HEADER_LEN + body as usize) |
| 878 | } |
| 879 | |
| 880 | /// Commit one base record and one record with a content of `blob_len` bytes; return the |
| 881 | /// second batch's extent. |
| 882 | fn two_batches(dir: &Path, key: &SigningKey, label: &str, content: &[u8]) -> (usize, usize) { |
| 883 | let mut store = reopen( |
| 884 | dir, |
| 885 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 886 | RecoveryPolicy::StrictFailClosed, |
| 887 | ); |
| 888 | let (env, blobs) = cs(key, &format!("{label}-base"), 100); |
| 889 | store.ingest_changeset(env, &blobs).unwrap(); |
| 890 | let (env, blobs) = make_signed_changeset( |
| 891 | key, |
| 892 | label, |
| 893 | &format!("src/{label}.bin"), |
| 894 | content, |
| 895 | vec![], |
| 896 | 1000, |
| 897 | ); |
| 898 | assert_eq!( |
| 899 | committed_seq_of(&store.ingest_changeset(env, &blobs).unwrap()), |
| 900 | WalSeq(2) |
| 901 | ); |
| 902 | drop(store); |
| 903 | let v2 = read_file(dir, wal2::WAL_V2_FILE); |
| 904 | let (_, first_end) = batch_extent(&v2, 0); |
| 905 | batch_extent(&v2, wal2::align_up(first_end as u64) as usize) |
| 906 | } |
| 907 | |
| 908 | fn letters(n: usize) -> Vec<u8> { |
| 909 | (0..n).map(|i| b'a' + (i * 7 % 26) as u8).collect() |
| 910 | } |
| 911 | |
| 912 | /// A torn last batch whose lost final sector holds fewer than 64 bytes of the batch is |
| 913 | /// still recognised as torn: strict open refuses it, `TruncateTornTail` drops it. |
| 914 | #[test] |
| 915 | fn test_torn_last_sector_with_short_tail_is_truncatable() { |
| 916 | let key = SigningKey::from_bytes(&[73u8; 32]); |
| 917 | // Search a content length that leaves 9 to 63 bytes of the batch (more than the |
| 918 | // trailer, less than 64) in its last 512-byte sector (the encoded size is not exactly linear in the content length). |
| 919 | let mut len: i64 = 2000; |
| 920 | let mut found = None; |
| 921 | for attempt in 0..16 { |
| 922 | let dir = temp_store_dir(&format!("gc-short-tail-{attempt}")); |
| 923 | let (start, end) = two_batches(&dir, &key, "short-tail", &letters(len as usize)); |
| 924 | let tail = (end % wal2::WAL_V2_SECTOR) as i64; |
| 925 | if (9..=63).contains(&tail) { |
| 926 | found = Some((dir, start, end)); |
| 927 | break; |
| 928 | } |
| 929 | let _ = fs::remove_dir_all(&dir); |
| 930 | let mut diff = (36 - tail).rem_euclid(512); |
| 931 | if diff > 256 { |
| 932 | diff -= 512; |
| 933 | } |
| 934 | len += diff.signum() * (diff.abs() * 7 / 8).max(1); |
| 935 | } |
| 936 | let (dir, start, end) = |
| 937 | found.expect("test setup: no content length ends 9 to 63 bytes into a sector"); |
| 938 | let tail = end % wal2::WAL_V2_SECTOR; |
| 939 | let last_sector = end - tail; |
| 940 | assert!(last_sector > start); |
| 941 | // The last sector never reached the disk. |
| 942 | let mut v2 = read_file(&dir, wal2::WAL_V2_FILE); |
| 943 | v2[last_sector..end].fill(0); |
| 944 | write_file(&dir, wal2::WAL_V2_FILE, &v2); |
| 945 | |
| 946 | let err = try_open( |
| 947 | &dir, |
| 948 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 949 | RecoveryPolicy::StrictFailClosed, |
| 950 | ) |
| 951 | .err() |
| 952 | .expect("strict open must refuse a torn tail"); |
| 953 | assert_eq!(err.code, RefusalCode::WalTornFrame, "{err:?}"); |
| 954 | let store = try_open( |
| 955 | &dir, |
| 956 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 957 | RecoveryPolicy::TruncateTornTail, |
| 958 | ) |
| 959 | .unwrap_or_else(|e| panic!("TruncateTornTail must drop the torn last batch: {e:?}")); |
| 960 | assert_eq!(store.committed_seq(), WalSeq(1)); |
| 961 | drop(store); |
| 962 | let store = reopen( |
| 963 | &dir, |
| 964 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 965 | RecoveryPolicy::StrictFailClosed, |
| 966 | ); |
| 967 | assert_eq!(store.committed_seq(), WalSeq(1)); |
| 968 | let _ = fs::remove_dir_all(&dir); |
| 969 | } |
| 970 | |
| 971 | /// Bit rot in an acknowledged last batch whose blob holds a whole zero sector is not a |
| 972 | /// torn write: both policies refuse to open and nothing is dropped. |
| 973 | #[test] |
| 974 | fn test_corrupt_last_batch_with_zero_sector_in_blob_is_not_dropped() { |
| 975 | let key = SigningKey::from_bytes(&[74u8; 32]); |
| 976 | let dir = temp_store_dir("gc-rot-zero-run"); |
| 977 | let mut content = b"// zero run\n".to_vec(); |
| 978 | content.extend(std::iter::repeat_n(0u8, 2048)); |
| 979 | content.extend_from_slice(b"ROTMARK"); |
| 980 | content.extend(letters(600)); |
| 981 | let (start, end) = two_batches(&dir, &key, "rot", &content); |
| 982 | let mut v2 = read_file(&dir, wal2::WAL_V2_FILE); |
| 983 | // The acknowledged batch contains an aligned all-zero sector (blob content). |
| 984 | assert!(v2[start..end] |
| 985 | .chunks(wal2::WAL_V2_SECTOR) |
| 986 | .any(|s| s.len() == wal2::WAL_V2_SECTOR && s.iter().all(|b| *b == 0))); |
| 987 | let at = start |
| 988 | + v2[start..end] |
| 989 | .windows(7) |
| 990 | .position(|w| w == b"ROTMARK") |
| 991 | .expect("blob bytes are inline in the batch"); |
| 992 | v2[at] ^= 0x04; // one flipped bit |
| 993 | write_file(&dir, wal2::WAL_V2_FILE, &v2); |
| 994 | |
| 995 | for recovery in [ |
| 996 | RecoveryPolicy::StrictFailClosed, |
| 997 | RecoveryPolicy::TruncateTornTail, |
| 998 | ] { |
| 999 | let err = try_open(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT, recovery) |
| 1000 | .err() |
| 1001 | .unwrap_or_else(|| panic!("{recovery:?} must refuse a corrupt acknowledged batch")); |
| 1002 | assert_ne!(err.code, RefusalCode::WalTornFrame, "{recovery:?}: {err:?}"); |
| 1003 | } |
| 1004 | assert_eq!( |
| 1005 | read_file(&dir, wal2::WAL_V2_FILE), |
| 1006 | v2, |
| 1007 | "nothing was truncated" |
| 1008 | ); |
| 1009 | let _ = fs::remove_dir_all(&dir); |
| 1010 | } |
| 1011 | |
| 1012 | /// The v1 to v2 upgrade replaces `wal.log` atomically: a crash while the new file is |
| 1013 | /// being written leaves only a stray temp file, and both the old v1 store and a later |
| 1014 | /// upgrade open cleanly. |
| 1015 | #[test] |
| 1016 | fn test_v2_upgrade_marker_is_atomic_and_survives_a_stray_temp_file() { |
| 1017 | let dir = temp_store_dir("gc-upgrade-atomic"); |
| 1018 | let key = SigningKey::from_bytes(&[75u8; 32]); |
| 1019 | let strict = RecoveryPolicy::StrictFailClosed; |
| 1020 | let root; |
| 1021 | { |
| 1022 | let mut v1 = reopen(&dir, FsyncPolicy::EveryCommit, strict); |
| 1023 | for i in 1..=2u64 { |
| 1024 | let (env, blobs) = cs(&key, &format!("ua-{i}"), 200); |
| 1025 | assert_eq!( |
| 1026 | committed_seq_of(&v1.ingest_changeset(env, &blobs).unwrap()), |
| 1027 | WalSeq(i) |
| 1028 | ); |
| 1029 | } |
| 1030 | root = v1.state_root_digest(None).unwrap(); |
| 1031 | } |
| 1032 | let v1_wal = read_file(&dir, "wal.log"); |
| 1033 | // Crash mid-upgrade: a partial copy with half a marker sits next to the old log. |
| 1034 | let mut partial = v1_wal.clone(); |
| 1035 | partial.extend_from_slice(&[0x53u8; 40]); |
| 1036 | write_file(&dir, "wal.log.tmp", &partial); |
| 1037 | { |
| 1038 | let store = reopen(&dir, FsyncPolicy::EveryCommit, strict); |
| 1039 | assert_eq!(store.committed_seq(), WalSeq(2)); |
| 1040 | assert!(!store.is_wal_v2()); |
| 1041 | } |
| 1042 | assert_eq!(read_file(&dir, "wal.log"), v1_wal); |
| 1043 | { |
| 1044 | let store = reopen(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT, strict); |
| 1045 | assert!(store.is_wal_v2()); |
| 1046 | assert_eq!(store.committed_seq(), WalSeq(2)); |
| 1047 | assert_eq!(store.state_root_digest(None).unwrap(), root); |
| 1048 | } |
| 1049 | assert!(!dir.join("wal.log.tmp").exists()); |
| 1050 | let upgraded = read_file(&dir, "wal.log"); |
| 1051 | assert_eq!(upgraded.len(), v1_wal.len() + WAL_HEADER_LEN); |
| 1052 | assert_eq!(&upgraded[..v1_wal.len()], &v1_wal[..]); |
| 1053 | let store = reopen(&dir, FsyncPolicy::GROUP_COMMIT_DEFAULT, strict); |
| 1054 | assert_eq!(store.committed_seq(), WalSeq(2)); |
| 1055 | assert_all_readable(&store, 2); |
| 1056 | let _ = fs::remove_dir_all(&dir); |
| 1057 | } |