From 272099d99393cbd15b6bf6ea8fe31671e9ca4938 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:37:53 +0100 Subject: [PATCH] feat(oplog): read past damage in the op log Damage in the middle of a segment hid every entry after it: readers stopped there, and so did appends. Readers now read past it, from both ends of the segment, and report how many entries it hid, on stderr and in `Read::damage`. The index rebuilds itself from the store when the op log lost entries, since those may have named records. The first reader to find damage in the last segment starts a new one, so appends continue past it. Damage at the end of the last segment hides how many entries it held: the next append skips as many sequence numbers as it could hold, so none is reused. A damaged length is never mistaken for a half-written last entry, and a segment shorter than its header is damage, not a panic. --- apps/origin-src/src/frames.rs | 11 ++ apps/origin-src/src/index.rs | 29 +++- apps/origin-src/src/oplog.rs | 247 ++++++++++++++++++++++++++++++++-- 3 files changed, 272 insertions(+), 15 deletions(-) diff --git a/apps/origin-src/src/frames.rs b/apps/origin-src/src/frames.rs index 8940d179..fe21bc23 100644 --- a/apps/origin-src/src/frames.rs +++ b/apps/origin-src/src/frames.rs @@ -133,6 +133,17 @@ impl Frames { unwanted.then_some(frames) } + /// The intact frames at the end of a file, decoded by `decode`, oldest + /// first: read backwards from the end, up to a broken one or the + /// header. They are those after damage that [`Frames::parse`] stops at. + pub(crate) fn parse_tail( + self, + bytes: &[u8], + decode: impl FnMut(&[u8]) -> Result, + ) -> Vec { + self.back(bytes, decode, |_| true).0 + } + /// Reads frames backwards from the end of `bytes`, oldest first, while /// `wanted` is true of them, up to a broken one or the header. Returns /// them, and whether it stopped at one `wanted` is false of. diff --git a/apps/origin-src/src/index.rs b/apps/origin-src/src/index.rs index 57ef4ca5..eae51a2f 100644 --- a/apps/origin-src/src/index.rs +++ b/apps/origin-src/src/index.rs @@ -276,14 +276,17 @@ impl Index { /// Adds the published records of the op log entries after the last one /// indexed, and appends them to the index, as the module explains. - /// Returns `false` if the op log no longer has them: then only a - /// rebuild can catch up. + /// Returns `false` if the op log no longer has them, or damage lost + /// some: then only a rebuild can catch up. fn catch_up(&mut self, store: &Store

) -> Result { let oplog = store.oplog(); let read = match oplog.after(self.applied) { Err(StoreError::Expired { .. }) => return Ok(false), read => read?, }; + if read.damage.is_some() { + return Ok(false); + } let Some(last) = read.entries.last() else { return Ok(true); }; @@ -913,6 +916,7 @@ mod tests { use origin_shared::{Base, BlobId, Inputs, Kind, Record, Tree, Verdict}; use super::*; + use crate::oplog::FramePart; fn store() -> (tempfile::TempDir, Store) { let dir = tempfile::tempdir().unwrap(); @@ -1230,6 +1234,27 @@ mod tests { assert_eq!(reopened.heads(change(1)), [revision_id(&written)]); } + #[test] + fn op_log_damage_rebuilds_the_index() { + let (_dir, store) = store(); + Index::open(&store).unwrap(); + let written: Vec<_> = (1..=3) + .map(|seed| revision(change(seed), &[], "lost")) + .collect(); + for revision in &written { + store.write_all(slice::from_ref(revision)).unwrap(); + } + // The entry of the second revision: the store has it, the op log + // no longer says so. + store + .oplog() + .damage(store.oplog().last_seq().unwrap() - 1, FramePart::Check); + let index = Index::open(&store).unwrap(); + for (seed, revision) in (1..).zip(&written) { + assert_eq!(index.heads(change(seed)), [revision_id(revision)]); + } + } + #[test] fn rebuilds_once_the_op_log_dropped_what_it_missed() { let (_dir, store) = store(); diff --git a/apps/origin-src/src/oplog.rs b/apps/origin-src/src/oplog.rs index 8fd66e95..fc2002a2 100644 --- a/apps/origin-src/src/oplog.rs +++ b/apps/origin-src/src/oplog.rs @@ -52,9 +52,15 @@ //! remove the file, and take the entries' effects as what they find //! published. So a crashed writer holds nothing back. //! -//! **Partial appends.** A crash in the middle of an append leaves part of a -//! frame at the end of the last segment. It never was an entry: readers -//! skip it, and the next append cuts it off. +//! **Damage.** A crash in the middle of an append leaves part of a frame at +//! the end of the last segment. It never was an entry: readers skip it, and +//! the next append cuts it off. Other damage loses the entries it hides. +//! Readers read past it, from both ends of the segment, and report how many +//! entries it hid; the index rebuilds itself from the store, since those +//! entries may have named records; and the first reader to find it in the +//! last segment starts a new one, so appends continue past it. Damage at the +//! end of the last segment hides how many entries it held: the next append +//! skips as many sequence numbers as it could hold, so none is reused. use std::ffi::OsStr; use std::fs::{self, File, OpenOptions}; @@ -68,7 +74,7 @@ use origin_platform::{DurableWrite, LockMode, LockedFile, Platform}; use origin_shared::object::{DecodeError, Reader}; use origin_shared::{AcceptanceId, ChangeId, ObjectId, TargetName}; -use crate::frames::{Frames, Writer}; +use crate::frames::{Frames, Tail, Writer}; use crate::index; use crate::queue::Proposal; use crate::store::{Store, StoreError}; @@ -150,11 +156,26 @@ enum WriterState { Crashed, } +/// Entries that damage in the middle of a segment hid, as the module +/// explains. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("the op log segment {segment:016x} is damaged: {lost} entries after #{after} are lost")] +pub struct Damage { + /// The segment's first sequence number. + pub segment: u64, + /// The last entry before the damage. + pub after: u64, + /// How many entries it hid, or at most, if none follows it. + pub lost: u64, +} + /// Entries read from the op log, oldest first. #[derive(Debug, Default)] pub struct Read { /// The entries. pub entries: Vec, + /// The damage found on the way, if any. + pub damage: Option, } /// An entry of the op log. @@ -327,6 +348,10 @@ impl<'a, P: Platform> OpLog<'a, P> { /// The most segments kept, 16 MiB of entries, about 100,000. const SEGMENTS: usize = if cfg!(test) { 4 } else { 64 }; + /// The smallest frame an entry makes: sequence number, operation, + /// writer, no workspace, an empty command, and a tag with an empty list. + const SMALLEST_FRAME: u64 = (Frames::FRAMING + 8 + 8 + 8 + 1 + 4 + 1 + 4) as u64; + /// The lock held while appending. const APPENDING: &str = "lock"; @@ -398,6 +423,7 @@ impl<'a, P: Platform> OpLog<'a, P> { /// The entries of the segment starting at `first`, or `None` if /// retention deleted it. Those after `after` at least: when they're at /// its end, which is usual, only they are read, backwards from the end. + /// Damage is read past, from both ends, as the module explains. fn read_segment(&self, first: u64, after: u64) -> Result, StoreError> { let path = self.segment(first); let bytes = match fs::read(&path) { @@ -408,11 +434,64 @@ impl<'a, P: Platform> OpLog<'a, P> { if let Some(entries) = Self::FRAMES.parse_back(&bytes, Entry::decode, |entry| entry.seq > after) { - return Ok(Some(Read { entries })); + return Ok(Some(Read { + entries, + damage: None, + })); } - let (frames, _) = Self::FRAMES.parse(&bytes, Entry::decode); - let entries = frames.into_iter().map(|(_, entry)| entry).collect(); - Ok(Some(Read { entries })) + let (frames, tail) = Self::FRAMES.parse(&bytes, Entry::decode); + let end = frames + .last() + .map_or(Self::FRAMES.header().len() as u64, |(offset, entry)| { + offset + entry.encode().len() as u64 + }); + let mut entries: Vec = frames.into_iter().map(|(_, entry)| entry).collect(); + if tail != Tail::Damaged { + return Ok(Some(Read { + entries, + damage: None, + })); + } + let before = entries.last().map_or(first - 1, |entry| entry.seq); + let after_damage: Vec = Self::FRAMES + .parse_tail(&bytes, Entry::decode) + .into_iter() + .filter(|entry| entry.seq > before) + .collect(); + let lost = match after_damage.first() { + Some(next) => next.seq - before - 1, + // A file shorter than its header, which no append makes: no + // entry fits in what's past it. + None => (bytes.len() as u64).saturating_sub(end) / Self::SMALLEST_FRAME, + }; + entries.extend(after_damage); + let damage = Damage { + segment: first, + after: before, + lost, + }; + if self.segments()?.last() == Some(&first) { + self.rotate(first)?; + } + Ok(Some(Read { + entries, + damage: Some(damage), + })) + } + + /// Starts a new segment after the damaged one starting at `first`, if + /// it's still the last, so appends continue past the damage. + fn rotate(&self, first: u64) -> Result<(), StoreError> { + let _lock = self.lock(Self::APPENDING, LockMode::Exclusive)?; + let segments = self.segments()?; + if segments.last() != Some(&first) { + return Ok(()); + } + let (next, open) = self.tail(first)?; + if open.is_some() { + self.start_segment(next, &segments)?; + } + Ok(()) } /// The sequence number of the latest entry, or 0 if there's none. @@ -445,7 +524,8 @@ impl<'a, P: Platform> OpLog<'a, P> { .unwrap_or(first - 1)) } - /// The entries after the sequence number `after`, oldest first. + /// The entries after the sequence number `after`, oldest first, and the + /// damage they were read past, which is also reported on stderr. /// /// # Errors /// @@ -476,6 +556,10 @@ impl<'a, P: Platform> OpLog<'a, P> { .into_iter() .filter(|entry| entry.seq > after), ); + if let Some(damage) = segment.damage.filter(|damage| damage.after >= after) { + eprintln!("warning: {damage}"); + read.damage = Some(damage); + } } Ok(read) } @@ -638,6 +722,23 @@ impl<'a, P: Platform> OpLog<'a, P> { Ok((seq, writer)) } + /// Damages `part` of the frame of the entry `seq`, as a bad disk would. + #[cfg(test)] + pub(crate) fn damage(&self, seq: u64, part: FramePart) { + let segments = self.segments().unwrap(); + let first = segments[segments.partition_point(|&first| first <= seq) - 1]; + let path = self.segment(first); + let mut bytes = fs::read(&path).unwrap(); + let (frames, _) = Self::FRAMES.parse(&bytes, Entry::decode); + let (offset, entry) = frames.iter().find(|(_, entry)| entry.seq == seq).unwrap(); + let offset = usize::try_from(*offset).unwrap(); + match part { + FramePart::Check => bytes[offset + entry.encode().len() - 6] ^= 1, + FramePart::Length => bytes[offset..offset + 3].fill(0xff), + } + fs::write(&path, &bytes).unwrap(); + } + /// Creates and locks the lock file of a writer whose first entry is /// `first`, about to be appended. A writer that crashed before /// appending it may have left the file, unlocked. @@ -656,8 +757,8 @@ impl<'a, P: Platform> OpLog<'a, P> { } /// The next sequence number after the last segment, which starts at - /// `first`, and that segment, opened for appending, unless it's full, - /// and the next entry starts a new one. + /// `first`, and that segment, opened for appending, unless it's full or + /// damaged, and the next entry starts a new one. fn tail(&self, first: u64) -> Result<(u64, Option), StoreError> { let path = self.segment(first); let io_error = |source| StoreError::io(&path, source); @@ -676,6 +777,22 @@ impl<'a, P: Platform> OpLog<'a, P> { })? } Ok(None) => first - 1, + Err(error) if error.kind() == io::ErrorKind::InvalidData => { + // Damage hides the entries after it. Skip as many sequence + // numbers as the damaged bytes could hold, so none is + // reused, and continue in a new segment. + let bytes = fs::read(&path).map_err(io_error)?; + let (entries, _) = Self::FRAMES.parse(&bytes, Entry::decode); + let (end, last) = entries.last().map_or( + (Self::FRAMES.header().len() as u64, first - 1), + |(offset, entry)| (offset + entry.encode().len() as u64, entry.seq), + ); + // Shorter than its header, which no append makes, the file + // hides no entry. + let hidden = (bytes.len() as u64).saturating_sub(end) / Self::SMALLEST_FRAME; + // Past the segment's own number, even if it held no entry. + return Ok(((last + hidden + 1).max(first + 1), None)); + } Err(source) => return Err(io_error(source)), }; let full = file.metadata().map_err(io_error)?.len() >= Self::SEGMENT_BYTES; @@ -718,6 +835,15 @@ impl<'a, P: Platform> OpLog<'a, P> { } } +/// A part of a frame [`OpLog::damage`] damages. +#[cfg(test)] +#[derive(Clone, Copy)] +pub(crate) enum FramePart { + Check, + /// Its leading length, which then runs past the end of the segment. + Length, +} + /// A segment open for appending. struct Segment { path: PathBuf, @@ -869,7 +995,7 @@ mod tests { } #[test] - fn partial_appends_are_cut() { + fn partial_appends_are_cut_and_damage_never_reuses_numbers() { let (_dir, store) = store(); let oplog = store.oplog(); log(&store, &wrote(1)); @@ -889,6 +1015,79 @@ mod tests { assert_eq!(oplog.last_seq().unwrap(), 1, "readers skip it"); assert_eq!(log(&store, &wrote(3)), 2, "the next append cuts it off"); assert_eq!(oplog.after(0).unwrap().entries.len(), 2); + + // Damage at the end of the segment, rather than a partial frame. + let mut bytes = fs::read(&segment).unwrap(); + let len = bytes.len(); + bytes[len - 6] ^= 1; + fs::write(&segment, &bytes).unwrap(); + assert_eq!(oplog.last_seq().unwrap(), 1, "readers stop at it"); + let next = log(&store, &wrote(4)); + assert!(next > 2, "{next} reuses a hidden number"); + assert_eq!(oplog.segments().unwrap(), [1, next], "in a new segment"); + assert_eq!(oplog.after(next - 1).unwrap().entries[0].effect, wrote(4)); + } + + #[test] + fn damage_in_the_middle_is_read_past_counted_and_rotated() { + let (_dir, store) = store(); + let oplog = store.oplog(); + for i in 1..=4 { + log(&store, &wrote(i)); + } + oplog.damage(2, FramePart::Check); + + let read = oplog.after(0).unwrap(); + let seqs: Vec<_> = read.entries.iter().map(|entry| entry.seq).collect(); + assert_eq!(seqs, [1, 3, 4], "the entries after it are read"); + assert_eq!( + read.damage, + Some(Damage { + segment: 1, + after: 1, + lost: 1 + }) + ); + assert_eq!( + oplog.segments().unwrap(), + [1, 5], + "appends continue past it" + ); + assert_eq!(log(&store, &wrote(5)), 5); + assert_eq!( + oplog.after(3).unwrap().damage, + None, + "only readers crossing it" + ); + } + + #[test] + fn damaged_lengths_are_damage_rather_than_partial_appends() { + let (_dir, store) = store(); + let oplog = store.oplog(); + for i in 1..=4 { + log(&store, &wrote(i)); + } + oplog.damage(2, FramePart::Length); + let read = oplog.after(0).unwrap(); + let seqs: Vec<_> = read.entries.iter().map(|entry| entry.seq).collect(); + assert_eq!(seqs, [1, 3, 4], "the entries after it are read"); + assert_eq!(read.damage.map(|damage| damage.lost), Some(1)); + assert_eq!( + oplog.segments().unwrap(), + [1, 5], + "appends continue past it" + ); + + // The last entry is never cut off, nor its number reused. + assert_eq!(log(&store, &wrote(5)), 5); + assert_eq!(log(&store, &wrote(6)), 6); + oplog.damage(6, FramePart::Length); + let segment = fs::read(oplog.segment(5)).unwrap(); + let next = log(&store, &wrote(7)); + assert!(next > 6, "{next} reuses a number"); + assert_eq!(fs::read(oplog.segment(5)).unwrap(), segment, "kept"); + assert_eq!(oplog.segments().unwrap(), [1, 5, next], "in a new segment"); } #[test] @@ -942,7 +1141,8 @@ mod tests { // Tests keep few small segments, so retention may // delete one mid-read: that read is skipped. match oplog.after(oplog.last_seq().unwrap().saturating_sub(1)) { - Ok(_) | Err(StoreError::Expired { .. }) => {} + Ok(read) => assert!(read.damage.is_none()), + Err(StoreError::Expired { .. }) => {} Err(error) => panic!("{error}"), } } @@ -959,4 +1159,25 @@ mod tests { } }); } + + /// Damage that cut a segment inside its header, which no append does, + /// is read past, and appends continue past it. + #[test] + fn segments_shorter_than_their_header_are_damage() { + let (_dir, store) = store(); + let oplog = store.oplog(); + fs::write(oplog.segment(1), &OpLog::::FRAMES.header()[..2]).unwrap(); + assert_eq!(log(&store, &wrote(1)), 2, "in a new segment"); + let read = oplog.after(0).unwrap(); + let seqs: Vec<_> = read.entries.iter().map(|entry| entry.seq).collect(); + assert_eq!(seqs, [2]); + assert_eq!( + read.damage, + Some(Damage { + segment: 1, + after: 0, + lost: 0 + }) + ); + } }