Skip to main content

nimiq_consensus/sync/live/diff_queue/
mod.rs

1//! Provides a queuing component that augments blocks with state trie diffs during live sync.
2
3use std::{
4    collections::{HashMap, HashSet},
5    future,
6    pin::Pin,
7    sync::Arc,
8    task::{Context, Poll},
9};
10
11use futures::{future::BoxFuture, Stream, StreamExt};
12use nimiq_hash::Blake2bHash;
13use nimiq_network_interface::{
14    network::Network,
15    request::{RequestCommon, RequestMarker},
16};
17use nimiq_primitives::trie::trie_diff::TrieDiff;
18use nimiq_serde::{Deserialize, Serialize};
19use nimiq_utils::stream::FuturesOrdered;
20use parking_lot::RwLock;
21
22use self::diff_request_component::{DiffRequestComponent, DiffRequestError};
23use super::block_queue::{BlockAndSource, BlockQueue, BlockSource, QueuedBlock};
24use crate::{
25    consensus::ResolveBlockRequest,
26    sync::{
27        live::{block_queue::live_sync::PushOpResult, queue::LiveSyncQueue},
28        peer_list::PeerList,
29        sync_interface::LiveSyncEvent,
30    },
31};
32
33pub mod diff_request_component;
34
35/// The max number of partial trie diffs requests per peer.
36pub const MAX_REQUEST_RESPONSE_TRIE_DIFFS: u32 = 100;
37
38/// The request of a trie diff.
39#[derive(Clone, Debug, Serialize, Deserialize)]
40pub struct RequestTrieDiff {
41    pub block_hash: Blake2bHash,
42}
43
44/// The response for trie diff requests.
45#[derive(Clone, Debug, Serialize, Deserialize)]
46#[repr(u8)]
47pub enum ResponseTrieDiff {
48    PartialDiff(TrieDiff),
49    UnknownBlockHash,
50    IncompleteState,
51}
52
53impl RequestCommon for RequestTrieDiff {
54    type Kind = RequestMarker;
55    const TYPE_ID: u16 = 218;
56    type Response = ResponseTrieDiff;
57
58    const MAX_REQUESTS: u32 = MAX_REQUEST_RESPONSE_TRIE_DIFFS;
59}
60
61/// Represents a block or set of blocks classified by how they should be processed.
62pub enum QueuedDiff<N: Network> {
63    Head(BlockAndSource<N>, Option<TrieDiff>),
64    Buffered(Vec<(BlockAndSource<N>, Option<TrieDiff>)>),
65    Missing(Vec<(BlockAndSource<N>, Option<TrieDiff>)>),
66    TooFarAhead(N::PeerId),
67    TooFarBehind(N::PeerId),
68    PeerIncompleteState(N::PeerId),
69}
70
71impl<N: Network> QueuedDiff<N> {
72    fn from_block_no_diff(block: QueuedBlock<N>) -> Self {
73        match block {
74            QueuedBlock::Head(block) => QueuedDiff::Head(block, None),
75            QueuedBlock::Buffered(blocks) => {
76                QueuedDiff::Buffered(blocks.into_iter().map(|block| (block, None)).collect())
77            }
78            QueuedBlock::Missing(blocks) => {
79                QueuedDiff::Missing(blocks.into_iter().map(|block| (block, None)).collect())
80            }
81            QueuedBlock::TooFarAhead(peer_id) => QueuedDiff::TooFarAhead(peer_id),
82            QueuedBlock::TooFarBehind(peer_id) => QueuedDiff::TooFarBehind(peer_id),
83        }
84    }
85}
86
87struct AugmentedDiff<N: Network> {
88    queued_diff: Option<QueuedDiff<N>>,
89    dropped_blocks: HashMap<Blake2bHash, BlockSource<N>>,
90}
91
92/// Fetches a batch concurrently while consuming its results in block order.
93///
94/// Requests after the first failing block are speculative: they may already have started or even
95/// completed before the ordered failure is observed. Only the successful prefix is retained.
96async fn get_multiple_diffs<N: Network>(
97    blocks: Vec<BlockAndSource<N>>,
98    mut get_diff: impl FnMut(
99        &BlockAndSource<N>,
100    ) -> BoxFuture<'static, Result<TrieDiff, DiffRequestError>>,
101) -> (
102    Vec<(BlockAndSource<N>, Option<TrieDiff>)>,
103    HashMap<Blake2bHash, BlockSource<N>>,
104) {
105    let mut blocks_with_diffs = Vec::with_capacity(blocks.len());
106    // `FuturesOrdered` polls all requests concurrently, but only yields them in insertion order.
107    // Indexing the results makes the prefix invariant explicit and avoids sorting after retrieval.
108    let mut diff_futures: FuturesOrdered<_> = blocks
109        .iter()
110        .enumerate()
111        .map(|(index, block)| {
112            let diff = get_diff(block);
113            async move { (index, diff.await) }
114        })
115        .collect();
116    let mut remaining_blocks = blocks.into_iter();
117
118    while let Some((index, result)) = diff_futures.next().await {
119        let block = remaining_blocks
120            .next()
121            .expect("one diff future is created per block");
122        debug_assert_eq!(index, blocks_with_diffs.len());
123
124        match result {
125            Ok(diff) => blocks_with_diffs.push((block, Some(diff))),
126            Err(DiffRequestError::MaxTriesExceeded) => {
127                let dropped_blocks = std::iter::once(block)
128                    .chain(remaining_blocks)
129                    .map(|(block, block_source)| (block.hash(), block_source))
130                    .collect();
131                // Returning drops the speculative suffix futures, stopping their local retry loops
132                // and releasing their semaphore permits. Requests already handed to the network
133                // cannot be withdrawn and may still complete; their responses are ignored.
134                return (blocks_with_diffs, dropped_blocks);
135            }
136        }
137    }
138
139    (blocks_with_diffs, HashMap::default())
140}
141
142async fn augment_block<N: Network>(
143    block: QueuedBlock<N>,
144    mut get_diff: impl FnMut(
145        &BlockAndSource<N>,
146    ) -> BoxFuture<'static, Result<TrieDiff, DiffRequestError>>,
147) -> AugmentedDiff<N> {
148    match block {
149        QueuedBlock::Head(block) => match get_diff(&block).await {
150            Ok(diff) => AugmentedDiff {
151                queued_diff: Some(QueuedDiff::Head(block, Some(diff))),
152                dropped_blocks: HashMap::default(),
153            },
154            Err(DiffRequestError::MaxTriesExceeded) => {
155                let (block, block_source) = block;
156                AugmentedDiff {
157                    queued_diff: None,
158                    dropped_blocks: HashMap::from([(block.hash(), block_source)]),
159                }
160            }
161        },
162        QueuedBlock::Buffered(blocks) => {
163            let (blocks_with_diffs, dropped_blocks) = get_multiple_diffs(blocks, get_diff).await;
164            AugmentedDiff {
165                queued_diff: (!blocks_with_diffs.is_empty())
166                    .then_some(QueuedDiff::Buffered(blocks_with_diffs)),
167                dropped_blocks,
168            }
169        }
170        QueuedBlock::Missing(blocks) => {
171            let (blocks_with_diffs, dropped_blocks) = get_multiple_diffs(blocks, get_diff).await;
172            AugmentedDiff {
173                queued_diff: (!blocks_with_diffs.is_empty())
174                    .then_some(QueuedDiff::Missing(blocks_with_diffs)),
175                dropped_blocks,
176            }
177        }
178        QueuedBlock::TooFarAhead(peer_id) => AugmentedDiff {
179            queued_diff: Some(QueuedDiff::TooFarAhead(peer_id)),
180            dropped_blocks: HashMap::default(),
181        },
182        QueuedBlock::TooFarBehind(peer_id) => AugmentedDiff {
183            queued_diff: Some(QueuedDiff::TooFarBehind(peer_id)),
184            dropped_blocks: HashMap::default(),
185        },
186    }
187}
188
189pub struct DiffQueue<N: Network> {
190    /// Reference to the network used to close validation of dropped gossip messages.
191    network: Arc<N>,
192
193    /// The BlockQueue component.
194    block_queue: BlockQueue<N>,
195
196    /// The chunk request component.
197    /// We use it to request chunks from up-to-date peers
198    diff_request_component: DiffRequestComponent<N>,
199
200    /// The pending TreeDiff requests to peers.
201    diffs: FuturesOrdered<BoxFuture<'static, AugmentedDiff<N>>>,
202
203    /// Flag indicating if diffs should be requested.
204    diff_needed: bool,
205}
206
207impl<N: Network> DiffQueue<N> {
208    /// Creates a new DiffQueue using an existing BlockQueue.
209    pub fn with_block_queue(network: Arc<N>, block_queue: BlockQueue<N>) -> Self {
210        let diff_request_component =
211            DiffRequestComponent::new(Arc::clone(&network), block_queue.peer_list());
212        Self {
213            network,
214            block_queue,
215            diff_request_component,
216            diffs: FuturesOrdered::new(),
217            diff_needed: true,
218        }
219    }
220
221    /// Removes blocks marked as invalid from the BlockQueue.
222    pub(crate) fn remove_invalid_blocks(&mut self, invalid_blocks: &mut HashSet<Blake2bHash>) {
223        // We remove invalid blocks from the block queue.
224        self.block_queue.remove_invalid_blocks(invalid_blocks);
225    }
226
227    pub(crate) fn process_push_result(
228        &mut self,
229        item: PushOpResult<N>,
230    ) -> Option<LiveSyncEvent<N::PeerId>> {
231        self.block_queue.process_push_result(item)
232    }
233
234    pub(crate) fn peers(&self) -> Vec<N::PeerId> {
235        self.block_queue.peers()
236    }
237
238    pub(crate) fn peer_list(&self) -> Arc<RwLock<PeerList<N>>> {
239        self.block_queue.peer_list()
240    }
241
242    pub(crate) fn num_peers(&self) -> usize {
243        self.block_queue.num_peers()
244    }
245
246    pub(crate) fn add_peer(&self, peer_id: N::PeerId) {
247        self.block_queue.add_peer(peer_id)
248    }
249
250    /// Adds a block stream by replacing the current block stream with a `select` of both streams.
251    pub(crate) fn add_block_stream<S>(&mut self, block_stream: S)
252    where
253        S: Stream<Item = BlockAndSource<N>> + Send + 'static,
254    {
255        self.block_queue.add_block_stream(block_stream)
256    }
257
258    pub(crate) fn num_buffered_heights(&self) -> usize {
259        self.block_queue.num_buffered_heights()
260    }
261
262    /// Sets whether diffs should be fetched for incoming blocks.
263    pub(crate) fn set_diff_needed(&mut self, diff_needed: bool) {
264        self.diff_needed = diff_needed;
265    }
266
267    pub(crate) fn resolve_block(&mut self, request: ResolveBlockRequest<N>) {
268        self.block_queue.resolve_block(request)
269    }
270
271    pub(crate) fn acceptance_window_size(&self) -> u32 {
272        self.block_queue.acceptance_window_size()
273    }
274
275    pub(crate) fn retry_with_diff(&mut self, block: QueuedBlock<N>) {
276        let get_diff = self.diff_request_component.request_diff();
277        // Prioritize retries over existing diff work. Repeated calls are therefore
278        // scheduled in LIFO order, but Buffered blocks are independently applicable
279        // because their parents are already stored. Ordered Missing chains are retried
280        // together and preserve their order.
281        self.diffs
282            .push_front(Box::pin(augment_block(block, get_diff)));
283    }
284
285    /// Ignores announced blocks whose diff requests failed and clears their pending markers.
286    /// A request failure is not proof of invalidity: `remove_invalid_blocks` would also reject
287    /// buffered descendants. `Ignore` closes gossipsub validation without penalizing the source,
288    /// while clearing `blocks_pending_push` allows a later announcement to enqueue the block again.
289    fn clear_pending_diff_requests(
290        &mut self,
291        dropped_blocks: HashMap<Blake2bHash, BlockSource<N>>,
292    ) {
293        for (block_hash, block_source) in dropped_blocks {
294            block_source.ignore_block(&self.network);
295            self.block_queue.on_block_processed(&block_hash);
296        }
297    }
298}
299
300impl<N: Network> Stream for DiffQueue<N> {
301    type Item = QueuedDiff<N>;
302
303    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
304        // Receive blocks from BlockQueue.
305        while let Poll::Ready(block) = self.block_queue.poll_next_unpin(cx) {
306            match (block, self.diff_needed) {
307                (Some(block), true) => {
308                    let get_diff = self.diff_request_component.request_diff();
309                    self.diffs
310                        .push_back(Box::pin(augment_block(block, get_diff)));
311                }
312                (Some(block), false) => {
313                    self.diffs.push_back(Box::pin(future::ready(AugmentedDiff {
314                        queued_diff: Some(QueuedDiff::from_block_no_diff(block)),
315                        dropped_blocks: HashMap::default(),
316                    })));
317                }
318                // The block queue only ends when something bad happens.
319                // Thus we immediately quit and do not wait for any pending diffs.
320                (None, ..) => return Poll::Ready(None),
321            }
322        }
323
324        // Check for blocks augmented with diffs.
325        while let Poll::Ready(Some(diff)) = self.diffs.poll_next_unpin(cx) {
326            if !diff.dropped_blocks.is_empty() {
327                debug!(
328                    dropped_block_hashes = ?diff.dropped_blocks.keys(),
329                    "dropping blocks after diff request failed"
330                );
331                self.clear_pending_diff_requests(diff.dropped_blocks);
332            }
333
334            if let Some(queued_diff) = diff.queued_diff {
335                return Poll::Ready(Some(queued_diff));
336            }
337        }
338
339        Poll::Pending
340    }
341}
342
343#[cfg(test)]
344mod tests {
345    use std::{
346        collections::{HashMap, HashSet},
347        future::{pending, ready},
348        sync::{
349            atomic::{AtomicBool, AtomicUsize, Ordering},
350            Arc,
351        },
352        time::Duration,
353    };
354
355    use futures::{join, StreamExt};
356    use nimiq_blockchain_proxy::BlockchainProxy;
357    use nimiq_network_interface::network::{MsgAcceptance, Network, PubsubId};
358    use nimiq_network_mock::{MockHub, MockId, MockNetwork, MockPeerId};
359    use nimiq_primitives::trie::trie_diff::TrieDiff;
360    use nimiq_test_log::test;
361    use nimiq_test_utils::block_production::TemporaryBlockProducer;
362    use tokio::{
363        sync::{mpsc, Notify},
364        time::timeout,
365    };
366    use tokio_stream::wrappers::ReceiverStream;
367
368    use super::{
369        augment_block, diff_request_component::DiffRequestError, AugmentedDiff, DiffQueue,
370        QueuedDiff, RequestTrieDiff, ResponseTrieDiff,
371    };
372    use crate::sync::live::{
373        block_queue::{BlockQueue, BlockSource, QueuedBlock},
374        queue::QueueConfig,
375    };
376
377    #[test(tokio::test)]
378    async fn failed_head_diff_request_ignores_message_and_allows_reannouncement() {
379        let mut hub = MockHub::new();
380        let local = TemporaryBlockProducer::new();
381        let local_blockchain = Arc::clone(&local.blockchain);
382        let network = Arc::new(hub.new_network());
383        let (block_tx, block_rx) = mpsc::channel(8);
384
385        let block_queue = BlockQueue::with_gossipsub_block_stream(
386            BlockchainProxy::from(&local_blockchain),
387            Arc::clone(&network),
388            ReceiverStream::new(block_rx).boxed(),
389            QueueConfig::default(),
390        );
391        let mut diff_queue = DiffQueue::with_block_queue(Arc::clone(&network), block_queue);
392
393        let source = TemporaryBlockProducer::new();
394        let source_network = Arc::new(hub.new_network());
395        let other_network = Arc::new(hub.new_network());
396        let mut source_requests = source_network.receive_requests::<RequestTrieDiff>();
397        let mut other_requests = other_network.receive_requests::<RequestTrieDiff>();
398
399        network.dial_mock(&source_network);
400        network.dial_mock(&other_network);
401        diff_queue.add_peer(source_network.get_local_peer_id());
402        diff_queue.add_peer(other_network.get_local_peer_id());
403
404        let block = source.next_block(vec![], false);
405        let source_id = MockId::new(source_network.get_local_peer_id());
406        block_tx
407            .send((block.clone(), source_id.clone()))
408            .await
409            .unwrap();
410
411        let (_, first_attempt) = join!(
412            async {
413                let (_, request_id, _) = source_requests.next().await.unwrap();
414                source_network
415                    .respond::<RequestTrieDiff>(request_id, ResponseTrieDiff::IncompleteState)
416                    .await
417                    .unwrap();
418
419                let (_, request_id, _) = other_requests.next().await.unwrap();
420                other_network
421                    .respond::<RequestTrieDiff>(request_id, ResponseTrieDiff::UnknownBlockHash)
422                    .await
423                    .unwrap();
424            },
425            async { timeout(Duration::from_millis(100), diff_queue.next()).await },
426        );
427        assert!(
428            first_attempt.is_err(),
429            "diff request failure should not emit an augmented block"
430        );
431        let validation_results = network.take_validation_results();
432        assert!(
433            matches!(
434                validation_results.as_slice(),
435                [(_, pubsub_id, MsgAcceptance::Ignore)]
436                    if pubsub_id.propagation_source() == source_id.propagation_source()
437            ),
438            "the dropped block announcement should be ignored without penalizing its source"
439        );
440
441        block_tx.send((block, source_id)).await.unwrap();
442
443        let (retry_request, retry_attempt) = join!(
444            async { timeout(Duration::from_millis(100), source_requests.next()).await },
445            async { timeout(Duration::from_millis(100), diff_queue.next()).await },
446        );
447        assert!(
448            matches!(retry_request, Ok(Some(_))),
449            "the same head block should be accepted again after the previous diff request was dropped"
450        );
451        assert!(
452            retry_attempt.is_err(),
453            "reannouncing the head block should still wait on the next diff request"
454        );
455    }
456
457    #[test(tokio::test)]
458    async fn dropped_diff_does_not_block_follow_up_items() {
459        let mut hub = MockHub::new();
460        let local = TemporaryBlockProducer::new();
461        let local_blockchain = Arc::clone(&local.blockchain);
462        let network = Arc::new(hub.new_network());
463        let (_block_tx, block_rx) = mpsc::channel(8);
464
465        let block_queue = BlockQueue::with_gossipsub_block_stream(
466            BlockchainProxy::from(&local_blockchain),
467            Arc::clone(&network),
468            ReceiverStream::new(block_rx).boxed(),
469            QueueConfig::default(),
470        );
471        let mut diff_queue = DiffQueue::with_block_queue(Arc::clone(&network), block_queue);
472
473        let peer_id = network.get_local_peer_id();
474        diff_queue.diffs.push_back(Box::pin(ready(AugmentedDiff {
475            queued_diff: None,
476            dropped_blocks: HashMap::default(),
477        })));
478        diff_queue.diffs.push_back(Box::pin(ready(AugmentedDiff {
479            queued_diff: Some(QueuedDiff::TooFarAhead(peer_id)),
480            dropped_blocks: HashMap::default(),
481        })));
482
483        let next_item = timeout(Duration::from_millis(100), diff_queue.next()).await;
484        assert!(
485            matches!(next_item, Ok(Some(QueuedDiff::TooFarAhead(id))) if id == peer_id),
486            "dropping a diff request failure must not block later queued items"
487        );
488    }
489
490    #[test(tokio::test)]
491    async fn buffered_diff_failure_keeps_prefix_and_reports_remaining_hashes() {
492        let source = TemporaryBlockProducer::new();
493        let first_block = source.next_block(vec![], false);
494        let second_block = source.next_block(vec![], false);
495        let third_block = source.next_block(vec![], false);
496        let first_block_hash = first_block.hash();
497        let second_block_hash = second_block.hash();
498        let third_block_hash = third_block.hash();
499        let failing_block_hash = second_block_hash.clone();
500
501        let result = augment_block(
502            QueuedBlock::<MockNetwork>::Buffered(vec![
503                (
504                    first_block,
505                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
506                ),
507                (
508                    second_block,
509                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
510                ),
511                (
512                    third_block,
513                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
514                ),
515            ]),
516            move |(block, _)| {
517                let block_hash = block.hash();
518                Box::pin(ready(if block_hash == failing_block_hash {
519                    Err(DiffRequestError::MaxTriesExceeded)
520                } else {
521                    Ok(TrieDiff::default())
522                }))
523            },
524        )
525        .await;
526
527        assert!(
528            matches!(
529                result,
530                AugmentedDiff {
531                    queued_diff: Some(QueuedDiff::Buffered(blocks_with_diffs)),
532                    dropped_blocks,
533                }
534                    if blocks_with_diffs.len() == 1
535                        && blocks_with_diffs[0].0.0.hash() == first_block_hash
536                        && blocks_with_diffs[0].1.is_some()
537                        && dropped_blocks.keys().cloned().collect::<HashSet<_>>()
538                            == HashSet::from([second_block_hash, third_block_hash])
539            ),
540            "buffered diff failures should keep the successful prefix and drop the failed suffix"
541        );
542    }
543
544    #[test(tokio::test)]
545    async fn missing_diff_failure_keeps_prefix_and_reports_remaining_hashes() {
546        let source = TemporaryBlockProducer::new();
547        let first_block = source.next_block(vec![], false);
548        let second_block = source.next_block(vec![], false);
549        let third_block = source.next_block(vec![], false);
550        let first_block_hash = first_block.hash();
551        let second_block_hash = second_block.hash();
552        let third_block_hash = third_block.hash();
553        let failing_block_hash = second_block_hash.clone();
554
555        let result = augment_block(
556            QueuedBlock::<MockNetwork>::Missing(vec![
557                (
558                    first_block,
559                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
560                ),
561                (
562                    second_block,
563                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
564                ),
565                (
566                    third_block,
567                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
568                ),
569            ]),
570            move |(block, _)| {
571                let block_hash = block.hash();
572                Box::pin(ready(if block_hash == failing_block_hash {
573                    Err(DiffRequestError::MaxTriesExceeded)
574                } else {
575                    Ok(TrieDiff::default())
576                }))
577            },
578        )
579        .await;
580
581        assert!(
582            matches!(
583                result,
584                AugmentedDiff {
585                    queued_diff: Some(QueuedDiff::Missing(blocks_with_diffs)),
586                    dropped_blocks,
587                }
588                    if blocks_with_diffs.len() == 1
589                        && blocks_with_diffs[0].0.0.hash() == first_block_hash
590                        && blocks_with_diffs[0].1.is_some()
591                        && dropped_blocks.keys().cloned().collect::<HashSet<_>>()
592                            == HashSet::from([second_block_hash, third_block_hash])
593            ),
594            "missing diff failures should keep the successful prefix and drop the failed suffix"
595        );
596    }
597
598    #[test(tokio::test)]
599    async fn missing_diff_requests_are_concurrent_but_stop_at_first_ordered_failure() {
600        struct SetOnDrop(Arc<AtomicBool>);
601
602        impl Drop for SetOnDrop {
603            fn drop(&mut self) {
604                self.0.store(true, Ordering::SeqCst);
605            }
606        }
607
608        let source = TemporaryBlockProducer::new();
609        let first_block = source.next_block(vec![], false);
610        let second_block = source.next_block(vec![], false);
611        let third_block = source.next_block(vec![], false);
612        let first_block_hash = first_block.hash();
613        let second_block_hash = second_block.hash();
614        let third_block_hash = third_block.hash();
615
616        let started_requests = Arc::new(AtomicUsize::new(0));
617        let started_requests_for_diff = Arc::clone(&started_requests);
618        let release_first = Arc::new(Notify::new());
619        let release_first_for_diff = Arc::clone(&release_first);
620        let suffix_cancelled = Arc::new(AtomicBool::new(false));
621        let suffix_cancelled_for_diff = Arc::clone(&suffix_cancelled);
622        let first_request_hash = first_block_hash.clone();
623        let second_request_hash = second_block_hash.clone();
624
625        let request = augment_block(
626            QueuedBlock::<MockNetwork>::Missing(vec![
627                (
628                    first_block,
629                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
630                ),
631                (
632                    second_block,
633                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
634                ),
635                (
636                    third_block,
637                    BlockSource::<MockNetwork>::requested(MockPeerId(0)),
638                ),
639            ]),
640            move |(block, _)| {
641                let block_hash = block.hash();
642                let started_requests = Arc::clone(&started_requests_for_diff);
643                let release_first = Arc::clone(&release_first_for_diff);
644                let suffix_cancelled = Arc::clone(&suffix_cancelled_for_diff);
645                let first_request_hash = first_request_hash.clone();
646                let second_request_hash = second_request_hash.clone();
647
648                Box::pin(async move {
649                    started_requests.fetch_add(1, Ordering::SeqCst);
650
651                    if block_hash == first_request_hash {
652                        // Hold the first result so that the ordered stream must poll the suffix.
653                        release_first.notified().await;
654                        Ok(TrieDiff::default())
655                    } else if block_hash == second_request_hash {
656                        Err(DiffRequestError::MaxTriesExceeded)
657                    } else {
658                        // This future must be dropped once the preceding error is consumed.
659                        let _set_on_drop = SetOnDrop(suffix_cancelled);
660                        pending().await
661                    }
662                })
663            },
664        );
665
666        let observe_concurrency = async {
667            timeout(Duration::from_secs(1), async {
668                while started_requests.load(Ordering::SeqCst) != 3 {
669                    tokio::task::yield_now().await;
670                }
671            })
672            .await
673            .expect("all diff futures should be polled concurrently");
674            release_first.notify_one();
675        };
676
677        let (result, ()) = join!(request, observe_concurrency);
678
679        assert!(
680            matches!(
681                result,
682                AugmentedDiff {
683                    queued_diff: Some(QueuedDiff::Missing(blocks_with_diffs)),
684                    dropped_blocks,
685                }
686                    if blocks_with_diffs.len() == 1
687                        && blocks_with_diffs[0].0.0.hash() == first_block_hash
688                        && blocks_with_diffs[0].1.is_some()
689                        && dropped_blocks.keys().cloned().collect::<HashSet<_>>()
690                            == HashSet::from([second_block_hash, third_block_hash])
691            ),
692            "ordered retrieval should retain the prefix and drop the failed suffix"
693        );
694        assert_eq!(started_requests.load(Ordering::SeqCst), 3);
695        assert!(
696            suffix_cancelled.load(Ordering::SeqCst),
697            "the unconsumed local suffix future should be cancelled"
698        );
699    }
700}