Skip to content

Conversation

simonzg
Copy link

@simonzg simonzg commented Jun 27, 2025

This PR supports multiple finalizeState so that the pipelined consensus algorithm (such as HotStuff) could work with cosmos-sdk.

Problem

A pipelined consensus algorithm, as its name suggests, works in a pipelined fashion: voting on trailing blocks will be considered as extra rounds of voting on the parent block, and each block has 3 rounds of voting before it's committed.

So, in terms of the ABCI interface, they will be calling the application in this sequence:

PrepareProposal(N) -> ProcessProposal(N) -> PrepareProposal(N+1) -> ProcessProposal (N+1) -> PrepareProposal(N+2) -> ProcessProposal(N+2) -> FinalizeBlock(N)

Which is quite different from a PBFT algorithm (such as cometBFT)

PrepareProposal(N) -> ProcessProposal(N) -> FinalizeBlock(N)

In the current implementation, finalizeState is just one state, and it's updated in InitChain and ProcessProposal, however, this is problematic for a pipelined calling sequence. In the case above, after calling ProcessProposal(N+2), the finalizeState will be updated to (N+2), and when we try to finalize (N), we can't get the correct state.

Description

In the commits of this PR, I kept the interface of the state manager as-is for easier integration. In the state manager, finalizeState is now defined as a sorted heap (by height and timestamp in headInfo). This way, ProcessProposal only pushs state into the heap, and in FinalizeBlock the state is finalized only if it matches with request by height and hash.

Summary by CodeRabbit

  • New Features
    • Improved block finalization accuracy by ensuring state management now supports multiple finalize states, ordered by block height and time.
  • Bug Fixes
    • Enhanced correctness during block replay and finalization by matching finalize states exactly to the requested block height and hash.

…d consensus algorithm such as HotStuff-pipeline
Copy link
Contributor

coderabbitai bot commented Jun 27, 2025

📝 Walkthrough

Walkthrough

The changes introduce a priority queue (min-heap) to manage multiple finalize states in the state manager, replacing the previous single-state approach. Methods for getting, setting, and clearing finalize states now interact with this heap. Block processing logic is updated to ensure finalize state selection matches block height and hash, improving accuracy during block replay or finalization.

Changes

File(s) Change Summary
baseapp/abci.go Updated block proposal and finalization logic to handle consensus hash and to iterate over finalize states, ensuring correct state selection by height and hash.
baseapp/state/manager.go Replaced single finalize state with a min-heap of states; introduced MinHeap type and updated all relevant methods to use the heap for managing finalize states. Added consensus hash to header info.

Sequence Diagram(s)

sequenceDiagram
    participant ConsensusEngine
    participant BaseApp
    participant StateManager (MinHeap)
    participant Store

    ConsensusEngine->>BaseApp: ProcessProposal(req)
    BaseApp->>StateManager: SetState(ExecModeFinalize, ..., header{ConsensusHash: req.Hash}, ...)
    StateManager->>StateManager: Push new State onto MinHeap

    ConsensusEngine->>BaseApp: internalFinalizeBlock(height, hash)
    loop Until matching finalize state found or heap exhausted
        BaseApp->>StateManager: GetState(ExecModeFinalize)
        alt Heap empty or no match
            BaseApp->>StateManager: ClearState(ExecModeFinalize)
        else Matching state found
            BaseApp->>Store: Use state for finalization
        end
    end
    alt No matching state found after loop
        BaseApp->>StateManager: SetState(ExecModeFinalize, ..., header, ...)
    end
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
baseapp/abci.go (1)

749-770: Consider improving readability of the state matching logic.

The implementation correctly handles finding the appropriate finalize state from the heap. However, the condition on line 763 could be more readable:

-		if (req.Height == app.initialHeight && firstState.Context().HeaderInfo().Height == app.initialHeight) || (req.Height == firstState.Context().HeaderInfo().Height && bytes.Equal(req.Hash, firstState.Context().HeaderInfo().Hash)) {
+		// Match state for initial height (special case) or by exact height and hash
+		isInitialHeightMatch := req.Height == app.initialHeight && firstState.Context().HeaderInfo().Height == app.initialHeight
+		isExactMatch := req.Height == firstState.Context().HeaderInfo().Height && bytes.Equal(req.Hash, firstState.Context().HeaderInfo().Hash)
+		
+		if isInitialHeightMatch || isExactMatch {
baseapp/state/manager.go (1)

41-41: Simplify the Less method implementation.

The MinHeap implementation correctly orders states by height and time. However, the Less method can be simplified:

 func (h MinHeap) Less(i, j int) bool {
-	if h[i].ctx.BlockHeight() < h[j].ctx.BlockHeight() {
-		return true
-	} else if h[i].ctx.BlockHeight() == h[j].ctx.BlockHeight() && h[i].ctx.BlockTime().Before(h[j].ctx.BlockTime()) {
-		return true
-	} else {
-		return false
-	}
+	if h[i].ctx.BlockHeight() != h[j].ctx.BlockHeight() {
+		return h[i].ctx.BlockHeight() < h[j].ctx.BlockHeight()
+	}
+	return h[i].ctx.BlockTime().Before(h[j].ctx.BlockTime())
 }

Also applies to: 47-59

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between da39d1b and 3932849.

📒 Files selected for processing (2)
  • baseapp/abci.go (3 hunks)
  • baseapp/state/manager.go (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
baseapp/abci.go (2)
baseapp/state/state.go (1)
  • State (11-16)
types/context.go (1)
  • Context (40-67)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (6)
baseapp/abci.go (1)

493-493: LGTM! Consensus hash properly propagated to state manager.

The addition of ConsensusHash to the header ensures that the block hash is available in the state for later matching during finalization.

baseapp/state/manager.go (5)

74-79: LGTM! Proper heap initialization.

The MinHeap is correctly initialized as an empty heap with heap.Init called as required by the container/heap package.


88-91: LGTM! Safe retrieval of the minimum state.

The implementation correctly returns the top element (minimum by height/time) from the heap with proper nil handling for empty heap.


119-119: LGTM! Hash field properly added to header info.

The consensus hash is correctly stored in the header info, enabling state matching by hash in the finalization logic.


143-143: LGTM! States correctly pushed to heap.

Using heap.Push ensures the heap property is maintained when adding new finalize states.


164-166: LGTM! Safe removal of the minimum state.

The implementation correctly removes the top element from the heap with proper empty check to prevent panic.

@simonzg
Copy link
Author

simonzg commented Jun 30, 2025

Any thoughts on this? @aljo242

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant