Skip to main content

consensus_core/
commit_finalizer.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::{BTreeMap, BTreeSet, VecDeque},
6    sync::Arc,
7    time::Duration,
8};
9
10use consensus_config::Stake;
11use consensus_types::block::{BlockRef, Round, TransactionIndex};
12use mysten_metrics::{
13    monitored_mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel},
14    monitored_scope, spawn_logged_monitored_task,
15};
16use parking_lot::RwLock;
17
18use crate::{
19    BlockAPI, CommitIndex, CommittedSubDag, VerifiedBlock,
20    commit::DEFAULT_WAVE_LENGTH,
21    context::Context,
22    dag_state::DagState,
23    error::{ConsensusError, ConsensusResult},
24    stake_aggregator::{QuorumThreshold, StakeAggregator},
25    task::{join_and_propagate_panic, spawn_blocking_join_error},
26    transaction_vote_tracker::TransactionVoteTracker,
27};
28
29/// For transaction T committed at leader round R, when a new leader at round >= R + INDIRECT_REJECT_DEPTH
30/// commits and T is still not finalized, T is rejected.
31/// NOTE: 3 round is the minimum depth possible for indirect finalization and rejection.
32pub(crate) const INDIRECT_REJECT_DEPTH: Round = 3;
33
34/// Handle to CommitFinalizer, for sending CommittedSubDag.
35pub(crate) struct CommitFinalizerHandle {
36    sender: Option<UnboundedSender<CommittedSubDag>>,
37    task: Option<tokio::task::JoinHandle<()>>,
38}
39
40impl CommitFinalizerHandle {
41    // Sends a CommittedSubDag to CommitFinalizer, which will finalize it before sending it to execution.
42    pub(crate) fn send(&self, commit: CommittedSubDag) -> ConsensusResult<()> {
43        self.sender
44            .as_ref()
45            .ok_or(ConsensusError::Shutdown)?
46            .send(commit)
47            .map_err(|e| {
48                tracing::warn!(
49                    "Failed to send to commit finalizer, probably due to shutdown: {e:?}"
50                );
51                ConsensusError::Shutdown
52            })
53    }
54
55    pub(crate) async fn stop(&mut self) {
56        // Closing the channel allows CommitFinalizer to drain accepted commits before exiting.
57        self.sender.take();
58        if let Some(task) = self.task.take() {
59            join_and_propagate_panic(task).await;
60        }
61    }
62}
63
64/// CommitFinalizer accepts a continuous stream of CommittedSubDag and outputs
65/// them when they are finalized.
66/// In finalized commits, every transaction is either finalized or rejected.
67/// It runs in a separate thread, to reduce the load on the core thread.
68///
69/// Life of a finalized commit:
70///
71/// For efficiency, finalization happens first for transactions without reject votes (common case).
72/// The pending undecided transactions with reject votes are individually finalized or rejected.
73/// When there is no more pending transactions, the commit is finalized.
74///
75/// This is correct because regardless if a commit leader was directly or indirectly committed,
76/// every committed block can be considered finalized, because at least one leader certificate of the commit
77/// will be committed, which can also serve as a certificate for the block and its transactions.
78///
79/// From the earliest buffered commit, pending blocks are checked to see if they are now finalized.
80/// New finalized blocks are removed from the pending blocks, and its transactions are moved to the
81/// finalized, rejected or pending state. If the commit now has no pending blocks or transactions,
82/// the commit is finalized and popped from the buffer. The next earliest commit is then processed
83/// similarly, until either the buffer becomes empty or a commit with pending blocks or transactions
84/// is encountered.
85pub struct CommitFinalizer {
86    context: Arc<Context>,
87    dag_state: Arc<RwLock<DagState>>,
88    transaction_vote_tracker: TransactionVoteTracker,
89    commit_sender: UnboundedSender<CommittedSubDag>,
90
91    // Last commit index processed by CommitFinalizer.
92    last_processed_commit: Option<CommitIndex>,
93    // Commits pending finalization.
94    pending_commits: VecDeque<CommitState>,
95    // Blocks in the pending commits.
96    blocks: Arc<RwLock<BTreeMap<BlockRef, RwLock<BlockState>>>>,
97}
98
99impl CommitFinalizer {
100    pub fn new(
101        context: Arc<Context>,
102        dag_state: Arc<RwLock<DagState>>,
103        transaction_vote_tracker: TransactionVoteTracker,
104        commit_sender: UnboundedSender<CommittedSubDag>,
105    ) -> Self {
106        Self {
107            context,
108            dag_state,
109            transaction_vote_tracker,
110            commit_sender,
111            last_processed_commit: None,
112            pending_commits: VecDeque::new(),
113            blocks: Arc::new(RwLock::new(BTreeMap::new())),
114        }
115    }
116
117    pub(crate) fn start(
118        context: Arc<Context>,
119        dag_state: Arc<RwLock<DagState>>,
120        transaction_vote_tracker: TransactionVoteTracker,
121        commit_sender: UnboundedSender<CommittedSubDag>,
122    ) -> CommitFinalizerHandle {
123        let processor = Self::new(context, dag_state, transaction_vote_tracker, commit_sender);
124        let (sender, receiver) = unbounded_channel("consensus_commit_finalizer");
125        let task =
126            spawn_logged_monitored_task!(processor.run(receiver), "consensus_commit_finalizer");
127        CommitFinalizerHandle {
128            sender: Some(sender),
129            task: Some(task),
130        }
131    }
132
133    async fn run(mut self, mut receiver: UnboundedReceiver<CommittedSubDag>) {
134        while let Some(committed_sub_dag) = receiver.recv().await {
135            let already_finalized = !self.context.protocol_config.transaction_voting_enabled()
136                || committed_sub_dag.recovered_rejected_transactions;
137            let finalized_commits = if !already_finalized {
138                match self.process_commit(committed_sub_dag).await {
139                    Ok(commits) => commits,
140                    Err(ConsensusError::Shutdown) => {
141                        tracing::info!("Stopping commit finalizer during runtime shutdown");
142                        return;
143                    }
144                    Err(error) => panic!("Failed to finalize commit: {error}"),
145                }
146            } else {
147                vec![committed_sub_dag]
148            };
149            if !finalized_commits.is_empty() {
150                // Transaction certifier state should be GC'ed as soon as new commits are finalized.
151                // But this is done outside of process_commit(), because during recovery process_commit()
152                // is not called to finalize commits, but GC still needs to run.
153                self.try_update_gc_round(finalized_commits.last().unwrap().leader.round);
154                let mut dag_state = self.dag_state.write();
155                if !already_finalized {
156                    // Records rejected transactions in newly finalized commits.
157                    for commit in &finalized_commits {
158                        dag_state.add_finalized_commit(
159                            commit.commit_ref,
160                            commit.rejected_transactions_by_block.clone(),
161                        );
162                    }
163                }
164                // Commits and committed blocks must be persisted to storage before sending them to Sui
165                // to execute their finalized transactions.
166                // Commit metadata and uncommitted blocks can be persisted more lazily because they are recoverable.
167                // But for simplicity, all unpersisted commits and blocks are flushed to storage.
168                dag_state.flush();
169            }
170            for commit in finalized_commits {
171                if let Err(e) = self.commit_sender.send(commit) {
172                    tracing::warn!(
173                        "Failed to send to commit handler, probably due to shutdown: {e:?}"
174                    );
175                    return;
176                }
177            }
178        }
179    }
180
181    // A shutdown error is terminal: discard this finalizer and recover from persisted commits.
182    pub async fn process_commit(
183        &mut self,
184        committed_sub_dag: CommittedSubDag,
185    ) -> ConsensusResult<Vec<CommittedSubDag>> {
186        let _scope = monitored_scope("CommitFinalizer::process_commit");
187
188        if let Some(last_processed_commit) = self.last_processed_commit {
189            assert_eq!(
190                last_processed_commit + 1,
191                committed_sub_dag.commit_ref.index
192            );
193        }
194        self.last_processed_commit = Some(committed_sub_dag.commit_ref.index);
195
196        self.pending_commits
197            .push_back(CommitState::new(committed_sub_dag));
198
199        let mut finalized_commits = vec![];
200
201        // The prerequisite for running direct finalization on a commit is that the commit must
202        // have either a quorum of leader certificates in the local DAG, or a committed leader certificate.
203        //
204        // A leader certificate is a finalization certificate for every block in the commit.
205        // When the prerequisite holds, all blocks in the current commit can be considered finalized.
206        // And any transaction in the current commit that has not observed reject votes will never be rejected.
207        // So these transactions are directly finalized.
208        //
209        // When a commit is direct, there are a quorum of its leader certificates in the local DAG.
210        //
211        // When a commit is indirect, it implies one of its leader certificates is in the committed blocks.
212        // So a leader certificate must exist in the local DAG as well.
213        //
214        // When a commit is received through commit sync and processed as certified commit, the commit might
215        // not have a leader certificate in the local DAG. So a committed transaction might not observe any reject
216        // vote from local DAG, although it will eventually get rejected. To finalize blocks in this commit,
217        // there must be another commit with leader round >= 3 (WAVE_LENGTH) rounds above the commit leader.
218        // From the indirect commit rule, a leader certificate must exist in committed blocks for the earliest commit.
219        for i in 0..self.pending_commits.len() {
220            let commit_state = &self.pending_commits[i];
221            if commit_state.pending_blocks.is_empty() {
222                // The commit has already been processed through direct finalization.
223                continue;
224            }
225            // Direct finalization cannot happen when
226            // -  This commit is remote.
227            // -  And the latest commit is less than 3 (WAVE_LENGTH) rounds above this commit.
228            // In this case, this commit's leader certificate is not guaranteed to be in local DAG.
229            if !commit_state.commit.decided_with_local_blocks {
230                let last_commit_state = self.pending_commits.back().unwrap();
231                if commit_state.commit.leader.round + DEFAULT_WAVE_LENGTH
232                    > last_commit_state.commit.leader.round
233                {
234                    break;
235                }
236            }
237            self.try_direct_finalize_commit(i);
238        }
239        let direct_finalized_commits = self.pop_finalized_commits();
240        self.context
241            .metrics
242            .node_metrics
243            .finalizer_output_commits
244            .with_label_values(&["direct"])
245            .inc_by(direct_finalized_commits.len() as u64);
246        finalized_commits.extend(direct_finalized_commits);
247
248        // Indirect finalization: one or more commits cannot be directly finalized.
249        // So the pending transactions need to be checked for indirect finalization.
250        if !self.pending_commits.is_empty() {
251            // Initialize the state of the last added commit for computing indirect finalization.
252            //
253            // As long as there are remaining commits, even if the last commit has been directly finalized,
254            // its state still needs to be initialized here to help indirectly finalize previous commits.
255            // This is because the last commit may have been directly finalized, but its previous commits
256            // may not have been directly finalized.
257            self.link_blocks_in_last_commit();
258            self.append_origin_descendants_from_last_commit();
259            // Try to indirectly finalize a prefix of the buffered commits.
260            // If only one commit remains, it cannot be indirectly finalized because there is no commit afterwards,
261            // so it is excluded.
262            while self.pending_commits.len() > 1 {
263                // Stop indirect finalization when the earliest commit has not been processed
264                // through direct finalization.
265                if !self.pending_commits[0].pending_blocks.is_empty() {
266                    break;
267                }
268                // Otherwise, try to indirectly finalize the earliest commit.
269                self.try_indirect_finalize_first_commit().await?;
270                let indirect_finalized_commits = self.pop_finalized_commits();
271                if indirect_finalized_commits.is_empty() {
272                    // No additional commits can be indirectly finalized.
273                    break;
274                }
275                self.context
276                    .metrics
277                    .node_metrics
278                    .finalizer_output_commits
279                    .with_label_values(&["indirect"])
280                    .inc_by(indirect_finalized_commits.len() as u64);
281                finalized_commits.extend(indirect_finalized_commits);
282            }
283        }
284
285        let utc_now = self.context.clock.timestamp_utc_ms();
286        for commit in &finalized_commits {
287            for block in commit
288                .blocks
289                .iter()
290                .filter(|block| block.author() == self.context.own_index)
291            {
292                let latency_ms = utc_now.saturating_sub(block.timestamp_ms());
293                self.context
294                    .metrics
295                    .node_metrics
296                    .proposed_block_finalization_latency
297                    .observe(Duration::from_millis(latency_ms).as_secs_f64());
298            }
299        }
300
301        self.context
302            .metrics
303            .node_metrics
304            .finalizer_buffered_commits
305            .set(self.pending_commits.len() as i64);
306
307        Ok(finalized_commits)
308    }
309
310    // Tries directly finalizing transactions in the commit.
311    // Direct commit means every transaction in the commit can be considered to have a quorum of post-commit certificates,
312    // unless (1) the transaction has reject votes that do not reach quorum, or
313    // (2) the block containing the transaction is outside the GC bound of the commit's leader.
314    // In the 2nd case, when the blocks voting and certifying this commit's leader were proposed, there is a chance
315    // that some of these voting and certifying blocks do not include votes for the transactions below the leader's GC bound.
316    // So conservatively, these transactions are not directly finalized. The logic here matches the GC logic in
317    // try_indirect_finalize_pending_transactions_in_block().
318    fn try_direct_finalize_commit(&mut self, index: usize) {
319        let metrics = &self.context.metrics.node_metrics;
320        let num_commits = self.pending_commits.len();
321        let commit_state = self
322            .pending_commits
323            .get_mut(index)
324            .unwrap_or_else(|| panic!("Commit {} does not exist. len = {}", index, num_commits));
325
326        // Estimate conservatively the GC round of the blocks voting and certifying this commit's leader of round (R).
327        //
328        // The key question we try to answer: "Could the voting blocks (R+1) and certifying blocks (R+2) have seen all blocks in this commit at the time they were proposed by their respective nodes, or
329        // could they have discarded them due to their local GC round already advanced by being ahead in their commit round?"
330        //
331        // It's not possible to know the exact GC round that was used when the voting and certifying blocks were proposed, so we use the most conservative threshold.
332        // We assume that the nodes proposing those blocks had already committed the `commit_state.commit.leader.round + INDIRECT_REJECT_DEPTH` - (R+3) and we calculate the gc_round of it as the cut off.
333        //
334        // Why we use the (R+3) leader round though?
335        //
336        // According to the protocol (R+3) is the min num of rounds needed for the leader's certificate to appear in a commit. Since we can't know which exact blocks form the certificate, we assume (R+3) being this minimum
337        // limit which also aligns with the assumptions made in the indirect finalization logic.
338        //
339        // So we assume as if the blocks that certify the leader (R) had advanced to the commit (R+3), and thus any block below the `vote_gc_round`, the gc round after the (R+3) leader was committed, could have been locally gced
340        // and never been voted by the certifying blocks.
341        let vote_gc_round = self
342            .dag_state
343            .read()
344            .calculate_gc_round(commit_state.commit.leader.round + INDIRECT_REJECT_DEPTH);
345        tracing::debug!(
346            "Trying to direct finalize commit {} using vote GC round {}",
347            commit_state.commit.commit_ref,
348            vote_gc_round,
349        );
350
351        // Each commit can only try direct finalization once.
352        assert!(!commit_state.pending_blocks.is_empty());
353        let pending_blocks = std::mem::take(&mut commit_state.pending_blocks);
354
355        for (block_ref, num_transactions) in pending_blocks {
356            if block_ref.round <= vote_gc_round && num_transactions > 0 {
357                // The block is outside of GC bound.
358                let transactions =
359                    (0..(num_transactions as TransactionIndex)).collect::<BTreeSet<_>>();
360                commit_state
361                    .pending_transactions
362                    .entry(block_ref)
363                    .or_default()
364                    .extend(transactions);
365                let hostname = &self.context.committee.authority(block_ref.author).hostname;
366                metrics
367                    .finalizer_skipped_voting_blocks
368                    .with_label_values(&[hostname.as_str(), "direct"])
369                    .inc();
370                tracing::debug!(
371                    "Block {} is potentially outside of GC bound from its leader {} in commit {}. Skipping direct finalization.",
372                    block_ref,
373                    commit_state.commit.leader,
374                    commit_state.commit.commit_ref
375                );
376                continue;
377            }
378            let reject_votes = self.transaction_vote_tracker.get_reject_votes(&block_ref)
379                .unwrap_or_else(|| panic!("No vote info found for {block_ref}. It is either incorrectly gc'ed or failed to be recovered after crash."));
380            metrics
381                .finalizer_transaction_status
382                .with_label_values(&["direct_finalize"])
383                .inc_by((num_transactions - reject_votes.len()) as u64);
384            let hostname = &self.context.committee.authority(block_ref.author).hostname;
385            metrics
386                .finalizer_reject_votes
387                .with_label_values(&[hostname])
388                .inc_by(reject_votes.len() as u64);
389            // If a transaction_index does not exist in reject_votes, the transaction has no reject votes.
390            // So it is finalized and does not need to be added to pending_transactions.
391            for (transaction_index, stake) in reject_votes {
392                // If the transaction has > 0 but < 2f+1 reject votes, it is still pending.
393                // Otherwise, it is rejected.
394                let entry = if stake < self.context.committee.quorum_threshold() {
395                    commit_state
396                        .pending_transactions
397                        .entry(block_ref)
398                        .or_default()
399                } else {
400                    metrics
401                        .finalizer_transaction_status
402                        .with_label_values(&["direct_reject"])
403                        .inc();
404                    commit_state
405                        .rejected_transactions
406                        .entry(block_ref)
407                        .or_default()
408                };
409                entry.insert(transaction_index);
410            }
411        }
412    }
413
414    // Creates an entry in the blocks map for each block in the commit,
415    // and have its ancestors link to the block.
416    fn link_blocks_in_last_commit(&mut self) {
417        let commit_state = self
418            .pending_commits
419            .back_mut()
420            .unwrap_or_else(|| panic!("No pending commit."));
421
422        // Link blocks in ascending order of round, to ensure ancestor block states are created
423        // before they are linked from.
424        let mut blocks = commit_state.commit.blocks.clone();
425        blocks.sort_by_key(|b| b.round());
426
427        let mut blocks_map = self.blocks.write();
428        for block in blocks {
429            let block_ref = block.reference();
430            // Link ancestors to the block.
431            for ancestor in block.ancestors() {
432                // Ancestor may not exist in the blocks map if it has been finalized or gc'ed.
433                // So skip linking if the ancestor does not exist.
434                if let Some(ancestor_block) = blocks_map.get(ancestor) {
435                    ancestor_block.write().children.insert(block_ref);
436                }
437            }
438            // Initialize the block state.
439            blocks_map.entry(block_ref).or_insert_with(|| {
440                RwLock::new(BlockState::new(block, commit_state.commit.commit_ref.index))
441            });
442        }
443    }
444
445    /// Updates the set of origin descendants, by appending blocks from the last commit to
446    /// origin descendants of previous linked blocks from the same origin.
447    ///
448    /// The purpose of maintaining the origin descendants per block is to save bandwidth by avoiding to explicitly
449    /// list all accept votes on transactions in blocks.
450    /// Instead when an ancestor block Ba is first included by a proposed block Bp, reject votes for transactions in Ba
451    /// are explicitly listed (if they exist). The rest of non-rejected transactions in Ba are assumed to be accepted by Bp.
452    /// This vote compression rule must be applied during vote aggregation as well.
453    ///
454    /// The above rule is equivalent to saying that transactions in a block can only be voted on by its immediate descendants.
455    /// A block Bp is an **immediate descendant** of Ba, if any directed path from Bp to Ba does not contain a block from Bp's own authority.
456    ///
457    /// This rule implies the following optimization is possible: after collecting votes for Ba from block Bp,
458    /// we can skip collecting votes from Bp's **origin descendants** (descendant blocks from the
459    /// same authority), because they cannot vote on Ba anyway.
460    ///
461    /// This vote compression rule is easy to implement when proposing blocks. Reject votes can be gathered against
462    /// all the newly included ancestors of the proposed block. But vote decompression is trickier to get right.
463    /// One edge case is when a block may not be an immediate descendant, because of GC. In this case votes from the
464    /// block should not be counted.
465    fn append_origin_descendants_from_last_commit(&mut self) {
466        let commit_state = self
467            .pending_commits
468            .back_mut()
469            .unwrap_or_else(|| panic!("No pending commit."));
470        let mut committed_blocks = commit_state.commit.blocks.clone();
471        committed_blocks.sort_by_key(|b| b.round());
472        let blocks_map = self.blocks.read();
473        for committed_block in committed_blocks {
474            let committed_block_ref = committed_block.reference();
475            // Each block must have at least one ancestor.
476            // Block verification ensures the first ancestor is from the block's own authority.
477            // Also, block verification ensures each authority appears at most once among ancestors.
478            let mut origin_ancestor_ref = *blocks_map
479                .get(&committed_block_ref)
480                .unwrap()
481                .read()
482                .block
483                .ancestors()
484                .first()
485                .unwrap();
486            while origin_ancestor_ref.author == committed_block_ref.author {
487                let Some(origin_ancestor_block) = blocks_map.get(&origin_ancestor_ref) else {
488                    break;
489                };
490                origin_ancestor_block
491                    .write()
492                    .origin_descendants
493                    .push(committed_block_ref);
494                origin_ancestor_ref = *origin_ancestor_block
495                    .read()
496                    .block
497                    .ancestors()
498                    .first()
499                    .unwrap();
500            }
501        }
502    }
503
504    // Tries indirectly finalizing the buffered commits at the given index.
505    async fn try_indirect_finalize_first_commit(&mut self) -> ConsensusResult<()> {
506        // Ensure direct finalization has been attempted for the commit.
507        assert!(!self.pending_commits.is_empty());
508        assert!(self.pending_commits[0].pending_blocks.is_empty());
509
510        // Optional optimization: re-check pending transactions to see if they are rejected by a quorum now.
511        self.check_pending_transactions_in_first_commit();
512
513        // The acceptance search must complete before depth-based rejection is safe.
514        // Cancellation must stop finalization instead of treating missing results as no acceptance.
515        self.try_indirect_finalize_pending_transactions_in_first_commit()
516            .await?;
517
518        // Check if remaining pending transactions can be indirectly rejected.
519        self.try_indirect_reject_pending_transactions_in_first_commit();
520        Ok(())
521    }
522
523    fn check_pending_transactions_in_first_commit(&mut self) {
524        let mut all_rejected_transactions: Vec<(BlockRef, Vec<TransactionIndex>)> = vec![];
525
526        // Collect all rejected transactions without modifying state
527        for (block_ref, pending_transactions) in &self.pending_commits[0].pending_transactions {
528            let reject_votes: BTreeMap<TransactionIndex, Stake> = self
529                .transaction_vote_tracker
530                .get_reject_votes(block_ref)
531                .unwrap_or_else(|| panic!("No vote info found for {block_ref}. It is incorrectly gc'ed or failed to be recovered after crash."))
532                .into_iter()
533                .collect();
534            let mut rejected_transactions = vec![];
535            for &transaction_index in pending_transactions {
536                // Pending transactions do not have reject votes when the block is outside of GC bound from the commit leader's round.
537                let reject_stake = reject_votes
538                    .get(&transaction_index)
539                    .copied()
540                    .unwrap_or_default();
541                if reject_stake < self.context.committee.quorum_threshold() {
542                    // The transaction cannot be rejected yet.
543                    continue;
544                }
545                // Otherwise, mark the transaction for rejection.
546                rejected_transactions.push(transaction_index);
547            }
548            if !rejected_transactions.is_empty() {
549                all_rejected_transactions.push((*block_ref, rejected_transactions));
550            }
551        }
552
553        // Move rejected transactions from pending_transactions.
554        for (block_ref, rejected_transactions) in all_rejected_transactions {
555            self.context
556                .metrics
557                .node_metrics
558                .finalizer_transaction_status
559                .with_label_values(&["direct_late_reject"])
560                .inc_by(rejected_transactions.len() as u64);
561            let curr_commit_state = &mut self.pending_commits[0];
562            curr_commit_state.remove_pending_transactions(&block_ref, &rejected_transactions);
563            curr_commit_state
564                .rejected_transactions
565                .entry(block_ref)
566                .or_default()
567                .extend(rejected_transactions);
568        }
569    }
570
571    async fn try_indirect_finalize_pending_transactions_in_first_commit(
572        &mut self,
573    ) -> ConsensusResult<()> {
574        tracing::debug!(
575            "Trying to indirectly finalize pending transactions in first commit {}",
576            self.pending_commits[0].commit.commit_ref,
577        );
578        let _scope = monitored_scope(
579            "CommitFinalizer::try_indirect_finalize_pending_transactions_in_first_commit",
580        );
581
582        let pending_blocks: Vec<_> = self.pending_commits[0]
583            .pending_transactions
584            .iter()
585            .map(|(k, v)| (*k, v.clone()))
586            .collect();
587
588        let gc_rounds = self
589            .pending_commits
590            .iter()
591            .map(|c| {
592                (
593                    c.commit.commit_ref.index,
594                    self.dag_state
595                        .read()
596                        .calculate_gc_round(c.commit.leader.round),
597                )
598            })
599            .collect::<Vec<_>>();
600
601        // Number of blocks to process in each task.
602        const BLOCKS_PER_INDIRECT_COMMIT_TASK: usize = 8;
603
604        // Process chunks in parallel.
605        let mut all_finalized_transactions = vec![];
606        let mut handles = Vec::new();
607        // TODO(fastpath): investigate using a cost based batching,
608        // for example each block has cost num authorities + pending_transactions.len().
609        for chunk in pending_blocks.chunks(BLOCKS_PER_INDIRECT_COMMIT_TASK) {
610            let context = self.context.clone();
611            let blocks = self.blocks.clone();
612            let gc_rounds = gc_rounds.clone();
613            let chunk: Vec<(BlockRef, BTreeSet<TransactionIndex>)> = chunk.to_vec();
614
615            let handle = tokio::task::spawn_blocking(move || {
616                let mut chunk_results = Vec::new();
617
618                for (block_ref, pending_transactions) in chunk {
619                    let finalized = Self::try_indirect_finalize_pending_transactions_in_block(
620                        &context,
621                        &blocks,
622                        &gc_rounds,
623                        block_ref,
624                        pending_transactions,
625                    );
626
627                    if !finalized.is_empty() {
628                        chunk_results.push((block_ref, finalized));
629                    }
630                }
631
632                chunk_results
633            });
634
635            handles.push(handle);
636        }
637
638        // Collect results from all chunks
639        for handle in handles {
640            all_finalized_transactions.extend(handle.await.map_err(spawn_blocking_join_error)?);
641        }
642
643        for (block_ref, finalized_transactions) in all_finalized_transactions {
644            self.context
645                .metrics
646                .node_metrics
647                .finalizer_transaction_status
648                .with_label_values(&["indirect_finalize"])
649                .inc_by(finalized_transactions.len() as u64);
650            // Remove finalized transactions from pending transactions.
651            self.pending_commits[0]
652                .remove_pending_transactions(&block_ref, &finalized_transactions);
653        }
654        Ok(())
655    }
656
657    fn try_indirect_reject_pending_transactions_in_first_commit(&mut self) {
658        let curr_leader_round = self.pending_commits[0].commit.leader.round;
659        let last_commit_leader_round = self.pending_commits.back().unwrap().commit.leader.round;
660        if curr_leader_round + INDIRECT_REJECT_DEPTH <= last_commit_leader_round {
661            let curr_commit_state = &mut self.pending_commits[0];
662            // This function is called after trying to indirectly finalize pending blocks.
663            // When last commit leader round is INDIRECT_REJECT_DEPTH rounds higher or more,
664            // all pending blocks should have been finalized.
665            assert!(curr_commit_state.pending_blocks.is_empty());
666            // This function is called after trying to indirectly finalize pending transactions.
667            // All remaining pending transactions, since they are not finalized, should now be
668            // indirectly rejected.
669            let pending_transactions = std::mem::take(&mut curr_commit_state.pending_transactions);
670            for (block_ref, pending_transactions) in pending_transactions {
671                self.context
672                    .metrics
673                    .node_metrics
674                    .finalizer_transaction_status
675                    .with_label_values(&["indirect_reject"])
676                    .inc_by(pending_transactions.len() as u64);
677                curr_commit_state
678                    .rejected_transactions
679                    .entry(block_ref)
680                    .or_default()
681                    .extend(pending_transactions);
682            }
683        }
684    }
685
686    // Returns the indices of the requested pending transactions that are indirectly finalized.
687    // This function is used for checking finalization of transactions, so it must traverse
688    // all blocks which can contribute to the requested transactions' finalizations.
689    fn try_indirect_finalize_pending_transactions_in_block(
690        context: &Arc<Context>,
691        blocks: &Arc<RwLock<BTreeMap<BlockRef, RwLock<BlockState>>>>,
692        gc_rounds: &[(CommitIndex, Round)],
693        pending_block_ref: BlockRef,
694        pending_transactions: BTreeSet<TransactionIndex>,
695    ) -> Vec<TransactionIndex> {
696        if pending_transactions.is_empty() {
697            return vec![];
698        }
699        let mut accept_votes: BTreeMap<TransactionIndex, StakeAggregator<QuorumThreshold>> =
700            pending_transactions
701                .into_iter()
702                .map(|transaction_index| (transaction_index, StakeAggregator::new()))
703                .collect();
704        let mut finalized_transactions = vec![];
705        let blocks_map = blocks.read();
706        // Use BTreeSet for to_visit_blocks, to visit blocks in the earliest round first.
707        let (pending_commit_index, mut to_visit_blocks) = {
708            let block_state = blocks_map.get(&pending_block_ref).unwrap().read();
709            (block_state.commit_index, block_state.children.clone())
710        };
711        // Blocks that have been visited.
712        let mut visited = BTreeSet::new();
713        // Blocks where votes and origin descendants should be ignored for processing.
714        let mut ignored = BTreeSet::new();
715        // Traverse children blocks breadth-first and accumulate accept votes for pending transactions.
716        while let Some(curr_block_ref) = to_visit_blocks.pop_first() {
717            if !visited.insert(curr_block_ref) {
718                continue;
719            }
720            let curr_block_state = blocks_map.get(&curr_block_ref).unwrap_or_else(|| panic!("Block {curr_block_ref} is either incorrectly gc'ed or failed to be recovered after crash.")).read();
721            // Check if transaction votes for the pending block are potentially not carried by the
722            // current block, because of GC at the current block's proposer.
723            // See comment above gced_transaction_votes_for_pending_block() for more details.
724            //
725            // Implicit transaction votes should only be considered in commit finalizer if they are definitely
726            // part of the transactions votes from the current block when it is proposed.
727            let votes_gced = Self::gced_transaction_votes_for_pending_block(
728                gc_rounds,
729                pending_block_ref.round,
730                pending_commit_index,
731                curr_block_state.commit_index,
732            );
733            // Skip counting votes from the block if it has been marked to be ignored.
734            if ignored.insert(curr_block_ref) {
735                // Skip collecting votes from origin descendants of current block.
736                // Votes from origin descendants of current block do not count for these transactions.
737                // Consider this case: block B is an origin descendant of block A (from the same authority),
738                // and both blocks A and B link to another block C.
739                // Only B's implicit and explicit transaction votes on C are considered.
740                // None of A's implicit or explicit transaction votes on C should be considered.
741                //
742                // See append_origin_descendants_from_last_commit() for more details.
743                ignored.extend(curr_block_state.origin_descendants.iter());
744                // Skip counting votes from current block if the votes on pending block could have been
745                // casted by an earlier block from the same origin, or the votes might not be proposed due to GC.
746                // Note: if the current block casts reject votes on transactions in the pending block,
747                // it can be assumed that accept votes are also casted to other transactions in the pending block.
748                // But we choose to skip counting the accept votes in this edge case for simplicity.
749                if votes_gced {
750                    let hostname = &context
751                        .committee
752                        .authority(pending_block_ref.author)
753                        .hostname;
754                    context
755                        .metrics
756                        .node_metrics
757                        .finalizer_skipped_voting_blocks
758                        .with_label_values(&[hostname.as_str(), "indirect"])
759                        .inc();
760                    tracing::debug!(
761                        "Block {} is potentially outside of GC bound from current block {}. Skipping indirect finalization.",
762                        pending_block_ref,
763                        curr_block_ref,
764                    );
765                    continue;
766                }
767                // Get reject votes from current block to the pending block.
768                let curr_block_reject_votes = curr_block_state
769                    .reject_votes
770                    .get(&pending_block_ref)
771                    .cloned()
772                    .unwrap_or_default();
773                // Because of lifetime, first collect finalized transactions, and then remove them from accept_votes.
774                let mut newly_finalized = vec![];
775                for (index, stake) in &mut accept_votes {
776                    // Skip if the transaction has been rejected by the current block.
777                    if curr_block_reject_votes.contains(index) {
778                        continue;
779                    }
780                    // Skip if the total stake has not reached quorum.
781                    if !stake.add(curr_block_ref.author, &context.committee) {
782                        continue;
783                    }
784                    newly_finalized.push(*index);
785                    finalized_transactions.push(*index);
786                }
787                // There is no need to aggregate additional votes for already finalized transactions.
788                for index in newly_finalized {
789                    accept_votes.remove(&index);
790                }
791                // End traversal if all blocks and requested transactions have reached quorum.
792                if accept_votes.is_empty() {
793                    break;
794                }
795            }
796            // Add additional children blocks to visit.
797            to_visit_blocks.extend(
798                curr_block_state
799                    .children
800                    .iter()
801                    .filter(|b| !visited.contains(*b)),
802            );
803        }
804        finalized_transactions
805    }
806
807    /// Returns true if transaction votes from the current block to the pending block
808    /// could have been be GC'ed. If this is the case, the current block cannot be assumed
809    /// to have implicitly voted to accept transactions in the pending block.
810    ///
811    /// When collecting transaction votes during proposal of the current block
812    /// (via DagState::link_causal_history()), votes against blocks in the DAG
813    /// below the proposer's GC round are skipped. Implicit accept votes cannot be assumed
814    /// for these GC'ed blocks. However, blocks do not carry the GC round when they are proposed.
815    /// So this function computes the highest possible GC round when the current block was proposed,
816    /// and use it as the minimum round threshold for implicit accept votes. Even if the computed
817    /// GC round here is higher than the actual GC round used by the current block, it is still
818    /// correct although less efficient.
819    ///
820    /// gc_rounds is a list of cached commit indices and the GC rounds resulting from the commits.
821    /// It must be a superset of commits in the range [pending_commit_index, current_commit_index].
822    /// The first element should have pending_commit_index, because pending commit should be the
823    /// first commit buffered in CommitFinalizer.
824    fn gced_transaction_votes_for_pending_block(
825        gc_rounds: &[(CommitIndex, Round)],
826        pending_block_round: Round,
827        pending_commit_index: CommitIndex,
828        current_commit_index: CommitIndex,
829    ) -> bool {
830        assert!(
831            pending_commit_index <= current_commit_index,
832            "Pending {pending_commit_index} should be <= current {current_commit_index}"
833        );
834        if pending_commit_index == current_commit_index {
835            return false;
836        }
837        // current_commit_index is the commit index which includes the current / voting block.
838        // When the current block was proposed, the latest/highest possible GC round that could have been used is the GC round computed
839        // from the leader of the previous commit (current_commit_index - 1). This acts as the most conservative threshold to make sure
840        // that the current block had actually "seen" the blocks within it's local GC bound.
841        let (commit_index, gc_round) = *gc_rounds
842            .get((current_commit_index - 1 - pending_commit_index) as usize)
843            .unwrap();
844        assert_eq!(
845            commit_index,
846            current_commit_index - 1,
847            "Commit index mismatch {commit_index} != {current_commit_index}"
848        );
849        pending_block_round <= gc_round
850    }
851
852    fn pop_finalized_commits(&mut self) -> Vec<CommittedSubDag> {
853        let mut finalized_commits = vec![];
854
855        while let Some(commit_state) = self.pending_commits.front() {
856            if !commit_state.pending_blocks.is_empty()
857                || !commit_state.pending_transactions.is_empty()
858            {
859                // The commit is not finalized yet.
860                break;
861            }
862
863            // Pop the finalized commit and set its rejected transactions.
864            let commit_state = self.pending_commits.pop_front().unwrap();
865            let mut commit = commit_state.commit;
866            for (block_ref, rejected_transactions) in commit_state.rejected_transactions {
867                commit
868                    .rejected_transactions_by_block
869                    .insert(block_ref, rejected_transactions.into_iter().collect());
870            }
871
872            // Clean up committed blocks.
873            let mut blocks_map = self.blocks.write();
874            for block in commit.blocks.iter() {
875                blocks_map.remove(&block.reference());
876            }
877
878            let round_delay = if let Some(last_commit_state) = self.pending_commits.back() {
879                last_commit_state.commit.leader.round - commit.leader.round
880            } else {
881                0
882            };
883            self.context
884                .metrics
885                .node_metrics
886                .finalizer_round_delay
887                .observe(round_delay as f64);
888
889            finalized_commits.push(commit);
890        }
891
892        finalized_commits
893    }
894
895    fn try_update_gc_round(&mut self, last_finalized_commit_round: Round) {
896        // GC TransactionVoteTracker state only with finalized commits, to ensure unfinalized transactions
897        // can access their reject votes from TransactionVoteTracker.
898        let gc_round = self
899            .dag_state
900            .read()
901            .calculate_gc_round(last_finalized_commit_round);
902        self.transaction_vote_tracker.run_gc(gc_round);
903    }
904
905    #[cfg(test)]
906    fn is_empty(&self) -> bool {
907        self.pending_commits.is_empty() && self.blocks.read().is_empty()
908    }
909}
910
911struct CommitState {
912    commit: CommittedSubDag,
913    // Blocks pending finalization, mapped to the number of transactions in the block.
914    // This field is populated by all blocks in the commit, before direct finalization.
915    // After direct finalization, this field becomes empty.
916    pending_blocks: BTreeMap<BlockRef, usize>,
917    // Transactions pending indirect finalization.
918    // This field is populated after direct finalization, if pending transactions exist.
919    // Values in this field are removed as transactions are indirectly finalized or directly rejected.
920    // When both pending_blocks and pending_transactions are empty, the commit is finalized.
921    pending_transactions: BTreeMap<BlockRef, BTreeSet<TransactionIndex>>,
922    // Transactions rejected by a quorum or indirectly, per block.
923    rejected_transactions: BTreeMap<BlockRef, BTreeSet<TransactionIndex>>,
924}
925
926impl CommitState {
927    fn new(commit: CommittedSubDag) -> Self {
928        let pending_blocks: BTreeMap<_, _> = commit
929            .blocks
930            .iter()
931            .map(|b| (b.reference(), b.transactions().len()))
932            .collect();
933        assert!(!pending_blocks.is_empty());
934        Self {
935            commit,
936            pending_blocks,
937            pending_transactions: BTreeMap::new(),
938            rejected_transactions: BTreeMap::new(),
939        }
940    }
941
942    fn remove_pending_transactions(
943        &mut self,
944        block_ref: &BlockRef,
945        transactions: &[TransactionIndex],
946    ) {
947        let Some(block_pending_txns) = self.pending_transactions.get_mut(block_ref) else {
948            return;
949        };
950        for t in transactions {
951            block_pending_txns.remove(t);
952        }
953        if block_pending_txns.is_empty() {
954            self.pending_transactions.remove(block_ref);
955        }
956    }
957}
958
959struct BlockState {
960    // Content of the block.
961    block: VerifiedBlock,
962    // Blocks which has an explicit ancestor linking to this block.
963    children: BTreeSet<BlockRef>,
964    // Reject votes casted by this block, and by linked ancestors from the same authority.
965    reject_votes: BTreeMap<BlockRef, BTreeSet<TransactionIndex>>,
966    // Other committed blocks that are origin descendants of this block.
967    // See the comment above append_origin_descendants_from_last_commit() for more details.
968    origin_descendants: Vec<BlockRef>,
969    // Commit which contains this block.
970    commit_index: CommitIndex,
971}
972
973impl BlockState {
974    fn new(block: VerifiedBlock, commit_index: CommitIndex) -> Self {
975        let reject_votes: BTreeMap<_, _> = block
976            .transaction_votes()
977            .iter()
978            .map(|v| (v.block_ref, v.rejects.clone().into_iter().collect()))
979            .collect();
980        // With at most 4 pending commits and assume 2 origin descendants per commit,
981        // there will be at most 8 origin descendants.
982        let origin_descendants = Vec::with_capacity(8);
983        Self {
984            block,
985            children: BTreeSet::new(),
986            reject_votes,
987            origin_descendants,
988            commit_index,
989        }
990    }
991}
992
993#[cfg(test)]
994mod tests {
995    use crate::{
996        CommitConsumerArgs, TestBlock, VerifiedBlock, block::BlockTransactionVotes,
997        block_verifier::NoopBlockVerifier, commit::load_committed_subdag_from_store,
998        commit_observer::CommitObserver, commit_test_fixture::CommitTestFixture,
999        test_dag_builder::DagBuilder,
1000    };
1001
1002    use super::*;
1003
1004    fn create_commit_finalizer_fixture() -> CommitTestFixture {
1005        CommitTestFixture::with_options(4, 0, Some(5))
1006    }
1007
1008    fn create_block(
1009        round: Round,
1010        authority: u32,
1011        mut ancestors: Vec<BlockRef>,
1012        num_transactions: usize,
1013        reject_votes: Vec<BlockTransactionVotes>,
1014    ) -> VerifiedBlock {
1015        // Move own authority ancestor to the front of the ancestors.
1016        let i = ancestors
1017            .iter()
1018            .position(|b| b.author.value() == authority as usize)
1019            .unwrap_or_else(|| {
1020                panic!("Authority {authority} (round {round}) not found in {ancestors:?}")
1021            });
1022        let b = ancestors.remove(i);
1023        ancestors.insert(0, b);
1024        // Create test block.
1025        let block = TestBlock::new(round, authority)
1026            .set_ancestors(ancestors)
1027            .set_transactions(vec![crate::Transaction::new(vec![1; 16]); num_transactions])
1028            .set_transaction_votes(reject_votes)
1029            .build();
1030        VerifiedBlock::new_for_test(block)
1031    }
1032
1033    #[tokio::test]
1034    async fn test_direct_finalize_no_reject_votes() {
1035        let mut fixture = create_commit_finalizer_fixture();
1036
1037        // Create round 1-4 blocks with 10 transactions each. Add these blocks to the transaction vote tracker.
1038        let mut dag_builder = DagBuilder::new(fixture.context.clone());
1039        dag_builder.layers(1..=4).num_transactions(10).build();
1040        let blocks = dag_builder.all_blocks();
1041        fixture.add_blocks(blocks.clone());
1042
1043        // Select a round 2 block as the leader and create CommittedSubDag.
1044        let leader = blocks.iter().find(|b| b.round() == 2).unwrap();
1045        let committed_sub_dags = fixture.linearizer.handle_commit(vec![leader.clone()]);
1046        assert_eq!(committed_sub_dags.len(), 1);
1047        let committed_sub_dag = &committed_sub_dags[0];
1048
1049        // This committed sub-dag can be directly finalized.
1050        let finalized_commits = fixture
1051            .commit_finalizer
1052            .process_commit(committed_sub_dag.clone())
1053            .await
1054            .unwrap();
1055        assert_eq!(finalized_commits.len(), 1);
1056        let finalized_commit = &finalized_commits[0];
1057        assert_eq!(committed_sub_dag, finalized_commit);
1058
1059        // CommitFinalizer should be empty.
1060        assert!(fixture.commit_finalizer.is_empty());
1061    }
1062
1063    // Commits can be directly finalized if when they are added to commit finalizer,
1064    // the rejected votes reach quorum if they exist on any transaction.
1065    #[tokio::test]
1066    async fn test_direct_finalize_with_reject_votes() {
1067        let mut fixture = create_commit_finalizer_fixture();
1068
1069        // Create round 1 blocks with 10 transactions each.
1070        let mut dag_builder = DagBuilder::new(fixture.context.clone());
1071        dag_builder.layer(1).num_transactions(10).build();
1072
1073        let round_1_blocks = dag_builder.all_blocks();
1074        fixture.add_blocks_with_own_votes(
1075            round_1_blocks
1076                .iter()
1077                .map(|b| {
1078                    if b.author().value() != 3 {
1079                        (b.clone(), vec![])
1080                    } else {
1081                        (b.clone(), vec![0, 3])
1082                    }
1083                })
1084                .collect(),
1085        );
1086
1087        // Select the block with rejected transaction.
1088        let block_with_rejected_txn = round_1_blocks[3].clone();
1089        let reject_vote = BlockTransactionVotes {
1090            block_ref: block_with_rejected_txn.reference(),
1091            rejects: vec![0, 3],
1092        };
1093
1094        // Create round 2 blocks without authority 3's block from round 1.
1095        let ancestors: Vec<BlockRef> = round_1_blocks[0..3].iter().map(|b| b.reference()).collect();
1096        // Leader links to block_with_rejected_txn, but other blocks do not.
1097        let round_2_blocks = vec![
1098            create_block(
1099                2,
1100                0,
1101                round_1_blocks.iter().map(|b| b.reference()).collect(),
1102                10,
1103                vec![reject_vote.clone()],
1104            ),
1105            create_block(2, 1, ancestors.clone(), 10, vec![]),
1106            create_block(2, 2, ancestors.clone(), 10, vec![]),
1107        ];
1108        fixture.add_blocks(round_2_blocks.clone());
1109
1110        // Select round 2 authority 0 block as the leader and create CommittedSubDag.
1111        let leader = round_2_blocks[0].clone();
1112        let committed_sub_dags = fixture.linearizer.handle_commit(vec![leader.clone()]);
1113        assert_eq!(committed_sub_dags.len(), 1);
1114        let committed_sub_dag = &committed_sub_dags[0];
1115        assert_eq!(committed_sub_dag.blocks.len(), 5);
1116
1117        // Create round 3 blocks voting on the leader.
1118        let ancestors: Vec<BlockRef> = round_2_blocks.iter().map(|b| b.reference()).collect();
1119        let round_3_blocks = vec![
1120            create_block(3, 0, ancestors.clone(), 0, vec![]),
1121            create_block(3, 1, ancestors.clone(), 0, vec![reject_vote.clone()]),
1122            create_block(3, 2, ancestors.clone(), 0, vec![reject_vote.clone()]),
1123            create_block(
1124                3,
1125                3,
1126                std::iter::once(round_1_blocks[3].reference())
1127                    .chain(ancestors.clone())
1128                    .collect(),
1129                0,
1130                vec![reject_vote.clone()],
1131            ),
1132        ];
1133        fixture.add_blocks(round_3_blocks.clone());
1134
1135        // Create round 4 blocks certifying the leader.
1136        let ancestors: Vec<BlockRef> = round_3_blocks.iter().map(|b| b.reference()).collect();
1137        let round_4_blocks = vec![
1138            create_block(4, 0, ancestors.clone(), 0, vec![]),
1139            create_block(4, 1, ancestors.clone(), 0, vec![]),
1140            create_block(4, 2, ancestors.clone(), 0, vec![]),
1141            create_block(4, 3, ancestors.clone(), 0, vec![]),
1142        ];
1143        fixture.add_blocks(round_4_blocks.clone());
1144
1145        // This committed sub-dag can be directly finalized because the rejected transactions
1146        // have a quorum of votes.
1147        let finalized_commits = fixture
1148            .commit_finalizer
1149            .process_commit(committed_sub_dag.clone())
1150            .await
1151            .unwrap();
1152        assert_eq!(finalized_commits.len(), 1);
1153        let finalized_commit = &finalized_commits[0];
1154        assert_eq!(committed_sub_dag.commit_ref, finalized_commit.commit_ref);
1155        assert_eq!(committed_sub_dag.blocks, finalized_commit.blocks);
1156        assert_eq!(finalized_commit.rejected_transactions_by_block.len(), 1);
1157        assert_eq!(
1158            finalized_commit
1159                .rejected_transactions_by_block
1160                .get(&block_with_rejected_txn.reference())
1161                .unwrap()
1162                .clone(),
1163            vec![0, 3],
1164        );
1165
1166        // CommitFinalizer should be empty.
1167        assert!(fixture.commit_finalizer.is_empty());
1168    }
1169
1170    // Test indirect finalization when:
1171    // 1. Reject votes on transaction does not reach quorum initially, but reach quorum later.
1172    // 2. Transaction is indirectly rejected.
1173    // 3. Transaction is indirectly finalized.
1174    fn indirect_finalize_with_reject_votes_fixture(
1175        last_leader_round: Round,
1176    ) -> (CommitTestFixture, Vec<CommittedSubDag>, BlockRef) {
1177        let mut fixture = create_commit_finalizer_fixture();
1178        assert!(!fixture.context.protocol_config.enable_v3());
1179
1180        // Create round 1 blocks with 10 transactions each.
1181        let mut dag_builder = DagBuilder::new(fixture.context.clone());
1182        dag_builder.layer(1).num_transactions(10).build();
1183
1184        let round_1_blocks = dag_builder.all_blocks();
1185        fixture.add_blocks_with_own_votes(
1186            round_1_blocks
1187                .iter()
1188                .map(|b| {
1189                    if b.author().value() != 3 {
1190                        (b.clone(), vec![])
1191                    } else {
1192                        (b.clone(), vec![0, 3])
1193                    }
1194                })
1195                .collect(),
1196        );
1197
1198        // Select the block with rejected transaction.
1199        let block_with_rejected_txn = round_1_blocks[3].clone();
1200        // How transactions in this block will be voted:
1201        // Txn 1 (quorum reject): 1 reject vote at round 2, 1 reject vote at round 3, and 1 at round 4.
1202        // Txn 4 (indirect reject): 1 reject vote at round 3, and 1 at round 4.
1203        // Txn 7 (indirect finalize): 1 reject vote at round 3.
1204
1205        // Create round 2 blocks without authority 3.
1206        let ancestors: Vec<BlockRef> = round_1_blocks[0..3].iter().map(|b| b.reference()).collect();
1207        // Leader links to block_with_rejected_txn, but other blocks do not.
1208        let round_2_blocks = vec![
1209            create_block(
1210                2,
1211                0,
1212                round_1_blocks.iter().map(|b| b.reference()).collect(),
1213                10,
1214                vec![BlockTransactionVotes {
1215                    block_ref: block_with_rejected_txn.reference(),
1216                    rejects: vec![1, 4],
1217                }],
1218            ),
1219            // Use ancestors without authority 3 to avoid voting on its transactions.
1220            create_block(2, 1, ancestors.clone(), 10, vec![]),
1221            create_block(2, 2, ancestors.clone(), 10, vec![]),
1222        ];
1223        fixture.add_blocks(round_2_blocks.clone());
1224
1225        // Select round 2 authority 0 block as the a leader.
1226        let mut leaders = vec![round_2_blocks[0].clone()];
1227
1228        // Create round 3 blocks voting on the leader and casting reject votes.
1229        let ancestors: Vec<BlockRef> = round_2_blocks.iter().map(|b| b.reference()).collect();
1230        let round_3_blocks = vec![
1231            create_block(3, 0, ancestors.clone(), 0, vec![]),
1232            create_block(
1233                3,
1234                1,
1235                ancestors.clone(),
1236                0,
1237                vec![BlockTransactionVotes {
1238                    block_ref: block_with_rejected_txn.reference(),
1239                    rejects: vec![1, 4, 7],
1240                }],
1241            ),
1242            create_block(
1243                3,
1244                3,
1245                std::iter::once(round_1_blocks[3].reference())
1246                    .chain(ancestors.clone())
1247                    .collect(),
1248                0,
1249                vec![],
1250            ),
1251        ];
1252        fixture.add_blocks(round_3_blocks.clone());
1253        leaders.push(round_3_blocks[2].clone());
1254
1255        // Create round 4 blocks certifying the leader and casting reject votes.
1256        let ancestors: Vec<BlockRef> = round_3_blocks.iter().map(|b| b.reference()).collect();
1257        let round_4_blocks = vec![
1258            create_block(4, 0, ancestors.clone(), 0, vec![]),
1259            create_block(4, 1, ancestors.clone(), 0, vec![]),
1260            create_block(
1261                4,
1262                2,
1263                std::iter::once(round_2_blocks[2].reference())
1264                    .chain(ancestors.clone())
1265                    .collect(),
1266                0,
1267                vec![BlockTransactionVotes {
1268                    block_ref: block_with_rejected_txn.reference(),
1269                    rejects: vec![1],
1270                }],
1271            ),
1272            create_block(4, 3, ancestors.clone(), 0, vec![]),
1273        ];
1274        fixture.add_blocks(round_4_blocks.clone());
1275        leaders.push(round_4_blocks[1].clone());
1276
1277        // Create round 5-7 blocks without casting reject votes.
1278        // Round 5 is needed to indirectly finalize transactions committed by the round 2 leader.
1279        let mut last_round_blocks = round_4_blocks.clone();
1280        for r in 5..=7 {
1281            let ancestors: Vec<BlockRef> =
1282                last_round_blocks.iter().map(|b| b.reference()).collect();
1283            let round_blocks: Vec<_> = (0..4)
1284                .map(|i| create_block(r, i, ancestors.clone(), 0, vec![]))
1285                .collect();
1286            fixture.add_blocks(round_blocks.clone());
1287            if r <= last_leader_round {
1288                leaders.push(round_blocks[0].clone());
1289            }
1290            last_round_blocks = round_blocks;
1291        }
1292
1293        // Create CommittedSubDag from leaders.
1294        assert_eq!(leaders.len(), last_leader_round as usize - 1);
1295        let committed_sub_dags = fixture.linearizer.handle_commit(leaders);
1296        assert_eq!(committed_sub_dags.len(), last_leader_round as usize - 1);
1297
1298        (
1299            fixture,
1300            committed_sub_dags,
1301            block_with_rejected_txn.reference(),
1302        )
1303    }
1304
1305    #[tokio::test]
1306    async fn test_indirect_finalize_with_reject_votes() {
1307        let (mut fixture, committed_sub_dags, block_with_rejected_txn) =
1308            indirect_finalize_with_reject_votes_fixture(5);
1309
1310        // Buffering the initial 3 commits should not finalize.
1311        for commit in committed_sub_dags.iter().take(3) {
1312            let finalized_commits = fixture
1313                .commit_finalizer
1314                .process_commit(commit.clone())
1315                .await
1316                .unwrap();
1317            assert_eq!(finalized_commits.len(), 0);
1318        }
1319
1320        // Buffering the 4th commit should finalize all commits.
1321        let finalized_commits = fixture
1322            .commit_finalizer
1323            .process_commit(committed_sub_dags[3].clone())
1324            .await
1325            .unwrap();
1326        assert_eq!(finalized_commits.len(), 4);
1327
1328        // Check rejected transactions.
1329        let rejected_transactions = finalized_commits[0].rejected_transactions_by_block.clone();
1330        assert_eq!(rejected_transactions.len(), 1);
1331        assert_eq!(
1332            rejected_transactions.get(&block_with_rejected_txn).unwrap(),
1333            &vec![1, 4]
1334        );
1335
1336        // Other commits should have no rejected transactions.
1337        for commit in finalized_commits.iter().skip(1) {
1338            assert!(commit.rejected_transactions_by_block.is_empty());
1339        }
1340
1341        // CommitFinalizer should be empty.
1342        assert!(fixture.commit_finalizer.is_empty());
1343    }
1344
1345    #[tokio::test]
1346    async fn test_indirect_finalization_shutdown_recovers_without_rejecting_accepted_transaction() {
1347        let (mut fixture, committed_sub_dags, block_with_rejected_txn) =
1348            indirect_finalize_with_reject_votes_fixture(6);
1349        let context = fixture.context.clone();
1350        let dag_state = fixture.commit_finalizer.dag_state.clone();
1351        let store = dag_state.read().store();
1352        // Consensus has persisted the commits, but none has finalized yet.
1353        dag_state.write().flush();
1354        for commit in committed_sub_dags.iter().take(3) {
1355            assert!(
1356                fixture
1357                    .commit_finalizer
1358                    .process_commit(commit.clone())
1359                    .await
1360                    .unwrap()
1361                    .is_empty()
1362            );
1363        }
1364
1365        let (commit_sender, mut commit_receiver) = unbounded_channel("shutdown_test_output");
1366        fixture.commit_finalizer.commit_sender = commit_sender;
1367        let (sender, receiver) = unbounded_channel("shutdown_test_input");
1368        // The fourth commit permits depth-based rejection; the fifth is queued when shutdown occurs.
1369        for commit in committed_sub_dags.iter().skip(3) {
1370            sender.send(commit.clone()).unwrap();
1371        }
1372        drop(sender);
1373
1374        // A task still being polled during shutdown can encounter an already closed blocking pool.
1375        let runtime = tokio::runtime::Builder::new_current_thread()
1376            .build()
1377            .unwrap();
1378        let runtime_handle = runtime.handle().clone();
1379        runtime.shutdown_background();
1380        let entered = runtime_handle.enter();
1381        fixture.commit_finalizer.run(receiver).await;
1382        drop(entered);
1383
1384        assert!(commit_receiver.recv().await.is_none());
1385        assert!(store.read_last_finalized_commit().unwrap().is_none());
1386        for commit in &committed_sub_dags {
1387            assert!(
1388                store
1389                    .read_rejected_transactions(commit.commit_ref)
1390                    .unwrap()
1391                    .is_none()
1392            );
1393        }
1394        for commit in store.scan_commits((1..=5).into()).unwrap() {
1395            let recovered = load_committed_subdag_from_store(store.as_ref(), commit);
1396            assert!(!recovered.recovered_rejected_transactions);
1397        }
1398
1399        // Recover through the production observer with fresh DAG/vote state and a live runtime.
1400        let recovered_dag = Arc::new(RwLock::new(DagState::new(context.clone(), store.clone())));
1401        let recovered_tracker = TransactionVoteTracker::new(
1402            context.clone(),
1403            Arc::new(NoopBlockVerifier {}),
1404            recovered_dag.clone(),
1405        );
1406        let (consumer, mut receiver) = CommitConsumerArgs::new(0, 0);
1407        let mut observer = tokio::time::timeout(
1408            Duration::from_secs(5),
1409            CommitObserver::new(context, consumer, recovered_dag, recovered_tracker),
1410        )
1411        .await
1412        .unwrap();
1413        tokio::time::timeout(Duration::from_secs(5), observer.stop())
1414            .await
1415            .unwrap();
1416
1417        let recovered = receiver.recv().await.unwrap();
1418        assert_eq!(recovered.commit_ref, committed_sub_dags[0].commit_ref);
1419        assert!(!recovered.recovered_rejected_transactions);
1420        assert_eq!(recovered.rejected_transactions_by_block.len(), 1);
1421        assert_eq!(
1422            recovered.rejected_transactions_by_block[&block_with_rejected_txn],
1423            vec![1, 4],
1424        );
1425        assert_eq!(
1426            store
1427                .read_rejected_transactions(recovered.commit_ref)
1428                .unwrap()
1429                .unwrap(),
1430            recovered.rejected_transactions_by_block,
1431        );
1432    }
1433
1434    // Test direct finalization when a block is at or below GC round from the block's own leader.
1435    #[tokio::test]
1436    async fn test_direct_finalize_with_gc() {
1437        let mut fixture = create_commit_finalizer_fixture();
1438        assert_eq!(fixture.context.protocol_config.gc_depth(), 5);
1439
1440        // Create round 1 blocks with 10 transactions each.
1441        let mut dag_builder = DagBuilder::new(fixture.context.clone());
1442        dag_builder.layer(1).num_transactions(10).build();
1443        let round_1_blocks = dag_builder.all_blocks();
1444        fixture.add_blocks(round_1_blocks.clone());
1445
1446        // Select B1(3) to be rejected due to GC.
1447        let block_rejected = round_1_blocks[3].clone();
1448
1449        // Create round 2-5 blocks without creating or linking to an authority 4 block.
1450        // The goal is to GC B1(3).
1451        let mut last_round_blocks: Vec<VerifiedBlock> = round_1_blocks
1452            .iter()
1453            .enumerate()
1454            .filter_map(|(i, b)| {
1455                if i != block_rejected.author().value() {
1456                    Some(b.clone())
1457                } else {
1458                    None
1459                }
1460            })
1461            .collect();
1462        for r in 2..=5 {
1463            let ancestors: Vec<BlockRef> =
1464                last_round_blocks.iter().map(|b| b.reference()).collect();
1465            last_round_blocks = [0, 1, 2]
1466                .map(|i| create_block(r, i, ancestors.clone(), 0, vec![]))
1467                .to_vec();
1468            fixture.add_blocks(last_round_blocks.clone());
1469        }
1470
1471        // Create round 6-9 blocks without authority 3 blocks.
1472        // And add a leader from authority 0 of each round. Only authority 0 blocks can link to B1(3).
1473        let mut leaders = vec![];
1474        for r in 6..=9 {
1475            let ancestors: Vec<BlockRef> =
1476                last_round_blocks.iter().map(|b| b.reference()).collect();
1477            last_round_blocks = [0, 1, 2]
1478                .map(|i| {
1479                    let mut ancestors = ancestors.clone();
1480                    if i == 0 {
1481                        // Link to the GC'ed block B1(3).
1482                        ancestors.push(block_rejected.reference());
1483                    }
1484                    create_block(r, i, ancestors, 0, vec![])
1485                })
1486                .to_vec();
1487            leaders.push(last_round_blocks[0].clone());
1488            fixture.add_blocks(last_round_blocks.clone());
1489        }
1490
1491        // Create CommittedSubDag from leaders.
1492        assert_eq!(leaders.len(), 4);
1493        let committed_sub_dags = fixture.linearizer.handle_commit(leaders);
1494        assert_eq!(committed_sub_dags.len(), 4);
1495
1496        // Ensure B1(3) is included in commit 0.
1497        assert!(committed_sub_dags[0].blocks.contains(&block_rejected));
1498
1499        // Buffering the initial 3 commits should not finalize.
1500        for commit in committed_sub_dags.iter().take(3) {
1501            assert!(commit.decided_with_local_blocks);
1502            let finalized_commits = fixture
1503                .commit_finalizer
1504                .process_commit(commit.clone())
1505                .await
1506                .unwrap();
1507            assert_eq!(finalized_commits.len(), 0);
1508        }
1509
1510        // Buffering the 4th commit should finalize all commits.
1511        let finalized_commits = fixture
1512            .commit_finalizer
1513            .process_commit(committed_sub_dags[3].clone())
1514            .await
1515            .unwrap();
1516        assert_eq!(finalized_commits.len(), 4);
1517
1518        // Check rejected transactions.
1519        // B1(3) all transactions get rejected as it is effectively voted only by one block from authority 3 (the block it self) and authority 0. Due to vote compression only the first block of authority 0 is counted.
1520        // The block is out of GC bound for the B7(1) and B7(2) blocks which are committed by the leader of round 8. Thus no accept votes are counted from authorities 1 & 2.
1521        let rejected_transactions = finalized_commits[0].rejected_transactions_by_block.clone();
1522        assert_eq!(rejected_transactions.len(), 1);
1523        assert_eq!(
1524            rejected_transactions
1525                .get(&block_rejected.reference())
1526                .unwrap(),
1527            &vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1528        );
1529
1530        // Other commits should have no rejected transactions.
1531        for commit in finalized_commits.iter().skip(1) {
1532            assert!(commit.rejected_transactions_by_block.is_empty());
1533        }
1534
1535        // CommitFinalizer should be empty.
1536        assert!(fixture.commit_finalizer.is_empty());
1537    }
1538
1539    // Test indirect finalization when transaction is rejected due to GC.
1540    #[tokio::test]
1541    async fn test_indirect_reject_with_gc() {
1542        let mut fixture = create_commit_finalizer_fixture();
1543        assert_eq!(fixture.context.protocol_config.gc_depth(), 5);
1544
1545        // Create round 1 blocks with 10 transactions each.
1546        let mut dag_builder = DagBuilder::new(fixture.context.clone());
1547        dag_builder.layer(1).num_transactions(10).build();
1548
1549        let round_1_blocks = dag_builder.all_blocks();
1550        fixture.add_blocks(round_1_blocks.clone());
1551
1552        // Select B1(3) to have a rejected transaction.
1553        let block_with_rejected_txn = round_1_blocks[3].clone();
1554        // How transactions in this block will be voted:
1555        // Txn 1 (GC reject): 1 reject vote at round 2. But the txn will get rejected because there are only
1556        // 2 accept votes.
1557
1558        // Create round 2 blocks, with B2(1) rejecting transaction 1 from B1(3).
1559        // Note that 3 blocks link to B1(3) without rejecting transaction 1.
1560        let ancestors: Vec<BlockRef> = round_1_blocks.iter().map(|b| b.reference()).collect();
1561        let round_2_blocks = vec![
1562            create_block(2, 0, ancestors.clone(), 0, vec![]),
1563            create_block(
1564                2,
1565                1,
1566                ancestors.clone(),
1567                0,
1568                vec![BlockTransactionVotes {
1569                    block_ref: block_with_rejected_txn.reference(),
1570                    rejects: vec![1],
1571                }],
1572            ),
1573            create_block(2, 2, ancestors.clone(), 0, vec![]),
1574            create_block(2, 3, ancestors.clone(), 0, vec![]),
1575        ];
1576        fixture.add_blocks(round_2_blocks.clone());
1577
1578        // Create round 3-6 blocks without creating or linking to an authority 2 block.
1579        // The goal is to GC B2(2).
1580        let mut last_round_blocks: Vec<VerifiedBlock> = round_2_blocks
1581            .iter()
1582            .enumerate()
1583            .filter_map(|(i, b)| if i != 2 { Some(b.clone()) } else { None })
1584            .collect();
1585        for r in 3..=6 {
1586            let ancestors: Vec<BlockRef> =
1587                last_round_blocks.iter().map(|b| b.reference()).collect();
1588            last_round_blocks = [0, 1, 3]
1589                .map(|i| create_block(r, i, ancestors.clone(), 0, vec![]))
1590                .to_vec();
1591            fixture.add_blocks(last_round_blocks.clone());
1592        }
1593
1594        // Create round 7-10 blocks and add a leader from authority 0 of each round.
1595        let mut leaders = vec![];
1596        for r in 7..=10 {
1597            let ancestors: Vec<BlockRef> =
1598                last_round_blocks.iter().map(|b| b.reference()).collect();
1599            last_round_blocks = (0..4)
1600                .map(|i| {
1601                    let mut ancestors = ancestors.clone();
1602                    if r == 7 && i == 2 {
1603                        // Link to the GC'ed block B2(2).
1604                        ancestors.push(round_2_blocks[2].reference());
1605                    }
1606                    create_block(r, i, ancestors, 0, vec![])
1607                })
1608                .collect();
1609            leaders.push(last_round_blocks[0].clone());
1610            fixture.add_blocks(last_round_blocks.clone());
1611        }
1612
1613        // Create CommittedSubDag from leaders.
1614        assert_eq!(leaders.len(), 4);
1615        let committed_sub_dags = fixture.linearizer.handle_commit(leaders);
1616        assert_eq!(committed_sub_dags.len(), 4);
1617
1618        // Ensure 1 reject vote is contained in B2(1) in commit 0.
1619        assert!(committed_sub_dags[0].blocks.contains(&round_2_blocks[1]));
1620        // Ensure B2(2) is GC'ed.
1621        for commit in committed_sub_dags.iter() {
1622            assert!(!commit.blocks.contains(&round_2_blocks[2]));
1623        }
1624
1625        // Buffering the initial 3 commits should not finalize.
1626        for commit in committed_sub_dags.iter().take(3) {
1627            assert!(commit.decided_with_local_blocks);
1628            let finalized_commits = fixture
1629                .commit_finalizer
1630                .process_commit(commit.clone())
1631                .await
1632                .unwrap();
1633            assert_eq!(finalized_commits.len(), 0);
1634        }
1635
1636        // Buffering the 4th commit should finalize all commits.
1637        let finalized_commits = fixture
1638            .commit_finalizer
1639            .process_commit(committed_sub_dags[3].clone())
1640            .await
1641            .unwrap();
1642        assert_eq!(finalized_commits.len(), 4);
1643
1644        // Check rejected transactions.
1645        // B1(3) txn 1 gets rejected, even though there are has 3 blocks links to B1(3) without rejecting txn 1.
1646        // This is because there are only 2 accept votes for this transaction, which is less than the quorum threshold.
1647        let rejected_transactions = finalized_commits[0].rejected_transactions_by_block.clone();
1648        assert_eq!(rejected_transactions.len(), 1);
1649        assert_eq!(
1650            rejected_transactions
1651                .get(&block_with_rejected_txn.reference())
1652                .unwrap(),
1653            &vec![1]
1654        );
1655
1656        // Other commits should have no rejected transactions.
1657        for commit in finalized_commits.iter().skip(1) {
1658            assert!(commit.rejected_transactions_by_block.is_empty());
1659        }
1660
1661        // CommitFinalizer should be empty.
1662        assert!(fixture.commit_finalizer.is_empty());
1663    }
1664
1665    #[tokio::test]
1666    async fn test_finalize_remote_commits_with_reject_votes() {
1667        let mut fixture: CommitTestFixture = create_commit_finalizer_fixture();
1668        let mut all_blocks = vec![];
1669
1670        // Create round 1 blocks with 10 transactions each.
1671        let mut dag_builder = DagBuilder::new(fixture.context.clone());
1672        dag_builder.layer(1).num_transactions(10).build();
1673        let round_1_blocks = dag_builder.all_blocks();
1674        all_blocks.push(round_1_blocks.clone());
1675
1676        // Collect leaders from round 1.
1677        let mut leaders = vec![round_1_blocks[0].clone()];
1678
1679        // Create round 2-9 blocks and set leaders until round 7.
1680        let mut last_round_blocks = round_1_blocks.clone();
1681        for r in 2..=9 {
1682            let ancestors: Vec<BlockRef> =
1683                last_round_blocks.iter().map(|b| b.reference()).collect();
1684            let round_blocks: Vec<_> = (0..4)
1685                .map(|i| create_block(r, i, ancestors.clone(), 0, vec![]))
1686                .collect();
1687            all_blocks.push(round_blocks.clone());
1688            if r <= 7 && r != 5 {
1689                leaders.push(round_blocks[r as usize % 4].clone());
1690            }
1691            last_round_blocks = round_blocks;
1692        }
1693
1694        // Leader rounds: 1, 2, 3, 4, 6, 7.
1695        assert_eq!(leaders.len(), 6);
1696
1697        async fn add_blocks_and_process_commit(
1698            fixture: &mut CommitTestFixture,
1699            leaders: &[VerifiedBlock],
1700            all_blocks: &[Vec<VerifiedBlock>],
1701            index: usize,
1702            local: bool,
1703        ) -> Vec<CommittedSubDag> {
1704            let leader = leaders[index].clone();
1705            // Add blocks related to the commit to DagState and TransactionVoteTracker.
1706            if local {
1707                for round_blocks in all_blocks.iter().take(leader.round() as usize + 2) {
1708                    fixture.add_blocks(round_blocks.clone());
1709                }
1710            } else {
1711                for round_blocks in all_blocks.iter().take(leader.round() as usize) {
1712                    fixture.add_blocks(round_blocks.clone());
1713                }
1714            };
1715            // Generate remote commit from leader.
1716            let mut committed_sub_dags = fixture.linearizer.handle_commit(vec![leader]);
1717            assert_eq!(committed_sub_dags.len(), 1);
1718            let mut remote_commit = committed_sub_dags.pop().unwrap();
1719            remote_commit.decided_with_local_blocks = local;
1720            // Process the remote commit.
1721            fixture
1722                .commit_finalizer
1723                .process_commit(remote_commit.clone())
1724                .await
1725                .unwrap()
1726        }
1727
1728        // Add commit 1-3 as remote commits. There should be no finalized commits.
1729        for i in 0..3 {
1730            let finalized_commits =
1731                add_blocks_and_process_commit(&mut fixture, &leaders, &all_blocks, i, false).await;
1732            assert!(finalized_commits.is_empty());
1733        }
1734
1735        // Buffer round 4 commit as a remote commit. This should finalize the 1st commit at round 1.
1736        let finalized_commits =
1737            add_blocks_and_process_commit(&mut fixture, &leaders, &all_blocks, 3, false).await;
1738        assert_eq!(finalized_commits.len(), 1);
1739        assert_eq!(finalized_commits[0].commit_ref.index, 1);
1740        assert_eq!(finalized_commits[0].leader.round, 1);
1741
1742        // Buffer round 6 (5th) commit as local commit. This should help finalize the commits at round 2 and 3.
1743        let finalized_commits =
1744            add_blocks_and_process_commit(&mut fixture, &leaders, &all_blocks, 4, true).await;
1745        assert_eq!(finalized_commits.len(), 2);
1746        assert_eq!(finalized_commits[0].commit_ref.index, 2);
1747        assert_eq!(finalized_commits[0].leader.round, 2);
1748        assert_eq!(finalized_commits[1].commit_ref.index, 3);
1749        assert_eq!(finalized_commits[1].leader.round, 3);
1750
1751        // Buffer round 7 (6th) commit as local commit. This should help finalize the commits at round 4, 6 and 7 (itself).
1752        let finalized_commits =
1753            add_blocks_and_process_commit(&mut fixture, &leaders, &all_blocks, 5, true).await;
1754        assert_eq!(finalized_commits.len(), 3);
1755        assert_eq!(finalized_commits[0].commit_ref.index, 4);
1756        assert_eq!(finalized_commits[0].leader.round, 4);
1757        assert_eq!(finalized_commits[1].commit_ref.index, 5);
1758        assert_eq!(finalized_commits[1].leader.round, 6);
1759        assert_eq!(finalized_commits[2].commit_ref.index, 6);
1760        assert_eq!(finalized_commits[2].leader.round, 7);
1761
1762        // CommitFinalizer should be empty.
1763        assert!(fixture.commit_finalizer.is_empty());
1764    }
1765}