Skip to main content

zebrad/components/sync/
diagnostics.rs

1//! Syncer state published for stall diagnosis.
2
3use std::{
4    collections::BTreeMap,
5    sync::{Arc, Mutex, MutexGuard},
6    time::{Duration, Instant},
7};
8
9use tokio::task::AbortHandle;
10
11use zebra_chain::block;
12
13/// Why a sync round ended.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum RestartReason {
16    /// The syncer downloaded every block its peers advertised.
17    ExhaustedTips,
18    /// Obtaining tips from peers took too long.
19    ObtainTipsTimeout,
20    /// Obtaining tips failed.
21    ObtainTipsError,
22    /// Extending tips failed.
23    ExtendTipsError,
24    /// The state tip did not advance for the block verify timeout during a sync round, so the
25    /// syncer backs off without cancelling pending downloads.
26    SyncStepTimeout,
27    /// A block download or verification failed with an error that restarts the sync.
28    BlockError,
29}
30
31impl RestartReason {
32    /// Returns the metric label and log field value for this reason.
33    pub fn as_str(self) -> &'static str {
34        match self {
35            RestartReason::ExhaustedTips => "exhausted_tips",
36            RestartReason::ObtainTipsTimeout => "obtain_tips_timeout",
37            RestartReason::ObtainTipsError => "obtain_tips_error",
38            RestartReason::ExtendTipsError => "extend_tips_error",
39            RestartReason::SyncStepTimeout => "sync_step_timeout",
40            RestartReason::BlockError => "block_error",
41        }
42    }
43}
44
45/// A snapshot of the syncer's state, read by the progress task when sync stalls.
46#[derive(Clone, Debug, Default)]
47pub struct SyncDiagnostics {
48    /// How the latest sync round ended.
49    pub last_restart: Option<RestartReason>,
50
51    /// The number of consecutive sync rounds that ended without the state tip advancing.
52    pub restarts_without_progress: u32,
53
54    /// The number of blocks being downloaded or verified.
55    pub in_flight: usize,
56
57    /// The blocks that might still be downloading or verifying, shared with the downloader.
58    pub in_flight_blocks: InFlightBlocks,
59}
60
61impl SyncDiagnostics {
62    /// Returns how long the oldest block that is still being downloaded or verified has been
63    /// queued, as of `now`.
64    pub fn oldest_in_flight_age(&self, now: Instant) -> Option<Duration> {
65        self.in_flight_blocks
66            .oldest_running_since()
67            .map(|queued_at| now.saturating_duration_since(queued_at))
68    }
69}
70
71/// The block download and verify tasks that might still be running, ordered by when they were
72/// queued.
73///
74/// The downloader and the progress task share it, because a finished task stays in the downloader
75/// until the syncer reads its result, which can be the next sync round for a node at the tip,
76/// and the syncer only republishes its state during a round.
77#[derive(Clone, Debug, Default)]
78pub struct InFlightBlocks(Arc<Mutex<BTreeMap<(Instant, [u8; 32]), AbortHandle>>>);
79
80impl InFlightBlocks {
81    /// Adds the task for `hash`, queued at `queued_at`.
82    pub fn insert(&self, queued_at: Instant, hash: block::Hash, task: AbortHandle) {
83        self.tasks().insert((queued_at, hash.0), task);
84    }
85
86    /// Removes the task for `hash`, queued at `queued_at`.
87    pub fn remove(&self, queued_at: Instant, hash: block::Hash) {
88        self.tasks().remove(&(queued_at, hash.0));
89    }
90
91    /// Removes every task.
92    pub fn clear(&self) {
93        self.tasks().clear();
94    }
95
96    /// Returns when the oldest task that is still running was queued, and forgets the older ones
97    /// that have finished.
98    pub fn oldest_running_since(&self) -> Option<Instant> {
99        let mut tasks = self.tasks();
100        while let Some(oldest) = tasks.first_entry() {
101            if !oldest.get().is_finished() {
102                return Some(oldest.key().0);
103            }
104            oldest.remove();
105        }
106
107        None
108    }
109
110    fn tasks(&self) -> MutexGuard<'_, BTreeMap<(Instant, [u8; 32]), AbortHandle>> {
111        self.0
112            .lock()
113            .expect("no code panics while holding the in-flight blocks lock")
114    }
115}