Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-store/src/blockdev/repair.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-store / src / blockdev / repair.rs` 1070 lines ยท 39886 bytes Raw Blame History 1 //! R1 store repair after a `CheckpointCorrupt` refusal (issue #105, follow-up to #103). 2 //! 3 //! When the newest superblock copy is damaged, mount refuses with `CheckpointCorrupt` 4 //! because the older copy would silently drop batches acknowledged after it. This module 5 //! gives the operator what the refusal lacks: 6 //! 7 //! * [`diagnose`] reads both superblock copies (read-only, no write of any kind) and says 8 //! which copy is damaged, which checkpoint the older copy holds, the exact device byte 9 //! range of the acknowledged data past it, and the WAL v2 batches found there (first 10 //! sequence number and record count, from a scan of the batch headers). It also lists 11 //! the signed repair history already on the device. 12 //! * [`repair`] writes only for the [`RepairAction`] the caller names: 13 //! - [`RepairAction::RollForward`] commits the slot past the older checkpoint, so every 14 //! acknowledged batch in it is kept byte for byte. The damaged commit can only have 15 //! been the rotation that raised the segment count (a metadata commit never puts 16 //! data in the next slot), so the repair rewrites exactly that commit. 17 //! - [`RepairAction::AdoptOlderCheckpoint`] keeps the older checkpoint and zeroes the 18 //! reported range, recording what was dropped. 19 //! 20 //! Before its first device write it saves every byte range it will overwrite to a new 21 //! backup file and syncs it ([`read_backup`] reads it back). The repair is one ordinary 22 //! metadata commit into the damaged copy's position: a new namespace that appends a 23 //! signed [`RepairEntry`] to the `repair.log` object, and the superblock that points at 24 //! it. Adopt writes that record before it zeroes anything, so a crash in between leaves 25 //! the record and a store that still refuses; running the same action again finishes 26 //! the zeroing without a second record. 27 //! * The repair log is append-only and hash-chained (each entry names the SHA-256 of the 28 //! one before it) and every entry carries the operator's Ed25519 signature. Mount 29 //! verifies the whole log and refuses a store whose log does not verify; 30 //! [`BlockDevice::repair_log`] returns it, so replay can show that a repair happened, 31 //! who signed it and which range it covered. 32 //! 33 //! Limit: the signature attributes an entry to a key; it does not stop someone with write 34 //! access to the device from replacing the whole log with one signed by another key. 35 //! Which operator keys to trust is not decided here. 36 37 use super::*; 38 use `ed25519`_dalek::{Signature, Signer, SigningKey, VerifyingKey}; 39 40 /// Named object holding the signed repair log. 41 pub const REPAIR_LOG_NAME: &str = "repair.log"; 42 /// Domain tag of the operator's signature over a repair entry. 43 pub const DOMAIN_R1_REPAIR_SIGN_V1: &[u8] = b"SYNAPSE_R1_REPAIR_SIGN_V1\0"; 44 /// Domain tag of the digest that chains repair entries. 45 pub const DOMAIN_R1_REPAIR_ENTRY_V1: &[u8] = b"SYNAPSE_R1_REPAIR_ENTRY_V1\0"; 46 const ENTRY_MAGIC: [u8; 4] = *b"SRP1"; 47 const ENTRY_VERSION: u16 = 1; 48 49 /// State of one superblock copy. 50 #[derive(Debug, Clone, PartialEq, Eq)] 51 pub enum CopyState { 52 /// All 4 KiB are zero. 53 Blank, 54 /// A valid superblock whose metadata region matches its digest. 55 Intact { 56 generation: u64, 57 segment_count: u64, 58 meta_slot: u8, 59 }, 60 /// A valid superblock whose metadata region does not match its digest. 61 MetaDamaged { generation: u64, segment_count: u64 }, 62 /// Not a valid superblock (the reason names the first failed check). 63 Damaged(String), 64 } 65 66 /// One superblock copy: index 0 or 1, at byte `copy * 4096`. 67 #[derive(Debug, Clone, PartialEq, Eq)] 68 pub struct CopyReport { 69 pub copy: u8, 70 pub state: CopyState, 71 } 72 73 /// One WAL v2 batch whose header was found in a slot past the checkpoint. 74 #[derive(Debug, Clone, PartialEq, Eq)] 75 pub struct LostBatch { 76 /// Device byte offset of the batch header. 77 pub offset: u64, 78 /// Sequence number of the batch's first record. 79 pub first_seq: u64, 80 /// Records in the batch. 81 pub records: u32, 82 } 83 84 /// Acknowledged data in a slot past the checkpoint the older copy holds. 85 #[derive(Debug, Clone, PartialEq, Eq)] 86 pub struct LostRange { 87 /// Segment slot id. 88 pub slot: u64, 89 /// Device byte offset of the first and one past the last non-zero byte. 90 pub start: u64, 91 pub end: u64, 92 /// Number of non-zero bytes in the slot. 93 pub nonzero_bytes: u64, 94 /// Batches found by walking the batch headers from the start of the slot. 95 pub batches: Vec, 96 } 97 98 impl LostRange { 99 /// Records in [`Self::batches`]. 100 pub fn records(&self) -> u64 { 101 self.batches.iter().map(|b| u64::from(b.records)).sum() 102 } 103 } 104 105 /// What the diagnosis concludes. 106 #[derive(Debug, Clone, PartialEq, Eq)] 107 pub enum Verdict { 108 /// The store opens as it is; nothing to repair. 109 Healthy, 110 /// A superblock copy is unusable but the other one loses no acknowledged data. 111 OneCopyDamagedNothingLost, 112 /// Adopting the older checkpoint drops the listed ranges. 113 OlderCheckpointLosesRange, 114 /// No usable checkpoint (or contradictory geometry, or a repair log that does not 115 /// verify): this tool cannot repair it. 116 Unrepairable(String), 117 } 118 119 /// Result of [`diagnose`]. 120 #[derive(Debug, Clone, PartialEq, Eq)] 121 pub struct RepairReport { 122 pub device_uuid: Option<[u8; 16]>, 123 pub copies: [CopyReport; 2], 124 /// Copy and generation of the checkpoint in force (the newest intact copy). 125 pub adopt: Option<(u8, u64)>, 126 pub segment_count: u64, 127 pub lost: Vec, 128 /// Signed repair entries already on the device, oldest first. 129 pub history: Vec, 130 pub verdict: Verdict, 131 } 132 133 impl std::fmt::Display for RepairReport { 134 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 135 writeln!(f, "R1 store diagnosis")?; 136 for c in &self.copies { 137 let at = u64::from(c.copy) * BLOCK; 138 match &c.state { 139 CopyState::Blank => { 140 writeln!(f, "superblock copy {} (byte {at}): blank", c.copy)? 141 } 142 CopyState::Intact { 143 generation, 144 segment_count, 145 meta_slot, 146 } => writeln!( 147 f, 148 "superblock copy {} (byte {at}): intact, generation {generation}, checkpoint: {segment_count} committed segments, metadata region {meta_slot}", 149 c.copy 150 )?, 151 CopyState::MetaDamaged { 152 generation, 153 segment_count, 154 } => writeln!( 155 f, 156 "superblock copy {} (byte {at}): CORRUPT metadata region, generation {generation}, {segment_count} committed segments", 157 c.copy 158 )?, 159 CopyState::Damaged(why) => { 160 writeln!(f, "superblock copy {} (byte {at}): CORRUPT, {why}", c.copy)? 161 } 162 } 163 } 164 if self.history.is_empty() { 165 writeln!(f, "repair history: none")?; 166 } 167 for (i, e) in self.history.iter().enumerate() { 168 writeln!(f, "repair history entry {}: {e}", i + 1)?; 169 } 170 match &self.verdict { 171 Verdict::Healthy => writeln!(f, "verdict: healthy, nothing to repair")?, 172 Verdict::OneCopyDamagedNothingLost => writeln!( 173 f, 174 "verdict: one copy is unusable, but the checkpoint in force loses no acknowledged data; the next commit rewrites the bad copy" 175 )?, 176 Verdict::Unrepairable(why) => { 177 writeln!(f, "verdict: cannot be repaired by this tool: {why}")? 178 } 179 Verdict::OlderCheckpointLosesRange => { 180 let (copy, generation) = self.adopt.unwrap_or((0, 0)); 181 writeln!( 182 f, 183 "verdict: the store refuses to open (CheckpointCorrupt). The checkpoint in force (copy {copy}, generation {generation}, {} committed segments) is behind acknowledged data:", 184 self.segment_count 185 )?; 186 for r in &self.lost { 187 writeln!( 188 f, 189 " segment slot {}: device bytes {}..{} ({} non-zero bytes), {} batches, {} records", 190 r.slot, 191 r.start, 192 r.end, 193 r.nonzero_bytes, 194 r.batches.len(), 195 r.records() 196 )?; 197 for b in &r.batches { 198 let last = b.first_seq + u64::from(b.records.max(1)) - 1; 199 writeln!( 200 f, 201 " batch at device byte {}: records {}..={} ({} records)", 202 b.offset, b.first_seq, last, b.records 203 )?; 204 } 205 } 206 writeln!( 207 f, 208 "nothing was written. Re-run with --operator-key --backup and one action:" 209 )?; 210 writeln!( 211 f, 212 " --roll-forward commit the slot past the checkpoint and keep every record above" 213 )?; 214 writeln!( 215 f, 216 " --adopt-older-checkpoint DROP the range above and record the loss in the signed repair log" 217 )?; 218 } 219 } 220 Ok(()) 221 } 222 } 223 224 // --- repair log --------------------------------------------------------------------- 225 226 /// The action a repair takes; the caller names it, there is no default. 227 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 228 pub enum RepairAction { 229 /// Commit the slot past the older checkpoint: every acknowledged batch in it is kept. 230 RollForward, 231 /// Keep the older checkpoint and zero the acknowledged data past it (a named loss). 232 AdoptOlderCheckpoint, 233 } 234 235 impl RepairAction { 236 fn code(self) -> u8 { 237 match self { 238 Self::RollForward => 1, 239 Self::AdoptOlderCheckpoint => 2, 240 } 241 } 242 fn from_code(c: u8) -> Option { 243 match c { 244 1 => Some(Self::RollForward), 245 2 => Some(Self::AdoptOlderCheckpoint), 246 _ => None, 247 } 248 } 249 } 250 251 /// A range a repair covered: kept by a roll forward, dropped by an adopt. 252 #[derive(Debug, Clone, PartialEq, Eq)] 253 pub struct RecordedRange { 254 pub slot: u64, 255 /// Block-aligned device byte range `start..end`. 256 pub start: u64, 257 pub end: u64, 258 pub nonzero_bytes: u64, 259 pub batches: u32, 260 pub records: u64, 261 /// First record sequence number (0 when no batch header was found). 262 pub first_seq: u64, 263 /// SHA-256 of the device bytes `start..end` before the repair. 264 pub bytes_sha256: [u8; 32], 265 } 266 267 /// One signed, hash-chained entry of the repair log. 268 #[derive(Debug, Clone, PartialEq, Eq)] 269 pub struct RepairEntry { 270 pub action: RepairAction, 271 pub device_uuid: [u8; 16], 272 /// Superblock generation the repair committed. 273 pub generation: u64, 274 pub segment_count_before: u64, 275 pub segment_count_after: u64, 276 /// Seconds since the Unix epoch, as given by the operator's tool. 277 pub unix_secs: u64, 278 /// Digest of the previous entry ([`Self::digest`]); zero for the first. 279 pub prev_sha256: [u8; 32], 280 /// SHA-256 of the 4 KiB superblock copy the repair overwrote, as it was before. 281 pub replaced_copy_sha256: [u8; 32], 282 pub ranges: Vec, 283 pub operator_key: [u8; 32], 284 pub signature: [u8; 64], 285 } 286 287 impl std::fmt::Display for RepairEntry { 288 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 289 let what = match self.action { 290 RepairAction::RollForward => "roll forward (kept)", 291 RepairAction::AdoptOlderCheckpoint => "adopt older checkpoint (DROPPED)", 292 }; 293 write!( 294 f, 295 "{what} at generation {}, segments {} -> {}, time {}, operator key {}", 296 self.generation, 297 self.segment_count_before, 298 self.segment_count_after, 299 self.unix_secs, 300 hex::encode(self.operator_key) 301 )?; 302 for r in &self.ranges { 303 write!( 304 f, 305 "; slot {} device bytes {}..{}, {} records from seq {}, sha256 {}", 306 r.slot, 307 r.start, 308 r.end, 309 r.records, 310 r.first_seq, 311 hex::encode(r.bytes_sha256) 312 )?; 313 } 314 Ok(()) 315 } 316 } 317 318 impl RepairEntry { 319 fn encode_unsigned(&self) -> Vec { 320 let mut b = Vec::new(); 321 b.extend_from_slice(&ENTRY_MAGIC); 322 b.extend_from_slice(&ENTRY_VERSION.to_le_bytes()); 323 b.push(self.action.code()); 324 b.push(0); 325 b.extend_from_slice(&self.device_uuid); 326 for v in [ 327 self.generation, 328 self.segment_count_before, 329 self.segment_count_after, 330 self.unix_secs, 331 ] { 332 b.extend_from_slice(&v.to_le_bytes()); 333 } 334 b.extend_from_slice(&self.prev_sha256); 335 b.extend_from_slice(&self.replaced_copy_sha256); 336 b.extend_from_slice(&(self.ranges.len() as u32).to_le_bytes()); 337 for r in &self.ranges { 338 for v in [r.slot, r.start, r.end, r.nonzero_bytes] { 339 b.extend_from_slice(&v.to_le_bytes()); 340 } 341 b.extend_from_slice(&r.batches.to_le_bytes()); 342 b.extend_from_slice(&r.records.to_le_bytes()); 343 b.extend_from_slice(&r.first_seq.to_le_bytes()); 344 b.extend_from_slice(&r.bytes_sha256); 345 } 346 b.extend_from_slice(&self.operator_key); 347 b 348 } 349 350 /// `DOMAIN_R1_REPAIR_SIGN_V1 || unsigned entry`: the bytes the operator signs. 351 pub fn signable_bytes(&self) -> Vec { 352 let mut m = DOMAIN_R1_REPAIR_SIGN_V1.to_vec(); 353 m.extend_from_slice(&self.encode_unsigned()); 354 m 355 } 356 357 fn encode(&self) -> Vec { 358 let mut b = self.encode_unsigned(); 359 b.extend_from_slice(&self.signature); 360 b 361 } 362 363 /// `SHA-256(DOMAIN_R1_REPAIR_ENTRY_V1 || entry with signature)`: the next entry's 364 /// `prev_sha256`. 365 pub fn digest(&self) -> [u8; 32] { 366 let mut h = Sha256::new(); 367 h.update(DOMAIN_R1_REPAIR_ENTRY_V1); 368 h.update(self.encode()); 369 h.finalize().into() 370 } 371 372 fn decode(b: &[u8]) -> Option { 373 let mut at = 0usize; 374 let mut take = |n: usize| -> Option<&[u8]> { 375 let s = b.get(at..at.checked_add(n)?)?; 376 at += n; 377 Some(s) 378 }; 379 if take(4)? != ENTRY_MAGIC || u16::from_le_bytes(take(2)?.try_into().ok()?) != ENTRY_VERSION 380 { 381 return None; 382 } 383 let action = RepairAction::from_code(take(1)?[0])?; 384 if take(1)?[0] != 0 { 385 return None; 386 } 387 let device_uuid = take(16)?.try_into().ok()?; 388 let mut u64s = [0u64; 4]; 389 for v in &mut u64s { 390 *v = u64::from_le_bytes(take(8)?.try_into().ok()?); 391 } 392 let prev_sha256 = take(32)?.try_into().ok()?; 393 let replaced_copy_sha256 = take(32)?.try_into().ok()?; 394 let n = u32::from_le_bytes(take(4)?.try_into().ok()?); 395 let mut ranges = Vec::new(); 396 for _ in 0..n { 397 let mut r = [0u64; 4]; 398 for v in &mut r { 399 *v = u64::from_le_bytes(take(8)?.try_into().ok()?); 400 } 401 let batches = u32::from_le_bytes(take(4)?.try_into().ok()?); 402 let records = u64::from_le_bytes(take(8)?.try_into().ok()?); 403 let first_seq = u64::from_le_bytes(take(8)?.try_into().ok()?); 404 ranges.push(RecordedRange { 405 slot: r[0], 406 start: r[1], 407 end: r[2], 408 nonzero_bytes: r[3], 409 batches, 410 records, 411 first_seq, 412 bytes_sha256: take(32)?.try_into().ok()?, 413 }); 414 } 415 let operator_key = take(32)?.try_into().ok()?; 416 let signature = take(64)?.try_into().ok()?; 417 (at == b.len()).then_some(Self { 418 action, 419 device_uuid, 420 generation: u64s[0], 421 segment_count_before: u64s[1], 422 segment_count_after: u64s[2], 423 unix_secs: u64s[3], 424 prev_sha256, 425 replaced_copy_sha256, 426 ranges, 427 operator_key, 428 signature, 429 }) 430 } 431 432 fn verify_signature(&self) -> bool { 433 VerifyingKey::from_bytes(&self.operator_key) 434 .and_then(|vk| { 435 vk.verify_strict( 436 &self.signable_bytes(), 437 &Signature::from_bytes(&self.signature), 438 ) 439 }) 440 .is_ok() 441 } 442 } 443 444 fn append_entry(log: &[u8], e: &RepairEntry) -> Vec { 445 let enc = e.encode(); 446 let mut out = log.to_vec(); 447 out.extend_from_slice(&(enc.len() as u32).to_le_bytes()); 448 out.extend_from_slice(&enc); 449 out 450 } 451 452 /// Parse and verify a repair log (`u32 len | entry` repeated): every entry decodes, 453 /// carries a valid operator signature, names this device and chains to the one before 454 /// it, and generations increase. Anything else is `CheckpointCorrupt`. 455 pub fn verify_repair_log(log: &[u8], device_uuid: &[u8; 16]) -> SynapseResult> { 456 let mut at = 0usize; 457 let mut prev = [0u8; 32]; 458 let mut last_generation = 0u64; 459 let mut out = Vec::new(); 460 while at < log.len() { 461 let n = log 462 .get(at..at + 4) 463 .map(|s| u32::from_le_bytes(s.try_into().expect("4")) as usize) 464 .ok_or_else(|| corrupt("repair log: truncated entry length"))?; 465 let k = out.len() + 1; 466 let body = log 467 .get(at + 4..at + 4 + n) 468 .ok_or_else(|| corrupt(format!("repair log entry {k}: truncated")))?; 469 let e = RepairEntry::decode(body) 470 .ok_or_else(|| corrupt(format!("repair log entry {k}: does not decode")))?; 471 if !e.verify_signature() { 472 return Err(corrupt(format!( 473 "repair log entry {k}: operator signature does not verify" 474 ))); 475 } 476 if &e.device_uuid != device_uuid { 477 return Err(corrupt(format!( 478 "repair log entry {k}: names another device" 479 ))); 480 } 481 if e.prev_sha256 != prev { 482 return Err(corrupt(format!( 483 "repair log entry {k}: breaks the hash chain (an entry was removed, reordered or changed)" 484 ))); 485 } 486 if e.generation <= last_generation { 487 return Err(corrupt(format!( 488 "repair log entry {k}: generation does not increase" 489 ))); 490 } 491 prev = e.digest(); 492 last_generation = e.generation; 493 out.push(e); 494 at += 4 + n; 495 } 496 Ok(out) 497 } 498 499 impl BlockDevice { 500 /// The signed repair log in force (verified at mount), oldest first. 501 pub fn repair_log(&self) -> SynapseResult> { 502 match self.read_named(REPAIR_LOG_NAME) { 503 Some(log) => verify_repair_log(&log, &self.geo.uuid), 504 None => Ok(Vec::new()), 505 } 506 } 507 } 508 509 // --- diagnosis ---------------------------------------------------------------------- 510 511 fn classify_copy( 512 b: &[u8], 513 i: u64, 514 io: &dyn BlockIo, 515 ) -> std::io::Result<(CopyState, Option)> { 516 if b.iter().all(|x| *x == 0) { 517 return Ok((CopyState::Blank, None)); 518 } 519 let bad = |why: &str| Ok((CopyState::Damaged(why.to_string()), None)); 520 if b[0..8] != SUPERBLOCK_MAGIC { 521 return bad("the Synapse magic is missing"); 522 } 523 if u32::from_le_bytes(b[160..164].try_into().expect("4")) != crc32c(&b[..160]) { 524 return bad("CRC-32C mismatch"); 525 } 526 let Some(sb) = Superblock::decode(b) else { 527 return bad("fields fail validation"); 528 }; 529 if sb.generation % 2 != i { 530 return bad("generation does not belong in this copy"); 531 } 532 if sb.geo.device_bytes > io.len() { 533 return bad("describes more bytes than the device holds"); 534 } 535 let mut meta = vec![0u8; sb.meta_len as usize]; 536 io.read_at(&mut meta, sb.geo.meta_offset[sb.meta_slot as usize])?; 537 if meta_digest(&meta) != sb.meta_sha256 || decode_meta(&meta).is_none() { 538 return Ok(( 539 CopyState::MetaDamaged { 540 generation: sb.generation, 541 segment_count: sb.segment_count, 542 }, 543 Some(sb), 544 )); 545 } 546 Ok(( 547 CopyState::Intact { 548 generation: sb.generation, 549 segment_count: sb.segment_count, 550 meta_slot: sb.meta_slot, 551 }, 552 Some(sb), 553 )) 554 } 555 556 /// Non-zero extent of slot `id`'s data: (first, one past last, count), block-unaligned. 557 fn nonzero_extent( 558 io: &dyn BlockIo, 559 geo: &Geometry, 560 id: u64, 561 ) -> std::io::Result> { 562 let start = geo.slot_offset(id) + BLOCK; 563 let mut buf = vec![0u8; (ZERO_CHUNK as u64).min(geo.segment_bytes) as usize]; 564 let (mut first, mut last, mut count) = (None, 0u64, 0u64); 565 let mut at = 0; 566 while at < geo.segment_bytes { 567 let n = buf.len().min((geo.segment_bytes - at) as usize); 568 io.read_at(&mut buf[..n], start + at)?; 569 for (k, b) in buf[..n].iter().enumerate() { 570 if *b != 0 { 571 let pos = start + at + k as u64; 572 first.get_or_insert(pos); 573 last = pos + 1; 574 count += 1; 575 } 576 } 577 at += n as u64; 578 } 579 Ok(first.map(|f| (f, last, count))) 580 } 581 582 /// Walk the WAL v2 batch headers from the start of slot `id`'s data; stop at the first 583 /// offset that holds no valid header. Headers only: the full frame and hash-chain check 584 /// is the store's recovery, which runs when the repaired store is opened. 585 fn scan_batches(io: &dyn BlockIo, geo: &Geometry, id: u64) -> std::io::Result> { 586 use crate::wal2::{parse_batch_header, WAL_V2_BATCH_HEADER_LEN}; 587 let base = geo.slot_offset(id) + BLOCK; 588 let hl = WAL_V2_BATCH_HEADER_LEN as u64; 589 let mut h = [0u8; WAL_V2_BATCH_HEADER_LEN]; 590 let mut out = Vec::new(); 591 let mut off = 0u64; 592 while off + hl <= geo.segment_bytes { 593 io.read_at(&mut h, base + off)?; 594 let Some((records, body, first)) = parse_batch_header(&h) else { 595 break; 596 }; 597 out.push(LostBatch { 598 offset: base + off, 599 first_seq: first.0, 600 records, 601 }); 602 match (off + hl).checked_add(body) { 603 Some(end) if end <= geo.segment_bytes => off = align_up(end, BLOCK), 604 _ => break, 605 } 606 } 607 Ok(out) 608 } 609 610 fn slot_header_valid(io: &dyn BlockIo, geo: &Geometry, id: u64) -> std::io::Result { 611 if id == 0 || id > geo.slot_count { 612 return Ok(false); 613 } 614 let mut b = vec![0u8; BLOCK as usize]; 615 io.read_at(&mut b, geo.slot_offset(id))?; 616 Ok(b == segment_header(geo, id)) 617 } 618 619 /// Diagnosis plus what [`repair`] needs: the superblock in force and its namespace. 620 struct Inspection { 621 report: RepairReport, 622 sb: Option, 623 names: BTreeMap>, 624 } 625 626 fn inspect(io: &dyn BlockIo) -> SynapseResult { 627 if io.len() < LABEL_BYTES { 628 return Err(refuse("device is smaller than the label area")); 629 } 630 match classify_device(io).map_err(io_err)? { 631 DeviceLabel::Synapse => {} 632 other => { 633 return Err(refuse(format!( 634 "refusing to diagnose: the device is not a Synapse store ({other:?})" 635 ))) 636 } 637 } 638 let mut parsed = Vec::new(); 639 for i in 0..2u64 { 640 let mut b = vec![0u8; BLOCK as usize]; 641 io.read_at(&mut b, i * BLOCK).map_err(io_err)?; 642 parsed.push(classify_copy(&b, i, io).map_err(io_err)?); 643 } 644 let copies = [ 645 CopyReport { 646 copy: 0, 647 state: parsed[0].0.clone(), 648 }, 649 CopyReport { 650 copy: 1, 651 state: parsed[1].0.clone(), 652 }, 653 ]; 654 let valid: Vec<&Superblock> = parsed.iter().filter_map(|(_, s)| s.as_ref()).collect(); 655 let device_uuid = valid.first().map(|s| s.geo.uuid); 656 let unrepairable = |why: String| Inspection { 657 report: RepairReport { 658 device_uuid, 659 copies: copies.clone(), 660 adopt: None, 661 segment_count: 0, 662 lost: vec![], 663 history: vec![], 664 verdict: Verdict::Unrepairable(why), 665 }, 666 sb: None, 667 names: BTreeMap::new(), 668 }; 669 if valid.len() == 2 && valid[0].geo != valid[1].geo { 670 return Ok(unrepairable( 671 "the two superblock copies disagree on the geometry".into(), 672 )); 673 } 674 // The checkpoint mount would use: newest intact copy. 675 let mut intact: Vec<(u8, &Superblock)> = parsed 676 .iter() 677 .enumerate() 678 .filter(|(_, (st, _))| matches!(st, CopyState::Intact { .. })) 679 .filter_map(|(i, (_, sb))| sb.as_ref().map(|s| (i as u8, s))) 680 .collect(); 681 intact.sort_by_key(|(_, s)| std::cmp::Reverse(s.generation)); 682 let Some((copy, sb)) = intact.first().copied() else { 683 return Ok(unrepairable( 684 "no superblock copy with an intact metadata region".into(), 685 )); 686 }; 687 let mut meta = vec![0u8; sb.meta_len as usize]; 688 io.read_at(&mut meta, sb.geo.meta_offset[sb.meta_slot as usize]) 689 .map_err(io_err)?; 690 let names = decode_meta(&meta).expect("an intact copy's region decodes"); 691 let history = match names.get(REPAIR_LOG_NAME) { 692 Some(log) => match verify_repair_log(log, &sb.geo.uuid) { 693 Ok(h) => h, 694 Err(e) => return Ok(unrepairable(e.message)), 695 }, 696 None => Vec::new(), 697 }; 698 let mut lost = Vec::new(); 699 let mut id = sb.segment_count + 1; 700 while slot_header_valid(io, &sb.geo, id).map_err(io_err)? { 701 if let Some((start, end, nonzero_bytes)) = 702 nonzero_extent(io, &sb.geo, id).map_err(io_err)? 703 { 704 lost.push(LostRange { 705 slot: id, 706 start, 707 end, 708 nonzero_bytes, 709 batches: scan_batches(io, &sb.geo, id).map_err(io_err)?, 710 }); 711 } 712 id += 1; 713 } 714 // A freshly formatted store has only generation 1 (in copy 1); copy 0 is blank. 715 let both_ok = intact.len() == 2 || (sb.generation == 1 && copies[0].state == CopyState::Blank); 716 let verdict = if !lost.is_empty() { 717 Verdict::OlderCheckpointLosesRange 718 } else if both_ok { 719 Verdict::Healthy 720 } else { 721 Verdict::OneCopyDamagedNothingLost 722 }; 723 Ok(Inspection { 724 report: RepairReport { 725 device_uuid, 726 copies, 727 adopt: Some((copy, sb.generation)), 728 segment_count: sb.segment_count, 729 lost, 730 history, 731 verdict, 732 }, 733 sb: Some(sb.clone()), 734 names, 735 }) 736 } 737 738 /// Read-only diagnosis of the device. Writes nothing. Refuses a device that does not 739 /// carry the Synapse magic (never inspects a foreign device further). 740 pub fn diagnose(io: &dyn BlockIo) -> SynapseResult { 741 Ok(inspect(io)?.report) 742 } 743 744 // --- backup --------------------------------------------------------------------- 745 746 const BACKUP_MAGIC: &[u8; 16] = b"SYNREPAIRBAK001\n"; 747 748 /// One saved byte range. 749 #[derive(Debug, Clone, PartialEq, Eq)] 750 pub struct BackupSection { 751 pub offset: u64, 752 pub bytes: Vec, 753 } 754 755 /// Contents of a repair backup file. 756 #[derive(Debug, Clone, PartialEq, Eq)] 757 pub struct Backup { 758 pub device_uuid: [u8; 16], 759 pub sections: Vec, 760 } 761 762 fn block_range(r: &LostRange) -> (u64, u64) { 763 (r.start / BLOCK * BLOCK, align_up(r.end, BLOCK)) 764 } 765 766 /// Parse and verify (trailing SHA-256) a backup file written by the repair. 767 pub fn read_backup(path: &Path) -> SynapseResult { 768 let b = fs::read(path).map_err(io_err)?; 769 if b.len() < 16 + 16 + 4 + 32 || &b[..16] != BACKUP_MAGIC { 770 return Err(refuse("not a repair backup file")); 771 } 772 let (body, tail) = b.split_at(b.len() - 32); 773 if Sha256::digest(body).as_slice() != tail { 774 return Err(refuse("repair backup digest mismatch")); 775 } 776 let device_uuid: [u8; 16] = body[16..32].try_into().expect("16"); 777 let n = u32::from_le_bytes(body[32..36].try_into().expect("4")); 778 let mut at = 36usize; 779 let mut sections = Vec::new(); 780 for _ in 0..n { 781 let data_start = at 782 .checked_add(16) 783 .ok_or_else(|| refuse("repair backup section header overflow"))?; 784 let hdr = body 785 .get(at..data_start) 786 .ok_or_else(|| refuse("truncated repair backup"))?; 787 let offset = u64::from_le_bytes(hdr[..8].try_into().expect("8")); 788 let len = usize::try_from(u64::from_le_bytes(hdr[8..].try_into().expect("8"))) 789 .map_err(|_| refuse("repair backup section length does not fit this host"))?; 790 let end = data_start 791 .checked_add(len) 792 .ok_or_else(|| refuse("repair backup section length overflow"))?; 793 let bytes = body 794 .get(data_start..end) 795 .ok_or_else(|| refuse("truncated repair backup"))? 796 .to_vec(); 797 sections.push(BackupSection { offset, bytes }); 798 at = end; 799 } 800 Ok(Backup { 801 device_uuid, 802 sections, 803 }) 804 } 805 806 /// Save the device bytes of every `(start, end)` range to a new file and sync it (and 807 /// its directory). An existing file is never overwritten. 808 fn write_backup( 809 io: &dyn BlockIo, 810 path: &Path, 811 uuid: [u8; 16], 812 ranges: &[(u64, u64)], 813 ) -> SynapseResult<()> { 814 let mut body = Vec::new(); 815 body.extend_from_slice(BACKUP_MAGIC); 816 body.extend_from_slice(&uuid); 817 body.extend_from_slice(&(ranges.len() as u32).to_le_bytes()); 818 for &(a, b) in ranges { 819 let mut bytes = vec![0u8; (b - a) as usize]; 820 io.read_at(&mut bytes, a).map_err(io_err)?; 821 body.extend_from_slice(&a.to_le_bytes()); 822 body.extend_from_slice(&(bytes.len() as u64).to_le_bytes()); 823 body.extend_from_slice(&bytes); 824 } 825 let digest = Sha256::digest(&body); 826 body.extend_from_slice(&digest); 827 // create_new: an existing file is never overwritten; owner-only. 828 let mut f = { 829 use std::os::unix::fs::OpenOptionsExt; 830 OpenOptions::new() 831 .write(true) 832 .create_new(true) 833 .mode(0o600) 834 .open(path) 835 .map_err(|e| refuse(format!("backup file {}: {e}", path.display())))? 836 }; 837 f.write_all(&body).map_err(io_err)?; 838 f.sync_all().map_err(io_err)?; 839 let dir = path 840 .parent() 841 .filter(|d| !d.as_os_str().is_empty()) 842 .unwrap_or_else(|| Path::new(".")); 843 File::open(dir).and_then(|d| d.sync_all()).map_err(io_err)?; 844 Ok(()) 845 } 846 847 // --- repair ------------------------------------------------------------------------- 848 849 /// What [`repair`] did: the diagnosis it acted on, and the signed entry it committed (or, 850 /// when it finished an interrupted adopt, the entry that already recorded it). 851 #[derive(Debug, Clone, PartialEq, Eq)] 852 pub struct RepairReceipt { 853 pub report: RepairReport, 854 /// `None` when there was nothing to repair and nothing was written. 855 pub entry: Option, 856 /// Whether the device was written. 857 pub wrote: bool, 858 } 859 860 impl std::fmt::Display for RepairReceipt { 861 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 862 match (&self.entry, self.wrote) { 863 (Some(e), true) => write!( 864 f, 865 "repair receipt: {e}; entry sha256 {}", 866 hex::encode(e.digest()) 867 ), 868 _ => write!(f, "nothing to repair; nothing was written"), 869 } 870 } 871 } 872 873 fn zero_ranges(io: &dyn BlockIo, ranges: &[(u64, u64)]) -> SynapseResult<()> { 874 let zero = vec![0u8; ZERO_CHUNK]; 875 for &(mut at, end) in ranges { 876 while at < end { 877 let n = (ZERO_CHUNK as u64).min(end - at) as usize; 878 io.write_at(&zero[..n], at).map_err(io_err)?; 879 at += n as u64; 880 } 881 } 882 io.flush().map_err(io_err) 883 } 884 885 fn sha256_range(io: &dyn BlockIo, (a, b): (u64, u64)) -> SynapseResult<[u8; 32]> { 886 let mut bytes = vec![0u8; (b - a) as usize]; 887 io.read_at(&mut bytes, a).map_err(io_err)?; 888 Ok(Sha256::digest(&bytes).into()) 889 } 890 891 /// Repair the store on `io` with the named `action`, signed by `operator`. 892 /// 893 /// * Nothing to repair ([`Verdict::Healthy`], [`Verdict::OneCopyDamagedNothingLost`]): 894 /// nothing is written, no backup is created. 895 /// * [`Verdict::Unrepairable`]: refused, nothing written. 896 /// * Otherwise: refuse unless `action` fits the diagnosis; save every byte range about 897 /// to be overwritten to `backup_path` (must not exist) and sync it; commit the new 898 /// superblock and a namespace whose repair log ends with the signed entry, in one 899 /// flush; for an adopt, then zero the dropped range and flush; re-diagnose and 900 /// refuse if anything is still past the checkpoint. 901 pub fn repair( 902 io: &dyn BlockIo, 903 action: RepairAction, 904 operator: &SigningKey, 905 backup_path: &Path, 906 unix_secs: u64, 907 ) -> SynapseResult { 908 let Inspection { report, sb, names } = inspect(io)?; 909 match &report.verdict { 910 Verdict::Unrepairable(_) => return Err(corrupt(format!("{report}"))), 911 Verdict::Healthy | Verdict::OneCopyDamagedNothingLost => { 912 return Ok(RepairReceipt { 913 report, 914 entry: None, 915 wrote: false, 916 }) 917 } 918 Verdict::OlderCheckpointLosesRange => {} 919 } 920 let sb = sb.expect("a repairable diagnosis has a checkpoint in force"); 921 let uuid = sb.geo.uuid; 922 let lost_blocks: Vec<(u64, u64)> = report.lost.iter().map(block_range).collect(); 923 924 // An adopt whose record committed but whose zeroing did not finish: the newest entry 925 // is that adopt, at the generation in force, and covers every range still holding 926 // data. Finish it; never record it twice, never roll it forward. 927 if let Some(last) = report.history.last().filter(|e| { 928 e.action == RepairAction::AdoptOlderCheckpoint 929 && e.generation == sb.generation 930 && lost_blocks.iter().zip(&report.lost).all(|(&(a, b), l)| { 931 e.ranges 932 .iter() 933 .any(|r| r.slot == l.slot && r.start <= a && b <= r.end) 934 }) 935 }) { 936 if action != RepairAction::AdoptOlderCheckpoint { 937 return Err(refuse(format!( 938 "refusing {action:?}: the signed repair log already records an adopt of this range that did not finish; re-run with the same action. Nothing was written.\n{report}" 939 ))); 940 } 941 let entry = last.clone(); 942 write_backup(io, backup_path, uuid, &lost_blocks)?; 943 zero_ranges(io, &lost_blocks)?; 944 return finish(io, report, entry); 945 } 946 947 if action == RepairAction::RollForward { 948 let next = sb.segment_count + 1; 949 if report.lost.len() != 1 || report.lost[0].slot != next { 950 return Err(refuse(format!( 951 "refusing to roll forward: exactly one slot (slot {next}) past the checkpoint may hold data, and this device has {} such slots; a damaged superblock loses one commit. Nothing was written.\n{report}", 952 report.lost.len() 953 ))); 954 } 955 if report.lost[0].batches.is_empty() { 956 return Err(refuse(format!( 957 "refusing to roll forward: slot {next} holds data but no WAL v2 batch header at its start. Nothing was written.\n{report}" 958 ))); 959 } 960 } 961 962 let generation = sb.generation + 1; 963 let target_copy = (generation % 2) * BLOCK; 964 let mut ranges = Vec::new(); 965 for (l, &(a, b)) in report.lost.iter().zip(&lost_blocks) { 966 ranges.push(RecordedRange { 967 slot: l.slot, 968 start: a, 969 end: b, 970 nonzero_bytes: l.nonzero_bytes, 971 batches: l.batches.len() as u32, 972 records: l.records(), 973 first_seq: l.batches.first().map_or(0, |x| x.first_seq), 974 bytes_sha256: sha256_range(io, (a, b))?, 975 }); 976 } 977 let mut entry = RepairEntry { 978 action, 979 device_uuid: uuid, 980 generation, 981 segment_count_before: sb.segment_count, 982 segment_count_after: match action { 983 RepairAction::RollForward => sb.segment_count + 1, 984 RepairAction::AdoptOlderCheckpoint => sb.segment_count, 985 }, 986 unix_secs, 987 prev_sha256: report.history.last().map_or([0u8; 32], |e| e.digest()), 988 replaced_copy_sha256: sha256_range(io, (target_copy, target_copy + BLOCK))?, 989 ranges, 990 operator_key: operator.verifying_key().to_bytes(), 991 signature: [0u8; 64], 992 }; 993 entry.signature = operator.sign(&entry.signable_bytes()).to_bytes(); 994 995 let mut new_names = names; 996 let log = new_names.remove(REPAIR_LOG_NAME).unwrap_or_default(); 997 new_names.insert(REPAIR_LOG_NAME.to_string(), append_entry(&log, &entry)); 998 let meta = encode_meta(&new_names); 999 if meta.len() as u64 > sb.geo.meta_region_bytes { 1000 return Err(refuse( 1001 "the repair entry does not fit the metadata region; nothing was written", 1002 )); 1003 } 1004 // The region no valid copy in force points at (the commit protocol's spare region). 1005 let meta_slot = 1 - sb.meta_slot; 1006 let region_at = sb.geo.meta_offset[meta_slot as usize]; 1007 let mut region = meta.clone(); 1008 region.resize(align_up(region.len() as u64, BLOCK) as usize, 0); 1009 let new_sb = Superblock { 1010 geo: sb.geo, 1011 generation, 1012 segment_count: entry.segment_count_after, 1013 meta_len: meta.len() as u64, 1014 meta_slot, 1015 meta_sha256: meta_digest(&meta), 1016 }; 1017 1018 let mut backup = vec![ 1019 (0u64, 2 * BLOCK), 1020 (region_at, region_at + region.len() as u64), 1021 ]; 1022 if action == RepairAction::AdoptOlderCheckpoint { 1023 backup.extend_from_slice(&lost_blocks); 1024 } 1025 write_backup(io, backup_path, uuid, &backup)?; 1026 io.write_at(®ion, region_at).map_err(io_err)?; 1027 io.write_at(&new_sb.encode(), target_copy).map_err(io_err)?; 1028 io.flush().map_err(io_err)?; 1029 if action == RepairAction::AdoptOlderCheckpoint { 1030 zero_ranges(io, &lost_blocks)?; 1031 } 1032 finish(io, report, entry) 1033 } 1034 1035 fn finish( 1036 io: &dyn BlockIo, 1037 report: RepairReport, 1038 entry: RepairEntry, 1039 ) -> SynapseResult { 1040 let after = diagnose(io)?; 1041 if after.verdict != Verdict::Healthy || after.history.last() != Some(&entry) { 1042 return Err(corrupt(format!( 1043 "the repair was written but the device does not diagnose healthy with the entry in force:\n{after}" 1044 ))); 1045 } 1046 Ok(RepairReceipt { 1047 report, 1048 entry: Some(entry), 1049 wrote: true, 1050 }) 1051 } 1052 1053 /// [`repair`] on the device at `path`, opened read-write under the same exclusive lock 1054 /// the store takes ([`DirectFile::open`]): refused while a store or another repair holds it. 1055 pub fn repair_path( 1056 path: &Path, 1057 action: RepairAction, 1058 operator: &SigningKey, 1059 backup_path: &Path, 1060 unix_secs: u64, 1061 ) -> SynapseResult { 1062 let io = DirectFile::open(path)?; 1063 repair(&io, action, operator, backup_path, unix_secs) 1064 } 1065 1066 /// [`diagnose`] on the device at `path`, opened read-only under the exclusive lock. 1067 pub fn diagnose_path(path: &Path) -> SynapseResult { 1068 let io = DirectFile::open_read_only(path)?; 1069 diagnose(&io) 1070 }