Skip to content

Re-sync filter headers when a segment file is missing #1501

In review

Description

@DCG-Claude

Filter-header storage keeps 50,000 headers per segment file. On open, it takes the tip from the highest segment file and never checks that the segments below it exist. If one segment file was never written (for example a persist that failed when the disk was full), its heights read back as all-zero sentinel headers. Filter-header sync still reports itself as synced, and filter sync then fails verification at the first height of that segment on every attempt, so it stalls for good. On open, the store now truncates to the last header before the first missing segment file, so filter-header sync downloads the lost range again.

Root cause

SegmentCache::load_or_new sets tip_height from the last valid slot of the highest-numbered segment file and start_height from the lowest. Segments in between are only loaded when needed. A missing file is then created in memory as all sentinels ([0; 32] for FilterHeader). In release builds get_items returns those sentinels without complaint, because its gap checks are debug assertions only. SegmentCache::persist only logs write errors, so a failed write (low disk space, unclean shutdown) can leave one segment file missing while higher segment files exist. The filter-headers manager resumes from the stored tip and so treats the range as complete. FilterValidator then compares every downloaded filter against an expected header of zero and fails. The failing height in the report, 450000, is exactly the first height of segment 9 (450000 / 50000). The same filter batch is retried indefinitely with no recovery path.

Reproduction

(First pass, superseded by the update below: at the time the sandbox had no Rust toolchain, so this was traced through the code.)

  1. segments.rs load_or_new takes the tip from the max segment id only.
  2. Segment::load returns a dirty, all-sentinel segment when the file is missing.
  3. get_items returns those sentinels in release builds.
  4. FilterHeadersManager::start_download starts from get_filter_tip_height() + 1, so the missing range is never fetched again.
  5. FiltersManager::store_and_match_batches validates against the zero header and returns InvalidFilterHeaderChain on every retry.

I added the regression test storage::filter_headers::tests::test_open_truncates_at_missing_segment. It stores just over three segments of headers, persists them, deletes segment 1's file and reopens the store. On the unchanged code the reopened tip stays at the old height instead of the end of segment 0, so the test is expected to fail there.

Confidence in this diagnosis: medium.

Update: verified with a real build and test run

The fix agent now builds and tests in its sandbox (Rust 1.98.1, dependencies vendored, offline), so this was re-run against dev at 6e15db8 with a real regression test.

SegmentCache::get_items returned the empty-slot sentinel (an all-zero FilterHeader) when a slot inside the stored range had never been written. In release builds that zero became the expected filter header. Filter verification then failed on the same batch on every attempt, so filter sync stayed stuck at one height and a restart or rescan could not move it. get_items now returns StorageError::Corruption for such a slot. That error already raises SyncEvent::StorageCorrupted, and the client handles it by wiping storage and syncing again.

Regression test: cargo test --offline -p dash-spv --lib storage::segments::tests::test_segment_cache_get_items_reports_gap_as_corruption

  • On the unchanged code: failed
  • With the fix: passed
  • Re-run by the service on the final commit: passed
Output on the unchanged code
thread 'storage::segments::tests::test_segment_cache_get_items_reports_gap_as_corruption' panicked at dash-spv/src/storage/segments.rs:294:26:
Trying to access invalid offset (0) in segment with first_valid_offset = Some(1)

failures:
    storage::segments::tests::test_segment_cache_get_items_reports_gap_as_corruption

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 771 filtered out; finished in 0.22s
Output with the fix
running 1 test
test storage::segments::tests::test_segment_cache_get_items_reports_gap_as_corruption ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 771 filtered out; finished in 0.20s

This verified fix takes a different route from the candidate diff above: instead of truncating the store when a segment file is missing, SegmentCache::get_items reports an empty slot inside the stored range as StorageError::Corruption. That raises the existing SyncEvent::StorageCorrupted recovery, which wipes storage and syncs again. It also covers holes inside a segment file, which the candidate above did not.

Changes:

  • dash-spv/src/storage/segments.rs: SegmentCache::get_items returns StorageError::Corruption with the missing height when a slot in the requested range holds the sentinel. This replaces the debug-only first_valid_offset/last_valid_offset panics.
  • dash-spv/src/storage/segments.rs: removed the debug-only gap assertion from Segment::get, since get_items now checks in every build. Updated the doc comment and the nearby comment that referred to the old assertion.
  • dash-spv/src/storage/segments.rs: added the regression test test_segment_cache_get_items_reports_gap_as_corruption.

Open questions:

  1. The fix makes the damage detectable and lets the existing corruption recovery repair it. It does not stop the hole from forming: each segment is still persisted on its own, and SegmentCache::persist only logs a write error. That deserves a follow-up.
  2. The recovery (handle_corruption) wipes storage and syncs from scratch. That is the existing behaviour for checksum failures, but it costs a full resync, possibly over mobile data.
  3. get_items is shared by the block header, filter header and filter stores. Any read that used to return sentinel values quietly in release builds now fails with Corruption. Reviewers should confirm no caller relies on reading empty slots inside [start, tip].
  4. Every get_items call now does a linear comparison against the sentinel in release builds too. Before, only debug builds did that check.
  5. The end-to-end recovery (filters manager error, then StorageCorrupted, then wipe and resync) was not tested here. The dashd integration tests were not run.
  6. The problem statement also suggested changes to the iOS wallet (progress stall detection, free-space checks, and making "Rescan Filters" reset the store). They belong in dashwallet-ios and were not attempted.

The draft pull request could not be pushed yet: the bot's fork is behind upstream, and GitHub refuses to let its token carry upstream's workflow-file commits without the workflow scope. It will be opened once that is sorted.

Candidate change

A change was prepared but not opened as a pull request, because the fix agent was not highly confident in it. Review it before using it.

Diff
diff --git a/dash-spv/src/storage/filter_headers.rs b/dash-spv/src/storage/filter_headers.rs
index 3ba40953..ab5345e1 100644
--- a/dash-spv/src/storage/filter_headers.rs
+++ b/dash-spv/src/storage/filter_headers.rs
@@ -72,7 +72,9 @@ impl PersistentStorage for PersistentFilterHeaderStorage {
         let storage_path = storage_path.into();
         let segments_folder = storage_path.join(Self::FOLDER_NAME);
 
-        let filter_headers = SegmentCache::load_or_new(segments_folder).await?;
+        let mut filter_headers = SegmentCache::load_or_new(segments_folder).await?;
+        // Filter headers must be contiguous: re-sync from a lost segment on.
+        filter_headers.truncate_at_missing_segment().await?;
 
         Ok(Self {
             filter_headers: RwLock::new(filter_headers),
@@ -119,6 +121,7 @@ impl FilterHeaderStorage for PersistentFilterHeaderStorage {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use crate::storage::segments::Persistable;
     use tempfile::TempDir;
 
     #[tokio::test]
@@ -134,4 +137,35 @@ mod tests {
         assert_eq!(storage.get_filter_tip_height().await.unwrap(), Some(2));
         assert_eq!(storage.get_filter_header(3).await.unwrap(), None);
     }
+
+    #[tokio::test]
+    async fn test_open_truncates_at_missing_segment() {
+        let tmp_dir = TempDir::new().unwrap();
+        let per_segment = FilterHeader::ITEMS_PER_SEGMENT;
+        let tip = 3 * per_segment + 10;
+
+        let mut storage = PersistentFilterHeaderStorage::open(tmp_dir.path()).await.unwrap();
+        let headers = FilterHeader::dummy_batch(0..tip + 1);
+        storage.store_filter_headers_at_height(&headers, 0).await.unwrap();
+        storage.persist(tmp_dir.path()).await.unwrap();
+        drop(storage);
+
+        // Lose the second segment, as an interrupted persist can.
+        let segments_dir = tmp_dir.path().join(PersistentFilterHeaderStorage::FOLDER_NAME);
+        std::fs::remove_file(segments_dir.join(FilterHeader::segment_file_name(1))).unwrap();
+
+        let storage = PersistentFilterHeaderStorage::open(tmp_dir.path()).await.unwrap();
+
+        // The tip falls back to the last header before the gap, so filter
+        // header sync downloads the lost range again.
+        assert_eq!(storage.get_filter_tip_height().await.unwrap(), Some(per_segment - 1));
+        assert_eq!(
+            storage.get_filter_header(per_segment - 1).await.unwrap(),
+            Some(headers[(per_segment - 1) as usize])
+        );
+        assert_eq!(storage.get_filter_header(per_segment).await.unwrap(), None);
+        // The orphaned segments above the gap are gone as well.
+        assert!(!segments_dir.join(FilterHeader::segment_file_name(2)).exists());
+        assert!(!segments_dir.join(FilterHeader::segment_file_name(3)).exists());
+    }
 }
diff --git a/dash-spv/src/storage/segments.rs b/dash-spv/src/storage/segments.rs
index c600e931..7c0d30af 100644
--- a/dash-spv/src/storage/segments.rs
+++ b/dash-spv/src/storage/segments.rs
@@ -441,6 +441,49 @@ impl<I: Persistable> SegmentCache<I> {
         Ok(())
     }
 
+    /// Drop every item above the first segment file missing between the
+    /// lowest and the highest stored segment.
+    ///
+    /// Only meaningful for stores that must be contiguous (such as filter
+    /// headers). A segment whose file was never written, for example because
+    /// a persist failed, would otherwise be read back as sentinels while the
+    /// tip still points past it, so the lost range would never be fetched again.
+    pub async fn truncate_at_missing_segment(&mut self) -> StorageResult<()> {
+        let (Some(start), Some(tip)) = (self.start_height, self.tip_height) else {
+            return Ok(());
+        };
+
+        let first_segment_id = Self::height_to_segment_id(start);
+        let last_segment_id = Self::height_to_segment_id(tip);
+
+        for segment_id in (first_segment_id + 1)..=last_segment_id {
+            if self.segments.contains_key(&segment_id)
+                || self.segments_dir.join(I::segment_file_name(segment_id)).exists()
+            {
+                continue;
+            }
+
+            let prev_segment_id = segment_id - 1;
+            let new_tip = self
+                .get_segment(&prev_segment_id)
+                .await?
+                .last_valid_offset()
+                .map(|offset| Self::segment_id_to_start_height(prev_segment_id) + offset);
+
+            tracing::warn!(
+                "SegmentCache<{}>: segment {segment_id} is missing below the tip {tip}, truncating to {new_tip:?}",
+                std::any::type_name::<I>()
+            );
+
+            return match new_tip {
+                Some(new_tip) => self.truncate_above(new_tip).await,
+                None => self.clear().await,
+            };
+        }
+
+        Ok(())
+    }
+
     /// Drop every stored item, leaving the cache empty.
     ///
     /// All backing segment files — including segments not currently resident

Open questions

  • Nothing was compiled or run; CI needs to build and run the new test.
  • The fix covers one cause only: a whole segment file missing between existing ones. It does not detect sentinel gaps inside a segment file that exists, and the report does not prove which case the affected device has. If the bad header turns out to be inside a file that exists, a further fix is needed: for example, invalidating the filter-header range when filter verification fails against it. That needs coordination between the filter and filter-header managers, and I did not attempt it.
  • After truncation, filter storage may still hold filters above the new filter-header tip. When those heights are downloaded again, Segment::insert hits its debug_assert that the slot is empty. That is only a problem in debug builds; release builds overwrite the slot. Reviewers should check that FiltersManager handles a filter-header tip lower than filters already stored.
  • The check runs only for filter headers. Block headers use the same SegmentCache and could be affected in the same way; I left them alone to keep the change small.
  • SegmentCache::persist still only logs write failures, which is the likely origin of the missing file.
  • The iOS wallet showing no error while progress is frozen belongs to the app or SDK side and is not addressed here.

🤖 Opened by dash-support-bot, an automated assistant, from a report to Dash support (internal support ticket 32912). The reporter's details are left out. It has not been reviewed by a human yet.

Activity

  1. added 2 commits that reference this issue on Dec 1, 2026
    3ae59f7
    072316d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions