Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: optimistic execution consensus v2 #22560

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

randygrok
Copy link
Collaborator

@randygrok randygrok commented Nov 19, 2024

Description

Closes: #XXXX


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features
    • Introduced optimistic execution functionality within the consensus mechanism.
    • New test suite for validating optimistic execution behavior.
  • Bug Fixes
    • Enhanced error handling related to optimistic execution scenarios.
  • Documentation
    • Added comments and structured code to improve clarity on optimistic execution processes.

Copy link
Contributor

coderabbitai bot commented Nov 19, 2024

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the consensus mechanism in the CometBFT server, primarily by adding optimistic execution functionality. A new field is added to the Consensus struct, along with methods to manage optimistic execution states. The PrepareProposal and ProcessProposal methods are updated to handle potential execution overlaps. Additionally, a new file is created for the OptimisticExecution struct, which manages execution contexts, and corresponding tests are implemented to validate this functionality.

Changes

File Change Summary
server/v2/cometbft/abci.go - Added field optimisticExec *oe.OptimisticExecution to Consensus struct.
- Added method SetOptimisticExecution.
- Updated FinalizeBlock, PrepareProposal, and ProcessProposal methods for optimistic execution handling.
server/v2/cometbft/abci_test.go - Added test TestOptimisticExecution for optimistic execution.
- Updated method signatures for getQueryRouterBuilder and getMsgRouterBuilder.
server/v2/cometbft/oe/optimistic_execution.go - Introduced OptimisticExecution struct and related methods for managing optimistic execution.
- Added NewOptimisticExecution and WithAbortRate functions.
server/v2/cometbft/oe/optimistic_execution_test.go - Created tests for OptimisticExecution, including a mock FinalizeBlock function.
server/v2/cometbft/server.go - Added import for cosmossdk.io/server/v2/cometbft/oe.
- Updated New function to include optimistic execution setup.

Possibly related PRs

Suggested labels

C:server/v2, C:server/v2 cometbft, backport/v0.52.x

Suggested reviewers

  • hieuvubk
  • julienrbrt
  • tac0turtle
  • facundomedica
  • kocubinski

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

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

@randygrok your pull request is missing a changelog!

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Nov 19, 2024
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: 8

🧹 Outside diff range and nitpick comments (2)
server/v2/cometbft/oe/optimistic_execution_test.go (1)

14-16: Enhance test helper function coverage

The current helper function only tests the error path. Consider expanding it to:

  1. Add documentation explaining its purpose
  2. Support both success and failure scenarios
  3. Make it parameterized for different test cases
+// testFinalizeBlock is a test helper that simulates finalization responses
+// for optimistic execution testing
 func testFinalizeBlock(_ context.Context, _ *abci.FinalizeBlockRequest) (*abci.FinalizeBlockResponse, error) {
-	return nil, errors.New("test error")
+	switch {
+	case len(req.Hash) == 0:
+		return nil, errors.New("test error")
+	default:
+		return &abci.FinalizeBlockResponse{}, nil
+	}
 }
server/v2/cometbft/abci_test.go (1)

721-792: Consider adding a test case for successful optimistic execution

Currently, the TestOptimisticExecution function simulates an error scenario by having optimisticMockFunc return an error. To thoroughly validate the optimistic execution feature, it would be beneficial to include a test case where optimisticMockFunc completes successfully. This would verify the behavior when optimistic execution proceeds without errors and ensures that both success and failure paths are adequately tested.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b1f9598 and 857f14c.

📒 Files selected for processing (5)
  • server/v2/cometbft/abci.go (8 hunks)
  • server/v2/cometbft/abci_test.go (4 hunks)
  • server/v2/cometbft/oe/optimistic_execution.go (1 hunks)
  • server/v2/cometbft/oe/optimistic_execution_test.go (1 hunks)
  • server/v2/cometbft/server.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
server/v2/cometbft/abci.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/cometbft/abci_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

server/v2/cometbft/oe/optimistic_execution.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/cometbft/oe/optimistic_execution_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

server/v2/cometbft/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (11)
server/v2/cometbft/oe/optimistic_execution_test.go (2)

1-12: LGTM: Clean package structure and imports

The package name and imports are well-organized and appropriate for the test file.


1-34: Verify test coverage for optimistic execution implementation

Let's ensure adequate test coverage for the optimistic execution functionality.

✅ Verification successful

Test coverage is comprehensive for optimistic execution implementation

The test coverage analysis shows that all critical methods of the OptimisticExecution struct are being tested:

  • Constructor (NewOptimisticExecution) and configuration (WithAbortRate)
  • Core functionality methods: Execute, WaitResult, AbortIfNeeded, Reset
  • State check methods: Enabled, Initialized

The test file includes:

  • Error handling verification
  • Hash mismatch scenarios
  • State transitions (initialization, execution, reset)
  • Proper mutex handling through concurrent operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check test coverage for the optimistic execution package

# Find the implementation file
implementation_file=$(fd -e go -E '*_test.go' . server/v2/cometbft/oe)

# Run coverage analysis
go test -coverprofile=coverage.out ./server/v2/cometbft/oe/...
go tool cover -func=coverage.out | grep -E "optimistic_execution.go.*statements"

Length of output: 392


Script:

#!/bin/bash
# Let's analyze the test coverage by examining the test file against the implementation

# First, find all functions in the implementation file
echo "=== Implementation functions ==="
ast-grep --pattern 'func $_($$$) $$$' server/v2/cometbft/oe/optimistic_execution.go

# Then, find all test functions to verify coverage
echo -e "\n=== Test functions ==="
ast-grep --pattern 'func Test$_($$$) $$$' server/v2/cometbft/oe/optimistic_execution_test.go

# Also check for any mock/helper test functions
echo -e "\n=== Helper/Mock functions ==="
ast-grep --pattern 'func $_($$$) $$$' server/v2/cometbft/oe/optimistic_execution_test.go

Length of output: 3231


Script:

#!/bin/bash
# Let's examine the implementation methods to ensure all are covered by tests

# Get all methods of OptimisticExecution struct
echo "=== OptimisticExecution methods ==="
ast-grep --pattern 'func (oe *OptimisticExecution) $_($$$) $$$' server/v2/cometbft/oe/optimistic_execution.go

# Get the struct definition to understand all fields that need testing
echo -e "\n=== OptimisticExecution struct ==="
ast-grep --pattern 'type OptimisticExecution struct {$$$}' server/v2/cometbft/oe/optimistic_execution.go

Length of output: 8522

server/v2/cometbft/server.go (2)

5-5: LGTM: Import statement follows Go conventions

The import statement for the optimistic execution package is correctly placed and follows the project's module structure.


137-138: Consider adding configuration and documentation for optimistic execution

While the integration point is correctly placed, there are a few considerations:

  1. Consider adding configuration options to enable/disable optimistic execution
  2. Add error handling for the setup process
  3. Document the feature and its implications in the code

Let's verify the configuration and documentation:

server/v2/cometbft/abci.go (3)

5-5: Import of oe package added correctly

The import of cosmossdk.io/server/v2/cometbft/oe is required for the OptimisticExecution feature.


16-16: Import of protoreflect package added correctly

The import of google.golang.org/protobuf/reflect/protoreflect is necessary for handling gRPC queries.


126-128: SetOptimisticExecution method added appropriately

The SetOptimisticExecution method correctly assigns the optimisticExec field.

server/v2/cometbft/abci_test.go (4)

5-5: Approved: Added import for optimistic execution package

The import of "cosmossdk.io/server/v2/cometbft/oe" is appropriate and necessary for implementing optimistic execution functionality in the tests.


8-8: Approved: Included standard errors package for error handling

Adding the "errors" package is essential for error generation and handling within the test code.


60-63: Approved: Enhanced generic parameters in getQueryRouterBuilder

The addition of generic parameters U and UT improves the flexibility and type safety of the getQueryRouterBuilder function, allowing it to handle a wider range of message types.


90-93: Approved: Enhanced generic parameters in getMsgRouterBuilder

The addition of generic parameters U and UT enhances the getMsgRouterBuilder function's capability to work with various message types, increasing its reusability and type safety.

Comment on lines +18 to +34
func TestOptimisticExecution(t *testing.T) {
oe := NewOptimisticExecution(log.NewNopLogger(), testFinalizeBlock)
assert.True(t, oe.Enabled())
oe.Execute(&abci.ProcessProposalRequest{
Hash: []byte("test"),
})
assert.True(t, oe.Initialized())

resp, err := oe.WaitResult()
assert.Nil(t, resp)
assert.EqualError(t, err, "test error")

assert.False(t, oe.AbortIfNeeded([]byte("test")))
assert.True(t, oe.AbortIfNeeded([]byte("wrong_hash")))

oe.Reset()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve test coverage and organization

While the test covers basic functionality, it needs improvements in several areas:

  1. Missing test cases for concurrent execution
  2. No validation of actual response content
  3. Lack of edge cases
  4. No cleanup mechanism

Consider restructuring the test like this:

func TestOptimisticExecution(t *testing.T) {
    tests := []struct {
        name     string
        hash     []byte
        wantErr  bool
        errMsg   string
        setup    func(*OptimisticExecution)
        validate func(*testing.T, *OptimisticExecution)
    }{
        {
            name:    "successful execution",
            hash:    []byte("test"),
            wantErr: false,
        },
        {
            name:    "error case",
            hash:    []byte{},
            wantErr: true,
            errMsg:  "test error",
        },
        // Add more test cases
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            oe := NewOptimisticExecution(log.NewNopLogger(), testFinalizeBlock)
            defer oe.Reset() // Ensure cleanup

            if tt.setup != nil {
                tt.setup(oe)
            }

            oe.Execute(&abci.ProcessProposalRequest{Hash: tt.hash})
            
            resp, err := oe.WaitResult()
            if tt.wantErr {
                assert.Error(t, err)
                assert.Equal(t, tt.errMsg, err.Error())
                assert.Nil(t, resp)
            } else {
                assert.NoError(t, err)
                assert.NotNil(t, resp)
            }

            if tt.validate != nil {
                tt.validate(t, oe)
            }
        })
    }
}

// Add concurrent execution test
func TestOptimisticExecutionConcurrent(t *testing.T) {
    oe := NewOptimisticExecution(log.NewNopLogger(), testFinalizeBlock)
    defer oe.Reset()

    const numGoroutines = 10
    var wg sync.WaitGroup
    wg.Add(numGoroutines)

    for i := 0; i < numGoroutines; i++ {
        go func() {
            defer wg.Done()
            oe.Execute(&abci.ProcessProposalRequest{Hash: []byte("test")})
            _, _ = oe.WaitResult()
        }()
    }

    wg.Wait()
}

defer oe.mtx.Unlock()

if !bytes.Equal(oe.request.Hash, reqHash) {
oe.logger.Error("OE aborted due to hash mismatch", "oe_hash", hex.EncodeToString(oe.request.Hash), "req_hash", hex.EncodeToString(reqHash), "oe_height", oe.request.Height, "req_height", oe.request.Height)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the logging of req_height in error message

In the error log within AbortIfNeeded, both oe_height and req_height are using oe.request.Height, which may not accurately reflect the current request's height. This could lead to confusion when diagnosing issues.

Adjust the log statement to use the correct height for req_height:

	oe.logger.Error("OE aborted due to hash mismatch",
		"oe_hash", hex.EncodeToString(oe.request.Hash),
		"req_hash", hex.EncodeToString(reqHash),
		"oe_height", oe.request.Height,
-		"req_height", oe.request.Height)
+		"req_height", currentRequestHeight)

If currentRequestHeight is not available in this context, you may need to pass the request's height as an additional parameter to AbortIfNeeded.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +131 to +134
if !bytes.Equal(oe.request.Hash, reqHash) {
oe.logger.Error("OE aborted due to hash mismatch", "oe_hash", hex.EncodeToString(oe.request.Hash), "req_hash", hex.EncodeToString(reqHash), "oe_height", oe.request.Height, "req_height", oe.request.Height)
oe.cancelFunc()
return true
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent potential nil pointer dereference when accessing oe.request

In the AbortIfNeeded method, if oe.request is nil, accessing oe.request.Hash will cause a runtime panic. This could happen if AbortIfNeeded is called before Execute, or if Execute failed to initialize oe.request.

Consider adding a nil check for oe.request before accessing its fields:

+	if oe.request == nil {
+		oe.logger.Error("OE aborted due to missing request")
+		oe.cancelFunc()
+		return true
+	}
	if !bytes.Equal(oe.request.Hash, reqHash) {
		oe.logger.Error("OE aborted due to hash mismatch", "oe_hash", hex.EncodeToString(oe.request.Hash), "req_hash", hex.EncodeToString(reqHash), "oe_height", oe.request.Height, "req_height", oe.request.Height)
		oe.cancelFunc()
		return true
	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if !bytes.Equal(oe.request.Hash, reqHash) {
oe.logger.Error("OE aborted due to hash mismatch", "oe_hash", hex.EncodeToString(oe.request.Hash), "req_hash", hex.EncodeToString(reqHash), "oe_height", oe.request.Height, "req_height", oe.request.Height)
oe.cancelFunc()
return true
if oe.request == nil {
oe.logger.Error("OE aborted due to missing request")
oe.cancelFunc()
return true
}
if !bytes.Equal(oe.request.Hash, reqHash) {
oe.logger.Error("OE aborted due to hash mismatch", "oe_hash", hex.EncodeToString(oe.request.Hash), "req_hash", hex.EncodeToString(reqHash), "oe_height", oe.request.Height, "req_height", oe.request.Height)
oe.cancelFunc()
return true

Comment on lines +71 to +74
// optimisticExec contains the context required for Optimistic Execution,
// including the goroutine handling.This is experimental and must be enabled
// by developers.
optimisticExec *oe.OptimisticExecution
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider initializing optimisticExec to avoid nil references

The optimisticExec field is added to the Consensus struct but may remain nil if SetOptimisticExecution is not called. To prevent potential nil pointer dereferences, consider initializing optimisticExec during construction or ensure it is always set before use.

Comment on lines +442 to +452
// Since the application can get access to FinalizeBlock state and write to it,
// we must be sure to reset it in case ProcessProposal timeouts and is called
// again in a subsequent round. However, we only want to do this after we've
// processed the first block, as we want to avoid overwriting the finalizeState
// after state changes during InitChain.
if req.Height > int64(c.initialHeight) {
// abort any running OE
c.optimisticExec.Abort()
//c.setState(execModeFinalize, header)
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential nil pointer dereference in ProcessProposal

In ProcessProposal, c.optimisticExec.Abort() is invoked without verifying if optimisticExec is nil. This could lead to a runtime panic if optimisticExec is not initialized.

Apply this diff to add a nil check before calling Abort():

         if req.Height > int64(c.initialHeight) {
             // abort any running OE
-            c.optimisticExec.Abort()
+            if c.optimisticExec != nil {
+                c.optimisticExec.Abort()
+            }
             //c.setState(execModeFinalize, header)
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Since the application can get access to FinalizeBlock state and write to it,
// we must be sure to reset it in case ProcessProposal timeouts and is called
// again in a subsequent round. However, we only want to do this after we've
// processed the first block, as we want to avoid overwriting the finalizeState
// after state changes during InitChain.
if req.Height > int64(c.initialHeight) {
// abort any running OE
c.optimisticExec.Abort()
//c.setState(execModeFinalize, header)
}
// Since the application can get access to FinalizeBlock state and write to it,
// we must be sure to reset it in case ProcessProposal timeouts and is called
// again in a subsequent round. However, we only want to do this after we've
// processed the first block, as we want to avoid overwriting the finalizeState
// after state changes during InitChain.
if req.Height > int64(c.initialHeight) {
// abort any running OE
if c.optimisticExec != nil {
c.optimisticExec.Abort()
}
//c.setState(execModeFinalize, header)
}

Comment on lines +490 to +505
if c.optimisticExec.Initialized() {
// check if the hash we got is the same as the one we are executing
aborted := c.optimisticExec.AbortIfNeeded(req.Hash)

// Wait for the OE to finish, regardless of whether it was aborted or not
res, err := c.optimisticExec.WaitResult()

// only return if we are not aborting
if !aborted {
return res, err
}

// if it was aborted, we need to reset the state
c.optimisticExec.Reset()
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential nil pointer dereference in FinalizeBlock

In FinalizeBlock, c.optimisticExec.Initialized() is called without checking if optimisticExec is nil. This could cause a runtime panic if optimisticExec is not initialized.

Apply this diff to add a nil check before calling Initialized():

     if c.optimisticExec != nil && c.optimisticExec.Initialized() {
         // Existing code...
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if c.optimisticExec.Initialized() {
// check if the hash we got is the same as the one we are executing
aborted := c.optimisticExec.AbortIfNeeded(req.Hash)
// Wait for the OE to finish, regardless of whether it was aborted or not
res, err := c.optimisticExec.WaitResult()
// only return if we are not aborting
if !aborted {
return res, err
}
// if it was aborted, we need to reset the state
c.optimisticExec.Reset()
}
if c.optimisticExec != nil && c.optimisticExec.Initialized() {
// check if the hash we got is the same as the one we are executing
aborted := c.optimisticExec.AbortIfNeeded(req.Hash)
// Wait for the OE to finish, regardless of whether it was aborted or not
res, err := c.optimisticExec.WaitResult()
// only return if we are not aborting
if !aborted {
return res, err
}
// if it was aborted, we need to reset the state
c.optimisticExec.Reset()
}

Comment on lines +398 to +405
// Abort any running OE so it cannot overlap with `PrepareProposal`. This could happen if optimistic
// `internalFinalizeBlock` from previous round takes a long time, but consensus has moved on to next round.
// Overlap is undesirable, since `internalFinalizeBlock` and `PrepareProoposal` could share access to
// in-memory structs depending on application implementation.
// No-op if OE is not enabled.
// Similar call to Abort() is done in `ProcessProposal`.
c.optimisticExec.Abort()

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential nil pointer dereference in PrepareProposal

In PrepareProposal, c.optimisticExec.Abort() is called without checking if optimisticExec is nil. If optimisticExec is nil, this will cause a runtime panic.

Apply this diff to add a nil check before calling Abort():

     // Similar call to Abort() is done in `ProcessProposal`.
-    c.optimisticExec.Abort()
+    if c.optimisticExec != nil {
+        c.optimisticExec.Abort()
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Abort any running OE so it cannot overlap with `PrepareProposal`. This could happen if optimistic
// `internalFinalizeBlock` from previous round takes a long time, but consensus has moved on to next round.
// Overlap is undesirable, since `internalFinalizeBlock` and `PrepareProoposal` could share access to
// in-memory structs depending on application implementation.
// No-op if OE is not enabled.
// Similar call to Abort() is done in `ProcessProposal`.
c.optimisticExec.Abort()
// Abort any running OE so it cannot overlap with `PrepareProposal`. This could happen if optimistic
// `internalFinalizeBlock` from previous round takes a long time, but consensus has moved on to next round.
// Overlap is undesirable, since `internalFinalizeBlock` and `PrepareProoposal` could share access to
// in-memory structs depending on application implementation.
// No-op if OE is not enabled.
// Similar call to Abort() is done in `ProcessProposal`.
if c.optimisticExec != nil {
c.optimisticExec.Abort()
}

Comment on lines +468 to +478
// Only execute optimistic execution if the proposal is accepted, OE is
// enabled and the block height is greater than the initial height. During
// the first block we'll be carrying state from InitChain, so it would be
// impossible for us to easily revert.
// After the first block has been processed, the next blocks will get executed
// optimistically, so that when the ABCI client calls `FinalizeBlock` the app
// can have a response ready.
if c.optimisticExec.Enabled() && req.Height > int64(c.initialHeight) {
c.optimisticExec.Execute(req)
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential nil pointer dereference when checking optimisticExec.Enabled()

In ProcessProposal, c.optimisticExec.Enabled() is called without verifying if optimisticExec is nil. This may result in a runtime panic if optimisticExec is not set.

Apply this diff to add a nil check:

     if c.optimisticExec != nil && c.optimisticExec.Enabled() && req.Height > int64(c.initialHeight) {
         c.optimisticExec.Execute(req)
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Only execute optimistic execution if the proposal is accepted, OE is
// enabled and the block height is greater than the initial height. During
// the first block we'll be carrying state from InitChain, so it would be
// impossible for us to easily revert.
// After the first block has been processed, the next blocks will get executed
// optimistically, so that when the ABCI client calls `FinalizeBlock` the app
// can have a response ready.
if c.optimisticExec.Enabled() && req.Height > int64(c.initialHeight) {
c.optimisticExec.Execute(req)
}
// Only execute optimistic execution if the proposal is accepted, OE is
// enabled and the block height is greater than the initial height. During
// the first block we'll be carrying state from InitChain, so it would be
// impossible for us to easily revert.
// After the first block has been processed, the next blocks will get executed
// optimistically, so that when the ABCI client calls `FinalizeBlock` the app
// can have a response ready.
if c.optimisticExec != nil && c.optimisticExec.Enabled() && req.Height > int64(c.initialHeight) {
c.optimisticExec.Execute(req)
}

Comment on lines +106 to +118
go func() {
start := time.Now()
resp, err := oe.finalizeBlockFunc(ctx, oe.request)

oe.mtx.Lock()

executionTime := time.Since(start)
oe.logger.Debug("OE finished", "duration", executionTime.String(), "height", oe.request.Height, "hash", hex.EncodeToString(oe.request.Hash))
oe.response, oe.err = resp, err

close(oe.stopCh)
oe.mtx.Unlock()
}()

Check notice

Code scanning / CodeQL

Spawning a Go routine Note

Spawning a Go routine may be a possible source of non-determinism
oe.initialized = true

go func() {
start := time.Now()

Check warning

Code scanning / CodeQL

Calling the system time Warning

Calling the system time may be a possible source of non-determinism

Choose a reason for hiding this comment

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

Copilot reviewed 5 out of 5 changed files in this pull request and generated no suggestions.

@@ -67,6 +68,11 @@ type Consensus[T transaction.Tx] struct {
extendVote handlers.ExtendVoteHandler
checkTxHandler handlers.CheckTxHandler[T]

// optimisticExec contains the context required for Optimistic Execution,
// including the goroutine handling.This is experimental and must be enabled
Copy link
Member

@julienrbrt julienrbrt Nov 19, 2024

Choose a reason for hiding this comment

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

let's always enable it, and possibly remove the way to disable it (cc @tac0turtle)

c.optimisticExec.Reset()
}

return c.internalFinalizeBlock(ctx, req)
Copy link
Member

@facundomedica facundomedica Nov 20, 2024

Choose a reason for hiding this comment

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

Can't comment on the right line below, but internalFinalizeBlock should not commit to store. I think internalFinalizeBlock should return stateChanges, then everything else should be done on the actual FinalizeBlock call.
This is because there could be an equivocation and we could be running the wrong finalize block request, and this would result in us writing bad data to disk. Also, if internalFinalizeBlock finishes then ProcessProposal would be accessing data that is in the "future"

Choose a reason for hiding this comment

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

Copilot reviewed 5 out of 5 changed files in this pull request and generated no suggestions.

Comments skipped due to low confidence (1)

server/v2/cometbft/abci_test.go:784

  • The comment should be 'Because it is aborted, the result comes from the normal execution'.
// Because is aborted, the result comes from the normal execution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:server/v2 cometbft C:server/v2 Issues related to server/v2
Projects
Status: 👀 Waiting / In review
Development

Successfully merging this pull request may close these issues.

4 participants