//! Segment management and persistence for items implementing the Persistable trait. use std::{ collections::{HashMap, HashSet}, fs, ops::Range, path::{Path, PathBuf}, sync::LazyLock, time::Instant, }; use dashcore::{ block::{Header as BlockHeader, Version}, consensus::{Decodable, Encodable}, hash_types::FilterHeader, Block, BlockHash, CompactTarget, }; use crate::{ error::StorageResult, storage::io::ChecksummedFile, types::{HashedBlock, HashedBlockHeader}, StorageError, }; pub(super) trait Persistable: Sized + Encodable + Decodable + PartialEq + Clone + 'static { const SEGMENT_PREFIX: &'static str = "segment"; const DATA_FILE_EXTENSION: &'static str = "dat"; const ITEMS_PER_SEGMENT: u32; /// The encoded size of every item, when it is fixed. const ENCODED_SIZE: Option = None; /// Whether every height between the start and the tip must hold an item. const CONTIGUOUS: bool = false; fn segment_file_name(segment_id: u32) -> String { format!("{}_{:06}.{}", Self::SEGMENT_PREFIX, segment_id, Self::DATA_FILE_EXTENSION) } /// Returns the value that marks an empty slot. fn sentinel() -> &'static Self; } impl Persistable for Vec { const ITEMS_PER_SEGMENT: u32 = 2_000; fn sentinel() -> &'static Self { static SENTINEL: Vec = Vec::new(); &SENTINEL } } impl Persistable for HashedBlockHeader { const ITEMS_PER_SEGMENT: u32 = 10_000; const ENCODED_SIZE: Option = Some(112); const CONTIGUOUS: bool = true; fn sentinel() -> &'static Self { // A lazy static, since building it X11-hashes the header. static SENTINEL: LazyLock = LazyLock::new(|| { let header = BlockHeader { version: Version::from_consensus(i32::MAX), // Invalid version prev_blockhash: BlockHash::from_byte_array([0xFF; 32]), // All 0xFF pattern merkle_root: dashcore::hashes::sha256d::Hash::from_byte_array([0xFF; 32]).into(), time: u32::MAX, // Far future timestamp bits: CompactTarget::from_consensus(0xFFFFFFFF), // Invalid difficulty nonce: u32::MAX, }; HashedBlockHeader::from(header) }); &SENTINEL } } impl Persistable for FilterHeader { const ITEMS_PER_SEGMENT: u32 = 50_000; const ENCODED_SIZE: Option = Some(32); const CONTIGUOUS: bool = true; fn sentinel() -> &'static Self { static SENTINEL: FilterHeader = FilterHeader::from_byte_array([0; 32]); &SENTINEL } } impl Persistable for HashedBlock { const ITEMS_PER_SEGMENT: u32 = 1_000; fn sentinel() -> &'static Self { // A lazy static, since building it X11-hashes the header. static SENTINEL: LazyLock = LazyLock::new(|| { HashedBlock::from(Block { header: *HashedBlockHeader::sentinel().header(), txdata: Vec::new(), }) }); &SENTINEL } } /// In-memory cache for all segments of items #[derive(Debug)] pub struct SegmentCache { segments: HashMap>, tip_height: Option, start_height: Option, segments_dir: PathBuf, } impl SegmentCache { const MAX_ACTIVE_SEGMENTS: usize = 2; pub async fn load_or_new(segments_dir: impl Into) -> StorageResult { let segments_dir = segments_dir.into(); let mut cache = Self { segments: HashMap::with_capacity(Self::MAX_ACTIVE_SEGMENTS), tip_height: None, start_height: None, segments_dir: segments_dir.clone(), }; // Building the metadata if let Ok(entries) = fs::read_dir(&segments_dir) { let mut max_seg_id = None; let mut min_seg_id = None; for entry in entries.flatten() { if let Some(name) = entry.file_name().to_str() { if let Some(id) = Self::parse_segment_id(name) { max_seg_id = Some(max_seg_id.map_or(id, |max: u32| max.max(id))); min_seg_id = Some(min_seg_id.map_or(id, |min: u32| min.min(id))); } } } if let Some(segment_id) = max_seg_id { let segment = cache.get_segment(&segment_id).await?; cache.tip_height = segment .last_valid_offset() .map(|offset| Self::segment_id_to_start_height(segment_id) + offset); } if let Some(segment_id) = min_seg_id { let segment = cache.get_segment(&segment_id).await?; cache.start_height = segment .first_valid_offset() .map(|offset| Self::segment_id_to_start_height(segment_id) + offset); } } if I::CONTIGUOUS { cache.truncate_at_first_gap().await?; } Ok(cache) } /// Parse the segment id out of a segment file name of the form /// `{SEGMENT_PREFIX}_{id:06}.{DATA_FILE_EXTENSION}` (see /// [`Persistable::segment_file_name`]). /// /// The entire remaining component between the `{prefix}_` and /// `.{extension}` fixtures must parse as a `u32`, so trailing junk /// (`segment_000000junk.dat`) is rejected and ids longer than the /// zero-padding width (`segment_1000000.dat`) are accepted, not truncated. pub(super) fn parse_segment_id(file_name: &str) -> Option { let separator = format!("{}_", I::SEGMENT_PREFIX); let suffix = format!(".{}", I::DATA_FILE_EXTENSION); file_name.strip_prefix(&separator)?.strip_suffix(&suffix)?.parse::().ok() } #[inline] fn height_to_segment_id(height: u32) -> u32 { height / Segment::::ITEMS_PER_SEGMENT } #[inline] fn segment_id_to_start_height(segment_id: u32) -> u32 { segment_id * Segment::::ITEMS_PER_SEGMENT } /// Get the segment offset for a given storage index. #[inline] fn height_to_offset(height: u32) -> u32 { height % Segment::::ITEMS_PER_SEGMENT } async fn get_segment(&mut self, segment_id: &u32) -> StorageResult<&Segment> { let segment = self.get_segment_mut(segment_id).await?; Ok(&*segment) } async fn get_segment_mut<'a>( &'a mut self, segment_id: &u32, ) -> StorageResult<&'a mut Segment> { if self.segments.contains_key(segment_id) { tracing::trace!( "SegmentCache<{}>: segment {segment_id} cache hit", std::any::type_name::() ); let segment = self.segments.get_mut(segment_id).expect("We already checked that it exists"); return Ok(segment); } if self.segments.len() >= Self::MAX_ACTIVE_SEGMENTS { let key_to_evict = self.segments.iter().min_by_key(|(_, s)| s.last_accessed).map(|(k, _)| *k); if let Some(key) = key_to_evict { if let Some(segment) = self.segments.get_mut(&key) { segment.persist(&self.segments_dir).await?; } self.segments.remove(&key); } } let segment = Segment::load(&self.segments_dir, *segment_id).await?; if segment.state == SegmentState::Clean { tracing::trace!( "SegmentCache<{}>: segment {segment_id} cache miss", std::any::type_name::() ); } let segment = self.segments.entry(*segment_id).or_insert(segment); Ok(segment) } /// Load a contiguous range of items by height. /// /// Returns `StorageError::InvalidArgument` when the requested range extends /// above the tip. Callers reading across a truncation boundary must clamp /// their range to `tip_height` first, or fall back to per-item reads via /// `get_item`, which returns `Ok(None)` for those slots. pub async fn get_items(&mut self, height_range: Range) -> StorageResult> { debug_assert!(height_range.start < height_range.end); let start = height_range.start; let end = height_range.end; // Reject ranges that extend past the current tip, including the // sentinel tail a `truncate_above` leaves in the boundary segment. if end > self.next_height() { return Err(StorageError::InvalidArgument(format!( "get_items range {height_range:?} extends above tip {:?}", self.tip_height ))); } // Reject ranges that begin below the lowest stored height: those slots // were never populated and hold only sentinels. Without this guard the // read would trip the `first_valid_offset` debug assertion below in // debug builds, and silently hand back sentinel data in release builds. if self.start_height.is_none_or(|lowest| start < lowest) { return Err(StorageError::InvalidArgument(format!( "get_items range {height_range:?} begins below the lowest stored height {:?}", self.start_height ))); } let mut items = Vec::with_capacity((end - start) as usize); let start_segment = Self::height_to_segment_id(start); // Because the end is not included, we dont want to visit the segment // where that height is present. // // Example: For start = 0 and end = ITEM_PER_SEGMENT, // Self::height_to_segment_id(end) = 1 but all the elements in // [start, end) are in segment 0. If we don't do the // subtraction we would do 2 iterations. let end_segment = Self::height_to_segment_id(end - 1); for segment_id in start_segment..=end_segment { let segment = self.get_segment_mut(&segment_id).await?; let seg_start = if segment_id == start_segment { Self::height_to_offset(start) } else { 0 }; let seg_end = if segment_id == end_segment { Self::height_to_offset(end) } else { Segment::::ITEMS_PER_SEGMENT }; #[cfg(debug_assertions)] { match segment.first_valid_offset() { Some(offset) if offset <= seg_start => {} _ => panic!("Trying to access invalid offset ({seg_start}) in segment with first_valid_offset = {:?}", segment.first_valid_offset()), } } // This edge case occurs when the end height is multiple of ITEMS_PER_SEGMENT. // In this case, we just extend from seg_start until the end. // // Note that 0 == ITEMS_PER_SEGMENT (mod ITEMS_PER_SEGMENT) if seg_end == 0 { items.extend_from_slice(segment.get(seg_start..Segment::::ITEMS_PER_SEGMENT)); continue; } #[cfg(debug_assertions)] { match segment.last_valid_offset() { Some(offset) if offset >= seg_end - 1 => {} // seg_end is not included, interval of the form [seg_start, seg_end) _ => panic!("Trying to access invalid offset ({}) in segment with last_valid_offset = {:?}", seg_end - 1, segment.last_valid_offset()), } } items.extend_from_slice(segment.get(seg_start..seg_end)); } Ok(items) } /// Get a single item by height. Returns `None` for sentinel (empty) slots. /// Unlike `get_items()`, this does not assert dense storage, safe for sparse data. /// /// For heights above the tip this returns `Ok(None)` rather than the /// `StorageError::InvalidArgument` that `get_items` returns. Callers must /// not interpret `Ok(None)` here as a fallback for an error from `get_items`. /// The two APIs report truncated slots differently by design. pub async fn get_item(&mut self, height: u32) -> StorageResult> { // Loading a segment outside the stored range would create it empty and // the next `persist` would write it back. if self.start_height.is_none_or(|start| height < start) || self.tip_height.is_none_or(|tip| height > tip) { return Ok(None); } let segment_id = Self::height_to_segment_id(height); let offset = Self::height_to_offset(height); // A fixed-size item of a segment that is not resident is read on its // own, without loading the segment. let item = match I::ENCODED_SIZE { Some(size) if !self.segments.contains_key(&segment_id) => { let path = self.segments_dir.join(I::segment_file_name(segment_id)); ChecksummedFile::new(path).read_unverified_at(offset as u64 * size)? } _ => self.get_segment_mut(&segment_id).await?.get_single(offset).clone(), }; Ok(Some(item).filter(|item| item != I::sentinel())) } pub async fn store_items_at_height( &mut self, items: &[I], start_height: u32, ) -> StorageResult<()> { if items.is_empty() { tracing::trace!("DiskStorage: no items to store"); return Ok(()); } let mut height = start_height; tracing::trace!( "SegmentsCache: storing {} items starting at height {}", items.len(), height, ); for item in items { let segment_id = Self::height_to_segment_id(height); let offset = Self::height_to_offset(height); // Update segment let segment = self.get_segment_mut(&segment_id).await?; segment.insert(item.clone(), offset); height += 1; } // Update cached tip height and start height // if needed self.tip_height = match self.tip_height { Some(current) => Some(current.max(height - 1)), None => Some(height - 1), }; self.start_height = match self.start_height { Some(current) => Some(current.min(start_height)), None => Some(start_height), }; Ok(()) } /// Truncate the cache so that no items above `target_height` remain. /// /// Segments entirely above the target are dropped from memory and their /// files deleted. The segment containing `target_height + 1` /// has its tail slots reset to `I::sentinel()` so subsequent `Segment::insert` /// calls into the same range remain sound. /// /// A `target_height` below `start_height` drops every item, as /// [`Self::clear`] does. /// /// The reset of the boundary segment is not durable until the next /// successful `persist` call. A crash in between reopens the cache with the /// boundary segment's pre-truncation items. pub async fn truncate_above(&mut self, target_height: u32) -> StorageResult<()> { let tip = match self.tip_height { Some(tip) => tip, None => return Ok(()), }; if target_height >= tip { return Ok(()); } if self.start_height.is_some_and(|start| target_height < start) { return self.clear().await; } let boundary_segment_id = Self::height_to_segment_id(target_height); let boundary_offset = Self::height_to_offset(target_height); let max_segment_id = Self::height_to_segment_id(tip); // Load the boundary segment first so a read error is surfaced before // mutating cache state. if boundary_offset + 1 < Segment::::ITEMS_PER_SEGMENT { let segment = self.get_segment_mut(&boundary_segment_id).await?; segment.reset_above(boundary_offset); } for id in (boundary_segment_id + 1)..=max_segment_id { self.remove_segment(id).await?; } self.tip_height = Some(target_height); Ok(()) } /// Drops every item above the first empty slot between the start and the tip. /// /// Segments are persisted one by one, so a crash or failed write can leave a hole below /// a tip that the next open reads as complete. async fn truncate_at_first_gap(&mut self) -> StorageResult<()> { let (Some(start), Some(tip)) = (self.start_height, self.tip_height) else { return Ok(()); }; for segment_id in Self::height_to_segment_id(start)..=Self::height_to_segment_id(tip) { let first_height = Self::segment_id_to_start_height(segment_id); let from = start.saturating_sub(first_height) as usize; let to = (tip - first_height + 1).min(Segment::::ITEMS_PER_SEGMENT) as usize; let segment = self.get_segment(&segment_id).await?; let Some(offset) = segment.items[from..to].iter().position(|item| item == I::sentinel()) else { continue; }; // The slot at `start` is never empty, so `gap` is above it. let gap = first_height + (from + offset) as u32; tracing::warn!( "SegmentCache<{}>: no item at height {gap} below the tip {tip}, truncating to {}", std::any::type_name::(), gap - 1 ); return self.truncate_above(gap - 1).await; } Ok(()) } /// Drop every stored item, leaving the cache empty. /// /// All backing segment files — including segments not currently resident /// in memory — are deleted. /// /// The directory scan runs to completion *before* any cache state is /// mutated: a failed scan must not leave the cache reporting empty while /// persisted segment files survive on disk, since those would resurrect /// after restart. A missing segments directory is treated as an empty /// (already-cleared) cache; any other I/O error is propagated. pub async fn clear(&mut self) -> StorageResult<()> { // Collect every on-disk segment file, discovered by directory scan since // only up to MAX_ACTIVE_SEGMENTS of them are resident in memory. let mut to_delete = HashSet::new(); match fs::read_dir(&self.segments_dir) { Ok(entries) => { for entry in entries { let entry = entry?; if let Some(name) = entry.file_name().to_str() { if let Some(id) = Self::parse_segment_id(name) { to_delete.insert(id); } } } } // No directory yet means nothing was ever persisted here. Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(StorageError::Io(e)), } // Scan succeeded — now it is safe to mutate cache state. Resident // segments may be dirty and not persisted yet, so the scan above // cannot see them; `remove_segment` ignores their missing files. to_delete.extend(self.segments.keys().copied()); for id in to_delete { self.remove_segment(id).await?; } self.tip_height = None; self.start_height = None; Ok(()) } pub async fn persist(&mut self, segments_dir: impl Into) { let segments_dir = segments_dir.into(); for (id, segments) in self.segments.iter_mut() { if let Err(e) = segments.persist(&segments_dir).await { tracing::error!("Failed to persist segment with id {id}: {e}"); } } } async fn remove_segment(&mut self, id: u32) -> StorageResult<()> { self.segments.remove(&id); let path = self.segments_dir.join(I::segment_file_name(id)); match tokio::fs::remove_file(&path).await { Ok(_) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(StorageError::WriteFailed(format!( "Failed to delete segment file {path:?}: {e}" ))), } } #[inline] pub fn tip_height(&self) -> Option { self.tip_height } #[inline] pub fn start_height(&self) -> Option { self.start_height } #[inline] pub fn next_height(&self) -> u32 { match self.tip_height() { Some(height) => height + 1, None => 0, } } } /// State of a segment in memory #[derive(Debug, Clone, PartialEq)] enum SegmentState { Clean, // No changes, up to date on disk Dirty, // Has changes, needs saving } /// In-memory cache for a segment of items #[derive(Debug, Clone)] pub struct Segment { segment_id: u32, items: Vec, state: SegmentState, last_accessed: Instant, } impl Segment { const ITEMS_PER_SEGMENT: u32 = I::ITEMS_PER_SEGMENT; fn new(segment_id: u32, mut items: Vec, state: SegmentState) -> Self { debug_assert!(items.len() <= Self::ITEMS_PER_SEGMENT as usize); items.resize(Self::ITEMS_PER_SEGMENT as usize, I::sentinel().clone()); Self { segment_id, items, state, last_accessed: Instant::now(), } } pub fn first_valid_offset(&self) -> Option { let sentinel = I::sentinel(); for (index, item) in self.items.iter().enumerate() { if item != sentinel { return Some(index as u32); } } None } pub fn last_valid_offset(&self) -> Option { let sentinel = I::sentinel(); for (index, item) in self.items.iter().enumerate().rev() { if item != sentinel { return Some(index as u32); } } None } pub async fn load(base_path: &Path, segment_id: u32) -> StorageResult { // Load segment from disk let segment_path = base_path.join(I::segment_file_name(segment_id)); let (items, state) = if segment_path.exists() { (ChecksummedFile::new(segment_path).read().await?, SegmentState::Clean) } else { let mut vec = Vec::new(); vec.resize(Self::ITEMS_PER_SEGMENT as usize, I::sentinel().clone()); (vec, SegmentState::Dirty) }; Ok(Self::new(segment_id, items, state)) } pub async fn persist(&mut self, segments_dir: impl Into) -> StorageResult<()> { if self.state == SegmentState::Clean { return Ok(()); } let segments_dir = segments_dir.into(); let path = segments_dir.join(I::segment_file_name(self.segment_id)); if let Err(e) = fs::create_dir_all(path.parent().unwrap()) { return Err(StorageError::WriteFailed(format!("Failed to persist segment: {}", e))); } ChecksummedFile::new(path).write(&self.items).await?; self.state = SegmentState::Clean; Ok(()) } /// Reset all slots strictly above `offset` to the sentinel value. /// The slot at `offset` is preserved. Marks the segment dirty if any /// slot was changed. fn reset_above(&mut self, offset: u32) { debug_assert!(offset < Self::ITEMS_PER_SEGMENT); let sentinel = I::sentinel(); let start = (offset as usize) + 1; let mut changed = false; for slot in &mut self.items[start..] { if slot != sentinel { *slot = sentinel.clone(); changed = true; } } if changed { self.state = SegmentState::Dirty; self.last_accessed = Instant::now(); } } pub fn insert(&mut self, item: I, offset: u32) { debug_assert!(offset < Self::ITEMS_PER_SEGMENT); let offset = offset as usize; // If, at any moment, we allow the Segment to replace non // sentinel items, feel free to remove this debug assert. // This a bug prevention mechanism based on the assumption that // we are not storing an already valid and stored item. debug_assert!(self.items[offset] == *I::sentinel()); self.items[offset] = item; self.state = SegmentState::Dirty; self.last_accessed = std::time::Instant::now(); } /// Get a single item by offset, returning the raw value (may be a sentinel). pub fn get_single(&mut self, offset: u32) -> &I { self.last_accessed = Instant::now(); &self.items[offset as usize] } pub fn get(&mut self, range: Range) -> &[I] { debug_assert!(range.start < self.items.len() as u32); debug_assert!(range.end <= self.items.len() as u32); self.last_accessed = std::time::Instant::now(); let res = &self.items[range.start as usize..range.end as usize]; // Checking for gaps in the requested range in development #[cfg(debug_assertions)] { let sentinel = I::sentinel(); for item in res { debug_assert!( item != sentinel, "Found a gap in segment {} in interval [{},{})", self.segment_id, range.start, range.end ); } } res } } #[cfg(test)] mod tests { use std::{fmt::Debug, fs}; use tempfile::TempDir; use super::*; #[tokio::test] async fn test_segment_cache_eviction() { let tmp_dir = TempDir::new().unwrap(); const MAX_SEGMENTS: u32 = SegmentCache::::MAX_ACTIVE_SEGMENTS as u32; let mut cache = SegmentCache::::load_or_new(tmp_dir.path()) .await .expect("Failed to create new segment_cache"); // This logic is a little tricky. Each cache can contain up to MAX_SEGMENTS segments in memory. // By storing MAX_SEGMENTS + 1 items, we ensure that the cache will evict the first introduced. // Then, by asking again in order starting in 0, we force the cache to load the evicted segment // evicting at the same time the next, 1 in this case. Then we ask for the 1 that we know is // evicted and so on. for i in 0..=MAX_SEGMENTS { let segment = cache.get_segment_mut(&i).await.expect("Failed to create a new segment"); assert!(segment.state == SegmentState::Dirty); segment.insert(FilterHeader::dummy(i), 0); } assert!(tmp_dir.path().join(FilterHeader::segment_file_name(0)).exists()); for i in 0..=MAX_SEGMENTS { assert_eq!(cache.segments.len(), MAX_SEGMENTS as usize); let segment = cache.get_segment_mut(&i).await.expect("Failed to load segment"); assert!(segment.state == SegmentState::Clean); assert_eq!(segment.get(0..1), [FilterHeader::dummy(i)]); } } #[tokio::test] async fn test_segment_cache_persist_load() { let tmp_dir = TempDir::new().unwrap(); let items = FilterHeader::dummy_batch(0..10); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()) .await .expect("Failed to create new segment_cache"); cache.store_items_at_height(&items, 10).await.expect("Failed to store items"); cache.persist(tmp_dir.path()).await; let mut cache = SegmentCache::::load_or_new(tmp_dir.path()) .await .expect("Failed to load new segment_cache"); assert_eq!( cache.get_items(10..20).await.expect("Failed to get items from segment cache"), items ); } #[tokio::test] async fn test_segment_cache_get_insert() { let tmp_dir = TempDir::new().unwrap(); const ITEMS_PER_SEGMENT: u32 = Segment::::ITEMS_PER_SEGMENT; let mut cache = SegmentCache::::load_or_new(tmp_dir.path()) .await .expect("Failed to create new segment_cache"); let items = FilterHeader::dummy_batch(0..ITEMS_PER_SEGMENT * 2 + ITEMS_PER_SEGMENT / 2); cache.store_items_at_height(&items, 0).await.expect("Failed to store items"); assert_eq!( items[0..ITEMS_PER_SEGMENT as usize], cache.get_items(0..ITEMS_PER_SEGMENT).await.expect("Failed to get items") ); assert_eq!( items[0..(ITEMS_PER_SEGMENT - 1) as usize], cache.get_items(0..ITEMS_PER_SEGMENT - 1).await.expect("Failed to get items") ); assert_eq!( items[0..(ITEMS_PER_SEGMENT + 1) as usize], cache.get_items(0..ITEMS_PER_SEGMENT + 1).await.expect("Failed to get items") ); } #[tokio::test] async fn test_segment_persist_load() { let tmp_dir = TempDir::new().unwrap(); let segment_id = 10; const MAX_ITEMS: u32 = Segment::::ITEMS_PER_SEGMENT; // Testing with half full segment let items = FilterHeader::dummy_batch(0..MAX_ITEMS / 2); let mut segment = Segment::new(segment_id, items.clone(), SegmentState::Dirty); assert_eq!(segment.first_valid_offset(), Some(0)); assert_eq!(segment.last_valid_offset(), Some(MAX_ITEMS / 2 - 1)); assert_eq!(segment.get(0..MAX_ITEMS / 2), &items[0..MAX_ITEMS as usize / 2]); assert_eq!( segment.get(MAX_ITEMS / 2 - 1..MAX_ITEMS / 2), [FilterHeader::dummy(MAX_ITEMS / 2 - 1)] ); assert_eq!(segment.state, SegmentState::Dirty); assert!(segment.persist(tmp_dir.path()).await.is_ok()); assert_eq!(segment.state, SegmentState::Clean); let mut loaded_segment = Segment::::load(tmp_dir.path(), segment_id).await.unwrap(); assert_eq!(loaded_segment.first_valid_offset(), Some(0)); assert_eq!(loaded_segment.last_valid_offset(), Some(MAX_ITEMS / 2 - 1)); assert_eq!(loaded_segment.get(0..MAX_ITEMS / 2), &items[0..MAX_ITEMS as usize / 2]); assert_eq!( loaded_segment.get(MAX_ITEMS / 2 - 1..MAX_ITEMS / 2), [FilterHeader::dummy(MAX_ITEMS / 2 - 1)] ); let path = tmp_dir.path().join(FilterHeader::segment_file_name(segment_id)); let mut bytes = fs::read(&path).unwrap(); bytes[0] ^= 1; fs::write(&path, bytes).unwrap(); let result = Segment::::load(tmp_dir.path(), segment_id).await; assert!(matches!(result, Err(StorageError::Corruption(_)))); } #[tokio::test] async fn test_truncate_above_within_segment() { let tmp_dir = TempDir::new().unwrap(); let items = FilterHeader::dummy_batch(0..20); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); assert_eq!(cache.tip_height(), Some(19)); cache.truncate_above(9).await.unwrap(); assert_eq!(cache.tip_height(), Some(9)); assert_eq!(cache.start_height(), Some(0)); let kept = cache.get_items(0..10).await.unwrap(); assert_eq!(kept, items[0..10]); // Re-store into the truncated range — must not panic on the sentinel debug_assert. let replacement = FilterHeader::dummy_batch(100..110); cache.store_items_at_height(&replacement, 10).await.unwrap(); assert_eq!(cache.tip_height(), Some(19)); let reread = cache.get_items(10..20).await.unwrap(); assert_eq!(reread, replacement); } #[tokio::test] async fn test_truncate_within_segment_persist_reload() { let tmp_dir = TempDir::new().unwrap(); let items = FilterHeader::dummy_batch(0..20); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.persist(tmp_dir.path()).await; let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.truncate_above(9).await.unwrap(); cache.persist(tmp_dir.path()).await; // Reopen without re-storing to verify the boundary segment was rewritten // with sentinel slots above the cut. If `reset_above`'s dirty flag were // skipped, the stale on-disk slots would survive and `tip_height` would // come back as 19. let mut reloaded = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); assert_eq!(reloaded.tip_height(), Some(9)); assert_eq!(reloaded.get_items(0..10).await.unwrap(), items[0..10]); for height in 10..20u32 { assert_eq!(reloaded.get_item(height).await.unwrap(), None); } } #[tokio::test] async fn test_truncate_above_segment_boundary() { let tmp_dir = TempDir::new().unwrap(); const ITEMS_PER_SEGMENT: u32 = Segment::::ITEMS_PER_SEGMENT; let items = FilterHeader::dummy_batch(0..ITEMS_PER_SEGMENT + 5); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); assert_eq!(cache.tip_height(), Some(ITEMS_PER_SEGMENT + 4)); // Persist first so segment 1's file is actually on disk, otherwise the // post-truncate `!exists()` check below would be trivially true. cache.persist(tmp_dir.path()).await; let dropped_segment_file = tmp_dir.path().join(FilterHeader::segment_file_name(1)); assert!(dropped_segment_file.exists()); cache.truncate_above(ITEMS_PER_SEGMENT - 1).await.unwrap(); assert_eq!(cache.tip_height(), Some(ITEMS_PER_SEGMENT - 1)); let kept = cache.get_items(0..ITEMS_PER_SEGMENT).await.unwrap(); assert_eq!(kept, items[0..ITEMS_PER_SEGMENT as usize]); cache.persist(tmp_dir.path()).await; assert!(!dropped_segment_file.exists()); // Reload and verify the truncation is durable. let mut reloaded = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); assert_eq!(reloaded.tip_height(), Some(ITEMS_PER_SEGMENT - 1)); // Re-storing into the dropped segment is sound. let new_items = FilterHeader::dummy_batch(500..505); reloaded.store_items_at_height(&new_items, ITEMS_PER_SEGMENT).await.unwrap(); assert_eq!(reloaded.tip_height(), Some(ITEMS_PER_SEGMENT + 4)); let reread = reloaded.get_items(ITEMS_PER_SEGMENT..ITEMS_PER_SEGMENT + 5).await.unwrap(); assert_eq!(reread, new_items); } #[tokio::test] async fn test_truncate_above_then_store_into_dropped_segment_without_persist() { let tmp_dir = TempDir::new().unwrap(); const ITEMS_PER_SEGMENT: u32 = Segment::::ITEMS_PER_SEGMENT; let items = FilterHeader::dummy_batch(0..ITEMS_PER_SEGMENT + 5); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.persist(tmp_dir.path()).await; let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.truncate_above(ITEMS_PER_SEGMENT - 1).await.unwrap(); // Re-store into the dropped segment before persist runs: its file is // gone, so the insert starts from an empty segment. let replacement = FilterHeader::dummy_batch(500..505); cache.store_items_at_height(&replacement, ITEMS_PER_SEGMENT).await.unwrap(); assert_eq!(cache.tip_height(), Some(ITEMS_PER_SEGMENT + 4)); let reread = cache.get_items(ITEMS_PER_SEGMENT..ITEMS_PER_SEGMENT + 5).await.unwrap(); assert_eq!(reread, replacement); cache.persist(tmp_dir.path()).await; let mut reloaded = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); assert_eq!(reloaded.tip_height(), Some(ITEMS_PER_SEGMENT + 4)); let reread = reloaded.get_items(ITEMS_PER_SEGMENT..ITEMS_PER_SEGMENT + 5).await.unwrap(); assert_eq!(reread, replacement); } #[tokio::test] async fn test_read_above_truncated_tip_preserves_deletion() { let tmp_dir = TempDir::new().unwrap(); const ITEMS_PER_SEGMENT: u32 = Segment::::ITEMS_PER_SEGMENT; let items = FilterHeader::dummy_batch(0..ITEMS_PER_SEGMENT + 5); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.persist(tmp_dir.path()).await; let dropped_segment_file = tmp_dir.path().join(FilterHeader::segment_file_name(1)); assert!(dropped_segment_file.exists()); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.truncate_above(ITEMS_PER_SEGMENT - 1).await.unwrap(); assert!(!dropped_segment_file.exists()); // Reading above the truncated tip must not bring the segment back as an // all-sentinel file on the next persist. assert_eq!(cache.get_item(ITEMS_PER_SEGMENT + 2).await.unwrap(), None); assert_eq!(cache.get_item(ITEMS_PER_SEGMENT).await.unwrap(), None); cache.persist(tmp_dir.path()).await; assert!(!dropped_segment_file.exists()); } #[tokio::test] async fn test_get_items_above_truncated_tip_preserves_deletion() { let tmp_dir = TempDir::new().unwrap(); const ITEMS_PER_SEGMENT: u32 = Segment::::ITEMS_PER_SEGMENT; let items = FilterHeader::dummy_batch(0..ITEMS_PER_SEGMENT + 5); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.persist(tmp_dir.path()).await; let dropped_segment_file = tmp_dir.path().join(FilterHeader::segment_file_name(1)); assert!(dropped_segment_file.exists()); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.truncate_above(ITEMS_PER_SEGMENT - 1).await.unwrap(); // A range read that spans into the dropped segment must error rather // than bring it back as sentinels. assert!(matches!( cache.get_items(ITEMS_PER_SEGMENT..ITEMS_PER_SEGMENT + 5).await, Err(StorageError::InvalidArgument(_)) )); cache.persist(tmp_dir.path()).await; assert!(!dropped_segment_file.exists()); } #[tokio::test] async fn test_get_items_above_truncated_tip_within_segment_errors() { let tmp_dir = TempDir::new().unwrap(); let items = FilterHeader::dummy_batch(0..20); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.truncate_above(9).await.unwrap(); // Reading past the truncated tip would land in the boundary segment's // sentinel tail. Fail fast instead of panicking on the // `last_valid_offset` debug_assert. assert!(matches!(cache.get_items(0..15).await, Err(StorageError::InvalidArgument(_)))); assert!(matches!(cache.get_items(8..11).await, Err(StorageError::InvalidArgument(_)))); let kept = cache.get_items(0..10).await.unwrap(); assert_eq!(kept, items[0..10]); } #[tokio::test] async fn test_truncate_above_noop_cases() { let tmp_dir = TempDir::new().unwrap(); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.truncate_above(0).await.unwrap(); cache.truncate_above(100).await.unwrap(); assert_eq!(cache.tip_height(), None); let items = FilterHeader::dummy_batch(0..10); cache.store_items_at_height(&items, 0).await.unwrap(); cache.truncate_above(9).await.unwrap(); assert_eq!(cache.tip_height(), Some(9)); cache.truncate_above(100).await.unwrap(); assert_eq!(cache.tip_height(), Some(9)); let kept = cache.get_items(0..10).await.unwrap(); assert_eq!(kept, items); } #[tokio::test] async fn test_truncate_below_start_clears() { let tmp_dir = TempDir::new().unwrap(); let items = FilterHeader::dummy_batch(0..5); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 10).await.unwrap(); assert_eq!(cache.start_height(), Some(10)); cache.truncate_above(5).await.unwrap(); assert_eq!(cache.tip_height(), None); assert_eq!(cache.start_height(), None); } #[tokio::test] async fn test_sequential_truncations_within_same_segment() { let tmp_dir = TempDir::new().unwrap(); let items = FilterHeader::dummy_batch(0..30); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.truncate_above(20).await.unwrap(); assert_eq!(cache.tip_height(), Some(20)); cache.truncate_above(10).await.unwrap(); assert_eq!(cache.tip_height(), Some(10)); assert_eq!(cache.start_height(), Some(0)); // Re-store into the doubly-truncated range. Both `reset_above` passes // must have left the slots as sentinels for `insert` to remain sound. let replacement = FilterHeader::dummy_batch(200..220); cache.store_items_at_height(&replacement, 11).await.unwrap(); assert_eq!(cache.tip_height(), Some(30)); assert_eq!(cache.get_items(11..31).await.unwrap(), replacement); } #[tokio::test] async fn test_sequential_truncations_across_segment_boundaries() { let tmp_dir = TempDir::new().unwrap(); const ITEMS_PER_SEGMENT: u32 = Segment::::ITEMS_PER_SEGMENT; let items = FilterHeader::dummy_batch(0..ITEMS_PER_SEGMENT * 3); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.persist(tmp_dir.path()).await; let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.truncate_above(ITEMS_PER_SEGMENT * 2 + 5).await.unwrap(); cache.truncate_above(ITEMS_PER_SEGMENT + 5).await.unwrap(); cache.persist(tmp_dir.path()).await; // Segment 2 must be gone on disk (dropped by the second cut), // segment 1 stays (its tail was reset by `reset_above`). assert!(!tmp_dir.path().join(FilterHeader::segment_file_name(2)).exists()); assert!(tmp_dir.path().join(FilterHeader::segment_file_name(1)).exists()); let mut reloaded = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); assert_eq!(reloaded.tip_height(), Some(ITEMS_PER_SEGMENT + 5)); let replacement = FilterHeader::dummy_batch(500..510); reloaded.store_items_at_height(&replacement, ITEMS_PER_SEGMENT + 6).await.unwrap(); assert_eq!( reloaded.get_items(ITEMS_PER_SEGMENT + 6..ITEMS_PER_SEGMENT + 16).await.unwrap(), replacement ); } /// Ranges that begin below the lowest stored height read never-populated /// sentinel slots and must fail with a typed error rather than panicking /// on the `first_valid_offset` debug assertion (or silently returning /// sentinels in release builds). #[tokio::test] async fn test_get_items_below_start_height_errors() { let tmp_dir = TempDir::new().unwrap(); let items = FilterHeader::dummy_batch(0..10); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 900).await.unwrap(); assert_eq!(cache.start_height(), Some(900)); // Entirely below the stored range (the #892 shape: a scan start far // below tip-region storage, within the same segment). assert!(matches!(cache.get_items(100..200).await, Err(StorageError::InvalidArgument(_)))); // Straddling the lowest stored height. assert!(matches!(cache.get_items(895..905).await, Err(StorageError::InvalidArgument(_)))); // The stored range itself is readable. assert_eq!(cache.get_items(900..910).await.unwrap(), items); // Same result when the never-populated slots live in a lower segment // than the stored data. const ITEMS_PER_SEGMENT: u32 = Segment::::ITEMS_PER_SEGMENT; let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, ITEMS_PER_SEGMENT + 5).await.unwrap(); assert!(matches!(cache.get_items(100..200).await, Err(StorageError::InvalidArgument(_)))); // An empty cache rejects every range. let mut cache = SegmentCache::::load_or_new(tmp_dir.path().join("empty")).await.unwrap(); assert!(matches!(cache.get_items(0..1).await, Err(StorageError::InvalidArgument(_)))); } #[tokio::test] async fn test_segment_cache_clear() { let tmp_dir = TempDir::new().unwrap(); const ITEMS_PER_SEGMENT: u32 = Segment::::ITEMS_PER_SEGMENT; // Two segments' worth of items, persisted to disk. let items = FilterHeader::dummy_batch(0..ITEMS_PER_SEGMENT + 5); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.persist(tmp_dir.path()).await; let file_0 = tmp_dir.path().join(FilterHeader::segment_file_name(0)); let file_1 = tmp_dir.path().join(FilterHeader::segment_file_name(1)); assert!(file_0.exists()); assert!(file_1.exists()); // Reopen (so only the min/max segments are resident) and clear. let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.clear().await.unwrap(); assert!(!file_0.exists()); assert!(!file_1.exists()); assert_eq!(cache.tip_height(), None); assert_eq!(cache.start_height(), None); assert_eq!(cache.get_item(3).await.unwrap(), None); assert!(cache.get_items(0..5).await.is_err()); // Reads after the clear must not bring the files back. cache.persist(tmp_dir.path()).await; assert!(!file_0.exists()); assert!(!file_1.exists()); // Storing a fresh range from a lower origin after clear is sound. let replacement = FilterHeader::dummy_batch(100..110); cache.store_items_at_height(&replacement, 100).await.unwrap(); assert_eq!(cache.start_height(), Some(100)); assert_eq!(cache.tip_height(), Some(109)); assert_eq!(cache.get_items(100..110).await.unwrap(), replacement); cache.persist(tmp_dir.path()).await; let mut reloaded = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); assert_eq!(reloaded.start_height(), Some(100)); assert_eq!(reloaded.tip_height(), Some(109)); assert_eq!(reloaded.get_items(100..110).await.unwrap(), replacement); } /// `clear` must also drop dirty in-memory state that was never persisted, /// and queue previously-persisted files of those same segments. #[tokio::test] async fn test_segment_cache_clear_unpersisted_state() { let tmp_dir = TempDir::new().unwrap(); let items = FilterHeader::dummy_batch(0..10); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.persist(tmp_dir.path()).await; // Dirty the resident segment again so it differs from disk, then clear // without an intervening persist. let more = FilterHeader::dummy_batch(100..105); cache.store_items_at_height(&more, 10).await.unwrap(); cache.clear().await.unwrap(); assert_eq!(cache.tip_height(), None); assert_eq!(cache.start_height(), None); cache.persist(tmp_dir.path()).await; assert!(!tmp_dir.path().join(FilterHeader::segment_file_name(0)).exists()); let reloaded = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); assert_eq!(reloaded.tip_height(), None); assert_eq!(reloaded.start_height(), None); } /// Stores `items` across two segments, then puts back a stale copy of segment 0. async fn check_load_truncates_at_stale_segment_hole(items: &[I]) { let tmp_dir = TempDir::new().unwrap(); let first_segment = tmp_dir.path().join(I::segment_file_name(0)); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items[..100], 0).await.unwrap(); cache.persist(tmp_dir.path()).await; let stale_first_segment = fs::read(&first_segment).unwrap(); cache.store_items_at_height(&items[100..], 100).await.unwrap(); cache.persist(tmp_dir.path()).await; drop(cache); // A kill after segment 1 reached disk but before segment 0 was rewritten. fs::write(&first_segment, stale_first_segment).unwrap(); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); assert_eq!(cache.tip_height(), Some(99)); assert_eq!(cache.get_items(0..100).await.unwrap(), items[..100]); assert!(!tmp_dir.path().join(I::segment_file_name(1)).exists()); } #[tokio::test] async fn test_load_truncates_at_stale_segment_hole() { let filter_headers = FilterHeader::dummy_batch(0..FilterHeader::ITEMS_PER_SEGMENT + 10); check_load_truncates_at_stale_segment_hole(&filter_headers).await; let headers: Vec<_> = BlockHeader::dummy_batch(0..HashedBlockHeader::ITEMS_PER_SEGMENT + 10) .iter() .map(HashedBlockHeader::from) .collect(); check_load_truncates_at_stale_segment_hole(&headers).await; } #[tokio::test] async fn test_load_truncates_at_missing_segment_file() { let tmp_dir = TempDir::new().unwrap(); let per_segment = FilterHeader::ITEMS_PER_SEGMENT; let items = FilterHeader::dummy_batch(0..2 * per_segment + 10); let mut cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); cache.store_items_at_height(&items, 0).await.unwrap(); cache.persist(tmp_dir.path()).await; drop(cache); fs::remove_file(tmp_dir.path().join(FilterHeader::segment_file_name(1))).unwrap(); let cache = SegmentCache::::load_or_new(tmp_dir.path()).await.unwrap(); assert_eq!(cache.tip_height(), Some(per_segment - 1)); assert!(!tmp_dir.path().join(FilterHeader::segment_file_name(2)).exists()); } #[test] fn test_parse_segment_id() { type Cache = SegmentCache; // Round-trips the writer's `{prefix}_{id:06}.{ext}` format for a range // of ids, including ones wider than the zero-padding. for id in [0u32, 1, 42, 999_999, 1_000_000, u32::MAX] { assert_eq!(Cache::parse_segment_id(&FilterHeader::segment_file_name(id)), Some(id)); } // Zero-padded low ids parse to their numeric value, not truncated. assert_eq!(Cache::parse_segment_id("segment_000000.dat"), Some(0)); assert_eq!(Cache::parse_segment_id("segment_000005.dat"), Some(5)); // Ids wider than the padding are accepted whole, never truncated to // the first six digits. assert_eq!(Cache::parse_segment_id("segment_1000000.dat"), Some(1_000_000)); // Trailing junk between the id and the extension is rejected rather // than silently parsed as a prefix of the component. assert_eq!(Cache::parse_segment_id("segment_0000junk.dat"), None); assert_eq!(Cache::parse_segment_id("segment_12ab.dat"), None); // Wrong prefix, wrong extension, missing separator, or a // non-numeric/empty id component are all rejected. assert_eq!(Cache::parse_segment_id("segment_0000.tmp"), None); assert_eq!(Cache::parse_segment_id("other_0000.dat"), None); assert_eq!(Cache::parse_segment_id("segment0000.dat"), None); assert_eq!(Cache::parse_segment_id("segment_.dat"), None); assert_eq!(Cache::parse_segment_id("segment_-1.dat"), None); assert_eq!(Cache::parse_segment_id("segment_0000.dat.bak"), None); // The filter storage's item type round-trips through the same helper. assert_eq!( SegmentCache::>::parse_segment_id(&>::segment_file_name(7)), Some(7) ); } #[test] fn test_cached_sentinels_carry_their_header_hash() { // Equality ignores the cached hash, so a wrong one would only show in persisted segments. let header = HashedBlockHeader::sentinel(); assert_eq!(*header.hash(), header.header().block_hash()); let block = HashedBlock::sentinel(); assert_eq!(*block.hash(), block.block().block_hash()); assert_eq!(block.block().header, *header.header()); } #[test] fn test_segment_insert_get() { let segment_id = 10; let items = FilterHeader::dummy_batch(0..10); let mut segment = Segment::new(segment_id, items, SegmentState::Dirty); assert_eq!(segment.first_valid_offset(), Some(0)); assert_eq!(segment.last_valid_offset(), Some(9)); assert_eq!(segment.get(0..10), &(0..10).map(FilterHeader::dummy).collect::>()); segment.insert(FilterHeader::dummy(10), 10); assert_eq!(segment.last_valid_offset(), Some(10)); assert_eq!(segment.get(0..11), &(0..11).map(FilterHeader::dummy).collect::>()); } }