Skip to main content

sui_network/state_sync/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Peer-to-peer data synchronization of checkpoints.
5//!
6//! This StateSync module is responsible for the synchronization and dissemination of checkpoints
7//! and the transactions, and their effects, contained within. This module is *not* responsible for
8//! the execution of the transactions included in a checkpoint, that process is left to another
9//! component in the system.
10//!
11//! # High-level Overview of StateSync
12//!
13//! StateSync discovers new checkpoints via a few different sources:
14//! 1. If this node is a Validator, checkpoints will be produced via consensus at which point
15//!    consensus can notify state-sync of the new checkpoint via [Handle::send_checkpoint].
16//! 2. A peer notifies us of the latest checkpoint which they have synchronized. State-Sync will
17//!    also periodically query its peers to discover what their latest checkpoint is.
18//!
19//! We keep track of two different watermarks:
20//! * highest_verified_checkpoint - This is the highest checkpoint header that we've locally
21//!   verified. This indicated that we have in our persistent store (and have verified) all
22//!   checkpoint headers up to and including this value.
23//! * highest_synced_checkpoint - This is the highest checkpoint that we've fully synchronized,
24//!   meaning we've downloaded and have in our persistent stores all of the transactions, and their
25//!   effects (but not the objects), for all checkpoints up to and including this point. This is
26//!   the watermark that is shared with other peers, either via notification or when they query for
27//!   our latest checkpoint, and is intended to be used as a guarantee of data availability.
28//!
29//! The `PeerHeights` struct is used to track the highest_synced_checkpoint watermark for all of
30//! our peers.
31//!
32//! When a new checkpoint is discovered, and we've determined that it is higher than our
33//! highest_verified_checkpoint, then StateSync will kick off a task to synchronize and verify all
34//! checkpoints between our highest_synced_checkpoint and the newly discovered checkpoint. This
35//! process is done by querying one of our peers for the checkpoints we're missing (using the
36//! `PeerHeights` struct as a way to intelligently select which peers have the data available for
37//! us to query) at which point we will locally verify the signatures on the checkpoint header with
38//! the appropriate committee (based on the epoch). As checkpoints are verified, the
39//! highest_synced_checkpoint watermark will be ratcheted up.
40//!
41//! Once we've ratcheted up our highest_verified_checkpoint, and if it is higher than
42//! highest_synced_checkpoint, StateSync will then kick off a task to synchronize the contents of
43//! all of the checkpoints from highest_synced_checkpoint..=highest_verified_checkpoint. After the
44//! contents of each checkpoint is fully downloaded, StateSync will update our
45//! highest_synced_checkpoint watermark and send out a notification on a broadcast channel
46//! indicating that a new checkpoint has been fully downloaded. Notifications on this broadcast
47//! channel will always be made in order. StateSync will also send out a notification to its peers
48//! of the newly synchronized checkpoint so that it can help other peers synchronize.
49
50use anemo::{PeerId, Request, Response, Result, types::PeerEvent};
51use futures::{
52    FutureExt, StreamExt,
53    stream::{FuturesOrdered, FuturesUnordered},
54};
55use rand::Rng;
56use std::{
57    collections::{HashMap, HashSet, VecDeque},
58    sync::{
59        Arc, RwLock,
60        atomic::{AtomicU64, Ordering},
61    },
62    time::{Duration, Instant},
63};
64use sui_config::p2p::StateSyncConfig;
65use sui_types::{
66    base_types::VerifiedExecutionData,
67    committee::Committee,
68    digests::CheckpointDigest,
69    messages_checkpoint::{
70        CertifiedCheckpointSummary as Checkpoint, CheckpointContents, CheckpointSequenceNumber,
71        EndOfEpochData, VerifiedCheckpoint, VerifiedCheckpointContents,
72        VersionedFullCheckpointContents,
73    },
74    storage::WriteStore,
75};
76use tap::Pipe;
77use tokio::sync::oneshot;
78use tokio::{
79    sync::{broadcast, mpsc, watch},
80    task::{AbortHandle, JoinSet},
81};
82use tracing::{debug, info, instrument, trace, warn};
83
84#[allow(clippy::result_large_err)]
85mod generated {
86    include!(concat!(env!("OUT_DIR"), "/sui.StateSync.rs"));
87}
88mod builder;
89mod metrics;
90mod server;
91#[cfg(test)]
92mod tests;
93mod worker;
94
95use self::{
96    metrics::{ContentRequestOutcome, HedgeEvent, Metrics},
97    server::CheckpointContentsDownloadLimitLayer,
98};
99use crate::state_sync::worker::process_archive_checkpoint;
100pub use builder::{Builder, UnstartedStateSync};
101pub use generated::{
102    state_sync_client::StateSyncClient,
103    state_sync_server::{StateSync, StateSyncServer},
104};
105pub use server::GetCheckpointAvailabilityResponse;
106pub use server::GetCheckpointSummaryRequest;
107pub use server::GetCheckpointTransactionsRequest;
108use sui_config::node::ArchiveReaderConfig;
109use sui_storage::object_store::util::{build_object_store, fetch_checkpoint};
110use sui_storage::verify_checkpoint;
111
112/// A handle to the StateSync subsystem.
113///
114/// This handle can be cloned and shared. Once all copies of a StateSync system's Handle have been
115/// dropped, the StateSync system will be gracefully shutdown.
116#[derive(Clone, Debug)]
117pub struct Handle {
118    sender: mpsc::Sender<StateSyncMessage>,
119    checkpoint_event_sender: broadcast::Sender<VerifiedCheckpoint>,
120    metrics: Metrics,
121}
122
123impl Handle {
124    /// Send a newly minted checkpoint from Consensus to StateSync so that it can be disseminated
125    /// to other nodes on the network.
126    ///
127    /// # Invariant
128    ///
129    /// Consensus must only notify StateSync of new checkpoints that have been fully committed to
130    /// persistent storage. This includes CheckpointContents and all Transactions and
131    /// TransactionEffects included therein.
132    pub async fn send_checkpoint(&self, checkpoint: VerifiedCheckpoint) {
133        self.sender
134            .send(StateSyncMessage::VerifiedCheckpoint(Box::new(checkpoint)))
135            .await
136            .unwrap()
137    }
138
139    /// Subscribe to the stream of checkpoints that have been fully synchronized and downloaded.
140    pub fn subscribe_to_synced_checkpoints(&self) -> broadcast::Receiver<VerifiedCheckpoint> {
141        self.checkpoint_event_sender.subscribe()
142    }
143
144    /// Returns the number of peers reported due to consistent state sync failures.
145    pub fn get_peers_reported_for_failure(&self) -> u64 {
146        self.metrics.get_peers_reported_for_failure()
147    }
148}
149
150pub(super) fn compute_adaptive_timeout(
151    tx_count: u64,
152    min_timeout: Duration,
153    max_timeout: Duration,
154) -> Duration {
155    const MAX_TRANSACTIONS_PER_CHECKPOINT: u64 = 10_000;
156    const JITTER_FRACTION: f64 = 0.1;
157
158    let max_timeout = max_timeout.max(min_timeout);
159    let ratio = (tx_count as f64 / MAX_TRANSACTIONS_PER_CHECKPOINT as f64).min(1.0);
160    let extra = Duration::from_secs_f64((max_timeout - min_timeout).as_secs_f64() * ratio);
161    let base = min_timeout + extra;
162
163    let jitter_range = base.as_secs_f64() * JITTER_FRACTION;
164    let jitter = rand::thread_rng().gen_range(-jitter_range..jitter_range);
165    Duration::from_secs_f64((base.as_secs_f64() + jitter).max(min_timeout.as_secs_f64()))
166}
167
168/// How long one checkpoint contents request to a peer took, as far as is known.
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170pub(super) enum ContentResponseTime {
171    /// The peer answered after this long.
172    Answered(Duration),
173    /// The request was cancelled after running this long because another peer answered first,
174    /// so the peer would have taken longer.
175    LongerThan(Duration),
176}
177
178/// Near the release frontier, how a contents request that is not a hedge relates to its
179/// peer's slow flag when it is sent (see [`SLOW_PEER_PROBE_INTERVAL`]).
180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
181pub(super) enum SlowPeerRequest {
182    /// The peer was not slow from this node.
183    PeerNotSlow,
184    /// The peer was slow, and the request is a slow-peer probe.
185    Probe,
186    /// The peer was slow, and the request is not a probe.
187    NotProbe,
188}
189
190impl SlowPeerRequest {
191    /// Whether the request's outcome is recorded as a response-time sample (see
192    /// `PeerScore::record_content_response_time`). While a peer is slow, only probes are.
193    /// Other requests to it are hedged right away once a peer that isn't slow has the
194    /// checkpoint, so their slow outcomes are cut short before the peer's slow-response
195    /// threshold while their fast answers still arrive. Recording them would make the peer look
196    /// less slow than it is.
197    pub(super) fn records_response_time(self) -> bool {
198        self != Self::NotProbe
199    }
200}
201
202#[cfg_attr(test, derive(Debug))]
203pub(super) struct PeerScore {
204    successes: VecDeque<(Instant, u64 /* response_size_bytes */, Duration)>,
205    /// Requests cancelled because another peer delivered the same contents first, with the time
206    /// they had run. That time is a lower bound on the response time, so a sample is kept only
207    /// if it lowers the throughput estimate (see `record_cancelled`). These samples count as
208    /// neither successes nor failures.
209    cancelled: VecDeque<(Instant, u64 /* response_size_bytes */, Duration)>,
210    /// How long recent checkpoint contents requests that were not hedges took, oldest first.
211    /// Used to decide whether requests to this peer should be hedged sooner (see
212    /// `slow_peer_hedge_delay`).
213    content_response_times: VecDeque<(Instant, ContentResponseTime)>,
214    /// Contents requests that were not hedges sent to this peer while it was slow since the last
215    /// slow-peer probe (see [`SLOW_PEER_PROBE_INTERVAL`]).
216    requests_since_probe: u32,
217    failures: VecDeque<Instant>,
218    window: Duration,
219    failure_rate: f64,
220    failing_since: Option<Instant>,
221}
222
223impl PeerScore {
224    /// How many of a peer's most recent samples of each kind (successes, failures, cancellations,
225    /// contents response times) are kept.
226    const MAX_SAMPLES: usize = 20;
227    const MIN_SAMPLES_FOR_FAILURE: usize = 10;
228    /// A contents response is slow when it takes more than 25% (this factor) longer than the peer's
229    /// fastest recent response, and at least [`Self::SLOW_RESPONSE_MIN_MARGIN`] longer.
230    const SLOW_RESPONSE_FACTOR: f64 = 1.25;
231    /// For a peer whose fastest response is under 80 ms, 25% of it is less than this margin. The
232    /// margin keeps such a peer's jitter, for example 12 ms answers that sometimes take 23 ms, from
233    /// counting as slow.
234    const SLOW_RESPONSE_MIN_MARGIN: Duration = Duration::from_millis(20);
235    /// A peer is slow when at least this share of its recent contents responses were slow.
236    const SLOW_PEER_SHARE: f64 = 0.25;
237    /// A peer can only be slow once it has at least this many recent contents responses whose
238    /// slowness is known: answers, and cancellations after its slow-response threshold.
239    const MIN_SAMPLES_FOR_SLOW: usize = 10;
240
241    pub(super) fn new(window: Duration, failure_rate: f64) -> Self {
242        Self {
243            successes: VecDeque::new(),
244            cancelled: VecDeque::new(),
245            content_response_times: VecDeque::new(),
246            requests_since_probe: 0,
247            failures: VecDeque::new(),
248            window,
249            failure_rate,
250            failing_since: None,
251        }
252    }
253
254    pub(super) fn record_success(&mut self, size: u64, response_time: Duration) {
255        let now = Instant::now();
256        self.successes.push_back((now, size, response_time));
257        while self.successes.len() > Self::MAX_SAMPLES {
258            self.successes.pop_front();
259        }
260        // Note: a single success does NOT clear `failing_since`. Whether the peer is
261        // "consistently failing" is driven by the windowed failure RATE (see
262        // `update_failing_state`), so an occasional success while the rate stays high (e.g.
263        // a brief reconnect during connection churn) must not keep resetting the clock and
264        // prevent the peer from ever being reported.
265    }
266
267    /// Records a request that was cancelled after `elapsed` because another peer delivered `size`
268    /// bytes first. `size / elapsed` is only an upper bound on this peer's throughput, so the
269    /// sample is kept only when it is below the current estimate, which it then lowers. Without
270    /// an estimate the sample carries no usable information and is dropped.
271    pub(super) fn record_cancelled(&mut self, size: u64, elapsed: Duration) {
272        let Some(current) = self.effective_throughput() else {
273            return;
274        };
275        if elapsed.is_zero() || size as f64 / elapsed.as_secs_f64() >= current {
276            return;
277        }
278        self.cancelled.push_back((Instant::now(), size, elapsed));
279        while self.cancelled.len() > Self::MAX_SAMPLES {
280            self.cancelled.pop_front();
281        }
282    }
283
284    /// Records how long a checkpoint contents request that was not a hedge took. Hedge requests
285    /// are left out: a hedge is cancelled whenever the request it hedged answers first, however
286    /// short a time it has run, so how often hedges are cut short says nothing about the peer.
287    /// Near the release frontier, requests sent while the peer was slow that were not slow-peer
288    /// probes are left out too (see [`SlowPeerRequest::records_response_time`]).
289    /// A request that was not a hedge and is cancelled after its peer's slow-response threshold
290    /// was slow. One cancelled sooner, for example by a hedge to a closer peer, might still have
291    /// answered in time, so `slow_peer_hedge_delay` counts it neither way. Such a sample is
292    /// dropped when the peer already has a slow-response threshold, so that it doesn't take the
293    /// place of a sample that counts; without a threshold yet, it is kept, because the threshold
294    /// it is compared against is only known once the peer answers.
295    pub(super) fn record_content_response_time(&mut self, response_time: ContentResponseTime) {
296        if let ContentResponseTime::LongerThan(elapsed) = response_time
297            && self
298                .slow_response_threshold()
299                .is_some_and(|threshold| elapsed < threshold)
300        {
301            return;
302        }
303        self.content_response_times
304            .push_back((Instant::now(), response_time));
305        while self.content_response_times.len() > Self::MAX_SAMPLES {
306            self.content_response_times.pop_front();
307        }
308    }
309
310    /// The fastest answer among this peer's recent contents requests that were not hedges.
311    pub(super) fn fastest_recent_content_answer(&self) -> Option<Duration> {
312        self.recent_content_response_times()
313            .filter_map(|response_time| match response_time {
314                ContentResponseTime::Answered(elapsed) => Some(elapsed),
315                ContentResponseTime::LongerThan(_) => None,
316            })
317            .min()
318    }
319
320    fn recent_content_response_times(&self) -> impl Iterator<Item = ContentResponseTime> + '_ {
321        let now = Instant::now();
322        self.content_response_times
323            .iter()
324            .filter(move |(ts, _)| now.duration_since(*ts) < self.window)
325            .map(|(_, response_time)| *response_time)
326    }
327
328    /// The peer's fastest recent contents response times [`Self::SLOW_RESPONSE_FACTOR`], or plus
329    /// [`Self::SLOW_RESPONSE_MIN_MARGIN`], whichever is more. Responses that take longer are
330    /// slow. `None` if the peer has no recent answers.
331    fn slow_response_threshold(&self) -> Option<Duration> {
332        let fastest = self.fastest_recent_content_answer()?;
333        Some(
334            fastest
335                .mul_f64(Self::SLOW_RESPONSE_FACTOR)
336                .max(fastest + Self::SLOW_RESPONSE_MIN_MARGIN),
337        )
338    }
339
340    /// If this peer is slow, its slow-response threshold (see `slow_response_threshold`), after
341    /// which requests to it should be hedged. The peer is slow when at least
342    /// [`Self::SLOW_PEER_SHARE`] of its recent responses took longer than the threshold. Returns
343    /// `None` if the peer isn't slow, or if it has too few recent samples to tell.
344    pub(super) fn slow_peer_hedge_delay(&self) -> Option<Duration> {
345        let threshold = self.slow_response_threshold()?;
346        let mut slow = 0;
347        let mut known = 0;
348        for response_time in self.recent_content_response_times() {
349            match response_time {
350                ContentResponseTime::Answered(elapsed) => {
351                    known += 1;
352                    if elapsed > threshold {
353                        slow += 1;
354                    }
355                }
356                ContentResponseTime::LongerThan(elapsed) if elapsed >= threshold => {
357                    known += 1;
358                    slow += 1;
359                }
360                // Cancelled before the threshold: whether the response would have been slow is
361                // unknown. Such samples are only stored while the peer has no threshold yet, or
362                // under an earlier, lower threshold.
363                ContentResponseTime::LongerThan(_) => {}
364            }
365        }
366        (known >= Self::MIN_SAMPLES_FOR_SLOW && slow as f64 >= Self::SLOW_PEER_SHARE * known as f64)
367            .then_some(threshold)
368    }
369
370    /// Called when a contents request that is not a hedge is about to be sent to this peer near
371    /// the release frontier. Every [`SLOW_PEER_PROBE_INTERVAL`]th such request sent while
372    /// the peer is slow is a slow-peer probe. Requests sent while the peer isn't slow are not
373    /// counted.
374    pub(super) fn classify_new_request(&mut self) -> SlowPeerRequest {
375        if self.slow_peer_hedge_delay().is_none() {
376            return SlowPeerRequest::PeerNotSlow;
377        }
378        self.requests_since_probe += 1;
379        if self.requests_since_probe < SLOW_PEER_PROBE_INTERVAL {
380            return SlowPeerRequest::NotProbe;
381        }
382        self.requests_since_probe = 0;
383        SlowPeerRequest::Probe
384    }
385
386    pub(super) fn record_failure(&mut self) {
387        let now = Instant::now();
388        self.failures.push_back(now);
389        while self.failures.len() > Self::MAX_SAMPLES {
390            self.failures.pop_front();
391        }
392    }
393
394    pub(super) fn is_failing(&self) -> bool {
395        let now = Instant::now();
396        let recent_failures = self
397            .failures
398            .iter()
399            .filter(|ts| now.duration_since(**ts) < self.window)
400            .count();
401        let recent_successes = self
402            .successes
403            .iter()
404            .filter(|(ts, _, _)| now.duration_since(*ts) < self.window)
405            .count();
406
407        let total = recent_failures + recent_successes;
408        if total < Self::MIN_SAMPLES_FOR_FAILURE {
409            return false;
410        }
411
412        let rate = recent_failures as f64 / total as f64;
413        rate >= self.failure_rate
414    }
415
416    pub(super) fn update_failing_state(&mut self) {
417        if self.is_failing() {
418            // Start the consistently-failing clock when the windowed failure rate first
419            // crosses the threshold, and let it accumulate while the rate stays high.
420            if self.failing_since.is_none() {
421                self.failing_since = Some(Instant::now());
422            }
423        } else {
424            // The windowed failure rate dropped below the threshold: the peer is no longer
425            // failing, so clear the clock. Only an actual drop in the rate resets it.
426            self.failing_since = None;
427        }
428    }
429
430    pub(super) fn reset_failing_since(&mut self) {
431        self.failing_since = None;
432    }
433
434    pub(super) fn consistently_failing(&self, threshold: Duration) -> bool {
435        match self.failing_since {
436            Some(since) => since.elapsed() >= threshold,
437            None => false,
438        }
439    }
440
441    pub(super) fn effective_throughput(&self) -> Option<f64> {
442        let now = Instant::now();
443        let (total_size, total_time) = self
444            .successes
445            .iter()
446            .chain(&self.cancelled)
447            .filter(|(ts, _, _)| now.duration_since(*ts) < self.window)
448            .fold((0u64, Duration::ZERO), |(size, time), (_, s, d)| {
449                (size + s, time + *d)
450            });
451
452        if total_size == 0 {
453            return None;
454        }
455
456        if total_time.is_zero() {
457            return None;
458        }
459
460        Some(total_size as f64 / total_time.as_secs_f64())
461    }
462}
463
464struct PeerHeights {
465    /// Table used to track the highest checkpoint for each of our peers.
466    peers: HashMap<PeerId, PeerStateSyncInfo>,
467    unprocessed_checkpoints: HashMap<CheckpointDigest, Checkpoint>,
468    sequence_number_to_digest: HashMap<CheckpointSequenceNumber, CheckpointDigest>,
469    scores: HashMap<PeerId, PeerScore>,
470
471    wait_interval_when_no_peer_to_sync_content: Duration,
472    peer_scoring_window: Duration,
473    peer_failure_rate: f64,
474    checkpoint_content_timeout_min: Duration,
475    checkpoint_content_timeout_max: Duration,
476    exploration_probability: f64,
477}
478
479#[derive(Copy, Clone, Debug, PartialEq, Eq)]
480struct PeerStateSyncInfo {
481    /// The digest of the Peer's genesis checkpoint.
482    genesis_checkpoint_digest: CheckpointDigest,
483    /// Indicates if this Peer is on the same chain as us.
484    on_same_chain_as_us: bool,
485    /// Highest checkpoint sequence number we know of for this Peer.
486    height: CheckpointSequenceNumber,
487    /// lowest available checkpoint watermark for this Peer.
488    /// This defaults to 0 for now.
489    lowest: CheckpointSequenceNumber,
490}
491
492impl PeerStateSyncInfo {
493    /// Whether the peer has announced `sequence_number` and still has its contents.
494    fn has_contents(&self, sequence_number: CheckpointSequenceNumber) -> bool {
495        self.height >= sequence_number && self.lowest <= sequence_number
496    }
497}
498
499impl PeerHeights {
500    pub fn highest_known_checkpoint_sequence_number(&self) -> Option<CheckpointSequenceNumber> {
501        self.peers
502            .values()
503            .filter_map(|info| info.on_same_chain_as_us.then_some(info.height))
504            .max()
505    }
506
507    pub fn peers_on_same_chain(&self) -> impl Iterator<Item = (&PeerId, &PeerStateSyncInfo)> {
508        self.peers
509            .iter()
510            .filter(|(_peer_id, info)| info.on_same_chain_as_us)
511    }
512
513    // Returns a bool that indicates if the update was done successfully.
514    //
515    // This will return false if the given peer doesn't have an entry or is not on the same chain
516    // as us
517    #[instrument(level = "debug", skip_all, fields(peer_id=?peer_id, checkpoint=?checkpoint.sequence_number()))]
518    pub fn update_peer_info(
519        &mut self,
520        peer_id: PeerId,
521        checkpoint: Checkpoint,
522        low_watermark: Option<CheckpointSequenceNumber>,
523    ) -> bool {
524        debug!("Update peer info");
525
526        let info = match self.peers.get_mut(&peer_id) {
527            Some(info) if info.on_same_chain_as_us => info,
528            _ => return false,
529        };
530
531        info.height = std::cmp::max(*checkpoint.sequence_number(), info.height);
532        if let Some(low_watermark) = low_watermark {
533            info.lowest = low_watermark;
534        }
535        self.insert_checkpoint(checkpoint);
536
537        true
538    }
539
540    #[instrument(level = "debug", skip_all, fields(peer_id=?peer_id, lowest = ?info.lowest, height = ?info.height))]
541    pub fn insert_peer_info(&mut self, peer_id: PeerId, info: PeerStateSyncInfo) {
542        use std::collections::hash_map::Entry;
543        debug!("Insert peer info");
544
545        match self.peers.entry(peer_id) {
546            Entry::Occupied(mut entry) => {
547                // If there's already an entry and the genesis checkpoint digests match then update
548                // the maximum height. Otherwise we'll use the more recent one
549                let entry = entry.get_mut();
550                if entry.genesis_checkpoint_digest == info.genesis_checkpoint_digest {
551                    entry.height = std::cmp::max(entry.height, info.height);
552                } else {
553                    *entry = info;
554                }
555            }
556            Entry::Vacant(entry) => {
557                entry.insert(info);
558            }
559        }
560    }
561
562    pub fn mark_peer_as_not_on_same_chain(&mut self, peer_id: PeerId) {
563        if let Some(info) = self.peers.get_mut(&peer_id) {
564            info.on_same_chain_as_us = false;
565        }
566        self.scores.remove(&peer_id);
567    }
568
569    /// Updates the peer's height without storing any checkpoint data.
570    /// Returns false if the peer doesn't exist or is not on the same chain.
571    pub fn update_peer_height(
572        &mut self,
573        peer_id: PeerId,
574        height: CheckpointSequenceNumber,
575        low_watermark: Option<CheckpointSequenceNumber>,
576    ) -> bool {
577        let info = match self.peers.get_mut(&peer_id) {
578            Some(info) if info.on_same_chain_as_us => info,
579            _ => return false,
580        };
581
582        info.height = std::cmp::max(height, info.height);
583        if let Some(low_watermark) = low_watermark {
584            info.lowest = low_watermark;
585        }
586
587        true
588    }
589
590    pub fn cleanup_old_checkpoints(&mut self, sequence_number: CheckpointSequenceNumber) {
591        self.unprocessed_checkpoints
592            .retain(|_digest, checkpoint| *checkpoint.sequence_number() > sequence_number);
593        self.sequence_number_to_digest
594            .retain(|&s, _digest| s > sequence_number);
595    }
596
597    /// Inserts a checkpoint into the unprocessed checkpoints store.
598    /// Only one checkpoint per sequence number is stored. If a checkpoint with the same
599    /// sequence number but different digest already exists, the new one is dropped.
600    // TODO: also record who gives this checkpoint info for peer quality measurement?
601    pub fn insert_checkpoint(&mut self, checkpoint: Checkpoint) {
602        let digest = *checkpoint.digest();
603        let sequence_number = *checkpoint.sequence_number();
604
605        // Check if we already have a checkpoint for this sequence number.
606        if let Some(existing_digest) = self.sequence_number_to_digest.get(&sequence_number) {
607            if *existing_digest == digest {
608                // Same checkpoint, nothing to do.
609                return;
610            }
611            tracing::info!(
612                ?sequence_number,
613                ?existing_digest,
614                ?digest,
615                "received checkpoint with same sequence number but different digest, dropping new checkpoint"
616            );
617            return;
618        }
619
620        self.unprocessed_checkpoints.insert(digest, checkpoint);
621        self.sequence_number_to_digest
622            .insert(sequence_number, digest);
623    }
624
625    pub fn remove_checkpoint(&mut self, digest: &CheckpointDigest) {
626        if let Some(checkpoint) = self.unprocessed_checkpoints.remove(digest) {
627            self.sequence_number_to_digest
628                .remove(checkpoint.sequence_number());
629        }
630    }
631
632    pub fn get_checkpoint_by_sequence_number(
633        &self,
634        sequence_number: CheckpointSequenceNumber,
635    ) -> Option<&Checkpoint> {
636        self.sequence_number_to_digest
637            .get(&sequence_number)
638            .and_then(|digest| self.get_checkpoint_by_digest(digest))
639    }
640
641    pub fn get_checkpoint_by_digest(&self, digest: &CheckpointDigest) -> Option<&Checkpoint> {
642        self.unprocessed_checkpoints.get(digest)
643    }
644
645    #[cfg(test)]
646    pub fn set_wait_interval_when_no_peer_to_sync_content(&mut self, duration: Duration) {
647        self.wait_interval_when_no_peer_to_sync_content = duration;
648    }
649
650    pub fn wait_interval_when_no_peer_to_sync_content(&self) -> Duration {
651        self.wait_interval_when_no_peer_to_sync_content
652    }
653
654    pub fn record_success(&mut self, peer_id: PeerId, size: u64, response_time: Duration) {
655        if !self.peers.contains_key(&peer_id) {
656            return;
657        }
658        self.scores
659            .entry(peer_id)
660            .or_insert_with(|| PeerScore::new(self.peer_scoring_window, self.peer_failure_rate))
661            .record_success(size, response_time);
662    }
663
664    /// Records a contents request that was cancelled after `elapsed` because another peer
665    /// delivered the same `size` bytes first. It can only lower the peer's throughput estimate
666    /// (see `PeerScore::record_cancelled`) and counts as neither success nor failure.
667    pub fn record_cancelled_request(&mut self, peer_id: PeerId, size: u64, elapsed: Duration) {
668        if let Some(score) = self.scores.get_mut(&peer_id) {
669            score.record_cancelled(size, elapsed);
670        }
671    }
672
673    /// Records how long a checkpoint contents request to `peer_id` that was not a hedge took
674    /// (see `PeerScore::record_content_response_time`).
675    pub fn record_content_response_time(
676        &mut self,
677        peer_id: PeerId,
678        response_time: ContentResponseTime,
679    ) {
680        if !self.peers.contains_key(&peer_id) {
681            return;
682        }
683        self.scores
684            .entry(peer_id)
685            .or_insert_with(|| PeerScore::new(self.peer_scoring_window, self.peer_failure_rate))
686            .record_content_response_time(response_time);
687    }
688
689    /// If `peer_id` is slow from this node, the delay after which a contents request to it
690    /// should be hedged (see `PeerScore::slow_peer_hedge_delay`).
691    pub fn slow_peer_hedge_delay(&self, peer_id: &PeerId) -> Option<Duration> {
692        self.scores
693            .get(peer_id)
694            .and_then(|score| score.slow_peer_hedge_delay())
695    }
696
697    /// Called when a contents request that is not a hedge is about to be sent to `peer_id` near
698    /// the release frontier (see `PeerScore::classify_new_request`).
699    pub fn classify_new_request(&mut self, peer_id: &PeerId) -> SlowPeerRequest {
700        self.scores
701            .get_mut(peer_id)
702            .map_or(SlowPeerRequest::PeerNotSlow, |score| {
703                score.classify_new_request()
704            })
705    }
706
707    /// The fastest answer among `peer_id`'s recent contents requests that were not hedges (see
708    /// `PeerScore::fastest_recent_content_answer`).
709    pub fn fastest_recent_content_answer(&self, peer_id: &PeerId) -> Option<Duration> {
710        self.scores
711            .get(peer_id)
712            .and_then(|score| score.fastest_recent_content_answer())
713    }
714
715    pub fn record_failure(&mut self, peer_id: PeerId) {
716        if !self.peers.contains_key(&peer_id) {
717            return;
718        }
719        self.scores
720            .entry(peer_id)
721            .or_insert_with(|| PeerScore::new(self.peer_scoring_window, self.peer_failure_rate))
722            .record_failure();
723    }
724
725    pub fn get_throughput(&self, peer_id: &PeerId) -> Option<f64> {
726        self.scores
727            .get(peer_id)
728            .and_then(|s| s.effective_throughput())
729    }
730
731    pub fn is_failing(&self, peer_id: &PeerId) -> bool {
732        self.scores
733            .get(peer_id)
734            .map(|s| s.is_failing())
735            .unwrap_or(false)
736    }
737
738    pub fn update_failing_states(&mut self) {
739        for score in self.scores.values_mut() {
740            score.update_failing_state();
741        }
742    }
743
744    pub fn find_peer_to_report_for_failure(&self, threshold: Duration) -> Option<PeerId> {
745        self.scores
746            .iter()
747            .filter(|(peer_id, score)| {
748                score.consistently_failing(threshold)
749                    && self
750                        .peers
751                        .get(peer_id)
752                        .is_some_and(|info| info.on_same_chain_as_us)
753            })
754            .max_by_key(|(_, score)| {
755                score
756                    .failing_since
757                    .map(|since| since.elapsed())
758                    .unwrap_or(Duration::ZERO)
759            })
760            .map(|(peer_id, _)| *peer_id)
761    }
762}
763
764// PeerBalancer selects peers using weighted random selection:
765// - Most of the time: select from known peers, weighted by throughput
766// - With configured probability: select from unknown peers (to explore)
767// - Failing peers: only as last resort
768#[derive(Clone)]
769struct PeerBalancer {
770    known_peers: Vec<(anemo::Peer, PeerStateSyncInfo, f64)>,
771    unknown_peers: Vec<(anemo::Peer, PeerStateSyncInfo, f64)>,
772    failing_peers: Vec<(anemo::Peer, PeerStateSyncInfo)>,
773    requested_checkpoint: Option<CheckpointSequenceNumber>,
774    request_type: PeerCheckpointRequestType,
775    exploration_probability: f64,
776}
777
778#[derive(Clone)]
779enum PeerCheckpointRequestType {
780    Summary,
781    Content,
782}
783
784impl PeerBalancer {
785    pub fn new(
786        network: &anemo::Network,
787        peer_heights: Arc<RwLock<PeerHeights>>,
788        request_type: PeerCheckpointRequestType,
789    ) -> Self {
790        let peer_heights_guard = peer_heights.read().unwrap();
791
792        let mut known_peers = Vec::new();
793        let mut unknown_peers = Vec::new();
794        let mut failing_peers = Vec::new();
795        let exploration_probability = peer_heights_guard.exploration_probability;
796
797        for (peer_id, info) in peer_heights_guard.peers_on_same_chain() {
798            let Some(peer) = network.peer(*peer_id) else {
799                continue;
800            };
801            let rtt_secs = peer.connection_rtt().as_secs_f64();
802
803            if peer_heights_guard.is_failing(peer_id) {
804                failing_peers.push((peer, *info));
805            } else if let Some(throughput) = peer_heights_guard.get_throughput(peer_id) {
806                known_peers.push((peer, *info, throughput));
807            } else {
808                unknown_peers.push((peer, *info, rtt_secs));
809            }
810        }
811        drop(peer_heights_guard);
812
813        unknown_peers.sort_by(|(_, _, rtt_a), (_, _, rtt_b)| {
814            rtt_a
815                .partial_cmp(rtt_b)
816                .unwrap_or(std::cmp::Ordering::Equal)
817        });
818
819        Self {
820            known_peers,
821            unknown_peers,
822            failing_peers,
823            requested_checkpoint: None,
824            request_type,
825            exploration_probability,
826        }
827    }
828
829    pub fn with_checkpoint(mut self, checkpoint: CheckpointSequenceNumber) -> Self {
830        self.requested_checkpoint = Some(checkpoint);
831        self
832    }
833
834    /// Removes `peers` from the candidates.
835    pub fn excluding(mut self, peers: &HashSet<PeerId>) -> Self {
836        self.known_peers
837            .retain(|(peer, _, _)| !peers.contains(&peer.peer_id()));
838        self.unknown_peers
839            .retain(|(peer, _, _)| !peers.contains(&peer.peer_id()));
840        self.failing_peers
841            .retain(|(peer, _)| !peers.contains(&peer.peer_id()));
842        self
843    }
844
845    fn is_eligible(&self, info: &PeerStateSyncInfo) -> bool {
846        let requested = self.requested_checkpoint.unwrap_or(0);
847        match &self.request_type {
848            PeerCheckpointRequestType::Summary => info.height >= requested,
849            PeerCheckpointRequestType::Content => info.has_contents(requested),
850        }
851    }
852
853    fn select_by_throughput(&mut self) -> Option<(anemo::Peer, PeerStateSyncInfo)> {
854        let eligible: Vec<_> = self
855            .known_peers
856            .iter()
857            .enumerate()
858            .filter(|(_, (_, info, _))| self.is_eligible(info))
859            .map(|(i, (_, _, t))| (i, *t))
860            .collect();
861
862        if eligible.is_empty() {
863            return None;
864        }
865
866        let total: f64 = eligible.iter().map(|(_, t)| t).sum();
867        let mut pick = rand::thread_rng().gen_range(0.0..total);
868
869        for (idx, throughput) in &eligible {
870            pick -= throughput;
871            if pick <= 0.0 {
872                let (peer, info, _) = self.known_peers.remove(*idx);
873                return Some((peer, info));
874            }
875        }
876
877        let (idx, _) = eligible.last().unwrap();
878        let (peer, info, _) = self.known_peers.remove(*idx);
879        Some((peer, info))
880    }
881
882    fn select_by_rtt(&mut self) -> Option<(anemo::Peer, PeerStateSyncInfo)> {
883        let pos = self
884            .unknown_peers
885            .iter()
886            .position(|(_, info, _)| self.is_eligible(info))?;
887        let (peer, info, _) = self.unknown_peers.remove(pos);
888        Some((peer, info))
889    }
890
891    fn select_failing(&mut self) -> Option<(anemo::Peer, PeerStateSyncInfo)> {
892        let pos = self
893            .failing_peers
894            .iter()
895            .position(|(_, info)| self.is_eligible(info))?;
896        Some(self.failing_peers.remove(pos))
897    }
898}
899
900impl Iterator for PeerBalancer {
901    type Item = StateSyncClient<anemo::Peer>;
902
903    fn next(&mut self) -> Option<Self::Item> {
904        let has_eligible_known = self
905            .known_peers
906            .iter()
907            .any(|(_, info, _)| self.is_eligible(info));
908        let has_eligible_unknown = self
909            .unknown_peers
910            .iter()
911            .any(|(_, info, _)| self.is_eligible(info));
912
913        let explore = has_eligible_unknown
914            && (!has_eligible_known || rand::thread_rng().gen_bool(self.exploration_probability));
915
916        if explore && let Some((peer, _)) = self.select_by_rtt() {
917            return Some(StateSyncClient::new(peer));
918        }
919
920        if has_eligible_known && let Some((peer, _)) = self.select_by_throughput() {
921            return Some(StateSyncClient::new(peer));
922        }
923
924        if let Some((peer, _)) = self.select_failing() {
925            return Some(StateSyncClient::new(peer));
926        }
927
928        None
929    }
930}
931
932#[derive(Clone, Debug)]
933enum StateSyncMessage {
934    StartSyncJob,
935    // Validators will send this to the StateSyncEventLoop in order to kick off notifying our peers
936    // of the new checkpoint.
937    VerifiedCheckpoint(Box<VerifiedCheckpoint>),
938    // Notification that the checkpoint content sync task will send to the event loop in the event
939    // it was able to successfully sync a checkpoint's contents. If multiple checkpoints were
940    // synced at the same time, only the highest checkpoint is sent.
941    SyncedCheckpoint(Box<VerifiedCheckpoint>),
942}
943
944struct StateSyncEventLoop<S> {
945    config: StateSyncConfig,
946
947    mailbox: mpsc::Receiver<StateSyncMessage>,
948    /// Weak reference to our own mailbox
949    weak_sender: mpsc::WeakSender<StateSyncMessage>,
950
951    tasks: JoinSet<()>,
952    sync_checkpoint_summaries_task: Option<AbortHandle>,
953    sync_checkpoint_contents_task: Option<AbortHandle>,
954    download_limit_layer: Option<CheckpointContentsDownloadLimitLayer>,
955
956    store: S,
957    peer_heights: Arc<RwLock<PeerHeights>>,
958    checkpoint_event_sender: broadcast::Sender<VerifiedCheckpoint>,
959    network: anemo::Network,
960    metrics: Metrics,
961
962    sync_checkpoint_from_archive_task: Option<AbortHandle>,
963    archive_config: Option<ArchiveReaderConfig>,
964    discovery_sender: Option<crate::discovery::Sender>,
965}
966
967impl<S> StateSyncEventLoop<S>
968where
969    S: WriteStore + Clone + Send + Sync + 'static,
970{
971    // Note: A great deal of care is taken to ensure that all event handlers are non-asynchronous
972    // and that the only "await" points are from the select macro picking which event to handle.
973    // This ensures that the event loop is able to process events at a high speed and reduce the
974    // chance for building up a backlog of events to process.
975    pub async fn start(mut self) {
976        info!("State-Synchronizer started");
977
978        self.config.pinned_checkpoints.sort();
979
980        let mut interval = tokio::time::interval(self.config.interval_period());
981        let mut peer_events = {
982            let (subscriber, peers) = self.network.subscribe().unwrap();
983            for peer_id in peers {
984                self.spawn_get_latest_from_peer(peer_id);
985            }
986            subscriber
987        };
988        let (
989            target_checkpoint_contents_sequence_sender,
990            target_checkpoint_contents_sequence_receiver,
991        ) = watch::channel(0);
992
993        // Spawn tokio task to update metrics periodically in the background
994        let (_sender, receiver) = oneshot::channel();
995        tokio::spawn(update_checkpoint_watermark_metrics(
996            receiver,
997            self.store.clone(),
998            self.metrics.clone(),
999        ));
1000
1001        // Start checkpoint contents sync loop.
1002        let task = sync_checkpoint_contents(
1003            self.network.clone(),
1004            self.store.clone(),
1005            self.peer_heights.clone(),
1006            self.weak_sender.clone(),
1007            self.checkpoint_event_sender.clone(),
1008            self.config.checkpoint_content_download_concurrency(),
1009            self.config.checkpoint_content_download_tx_concurrency(),
1010            self.config.use_get_checkpoint_contents_v2(),
1011            self.config.checkpoint_content_hedge_delay(),
1012            self.metrics.clone(),
1013            target_checkpoint_contents_sequence_receiver,
1014        );
1015        let task_handle = self.tasks.spawn(task);
1016        self.sync_checkpoint_contents_task = Some(task_handle);
1017
1018        // Start archive based checkpoint content sync loop.
1019        // TODO: Consider switching to sync from archive only on startup.
1020        // Right now because the peer set is fixed at startup, a node may eventually
1021        // end up with peers who have all purged their local state. In such a scenario it will be
1022        // stuck until restart when it ends up with a different set of peers. Once the discovery
1023        // mechanism can dynamically identify and connect to other peers on the network, we will rely
1024        // on sync from archive as a fall back.
1025        let task = sync_checkpoint_contents_from_archive(
1026            self.network.clone(),
1027            self.archive_config.clone(),
1028            self.store.clone(),
1029            self.peer_heights.clone(),
1030            self.metrics.clone(),
1031        );
1032        let task_handle = self.tasks.spawn(task);
1033        self.sync_checkpoint_from_archive_task = Some(task_handle);
1034
1035        // Start main loop.
1036        loop {
1037            tokio::select! {
1038                now = interval.tick() => {
1039                    self.handle_tick(now.into_std());
1040                },
1041                maybe_message = self.mailbox.recv() => {
1042                    // Once all handles to our mailbox have been dropped this
1043                    // will yield `None` and we can terminate the event loop
1044                    if let Some(message) = maybe_message {
1045                        self.handle_message(message);
1046                    } else {
1047                        break;
1048                    }
1049                },
1050                peer_event = peer_events.recv() => {
1051                    self.handle_peer_event(peer_event);
1052                },
1053                Some(task_result) = self.tasks.join_next() => {
1054                    match task_result {
1055                        Ok(()) => {},
1056                        Err(e) => {
1057                            if e.is_cancelled() {
1058                                // avoid crashing on ungraceful shutdown
1059                            } else if e.is_panic() {
1060                                // propagate panics.
1061                                std::panic::resume_unwind(e.into_panic());
1062                            } else {
1063                                panic!("task failed: {e}");
1064                            }
1065                        },
1066                    };
1067
1068                    if matches!(&self.sync_checkpoint_contents_task, Some(t) if t.is_finished()) {
1069                        panic!("sync_checkpoint_contents task unexpectedly terminated")
1070                    }
1071
1072                    if matches!(&self.sync_checkpoint_summaries_task, Some(t) if t.is_finished()) {
1073                        self.sync_checkpoint_summaries_task = None;
1074                    }
1075
1076                    if matches!(&self.sync_checkpoint_from_archive_task, Some(t) if t.is_finished()) {
1077                        panic!("sync_checkpoint_from_archive task unexpectedly terminated")
1078                    }
1079                },
1080            }
1081
1082            self.maybe_start_checkpoint_summary_sync_task();
1083            self.maybe_trigger_checkpoint_contents_sync_task(
1084                &target_checkpoint_contents_sequence_sender,
1085            );
1086        }
1087
1088        info!("State-Synchronizer ended");
1089    }
1090
1091    fn handle_message(&mut self, message: StateSyncMessage) {
1092        debug!("Received message: {:?}", message);
1093        match message {
1094            StateSyncMessage::StartSyncJob => self.maybe_start_checkpoint_summary_sync_task(),
1095            StateSyncMessage::VerifiedCheckpoint(checkpoint) => {
1096                self.handle_checkpoint_from_consensus(checkpoint)
1097            }
1098            // After we've successfully synced a checkpoint we can notify our peers
1099            StateSyncMessage::SyncedCheckpoint(checkpoint) => {
1100                self.spawn_notify_peers_of_checkpoint(*checkpoint)
1101            }
1102        }
1103    }
1104
1105    // Handle a checkpoint that we received from consensus
1106    #[instrument(level = "debug", skip_all)]
1107    fn handle_checkpoint_from_consensus(&mut self, checkpoint: Box<VerifiedCheckpoint>) {
1108        // Always check previous_digest matches in case there is a gap between
1109        // state sync and consensus.
1110        let prev_digest = *self.store.get_checkpoint_by_sequence_number(checkpoint.sequence_number() - 1)
1111            .unwrap_or_else(|| panic!("Got checkpoint {} from consensus but cannot find checkpoint {} in certified_checkpoints", checkpoint.sequence_number(), checkpoint.sequence_number() - 1))
1112            .digest();
1113        if checkpoint.previous_digest != Some(prev_digest) {
1114            panic!(
1115                "Checkpoint {} from consensus has mismatched previous_digest, expected: {:?}, actual: {:?}",
1116                checkpoint.sequence_number(),
1117                Some(prev_digest),
1118                checkpoint.previous_digest
1119            );
1120        }
1121
1122        let latest_checkpoint = self
1123            .store
1124            .get_highest_verified_checkpoint()
1125            .expect("store operation should not fail");
1126
1127        // If this is an older checkpoint, just ignore it
1128        if latest_checkpoint.sequence_number() >= checkpoint.sequence_number() {
1129            return;
1130        }
1131
1132        let checkpoint = *checkpoint;
1133        let next_sequence_number = latest_checkpoint.sequence_number().checked_add(1).unwrap();
1134        if *checkpoint.sequence_number() > next_sequence_number {
1135            debug!(
1136                "consensus sent too new of a checkpoint, expecting: {}, got: {}",
1137                next_sequence_number,
1138                checkpoint.sequence_number()
1139            );
1140        }
1141
1142        // Because checkpoint from consensus sends in order, when we have checkpoint n,
1143        // we must have all of the checkpoints before n from either state sync or consensus.
1144        #[cfg(debug_assertions)]
1145        {
1146            let _ = (next_sequence_number..=*checkpoint.sequence_number())
1147                .map(|n| {
1148                    let checkpoint = self
1149                        .store
1150                        .get_checkpoint_by_sequence_number(n)
1151                        .unwrap_or_else(|| panic!("store should contain checkpoint {n}"));
1152                    self.store
1153                        .get_full_checkpoint_contents(Some(n), &checkpoint.content_digest)
1154                        .unwrap_or_else(|| {
1155                            panic!(
1156                                "store should contain checkpoint contents for {:?}",
1157                                checkpoint.content_digest
1158                            )
1159                        });
1160                })
1161                .collect::<Vec<_>>();
1162        }
1163
1164        // If this is the last checkpoint of a epoch, we need to make sure
1165        // new committee is in store before we verify newer checkpoints in next epoch.
1166        // This could happen before this validator's reconfiguration finishes, because
1167        // state sync does not reconfig.
1168        // TODO: make CheckpointAggregator use WriteStore so we don't need to do this
1169        // committee insertion in two places (only in `insert_checkpoint`).
1170        if let Some(EndOfEpochData {
1171            next_epoch_committee,
1172            ..
1173        }) = checkpoint.end_of_epoch_data.as_ref()
1174        {
1175            let next_committee = next_epoch_committee.iter().cloned().collect();
1176            let committee =
1177                Committee::new(checkpoint.epoch().checked_add(1).unwrap(), next_committee);
1178            self.store
1179                .insert_committee(committee)
1180                .expect("store operation should not fail");
1181        }
1182
1183        self.store
1184            .update_highest_verified_checkpoint(&checkpoint)
1185            .expect("store operation should not fail");
1186        self.store
1187            .update_highest_synced_checkpoint(&checkpoint)
1188            .expect("store operation should not fail");
1189
1190        // We don't care if no one is listening as this is a broadcast channel
1191        let _ = self.checkpoint_event_sender.send(checkpoint.clone());
1192
1193        self.spawn_notify_peers_of_checkpoint(checkpoint);
1194    }
1195
1196    fn handle_peer_event(
1197        &mut self,
1198        peer_event: Result<PeerEvent, tokio::sync::broadcast::error::RecvError>,
1199    ) {
1200        use tokio::sync::broadcast::error::RecvError;
1201
1202        match peer_event {
1203            Ok(PeerEvent::NewPeer(peer_id)) => {
1204                self.spawn_get_latest_from_peer(peer_id);
1205            }
1206            Ok(PeerEvent::LostPeer(peer_id, _)) => {
1207                let mut heights = self.peer_heights.write().unwrap();
1208                heights.peers.remove(&peer_id);
1209                heights.scores.remove(&peer_id);
1210            }
1211
1212            Err(RecvError::Closed) => {
1213                panic!("PeerEvent channel shouldn't be able to be closed");
1214            }
1215
1216            Err(RecvError::Lagged(_)) => {
1217                trace!("State-Sync fell behind processing PeerEvents");
1218            }
1219        }
1220    }
1221
1222    fn spawn_get_latest_from_peer(&mut self, peer_id: PeerId) {
1223        if let Some(peer) = self.network.peer(peer_id) {
1224            let genesis_checkpoint_digest = *self
1225                .store
1226                .get_checkpoint_by_sequence_number(0)
1227                .expect("store should contain genesis checkpoint")
1228                .digest();
1229            let task = get_latest_from_peer(
1230                genesis_checkpoint_digest,
1231                peer,
1232                self.peer_heights.clone(),
1233                self.config.timeout(),
1234            );
1235            self.tasks.spawn(task);
1236        }
1237    }
1238
1239    fn handle_tick(&mut self, _now: std::time::Instant) {
1240        let task = query_peers_for_their_latest_checkpoint(
1241            self.network.clone(),
1242            self.peer_heights.clone(),
1243            self.weak_sender.clone(),
1244            self.config.timeout(),
1245        );
1246        self.tasks.spawn(task);
1247
1248        if let Some(layer) = self.download_limit_layer.as_ref() {
1249            layer.maybe_prune_map();
1250        }
1251
1252        self.maybe_report_failing_peer();
1253    }
1254
1255    fn maybe_report_failing_peer(&mut self) {
1256        let threshold = self.config.peer_disconnect_threshold();
1257        if threshold.is_zero() {
1258            return;
1259        }
1260
1261        let mut peer_heights = self.peer_heights.write().unwrap();
1262        peer_heights.update_failing_states();
1263
1264        let Some(peer_id) = peer_heights.find_peer_to_report_for_failure(threshold) else {
1265            return;
1266        };
1267        // Reset the failing clock so this peer isn't re-reported on the next tick.
1268        // If the peer is still failing, update_failing_states will restart the clock
1269        // and the peer must fail for another full threshold before being reported again.
1270        // Discovery may decline to disconnect (e.g. too few peers), so this also
1271        // prevents spamming reports every tick in that case.
1272        if let Some(score) = peer_heights.scores.get_mut(&peer_id) {
1273            score.reset_failing_since();
1274        }
1275        drop(peer_heights);
1276
1277        info!("reporting peer {peer_id} for consistent state sync failures");
1278        if let Some(sender) = &self.discovery_sender {
1279            sender.report_peer_failure(peer_id);
1280        } else {
1281            let _ = self.network.disconnect(peer_id);
1282        }
1283        self.metrics.inc_peers_reported_for_failure();
1284    }
1285
1286    fn maybe_start_checkpoint_summary_sync_task(&mut self) {
1287        // Only run one sync task at a time
1288        if self.sync_checkpoint_summaries_task.is_some() {
1289            return;
1290        }
1291
1292        let highest_processed_checkpoint = self
1293            .store
1294            .get_highest_verified_checkpoint()
1295            .expect("store operation should not fail");
1296
1297        let highest_known_sequence_number = self
1298            .peer_heights
1299            .read()
1300            .unwrap()
1301            .highest_known_checkpoint_sequence_number();
1302
1303        if let Some(target_seq) = highest_known_sequence_number
1304            && *highest_processed_checkpoint.sequence_number() < target_seq
1305        {
1306            // Limit the per-sync batch size according to config.
1307            let max_batch_size = self.config.max_checkpoint_sync_batch_size();
1308            let limited_target = std::cmp::min(
1309                target_seq,
1310                highest_processed_checkpoint
1311                    .sequence_number()
1312                    .saturating_add(max_batch_size),
1313            );
1314            let was_limited = limited_target < target_seq;
1315
1316            // Start sync job.
1317            let weak_sender = self.weak_sender.clone();
1318            let task = sync_to_checkpoint(
1319                self.network.clone(),
1320                self.store.clone(),
1321                self.peer_heights.clone(),
1322                self.metrics.clone(),
1323                self.config.pinned_checkpoints.clone(),
1324                self.config.checkpoint_header_download_concurrency(),
1325                self.config.timeout(),
1326                limited_target,
1327            )
1328            .map(move |result| match result {
1329                Ok(()) => {
1330                    // If we limited the sync range, immediately trigger
1331                    // another sync to continue catching up.
1332                    if was_limited && let Some(sender) = weak_sender.upgrade() {
1333                        let _ = sender.try_send(StateSyncMessage::StartSyncJob);
1334                    }
1335                }
1336                Err(e) => {
1337                    debug!("error syncing checkpoint {e}");
1338                }
1339            });
1340            let task_handle = self.tasks.spawn(task);
1341            self.sync_checkpoint_summaries_task = Some(task_handle);
1342        }
1343    }
1344
1345    fn maybe_trigger_checkpoint_contents_sync_task(
1346        &mut self,
1347        target_sequence_channel: &watch::Sender<CheckpointSequenceNumber>,
1348    ) {
1349        let highest_verified_checkpoint = self
1350            .store
1351            .get_highest_verified_checkpoint()
1352            .expect("store operation should not fail");
1353        let highest_synced_checkpoint = self
1354            .store
1355            .get_highest_synced_checkpoint()
1356            .expect("store operation should not fail");
1357
1358        if highest_verified_checkpoint.sequence_number()
1359            > highest_synced_checkpoint.sequence_number()
1360            // skip if we aren't connected to any peers that can help
1361            && self
1362                .peer_heights
1363                .read()
1364                .unwrap()
1365                .highest_known_checkpoint_sequence_number()
1366                > Some(*highest_synced_checkpoint.sequence_number())
1367        {
1368            let _ = target_sequence_channel.send_if_modified(|num| {
1369                let new_num = *highest_verified_checkpoint.sequence_number();
1370                if *num == new_num {
1371                    return false;
1372                }
1373                *num = new_num;
1374                true
1375            });
1376        }
1377    }
1378
1379    fn spawn_notify_peers_of_checkpoint(&mut self, checkpoint: VerifiedCheckpoint) {
1380        let task = notify_peers_of_checkpoint(
1381            self.network.clone(),
1382            self.peer_heights.clone(),
1383            checkpoint,
1384            self.config.timeout(),
1385        );
1386        self.tasks.spawn(task);
1387    }
1388}
1389
1390async fn notify_peers_of_checkpoint(
1391    network: anemo::Network,
1392    peer_heights: Arc<RwLock<PeerHeights>>,
1393    checkpoint: VerifiedCheckpoint,
1394    timeout: Duration,
1395) {
1396    let futs = peer_heights
1397        .read()
1398        .unwrap()
1399        .peers_on_same_chain()
1400        // Filter out any peers who we know already have a checkpoint higher than this one
1401        .filter_map(|(peer_id, info)| {
1402            (*checkpoint.sequence_number() > info.height).then_some(peer_id)
1403        })
1404        // Filter out any peers who we aren't connected with
1405        .flat_map(|peer_id| network.peer(*peer_id))
1406        .map(StateSyncClient::new)
1407        .map(|mut client| {
1408            let request = Request::new(checkpoint.inner().clone()).with_timeout(timeout);
1409            async move { client.push_checkpoint_summary(request).await }
1410        })
1411        .collect::<Vec<_>>();
1412    futures::future::join_all(futs).await;
1413}
1414
1415async fn get_latest_from_peer(
1416    our_genesis_checkpoint_digest: CheckpointDigest,
1417    peer: anemo::Peer,
1418    peer_heights: Arc<RwLock<PeerHeights>>,
1419    timeout: Duration,
1420) {
1421    let peer_id = peer.peer_id();
1422    let mut client = StateSyncClient::new(peer);
1423
1424    let info = {
1425        let maybe_info = peer_heights.read().unwrap().peers.get(&peer_id).copied();
1426
1427        if let Some(info) = maybe_info {
1428            info
1429        } else {
1430            // TODO do we want to create a new API just for querying a node's chainid?
1431            //
1432            // We need to query this node's genesis checkpoint to see if they're on the same chain
1433            // as us
1434            let request = Request::new(GetCheckpointSummaryRequest::BySequenceNumber(0))
1435                .with_timeout(timeout);
1436            let response = client
1437                .get_checkpoint_summary(request)
1438                .await
1439                .map(Response::into_inner);
1440
1441            let info = match response {
1442                Ok(Some(checkpoint)) => {
1443                    let digest = *checkpoint.digest();
1444                    PeerStateSyncInfo {
1445                        genesis_checkpoint_digest: digest,
1446                        on_same_chain_as_us: our_genesis_checkpoint_digest == digest,
1447                        height: *checkpoint.sequence_number(),
1448                        lowest: CheckpointSequenceNumber::default(),
1449                    }
1450                }
1451                Ok(None) => PeerStateSyncInfo {
1452                    genesis_checkpoint_digest: CheckpointDigest::default(),
1453                    on_same_chain_as_us: false,
1454                    height: CheckpointSequenceNumber::default(),
1455                    lowest: CheckpointSequenceNumber::default(),
1456                },
1457                Err(status) => {
1458                    trace!("get_latest_checkpoint_summary request failed: {status:?}");
1459                    return;
1460                }
1461            };
1462            peer_heights
1463                .write()
1464                .unwrap()
1465                .insert_peer_info(peer_id, info);
1466            info
1467        }
1468    };
1469
1470    // Bail early if this node isn't on the same chain as us
1471    if !info.on_same_chain_as_us {
1472        trace!(?info, "Peer {peer_id} not on same chain as us");
1473        return;
1474    }
1475    let Ok(Some((highest_checkpoint, low_watermark))) =
1476        query_peer_for_latest_info(&mut client, timeout).await
1477    else {
1478        return;
1479    };
1480    peer_heights
1481        .write()
1482        .unwrap()
1483        .update_peer_info(peer_id, highest_checkpoint, low_watermark);
1484}
1485
1486/// Queries a peer for their highest_synced_checkpoint and low checkpoint watermark.
1487///
1488/// Distinguishes three outcomes so callers can score the peer:
1489/// - `Ok(Some(..))`: the peer answered with usable latest-checkpoint info.
1490/// - `Ok(None)`: the peer answered but had nothing useful to report (e.g. a pre-upgrade peer
1491///   that returns no latest summary). This is not a failure.
1492/// - `Err(())`: the request itself failed (timeout / transport error). This is a failure: a
1493///   peer that consistently fails these liveness queries is consistently unreachable.
1494async fn query_peer_for_latest_info(
1495    client: &mut StateSyncClient<anemo::Peer>,
1496    timeout: Duration,
1497) -> Result<Option<(Checkpoint, Option<CheckpointSequenceNumber>)>, ()> {
1498    let request = Request::new(()).with_timeout(timeout);
1499    let response = client
1500        .get_checkpoint_availability(request)
1501        .await
1502        .map(Response::into_inner);
1503    match response {
1504        Ok(GetCheckpointAvailabilityResponse {
1505            highest_synced_checkpoint,
1506            lowest_available_checkpoint,
1507        }) => {
1508            return Ok(Some((
1509                highest_synced_checkpoint,
1510                Some(lowest_available_checkpoint),
1511            )));
1512        }
1513        Err(status) => {
1514            // If peer hasn't upgraded they would return 404 NotFound error
1515            if status.status() != anemo::types::response::StatusCode::NotFound {
1516                trace!("get_checkpoint_availability request failed: {status:?}");
1517                return Err(());
1518            }
1519        }
1520    };
1521
1522    // Then we try the old query
1523    // TODO: remove this once the new feature stabilizes
1524    let request = Request::new(GetCheckpointSummaryRequest::Latest).with_timeout(timeout);
1525    let response = client
1526        .get_checkpoint_summary(request)
1527        .await
1528        .map(Response::into_inner);
1529    match response {
1530        Ok(Some(checkpoint)) => Ok(Some((checkpoint, None))),
1531        Ok(None) => Ok(None),
1532        Err(status) => {
1533            trace!("get_checkpoint_summary (latest) request failed: {status:?}");
1534            Err(())
1535        }
1536    }
1537}
1538
1539#[instrument(level = "debug", skip_all)]
1540async fn query_peers_for_their_latest_checkpoint(
1541    network: anemo::Network,
1542    peer_heights: Arc<RwLock<PeerHeights>>,
1543    sender: mpsc::WeakSender<StateSyncMessage>,
1544    timeout: Duration,
1545) {
1546    let peer_heights = &peer_heights;
1547    let futs = peer_heights
1548        .read()
1549        .unwrap()
1550        .peers_on_same_chain()
1551        // Filter out any peers who we aren't connected with
1552        .flat_map(|(peer_id, _info)| network.peer(*peer_id))
1553        .map(|peer| {
1554            let peer_id = peer.peer_id();
1555            let mut client = StateSyncClient::new(peer);
1556
1557            async move {
1558                let start = Instant::now();
1559                let response = query_peer_for_latest_info(&mut client, timeout).await;
1560                let elapsed = start.elapsed();
1561                match response {
1562                    Ok(Some((highest_checkpoint, low_watermark))) => {
1563                        // A peer that answers our periodic liveness/discovery query is healthy;
1564                        // record it so its success rate offsets occasional failures.
1565                        let size = bcs::serialized_size(&highest_checkpoint).unwrap_or(0) as u64;
1566                        let mut peer_heights = peer_heights.write().unwrap();
1567                        peer_heights.record_success(peer_id, size, elapsed);
1568                        peer_heights
1569                            .update_peer_info(peer_id, highest_checkpoint.clone(), low_watermark)
1570                            .then_some(highest_checkpoint)
1571                    }
1572                    // Peer responded but had nothing useful; neutral, do not score.
1573                    Ok(None) => None,
1574                    // Request failed (timeout / transport). A peer that consistently fails
1575                    // these liveness queries is consistently unreachable, so record the
1576                    // failure to feed the scorer even when we are not actively syncing from
1577                    // it. Without this, an unreachable peer is only scored while there is
1578                    // active sync traffic, so it can evade the consistently-failing-peer
1579                    // disconnect logic indefinitely.
1580                    Err(()) => {
1581                        peer_heights.write().unwrap().record_failure(peer_id);
1582                        None
1583                    }
1584                }
1585            }
1586        })
1587        .collect::<Vec<_>>();
1588
1589    debug!("Query {} peers for latest checkpoint", futs.len());
1590
1591    let checkpoints = futures::future::join_all(futs).await.into_iter().flatten();
1592
1593    let highest_checkpoint_seq = checkpoints
1594        .map(|checkpoint| *checkpoint.sequence_number())
1595        .max();
1596
1597    let our_highest_seq = peer_heights
1598        .read()
1599        .unwrap()
1600        .highest_known_checkpoint_sequence_number();
1601
1602    debug!(
1603        "Our highest checkpoint {our_highest_seq:?}, peers' highest checkpoint {highest_checkpoint_seq:?}"
1604    );
1605
1606    let _new_checkpoint = match (highest_checkpoint_seq, our_highest_seq) {
1607        (Some(theirs), None) => theirs,
1608        (Some(theirs), Some(ours)) if theirs > ours => theirs,
1609        _ => return,
1610    };
1611
1612    if let Some(sender) = sender.upgrade() {
1613        let _ = sender.send(StateSyncMessage::StartSyncJob).await;
1614    }
1615}
1616
1617async fn sync_to_checkpoint<S>(
1618    network: anemo::Network,
1619    store: S,
1620    peer_heights: Arc<RwLock<PeerHeights>>,
1621    metrics: Metrics,
1622    pinned_checkpoints: Vec<(CheckpointSequenceNumber, CheckpointDigest)>,
1623    checkpoint_header_download_concurrency: usize,
1624    timeout: Duration,
1625    target_sequence_number: CheckpointSequenceNumber,
1626) -> Result<()>
1627where
1628    S: WriteStore,
1629{
1630    metrics.set_highest_known_checkpoint(target_sequence_number);
1631
1632    let mut current = store
1633        .get_highest_verified_checkpoint()
1634        .expect("store operation should not fail");
1635    if *current.sequence_number() >= target_sequence_number {
1636        return Err(anyhow::anyhow!(
1637            "target checkpoint {} is older than highest verified checkpoint {}",
1638            target_sequence_number,
1639            current.sequence_number(),
1640        ));
1641    }
1642
1643    let peer_balancer = PeerBalancer::new(
1644        &network,
1645        peer_heights.clone(),
1646        PeerCheckpointRequestType::Summary,
1647    );
1648    // range of the next sequence_numbers to fetch
1649    let mut request_stream = (current.sequence_number().checked_add(1).unwrap()
1650        ..=target_sequence_number)
1651        .map(|next| {
1652            let peers = peer_balancer.clone().with_checkpoint(next);
1653            let peer_heights = peer_heights.clone();
1654            let pinned_checkpoints = &pinned_checkpoints;
1655            async move {
1656                if let Some(checkpoint) = peer_heights
1657                    .read()
1658                    .unwrap()
1659                    .get_checkpoint_by_sequence_number(next)
1660                {
1661                    return (Some(checkpoint.to_owned()), next, None);
1662                }
1663
1664                // Iterate through peers trying each one in turn until we're able to
1665                // successfully get the target checkpoint.
1666                for mut peer in peers {
1667                    let peer_id = peer.inner().peer_id();
1668                    let request = Request::new(GetCheckpointSummaryRequest::BySequenceNumber(next))
1669                        .with_timeout(timeout);
1670                    let start = Instant::now();
1671                    let result = peer.get_checkpoint_summary(request).await;
1672                    let elapsed = start.elapsed();
1673
1674                    let checkpoint = match result {
1675                        Ok(response) => match response.into_inner() {
1676                            Some(cp) => Some(cp),
1677                            None => {
1678                                trace!("peer unable to help sync");
1679                                peer_heights.write().unwrap().record_failure(peer_id);
1680                                None
1681                            }
1682                        },
1683                        Err(e) => {
1684                            trace!("{e:?}");
1685                            peer_heights.write().unwrap().record_failure(peer_id);
1686                            None
1687                        }
1688                    };
1689
1690                    let Some(checkpoint) = checkpoint else {
1691                        continue;
1692                    };
1693
1694                    let size = bcs::serialized_size(&checkpoint).expect("serialization should not fail") as u64;
1695                    peer_heights.write().unwrap().record_success(peer_id, size, elapsed);
1696
1697                    // peer didn't give us a checkpoint with the height that we requested
1698                    if *checkpoint.sequence_number() != next {
1699                        tracing::debug!(
1700                            "peer returned checkpoint with wrong sequence number: expected {next}, got {}",
1701                            checkpoint.sequence_number()
1702                        );
1703                        peer_heights
1704                            .write()
1705                            .unwrap()
1706                            .mark_peer_as_not_on_same_chain(peer_id);
1707                        continue;
1708                    }
1709
1710                    // peer gave us a checkpoint whose digest does not match pinned digest
1711                    let checkpoint_digest = checkpoint.digest();
1712                    if let Ok(pinned_digest_index) = pinned_checkpoints.binary_search_by_key(
1713                        checkpoint.sequence_number(),
1714                        |(seq_num, _digest)| *seq_num
1715                    )
1716                        && pinned_checkpoints[pinned_digest_index].1 != *checkpoint_digest
1717                    {
1718                        tracing::debug!(
1719                            "peer returned checkpoint with digest that does not match pinned digest: expected {:?}, got {:?}",
1720                            pinned_checkpoints[pinned_digest_index].1,
1721                            checkpoint_digest
1722                        );
1723                        peer_heights
1724                            .write()
1725                            .unwrap()
1726                            .mark_peer_as_not_on_same_chain(peer.inner().peer_id());
1727                        continue;
1728                    }
1729
1730                    // Insert in our store in the event that things fail and we need to retry
1731                    peer_heights
1732                        .write()
1733                        .unwrap()
1734                        .insert_checkpoint(checkpoint.clone());
1735                    return (Some(checkpoint), next, Some(peer_id));
1736                }
1737                (None, next, None)
1738            }
1739        })
1740        .pipe(futures::stream::iter)
1741        .buffered(checkpoint_header_download_concurrency);
1742
1743    while let Some((maybe_checkpoint, next, maybe_peer_id)) = request_stream.next().await {
1744        assert_eq!(
1745            current
1746                .sequence_number()
1747                .checked_add(1)
1748                .expect("exhausted u64"),
1749            next
1750        );
1751
1752        // Verify the checkpoint
1753        let checkpoint = 'cp: {
1754            let checkpoint = maybe_checkpoint.ok_or_else(|| {
1755                anyhow::anyhow!("no peers were able to help sync checkpoint {next}")
1756            })?;
1757            // Skip verification for manually pinned checkpoints.
1758            if pinned_checkpoints
1759                .binary_search_by_key(checkpoint.sequence_number(), |(seq_num, _digest)| *seq_num)
1760                .is_ok()
1761            {
1762                break 'cp VerifiedCheckpoint::new_unchecked(checkpoint);
1763            }
1764            match verify_checkpoint(&current, &store, checkpoint) {
1765                Ok(verified_checkpoint) => verified_checkpoint,
1766                Err(checkpoint) => {
1767                    let mut peer_heights = peer_heights.write().unwrap();
1768                    // Remove the checkpoint from our temporary store so that we can try querying
1769                    // another peer for a different one
1770                    peer_heights.remove_checkpoint(checkpoint.digest());
1771
1772                    // Mark peer as not on the same chain as us
1773                    if let Some(peer_id) = maybe_peer_id {
1774                        peer_heights.mark_peer_as_not_on_same_chain(peer_id);
1775                    }
1776
1777                    return Err(anyhow::anyhow!(
1778                        "unable to verify checkpoint {checkpoint:?}"
1779                    ));
1780                }
1781            }
1782        };
1783
1784        debug!(checkpoint_seq = ?checkpoint.sequence_number(), "verified checkpoint summary");
1785        if let Some((checkpoint_summary_age_metric, checkpoint_summary_age_metric_deprecated)) =
1786            metrics.checkpoint_summary_age_metrics()
1787        {
1788            checkpoint.report_checkpoint_age(
1789                checkpoint_summary_age_metric,
1790                checkpoint_summary_age_metric_deprecated,
1791            );
1792        }
1793
1794        // Insert the newly verified checkpoint into our store, which will bump our highest
1795        // verified checkpoint watermark as well.
1796        store
1797            .insert_checkpoint(&checkpoint)
1798            .expect("store operation should not fail");
1799
1800        current = checkpoint;
1801    }
1802
1803    peer_heights
1804        .write()
1805        .unwrap()
1806        .cleanup_old_checkpoints(*current.sequence_number());
1807
1808    Ok(())
1809}
1810
1811async fn sync_checkpoint_contents_from_archive<S>(
1812    network: anemo::Network,
1813    archive_config: Option<ArchiveReaderConfig>,
1814    store: S,
1815    peer_heights: Arc<RwLock<PeerHeights>>,
1816    metrics: Metrics,
1817) where
1818    S: WriteStore + Clone + Send + Sync + 'static,
1819{
1820    loop {
1821        sync_checkpoint_contents_from_archive_iteration(
1822            &network,
1823            &archive_config,
1824            store.clone(),
1825            peer_heights.clone(),
1826            metrics.clone(),
1827        )
1828        .await;
1829        tokio::time::sleep(Duration::from_secs(5)).await;
1830    }
1831}
1832
1833async fn sync_checkpoint_contents_from_archive_iteration<S>(
1834    network: &anemo::Network,
1835    archive_config: &Option<ArchiveReaderConfig>,
1836    store: S,
1837    peer_heights: Arc<RwLock<PeerHeights>>,
1838    metrics: Metrics,
1839) where
1840    S: WriteStore + Clone + Send + Sync + 'static,
1841{
1842    let peers: Vec<_> = peer_heights
1843        .read()
1844        .unwrap()
1845        .peers_on_same_chain()
1846        // Filter out any peers who we aren't connected with.
1847        .filter_map(|(peer_id, info)| network.peer(*peer_id).map(|peer| (peer, *info)))
1848        .collect();
1849    let lowest_checkpoint_on_peers = peers
1850        .iter()
1851        .map(|(_p, state_sync_info)| state_sync_info.lowest)
1852        .min();
1853    let highest_synced = store
1854        .get_highest_synced_checkpoint()
1855        .expect("store operation should not fail")
1856        .sequence_number;
1857    let sync_from_archive = if let Some(lowest_checkpoint_on_peers) = lowest_checkpoint_on_peers {
1858        highest_synced < lowest_checkpoint_on_peers
1859    } else {
1860        false
1861    };
1862    debug!(
1863        "Syncing checkpoint contents from archive: {sync_from_archive},  highest_synced: {highest_synced},  lowest_checkpoint_on_peers: {}",
1864        lowest_checkpoint_on_peers.map_or_else(|| "None".to_string(), |l| l.to_string())
1865    );
1866    if sync_from_archive {
1867        let start = highest_synced
1868            .checked_add(1)
1869            .expect("Checkpoint seq num overflow");
1870        let end = lowest_checkpoint_on_peers.unwrap();
1871
1872        let Some(archive_config) = archive_config else {
1873            warn!("Failed to find an archive reader to complete the state sync request");
1874            return;
1875        };
1876        let Some(ingestion_url) = &archive_config.ingestion_url else {
1877            warn!("Archival ingestion url for state sync is not configured");
1878            return;
1879        };
1880        if ingestion_url.contains("checkpoints.mainnet.sui.io") {
1881            warn!("{} can't be used as an archival fallback", ingestion_url);
1882            return;
1883        }
1884        let obj_store = build_object_store(
1885            ingestion_url,
1886            archive_config.remote_store_options.clone(),
1887            archive_config.remote_store_headers.clone(),
1888        );
1889        let mut checkpoint_stream = futures::stream::iter(start..=end)
1890            .map(|seq| {
1891                let obj_store = obj_store.clone();
1892                async move { (seq, fetch_checkpoint(&obj_store, seq).await) }
1893            })
1894            .buffered(archive_config.download_concurrency.get());
1895
1896        while let Some((seq, result)) = checkpoint_stream.next().await {
1897            let checkpoint = match result {
1898                Ok(checkpoint) => checkpoint,
1899                Err(err) => {
1900                    warn!("State sync from archive failed fetching checkpoint {seq}: {err}");
1901                    return;
1902                }
1903            };
1904            if let Err(err) = process_archive_checkpoint(&store, &checkpoint, &metrics) {
1905                warn!("State sync from archive failed processing checkpoint {seq}: {err}");
1906                return;
1907            }
1908        }
1909    }
1910}
1911
1912async fn sync_checkpoint_contents<S>(
1913    network: anemo::Network,
1914    store: S,
1915    peer_heights: Arc<RwLock<PeerHeights>>,
1916    sender: mpsc::WeakSender<StateSyncMessage>,
1917    checkpoint_event_sender: broadcast::Sender<VerifiedCheckpoint>,
1918    checkpoint_content_download_concurrency: usize,
1919    checkpoint_content_download_tx_concurrency: u64,
1920    use_get_checkpoint_contents_v2: bool,
1921    checkpoint_content_hedge_delay: Option<Duration>,
1922    metrics: Metrics,
1923    mut target_sequence_channel: watch::Receiver<CheckpointSequenceNumber>,
1924) where
1925    S: WriteStore + Clone,
1926{
1927    let mut highest_synced = store
1928        .get_highest_synced_checkpoint()
1929        .expect("store operation should not fail");
1930
1931    let mut current_sequence = highest_synced.sequence_number().checked_add(1).unwrap();
1932    let mut target_sequence_cursor = 0;
1933    let mut highest_started_network_total_transactions = highest_synced.network_total_transactions;
1934    let mut checkpoint_contents_tasks = FuturesOrdered::new();
1935
1936    let mut tx_in_flight: u64 = 0;
1937
1938    let hedge = checkpoint_content_hedge_delay.map(|delay| ContentHedge {
1939        delay,
1940        highest_synced: Arc::new(AtomicU64::new(*highest_synced.sequence_number())),
1941    });
1942
1943    loop {
1944        tokio::select! {
1945            result = target_sequence_channel.changed() => {
1946                match result {
1947                    Ok(()) => {
1948                        target_sequence_cursor = (*target_sequence_channel.borrow_and_update()).checked_add(1).unwrap();
1949                    }
1950                    Err(_) => {
1951                        // Watch channel is closed, exit loop.
1952                        return
1953                    }
1954                }
1955            },
1956            Some(maybe_checkpoint) = checkpoint_contents_tasks.next() => {
1957                match maybe_checkpoint {
1958                    Ok(checkpoint) => {
1959                        let _: &VerifiedCheckpoint = &checkpoint;  // type hint
1960
1961                        store
1962                            .update_highest_synced_checkpoint(&checkpoint)
1963                            .expect("store operation should not fail");
1964                        // We don't care if no one is listening as this is a broadcast channel
1965                        let _ = checkpoint_event_sender.send(checkpoint.clone());
1966                        tx_in_flight -= checkpoint.network_total_transactions - highest_synced.network_total_transactions;
1967                        highest_synced = checkpoint;
1968                        if let Some(hedge) = &hedge {
1969                            hedge
1970                                .highest_synced
1971                                .store(*highest_synced.sequence_number(), Ordering::Relaxed);
1972                        }
1973
1974                    }
1975                    Err(checkpoint) => {
1976                        let _: &VerifiedCheckpoint = &checkpoint;  // type hint
1977                        if let Some(lowest_peer_checkpoint) =
1978                            peer_heights.read().ok().and_then(|x| x.peers.values().map(|state_sync_info| state_sync_info.lowest).min()) {
1979                            if checkpoint.sequence_number() >= &lowest_peer_checkpoint {
1980                                info!("unable to sync contents of checkpoint through state sync {} with lowest peer checkpoint: {}", checkpoint.sequence_number(), lowest_peer_checkpoint);
1981                            }
1982                        } else {
1983                            info!("unable to sync contents of checkpoint through state sync {}", checkpoint.sequence_number());
1984
1985                        }
1986                        // Calculate tx_count for retry by getting previous checkpoint
1987                        let retry_tx_count = if *checkpoint.sequence_number() == 0 {
1988                            checkpoint.network_total_transactions
1989                        } else {
1990                            let prev = store
1991                                .get_checkpoint_by_sequence_number(checkpoint.sequence_number() - 1)
1992                                .expect("previous checkpoint must exist")
1993                                .network_total_transactions;
1994                            checkpoint.network_total_transactions - prev
1995                        };
1996                        // Retry contents sync on failure.
1997                        checkpoint_contents_tasks.push_front(sync_one_checkpoint_contents(
1998                            network.clone(),
1999                            &store,
2000                            peer_heights.clone(),
2001                            use_get_checkpoint_contents_v2,
2002                            hedge.clone(),
2003                            metrics.clone(),
2004                            retry_tx_count,
2005                            checkpoint,
2006                        ));
2007                    }
2008                }
2009            },
2010        }
2011
2012        // Start new tasks up to configured concurrency limits.
2013        while current_sequence < target_sequence_cursor
2014            && checkpoint_contents_tasks.len() < checkpoint_content_download_concurrency
2015        {
2016            let next_checkpoint = store
2017                .get_checkpoint_by_sequence_number(current_sequence)
2018                .unwrap_or_else(|| panic!(
2019                    "BUG: store should have all checkpoints older than highest_verified_checkpoint (checkpoint {})",
2020                    current_sequence
2021                ));
2022
2023            // Enforce transaction count concurrency limit. A checkpoint is always admitted when
2024            // nothing is in flight, so a checkpoint with more transactions than the limit is still
2025            // downloaded.
2026            let tx_count = next_checkpoint.network_total_transactions
2027                - highest_started_network_total_transactions;
2028            if !checkpoint_contents_tasks.is_empty()
2029                && tx_in_flight + tx_count > checkpoint_content_download_tx_concurrency
2030            {
2031                break;
2032            }
2033            tx_in_flight += tx_count;
2034
2035            highest_started_network_total_transactions = next_checkpoint.network_total_transactions;
2036            current_sequence += 1;
2037            checkpoint_contents_tasks.push_back(sync_one_checkpoint_contents(
2038                network.clone(),
2039                &store,
2040                peer_heights.clone(),
2041                use_get_checkpoint_contents_v2,
2042                hedge.clone(),
2043                metrics.clone(),
2044                tx_count,
2045                next_checkpoint,
2046            ));
2047        }
2048
2049        if highest_synced
2050            .sequence_number()
2051            .is_multiple_of(checkpoint_content_download_concurrency as u64)
2052            || checkpoint_contents_tasks.is_empty()
2053        {
2054            // Periodically notify event loop to notify our peers that we've synced to a new checkpoint height
2055            if let Some(sender) = sender.upgrade() {
2056                let message = StateSyncMessage::SyncedCheckpoint(Box::new(highest_synced.clone()));
2057                let _ = sender.send(message).await;
2058            }
2059        }
2060    }
2061}
2062
2063// Err hands the checkpoint back so the caller can retry it; Ok carries the same type, so boxing
2064// the error would not shrink the Result.
2065#[allow(clippy::result_large_err)]
2066#[instrument(level = "debug", skip_all, fields(sequence_number = ?checkpoint.sequence_number()))]
2067async fn sync_one_checkpoint_contents<S>(
2068    network: anemo::Network,
2069    store: S,
2070    peer_heights: Arc<RwLock<PeerHeights>>,
2071    use_get_checkpoint_contents_v2: bool,
2072    hedge: Option<ContentHedge>,
2073    metrics: Metrics,
2074    tx_count: u64,
2075    checkpoint: VerifiedCheckpoint,
2076) -> Result<VerifiedCheckpoint, VerifiedCheckpoint>
2077where
2078    S: WriteStore + Clone,
2079{
2080    let (timeout_min, timeout_max) = {
2081        let ph = peer_heights.read().unwrap();
2082        (
2083            ph.checkpoint_content_timeout_min,
2084            ph.checkpoint_content_timeout_max,
2085        )
2086    };
2087    let timeout = compute_adaptive_timeout(tx_count, timeout_min, timeout_max);
2088    debug!(
2089        "syncing checkpoint contents with adaptive timeout {:?} for {} txns",
2090        timeout, tx_count
2091    );
2092
2093    // Check if we already have produced this checkpoint locally. If so, we don't need
2094    // to get it from peers anymore.
2095    if store
2096        .get_highest_synced_checkpoint()
2097        .expect("store operation should not fail")
2098        .sequence_number()
2099        >= checkpoint.sequence_number()
2100    {
2101        debug!("checkpoint was already created via consensus output");
2102        return Ok(checkpoint);
2103    }
2104
2105    // Request checkpoint contents from peers.
2106    let now = tokio::time::Instant::now();
2107    let fetch = ContentFetch {
2108        network: &network,
2109        peer_heights: &peer_heights,
2110        checkpoint: &checkpoint,
2111        use_get_checkpoint_contents_v2,
2112        timeout,
2113        metrics: &metrics,
2114    };
2115    if !get_full_checkpoint_contents(fetch, &store, hedge.as_ref()).await {
2116        // Delay completion in case of error so we don't hammer the network with retries.
2117        let duration = peer_heights
2118            .read()
2119            .unwrap()
2120            .wait_interval_when_no_peer_to_sync_content();
2121        if now.elapsed() < duration {
2122            let duration = duration - now.elapsed();
2123            info!("retrying checkpoint sync after {:?}", duration);
2124            tokio::time::sleep(duration).await;
2125        }
2126        return Err(checkpoint);
2127    };
2128    debug!("completed checkpoint contents sync");
2129    Ok(checkpoint)
2130}
2131
2132/// In hedged mode, the most requests for one checkpoint's contents that are in flight at once.
2133const MAX_CONCURRENT_CONTENT_REQUESTS: usize = 2;
2134
2135/// In hedged mode, only checkpoints at most this far past the highest synced checkpoint are
2136/// hedged, or keep looking for a peer after every peer that had the checkpoint failed.
2137/// Checkpoints are released in order, so a later checkpoint can't be released before the ones
2138/// ahead of it. Extra requests for it would add load (for example during catch-up, with hundreds
2139/// of downloads in flight) without reducing how long it takes to release.
2140const CONTENT_HEDGE_WINDOW: CheckpointSequenceNumber = 8;
2141
2142/// How often a download near the release frontier checks which peers have announced the
2143/// checkpoint: while a hedge is due or every request failed, and, for measuring when peers
2144/// announce it and for early hedges, for the whole download after its first request.
2145const CONTENT_CANDIDATE_POLL_INTERVAL: Duration = Duration::from_millis(10);
2146
2147/// How much sooner a peer that hasn't been asked yet must be expected to finish than the request
2148/// in flight for a hedge to go out to it right away. Keeps small differences in expected response
2149/// times, which are within their measurement noise, from sending extra requests.
2150const CLOSER_PEER_MIN_GAIN: Duration = Duration::from_millis(50);
2151
2152/// Near the release frontier, one in this many requests that are not hedges sent to a peer
2153/// while it is slow from this node is a slow-peer probe. Requests to a slow peer are otherwise
2154/// hedged right away once a peer that isn't slow has the checkpoint, so their slow outcomes are
2155/// cut short before the slow peer's slow-response threshold, where they don't count (see
2156/// `PeerScore::slow_peer_hedge_delay`), while their fast answers still arrive. Recording those
2157/// would make the peer look less slow than it is, so while a peer is slow, only probes add
2158/// response-time samples (see `SlowPeerRequest::records_response_time`). Samples from before it
2159/// became slow still count until newer ones replace them or they age out.
2160/// A probe is only hedged after its hedge delay (see `ContentFetch::hedge_delay_for`) or to a
2161/// peer expected to finish at least [`CLOSER_PEER_MIN_GAIN`] sooner, so it usually ends in a
2162/// sample that counts: an answer, or a cancellation at or after the threshold. Probes keep the
2163/// slow flag measurable and re-check the peer every so often, so that it stops being treated as
2164/// slow once it answers in time again.
2165const SLOW_PEER_PROBE_INTERVAL: u32 = 4;
2166
2167/// Settings for hedged checkpoint contents downloads.
2168#[derive(Clone)]
2169struct ContentHedge {
2170    /// How long a request to a peer that is not slow from this node may run before another peer
2171    /// is also asked. Requests to a slow peer are hedged after the peer's slow-response threshold
2172    /// if that is shorter (see [`ContentFetch::hedge_delay_for`]).
2173    delay: Duration,
2174    /// Sequence number of the highest checkpoint whose contents are synced and released.
2175    highest_synced: Arc<AtomicU64>,
2176}
2177
2178impl ContentHedge {
2179    fn covers(&self, sequence_number: CheckpointSequenceNumber) -> bool {
2180        sequence_number
2181            <= self
2182                .highest_synced
2183                .load(Ordering::Relaxed)
2184                .saturating_add(CONTENT_HEDGE_WINDOW)
2185    }
2186}
2187
2188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2189enum ContentRequestKind {
2190    /// The first request for a checkpoint's contents.
2191    First,
2192    /// A request sent while an earlier request for the same checkpoint was still running.
2193    Hedge,
2194    /// A request sent after every earlier request for the same checkpoint failed.
2195    Fallback,
2196}
2197
2198/// A request for one checkpoint's contents that is still in flight.
2199#[derive(Clone, Copy)]
2200struct InFlightContentRequest {
2201    start: Instant,
2202    kind: ContentRequestKind,
2203    /// For a request that is not a hedge, near the release frontier, whether its peer was slow
2204    /// from this node when it was sent and whether it is a slow-peer probe. A probe is not hedged
2205    /// right away just because its peer is slow, and while a peer is slow, only probes record
2206    /// response-time samples (see [`SLOW_PEER_PROBE_INTERVAL`]). `PeerNotSlow` for hedges and for
2207    /// downloads that started outside the hedge window.
2208    slow_peer: SlowPeerRequest,
2209}
2210
2211/// A peer that could be asked for a checkpoint's contents.
2212struct UnaskedPeer {
2213    peer: anemo::Peer,
2214    /// See [`expected_response_time`].
2215    expected: Duration,
2216    /// Whether the peer is slow from this node (see `PeerHeights::slow_peer_hedge_delay`).
2217    slow: bool,
2218}
2219
2220/// A finished request for one checkpoint's contents to one peer.
2221struct ContentResponse {
2222    peer_id: PeerId,
2223    elapsed: Duration,
2224    /// `None` if the request failed or timed out, or the peer had no contents.
2225    contents: Option<VersionedFullCheckpointContents>,
2226}
2227
2228/// Outcome of a full contents download.
2229enum FullContentsDownload {
2230    /// A peer delivered valid contents.
2231    Done(VersionedFullCheckpointContents),
2232    /// Every peer that was asked failed to deliver valid contents.
2233    Failed,
2234    /// No peer had the checkpoint.
2235    NoPeers,
2236}
2237
2238/// Downloads the contents of one checkpoint from peers.
2239struct ContentFetch<'a> {
2240    network: &'a anemo::Network,
2241    peer_heights: &'a Arc<RwLock<PeerHeights>>,
2242    checkpoint: &'a VerifiedCheckpoint,
2243    use_get_checkpoint_contents_v2: bool,
2244    timeout: Duration,
2245    metrics: &'a Metrics,
2246}
2247
2248impl ContentFetch<'_> {
2249    /// Peers that, as of now, have announced the checkpoint and still have its contents.
2250    fn candidates(&self) -> PeerBalancer {
2251        PeerBalancer::new(
2252            self.network,
2253            self.peer_heights.clone(),
2254            PeerCheckpointRequestType::Content,
2255        )
2256        .with_checkpoint(*self.checkpoint.sequence_number())
2257    }
2258
2259    /// Whether a connected peer not in `asked` has announced the checkpoint and still has its
2260    /// contents. Cheaper than [`Self::candidates`], for frequent checks.
2261    fn has_unasked_candidate(&self, asked: &HashSet<PeerId>) -> bool {
2262        let sequence_number = *self.checkpoint.sequence_number();
2263        self.peer_heights
2264            .read()
2265            .unwrap()
2266            .peers_on_same_chain()
2267            .any(|(peer_id, info)| {
2268                info.has_contents(sequence_number)
2269                    && !asked.contains(peer_id)
2270                    && self.network.peer(*peer_id).is_some()
2271            })
2272    }
2273
2274    /// The next peer to ask among the peers not in `asked` that have the checkpoint now.
2275    fn next_candidate(&self, asked: &HashSet<PeerId>) -> Option<StateSyncClient<anemo::Peer>> {
2276        if !self.has_unasked_candidate(asked) {
2277            return None;
2278        }
2279        self.candidates().excluding(asked).next()
2280    }
2281
2282    /// Connected peers on the same chain that, as of now, have announced the checkpoint and
2283    /// still have its contents, whether or not they were asked.
2284    fn peers_with_checkpoint(&self) -> Vec<anemo::Peer> {
2285        let sequence_number = *self.checkpoint.sequence_number();
2286        self.peer_heights
2287            .read()
2288            .unwrap()
2289            .peers_on_same_chain()
2290            .filter(|(_, info)| info.has_contents(sequence_number))
2291            .filter_map(|(peer_id, _)| self.network.peer(*peer_id))
2292            .collect()
2293    }
2294
2295    /// Among the peers in `peers` that are not in `asked` and have no recent failures, the one
2296    /// with the lowest [`expected_response_time`], preferring peers that are not slow from this
2297    /// node (see `PeerHeights::slow_peer_hedge_delay`).
2298    fn closest_unasked_peer(
2299        &self,
2300        peers: &[anemo::Peer],
2301        asked: &HashSet<PeerId>,
2302    ) -> Option<UnaskedPeer> {
2303        let peer_heights = self.peer_heights.read().unwrap();
2304        peers
2305            .iter()
2306            .filter(|peer| {
2307                let peer_id = peer.peer_id();
2308                !asked.contains(&peer_id) && !peer_heights.is_failing(&peer_id)
2309            })
2310            .map(|peer| {
2311                let slow = peer_heights
2312                    .slow_peer_hedge_delay(&peer.peer_id())
2313                    .is_some();
2314                (peer, expected_response_time(peer, &peer_heights), slow)
2315            })
2316            .min_by_key(|(_, expected, slow)| (*slow, *expected))
2317            .map(|(peer, expected, slow)| UnaskedPeer {
2318                peer: peer.clone(),
2319                expected,
2320                slow,
2321            })
2322    }
2323
2324    /// The peer to send a request to other than an early hedge: with `prefer_closest`,
2325    /// [`Self::closest_unasked_peer`] among the peers that have the checkpoint now, or
2326    /// [`Self::next_candidate`] if that finds no peer; otherwise [`Self::next_candidate`].
2327    fn candidate(
2328        &self,
2329        asked: &HashSet<PeerId>,
2330        prefer_closest: bool,
2331    ) -> Option<StateSyncClient<anemo::Peer>> {
2332        if prefer_closest
2333            && let Some(closest) = self.closest_unasked_peer(&self.peers_with_checkpoint(), asked)
2334        {
2335            return Some(StateSyncClient::new(closest.peer));
2336        }
2337        self.next_candidate(asked)
2338    }
2339
2340    /// With one request in flight, the peer to hedge to right away, if any, and the event that
2341    /// counts the hedge. `peers` are the peers that have the checkpoint now; the hedge can only go
2342    /// to [`Self::closest_unasked_peer`] among them. It does if that peer is not slow from this
2343    /// node while the request in flight is to a slow peer and is not a slow-peer probe
2344    /// ([`HedgeEvent::SentAroundSlowPeer`]), or if that peer is expected to finish at least
2345    /// [`CLOSER_PEER_MIN_GAIN`] before the request in flight (see [`worth_hedging_early`],
2346    /// [`HedgeEvent::SentToCloserPeer`]). Returns `None` if the in-flight request's peer is no
2347    /// longer connected.
2348    fn early_hedge(
2349        &self,
2350        peers: &[anemo::Peer],
2351        asked: &HashSet<PeerId>,
2352        in_flight_peer_id: PeerId,
2353        in_flight: &InFlightContentRequest,
2354    ) -> Option<(StateSyncClient<anemo::Peer>, HedgeEvent)> {
2355        let in_flight_peer = self.network.peer(in_flight_peer_id)?;
2356        let (in_flight_expected, in_flight_peer_slow) = {
2357            let peer_heights = self.peer_heights.read().unwrap();
2358            (
2359                expected_response_time(&in_flight_peer, &peer_heights),
2360                peer_heights
2361                    .slow_peer_hedge_delay(&in_flight_peer_id)
2362                    .is_some(),
2363            )
2364        };
2365        let closest = self.closest_unasked_peer(peers, asked)?;
2366        let event = if in_flight_peer_slow
2367            && in_flight.slow_peer != SlowPeerRequest::Probe
2368            && !closest.slow
2369        {
2370            HedgeEvent::SentAroundSlowPeer
2371        } else if worth_hedging_early(
2372            Instant::now(),
2373            in_flight.start,
2374            in_flight_expected,
2375            closest.expected,
2376        ) {
2377            HedgeEvent::SentToCloserPeer
2378        } else {
2379            return None;
2380        };
2381        Some((StateSyncClient::new(closest.peer), event))
2382    }
2383
2384    /// How long a request to `peer_id` may run before it is hedged: `hedge.delay`, or the peer's
2385    /// slow-response threshold if the peer is slow from this node and the threshold is shorter.
2386    fn hedge_delay_for(&self, hedge: &ContentHedge, peer_id: PeerId) -> Duration {
2387        self.peer_heights
2388            .read()
2389            .unwrap()
2390            .slow_peer_hedge_delay(&peer_id)
2391            .filter(|delay| *delay < hedge.delay)
2392            .unwrap_or(hedge.delay)
2393    }
2394
2395    /// [`Self::hedge_delay_for`] a request about to be sent to `peer_id`. If the delay is
2396    /// shortened and the checkpoint is in the hedge window, where the delay can trigger a hedge,
2397    /// records it in `state_sync_checkpoint_content_slow_peer_hedge_delay`.
2398    fn new_request_hedge_delay(&self, hedge: &ContentHedge, peer_id: PeerId) -> Duration {
2399        let delay = self.hedge_delay_for(hedge, peer_id);
2400        if delay < hedge.delay && hedge.covers(*self.checkpoint.sequence_number()) {
2401            self.metrics
2402                .record_checkpoint_content_slow_peer_hedge_delay(
2403                    &content_metrics_peer_label(self.network, peer_id),
2404                    delay,
2405                );
2406        }
2407        delay
2408    }
2409
2410    /// Called when a request that is not a hedge is about to be sent to `peer_id` near the
2411    /// release frontier: whether the peer is slow and the request is a slow-peer probe (see
2412    /// [`SLOW_PEER_PROBE_INTERVAL`]). Counts probes in
2413    /// `state_sync_checkpoint_content_slow_peer_probes`.
2414    fn classify_new_request(&self, peer_id: PeerId) -> SlowPeerRequest {
2415        let slow_peer = self
2416            .peer_heights
2417            .write()
2418            .unwrap()
2419            .classify_new_request(&peer_id);
2420        if slow_peer == SlowPeerRequest::Probe {
2421            self.metrics
2422                .inc_checkpoint_content_slow_peer_probe(&content_metrics_peer_label(
2423                    self.network,
2424                    peer_id,
2425                ));
2426        }
2427        slow_peer
2428    }
2429
2430    fn request(
2431        &self,
2432        mut peer: StateSyncClient<anemo::Peer>,
2433        kind: ContentRequestKind,
2434    ) -> impl Future<Output = ContentResponse> {
2435        let peer_id = peer.inner().peer_id();
2436        let digest = self.checkpoint.content_digest;
2437        let timeout = self.timeout;
2438        let use_get_checkpoint_contents_v2 = self.use_get_checkpoint_contents_v2;
2439        debug!(
2440            ?timeout,
2441            ?kind,
2442            "requesting checkpoint contents from {}",
2443            peer_id
2444        );
2445        async move {
2446            let request = Request::new(digest).with_timeout(timeout);
2447            let start = Instant::now();
2448            let result = if use_get_checkpoint_contents_v2 {
2449                peer.get_checkpoint_contents_v2(request).await
2450            } else {
2451                peer.get_checkpoint_contents(request)
2452                    .await
2453                    .map(|r| r.map(|c| c.map(VersionedFullCheckpointContents::V1)))
2454            };
2455            let elapsed = start.elapsed();
2456            let contents = match result {
2457                Ok(response) => {
2458                    let contents = response.into_inner();
2459                    if contents.is_none() {
2460                        trace!("peer unable to help sync");
2461                    }
2462                    contents
2463                }
2464                Err(e) => {
2465                    trace!("{e:?}");
2466                    None
2467                }
2468            };
2469            ContentResponse {
2470                peer_id,
2471                elapsed,
2472                contents,
2473            }
2474        }
2475    }
2476
2477    /// Scores the peer and records metrics for a finished request. Returns the contents and
2478    /// their serialized size if they match the checkpoint's content digest.
2479    fn record_response(
2480        &self,
2481        response: ContentResponse,
2482    ) -> Option<(VersionedFullCheckpointContents, u64)> {
2483        let ContentResponse {
2484            peer_id,
2485            elapsed,
2486            contents,
2487        } = response;
2488        let peer_label = content_metrics_peer_label(self.network, peer_id);
2489        let Some(contents) = contents else {
2490            self.peer_heights.write().unwrap().record_failure(peer_id);
2491            self.metrics.record_checkpoint_content_peer_request(
2492                &peer_label,
2493                ContentRequestOutcome::Failure,
2494                elapsed,
2495            );
2496            return None;
2497        };
2498        if contents
2499            .verify_digests(self.checkpoint.content_digest)
2500            .is_err()
2501        {
2502            self.metrics.record_checkpoint_content_peer_request(
2503                &peer_label,
2504                ContentRequestOutcome::Failure,
2505                elapsed,
2506            );
2507            return None;
2508        }
2509        let size = bcs::serialized_size(&contents).expect("serialization should not fail") as u64;
2510        self.peer_heights
2511            .write()
2512            .unwrap()
2513            .record_success(peer_id, size, elapsed);
2514        self.metrics.record_checkpoint_content_peer_request(
2515            &peer_label,
2516            ContentRequestOutcome::Success,
2517            elapsed,
2518        );
2519        Some((contents, size))
2520    }
2521
2522    /// Tries the peers that had the checkpoint when the download started, one at a time.
2523    async fn one_peer_at_a_time(&self) -> FullContentsDownload {
2524        let mut kind = ContentRequestKind::First;
2525        for peer in self.candidates() {
2526            if kind == ContentRequestKind::Fallback {
2527                self.metrics.inc_checkpoint_content_fallback_requests();
2528            }
2529            let response = self.request(peer, kind).await;
2530            if let Some((contents, _size)) = self.record_response(response) {
2531                return FullContentsDownload::Done(contents);
2532            }
2533            kind = ContentRequestKind::Fallback;
2534        }
2535        if kind == ContentRequestKind::First {
2536            FullContentsDownload::NoPeers
2537        } else {
2538            FullContentsDownload::Failed
2539        }
2540    }
2541
2542    /// Sends a hedge request to another peer when the latest request has run for its peer's
2543    /// hedge delay (see [`Self::hedge_delay_for`]) without a valid response, with at most
2544    /// [`MAX_CONCURRENT_CONTENT_REQUESTS`] requests in flight. If no other peer has the
2545    /// checkpoint at that point, checks again every [`CONTENT_CANDIDATE_POLL_INTERVAL`]. When
2546    /// every request has failed, asks another peer right away. Peers are picked from the peers
2547    /// that have announced the checkpoint at the time each request is sent, not when the download
2548    /// started. The first valid response wins, and the other request is cancelled.
2549    ///
2550    /// A download near the release frontier when it starts sends its first request, hedges after
2551    /// the hedge delay, and requests after every request failed to the peer with the lowest
2552    /// [`expected_response_time`], preferring peers that are not slow from this node (see
2553    /// [`Self::closest_unasked_peer`]). From its first request until it ends, it checks every
2554    /// [`CONTENT_CANDIDATE_POLL_INTERVAL`] which peers have the checkpoint (see
2555    /// [`PeerAnnouncements`]). At each check while only one request is in flight, it hedges right
2556    /// away to a peer that hasn't been asked yet if the request in flight is to a slow peer and is
2557    /// not a slow-peer probe (see [`SLOW_PEER_PROBE_INTERVAL`]) and a peer that isn't slow has the
2558    /// checkpoint, or if a peer is expected to finish at least [`CLOSER_PEER_MIN_GAIN`] before the
2559    /// request in flight (see [`Self::early_hedge`]).
2560    async fn hedged(&self, hedge: &ContentHedge) -> FullContentsDownload {
2561        let sequence_number = *self.checkpoint.sequence_number();
2562        let near_frontier = hedge.covers(sequence_number);
2563        let wait_interval = self
2564            .peer_heights
2565            .read()
2566            .unwrap()
2567            .wait_interval_when_no_peer_to_sync_content();
2568        let download_start = tokio::time::Instant::now();
2569        let mut asked = HashSet::new();
2570        let mut in_flight = FuturesUnordered::new();
2571        // Each request still in flight, by peer.
2572        let mut in_flight_requests: HashMap<PeerId, InFlightContentRequest> = HashMap::new();
2573        let mut no_hedge_candidate_reported = false;
2574        let mut announcements = PeerAnnouncements::default();
2575        let next_hedge = tokio::time::sleep(hedge.delay);
2576        tokio::pin!(next_hedge);
2577        let next_other_peer_check = tokio::time::sleep(CONTENT_CANDIDATE_POLL_INTERVAL);
2578        tokio::pin!(next_other_peer_check);
2579
2580        loop {
2581            // The next request to send: a first or fallback request when nothing is in flight,
2582            // otherwise a hedge.
2583            let (peer, kind, slow_peer) = if in_flight.is_empty() {
2584                // Either nothing was sent yet or every request failed. Ask the next peer that has
2585                // the checkpoint now instead of waiting for the retry interval.
2586                if let Some(peer) = self.candidate(&asked, near_frontier) {
2587                    let kind = if asked.is_empty() {
2588                        ContentRequestKind::First
2589                    } else {
2590                        self.metrics.inc_checkpoint_content_fallback_requests();
2591                        ContentRequestKind::Fallback
2592                    };
2593                    let slow_peer = if near_frontier {
2594                        self.classify_new_request(peer.inner().peer_id())
2595                    } else {
2596                        SlowPeerRequest::PeerNotSlow
2597                    };
2598                    (peer, kind, slow_peer)
2599                } else if hedge.covers(sequence_number) && download_start.elapsed() < wait_interval
2600                {
2601                    // No peer that hasn't been asked has the checkpoint yet. Near the release
2602                    // frontier, check again after a short poll interval, or when the retry
2603                    // interval ends if that is sooner.
2604                    let next_check = tokio::time::Instant::now() + CONTENT_CANDIDATE_POLL_INTERVAL;
2605                    tokio::time::sleep_until(next_check.min(download_start + wait_interval)).await;
2606                    continue;
2607                } else if asked.is_empty() {
2608                    return FullContentsDownload::NoPeers;
2609                } else {
2610                    return FullContentsDownload::Failed;
2611                }
2612            } else {
2613                tokio::select! {
2614                    biased;
2615                    Some(response) = in_flight.next() => {
2616                        // Inference only learns the request type from the `push` below.
2617                        let response: ContentResponse = response;
2618                        // Every request in flight is in `in_flight_requests`: each peer is asked
2619                        // at most once per download, and a request is tracked from the moment it
2620                        // is sent.
2621                        let finished = in_flight_requests
2622                            .remove(&response.peer_id)
2623                            .expect("every request in flight is tracked");
2624                        let (peer_id, elapsed) = (response.peer_id, response.elapsed);
2625                        let Some((contents, size)) = self.record_response(response) else {
2626                            // The request still running, if any, is now the latest one: hedge it
2627                            // once it has run for its own hedge delay, which may already have
2628                            // passed.
2629                            if let Some((&running_peer_id, running)) =
2630                                in_flight_requests.iter().next()
2631                            {
2632                                next_hedge.as_mut().reset(tokio::time::Instant::from_std(
2633                                    running.start + self.hedge_delay_for(hedge, running_peer_id),
2634                                ));
2635                            }
2636                            continue;
2637                        };
2638                        if finished.kind == ContentRequestKind::Hedge {
2639                            self.metrics.inc_checkpoint_content_hedge(HedgeEvent::Won);
2640                        } else if finished.slow_peer.records_response_time() {
2641                            self.peer_heights.write().unwrap().record_content_response_time(
2642                                peer_id,
2643                                ContentResponseTime::Answered(elapsed),
2644                            );
2645                        }
2646                        // Dropping `in_flight` on return cancels the requests that lost.
2647                        for (peer_id, request) in in_flight_requests {
2648                            let cancelled_after = request.start.elapsed();
2649                            self.metrics.record_checkpoint_content_peer_request(
2650                                &content_metrics_peer_label(self.network, peer_id),
2651                                ContentRequestOutcome::Cancelled,
2652                                cancelled_after,
2653                            );
2654                            let mut peer_heights = self.peer_heights.write().unwrap();
2655                            peer_heights.record_cancelled_request(peer_id, size, cancelled_after);
2656                            if request.kind != ContentRequestKind::Hedge
2657                                && request.slow_peer.records_response_time()
2658                            {
2659                                peer_heights.record_content_response_time(
2660                                    peer_id,
2661                                    ContentResponseTime::LongerThan(cancelled_after),
2662                                );
2663                            }
2664                        }
2665                        return FullContentsDownload::Done(contents);
2666                    }
2667                    () = next_hedge.as_mut(), if in_flight.len() < MAX_CONCURRENT_CONTENT_REQUESTS => {
2668                        if !hedge.covers(sequence_number) {
2669                            next_hedge
2670                                .as_mut()
2671                                .reset(tokio::time::Instant::now() + hedge.delay);
2672                            continue;
2673                        }
2674                        let Some(peer) = self.candidate(&asked, near_frontier) else {
2675                            if !no_hedge_candidate_reported {
2676                                no_hedge_candidate_reported = true;
2677                                self.metrics
2678                                    .inc_checkpoint_content_hedge(HedgeEvent::NoCandidate);
2679                            }
2680                            next_hedge
2681                                .as_mut()
2682                                .reset(tokio::time::Instant::now() + CONTENT_CANDIDATE_POLL_INTERVAL);
2683                            continue;
2684                        };
2685                        self.metrics.inc_checkpoint_content_hedge(HedgeEvent::Sent);
2686                        (peer, ContentRequestKind::Hedge, SlowPeerRequest::PeerNotSlow)
2687                    }
2688                    // Requests are in flight, so the first request has gone out.
2689                    () = next_other_peer_check.as_mut(), if near_frontier => {
2690                        next_other_peer_check
2691                            .as_mut()
2692                            .reset(tokio::time::Instant::now() + CONTENT_CANDIDATE_POLL_INTERVAL);
2693                        let peers = self.peers_with_checkpoint();
2694                        announcements.observe(&peers, self.network, self.metrics);
2695                        if in_flight.len() >= MAX_CONCURRENT_CONTENT_REQUESTS {
2696                            continue;
2697                        }
2698                        let Some((peer, event)) = in_flight_requests
2699                            .iter()
2700                            .next()
2701                            .and_then(|(&in_flight_peer_id, in_flight_request)| {
2702                                self.early_hedge(&peers, &asked, in_flight_peer_id, in_flight_request)
2703                            })
2704                        else {
2705                            continue;
2706                        };
2707                        self.metrics.inc_checkpoint_content_hedge(HedgeEvent::Sent);
2708                        self.metrics.inc_checkpoint_content_hedge(event);
2709                        (peer, ContentRequestKind::Hedge, SlowPeerRequest::PeerNotSlow)
2710                    }
2711                }
2712            };
2713
2714            let peer_id = peer.inner().peer_id();
2715            asked.insert(peer_id);
2716            in_flight_requests.insert(
2717                peer_id,
2718                InFlightContentRequest {
2719                    start: Instant::now(),
2720                    kind,
2721                    slow_peer,
2722                },
2723            );
2724            in_flight.push(self.request(peer, kind));
2725            next_hedge
2726                .as_mut()
2727                .reset(tokio::time::Instant::now() + self.new_request_hedge_delay(hedge, peer_id));
2728            if kind == ContentRequestKind::First && near_frontier {
2729                announcements.first_request_sent();
2730                next_other_peer_check
2731                    .as_mut()
2732                    .reset(tokio::time::Instant::now() + CONTENT_CANDIDATE_POLL_INTERVAL);
2733                announcements.observe(&self.peers_with_checkpoint(), self.network, self.metrics);
2734            }
2735        }
2736    }
2737}
2738
2739/// For a download near the release frontier, tracks from its first request which peers have the
2740/// checkpoint, and records for each peer how long after the first request a check first saw it
2741/// having the checkpoint (`state_sync_checkpoint_content_peer_announce_delay`).
2742#[derive(Default)]
2743struct PeerAnnouncements {
2744    /// When the first request went out, once it has.
2745    first_request_at: Option<Instant>,
2746    /// Peers seen having the checkpoint since the first request.
2747    seen: HashSet<PeerId>,
2748}
2749
2750impl PeerAnnouncements {
2751    fn first_request_sent(&mut self) {
2752        self.first_request_at = Some(Instant::now());
2753    }
2754
2755    /// Records the announce delay of each peer in `peers`, the peers that have the checkpoint
2756    /// now, that wasn't seen having it before.
2757    fn observe(&mut self, peers: &[anemo::Peer], network: &anemo::Network, metrics: &Metrics) {
2758        let Some(first_request_at) = self.first_request_at else {
2759            return;
2760        };
2761        let delay = first_request_at.elapsed();
2762        for peer in peers {
2763            let peer_id = peer.peer_id();
2764            if self.seen.insert(peer_id) {
2765                metrics.record_checkpoint_content_peer_announce_delay(
2766                    &content_metrics_peer_label(network, peer_id),
2767                    delay,
2768                );
2769            }
2770        }
2771    }
2772}
2773
2774/// How long a contents request to `peer` is expected to take: the longer of the connection's
2775/// round-trip time and the peer's fastest recent answer (see
2776/// `PeerHeights::fastest_recent_content_answer`), or the round-trip time alone if the peer has
2777/// no recent answers. A request needs at least one round trip, and a peer that answered in some
2778/// time recently is not expected to answer faster.
2779fn expected_response_time(peer: &anemo::Peer, peer_heights: &PeerHeights) -> Duration {
2780    let rtt = peer.connection_rtt();
2781    peer_heights
2782        .fastest_recent_content_answer(&peer.peer_id())
2783        .map_or(rtt, |fastest| fastest.max(rtt))
2784}
2785
2786/// Whether a peer with expected response time `candidate_expected`, asked at `now`, is expected to
2787/// finish at least [`CLOSER_PEER_MIN_GAIN`] before the request in flight, which was sent at
2788/// `in_flight_start` to a peer with expected response time `in_flight_expected`. A request in
2789/// flight that has run past its expected finish never qualifies.
2790fn worth_hedging_early(
2791    now: Instant,
2792    in_flight_start: Instant,
2793    in_flight_expected: Duration,
2794    candidate_expected: Duration,
2795) -> bool {
2796    now + candidate_expected + CLOSER_PEER_MIN_GAIN <= in_flight_start + in_flight_expected
2797}
2798
2799/// Label for per-peer content request metrics. Only peers in the network's known-peer set get
2800/// their own label, which bounds the label cardinality.
2801fn content_metrics_peer_label(network: &anemo::Network, peer_id: PeerId) -> String {
2802    if network.known_peers().get(&peer_id).is_some() {
2803        peer_id.to_string()
2804    } else {
2805        "other".to_owned()
2806    }
2807}
2808
2809/// Downloads the checkpoint's contents into `store`. Returns whether the store has them.
2810#[instrument(level = "debug", skip_all)]
2811async fn get_full_checkpoint_contents<S>(
2812    fetch: ContentFetch<'_>,
2813    store: S,
2814    hedge: Option<&ContentHedge>,
2815) -> bool
2816where
2817    S: WriteStore,
2818{
2819    let checkpoint = fetch.checkpoint;
2820    let digest = checkpoint.content_digest;
2821    // Stored contents imply that their transactions and effects are stored, so this does not
2822    // need to load them.
2823    if store.get_checkpoint_contents_by_digest(&digest).is_some() {
2824        debug!("store already contains checkpoint contents");
2825        return true;
2826    }
2827
2828    let start = Instant::now();
2829    let outcome = match hedge {
2830        None => fetch.one_peer_at_a_time().await,
2831        Some(hedge) => fetch.hedged(hedge).await,
2832    };
2833    let downloaded = match outcome {
2834        FullContentsDownload::Done(contents) => {
2835            let verified_contents = VerifiedCheckpointContents::new_unchecked(contents);
2836            store
2837                .insert_checkpoint_contents(checkpoint, verified_contents)
2838                .expect("store operation should not fail");
2839            true
2840        }
2841        FullContentsDownload::NoPeers => {
2842            debug!("no peers had checkpoint contents");
2843            false
2844        }
2845        FullContentsDownload::Failed => {
2846            // The paginated download works for checkpoints of any size.
2847            debug!("full checkpoint contents download failed, falling back to paginated download");
2848            let downloaded = get_paginated_checkpoint_contents(
2849                fetch.candidates(),
2850                &store,
2851                fetch.peer_heights,
2852                checkpoint,
2853            )
2854            .await;
2855            if !downloaded {
2856                debug!("paginated checkpoint contents download failed");
2857            }
2858            downloaded
2859        }
2860    };
2861    if downloaded {
2862        fetch
2863            .metrics
2864            .record_checkpoint_content_download(start.elapsed());
2865    }
2866    downloaded
2867}
2868
2869/// Downloads the checkpoint's contents in pages, from the peers that have it one at a time,
2870/// and inserts each page into `store` as it arrives. Unlike full contents, this works for a
2871/// checkpoint of any size, and never holds all of its transactions in memory. A peer that
2872/// fails is replaced by the next one, which resumes where the failed peer stopped.
2873async fn get_paginated_checkpoint_contents<S: WriteStore>(
2874    peers: PeerBalancer,
2875    store: &S,
2876    peer_heights: &RwLock<PeerHeights>,
2877    checkpoint: &VerifiedCheckpoint,
2878) -> bool {
2879    let mut progress = PaginatedProgress {
2880        contents: None,
2881        next: 0,
2882        max_items: u64::MAX,
2883        last_page_len: None,
2884    };
2885    for peer in peers {
2886        let peer_id = peer.inner().peer_id();
2887        let start = Instant::now();
2888        match get_paginated_checkpoint_contents_from_peer(
2889            peer,
2890            store,
2891            peer_heights,
2892            checkpoint,
2893            &mut progress,
2894        )
2895        .await
2896        {
2897            Ok(size) => {
2898                peer_heights
2899                    .write()
2900                    .unwrap()
2901                    .record_success(peer_id, size, start.elapsed());
2902                return true;
2903            }
2904            Err(e) => {
2905                debug!("paginated contents download from {peer_id} failed: {e:?}");
2906                peer_heights.write().unwrap().record_failure(peer_id);
2907            }
2908        }
2909    }
2910    false
2911}
2912
2913/// Downloads the rest of the checkpoint's contents from one peer in pages, starting from
2914/// `progress`. Returns the number of bytes downloaded.
2915async fn get_paginated_checkpoint_contents_from_peer<S: WriteStore>(
2916    mut peer: StateSyncClient<anemo::Peer>,
2917    store: &S,
2918    peer_heights: &RwLock<PeerHeights>,
2919    checkpoint: &VerifiedCheckpoint,
2920    progress: &mut PaginatedProgress,
2921) -> anyhow::Result<u64> {
2922    let sequence_number = *checkpoint.sequence_number();
2923    // Pages are bounded in bytes, not transactions, so the adaptive timeout for full
2924    // contents does not apply.
2925    let page_timeout = peer_heights.read().unwrap().checkpoint_content_timeout_max;
2926    let mut size = 0;
2927    if progress.contents.is_none() {
2928        let contents = peer
2929            .get_checkpoint_contents_digests(
2930                Request::new(sequence_number).with_timeout(page_timeout),
2931            )
2932            .await
2933            .map_err(|e| anyhow::anyhow!("{e:?}"))?
2934            .into_inner()
2935            .ok_or_else(|| anyhow::anyhow!("peer does not have the checkpoint contents"))?;
2936        anyhow::ensure!(
2937            *contents.digest() == checkpoint.content_digest,
2938            "checkpoint contents digest {} does not match expected digest {}",
2939            contents.digest(),
2940            checkpoint.content_digest
2941        );
2942        size += bcs::serialized_size(&contents)? as u64;
2943        progress.contents = Some(contents);
2944    }
2945    let contents = progress.contents.as_ref().expect("set above");
2946
2947    let num_transactions = contents.size() as u64;
2948    while progress.next < num_transactions {
2949        let next = progress.next;
2950        let request = GetCheckpointTransactionsRequest {
2951            sequence_number,
2952            start: next,
2953            end: next
2954                .saturating_add(progress.max_items)
2955                .min(num_transactions),
2956        };
2957        let requested = request.end - request.start;
2958        let response = peer
2959            .get_checkpoint_transactions(Request::new(request).with_timeout(page_timeout))
2960            .await;
2961        let page = match response {
2962            Ok(response) => response
2963                .into_inner()
2964                .ok_or_else(|| anyhow::anyhow!("peer does not have the checkpoint transactions"))?,
2965            Err(e) => {
2966                // A page can fail because it is too large to arrive in time, so ask the next
2967                // peer for a smaller one. Pages never grow, so the download does not return to a
2968                // page size that failed.
2969                progress.max_items =
2970                    (progress.last_page_len.unwrap_or(requested).min(requested) / 2).max(1);
2971                anyhow::bail!("{e:?}");
2972            }
2973        };
2974        anyhow::ensure!(
2975            !page.is_empty() && page.len() as u64 <= num_transactions - next,
2976            "page of {} transactions does not fit range [{next}, {num_transactions})",
2977            page.len()
2978        );
2979        let mut verified = Vec::with_capacity(page.len());
2980        for (offset, data) in page.into_iter().enumerate() {
2981            let index = next as usize + offset;
2982            let expected = contents
2983                .inner()
2984                .get_digests(index)
2985                .copied()
2986                .expect("index is within the checkpoint contents");
2987            anyhow::ensure!(
2988                data.digests() == expected,
2989                "transaction {index} has digests {:?}, expected {expected:?}",
2990                data.digests()
2991            );
2992            size += bcs::serialized_size(&data)? as u64;
2993            verified.push(VerifiedExecutionData::new_unchecked(data));
2994        }
2995        store
2996            .insert_transactions_and_effects(&verified)
2997            .expect("store operation should not fail");
2998        progress.next += verified.len() as u64;
2999        progress.last_page_len = Some(verified.len() as u64);
3000    }
3001    store
3002        .insert_checkpoint_contents_digests(
3003            checkpoint,
3004            progress.contents.take().expect("set above"),
3005        )
3006        .expect("store operation should not fail");
3007    Ok(size)
3008}
3009
3010/// State of a paginated contents download, kept across peers.
3011struct PaginatedProgress {
3012    /// The checkpoint's contents, once downloaded and verified.
3013    contents: Option<CheckpointContents>,
3014    /// Index of the first transaction not yet stored.
3015    next: u64,
3016    /// Most transactions to request in one page. The server also limits each page by bytes.
3017    /// Halved after a page fails, so that pages too large to arrive in time get smaller.
3018    max_items: u64,
3019    /// Length of the last page received.
3020    last_page_len: Option<u64>,
3021}
3022
3023async fn update_checkpoint_watermark_metrics<S>(
3024    mut recv: oneshot::Receiver<()>,
3025    store: S,
3026    metrics: Metrics,
3027) -> Result<()>
3028where
3029    S: WriteStore + Clone + Send + Sync,
3030{
3031    let mut interval = tokio::time::interval(Duration::from_secs(5));
3032    loop {
3033        tokio::select! {
3034             _now = interval.tick() => {
3035                let highest_verified_checkpoint = store.get_highest_verified_checkpoint()
3036                    .expect("store operation should not fail");
3037                metrics.set_highest_verified_checkpoint(highest_verified_checkpoint.sequence_number);
3038                let highest_synced_checkpoint = store.get_highest_synced_checkpoint()
3039                    .expect("store operation should not fail");
3040                metrics.set_highest_synced_checkpoint(highest_synced_checkpoint.sequence_number);
3041             },
3042            _ = &mut recv => break,
3043        }
3044    }
3045    Ok(())
3046}