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(async): Async PreBlock part 1 #1511

Merged
merged 20 commits into from
Jun 18, 2024
Merged

feat(async): Async PreBlock part 1 #1511

merged 20 commits into from
Jun 18, 2024

Conversation

itsdevbear
Copy link
Contributor

@itsdevbear itsdevbear commented Jun 17, 2024

Summary by CodeRabbit

  • New Features

    • Introduced the ABCIMiddleware for enhanced block processing, proposal handling, and validator updates management.
    • Added ValidatorUpdates type with methods to remove duplicates and sort updates.
  • Bug Fixes

    • Improved management of validator data by eliminating duplicates and sorting entries.
  • Refactor

    • Renamed ValidatorMiddleware to ABCIMiddleware across several components for consistency.
    • Removed outdated finalize block middleware functions.
  • Tests

    • Added tests for ValidatorUpdates to ensure correct removal of duplicates and sorting.

@itsdevbear itsdevbear requested a review from ocnc as a code owner June 17, 2024 21:15
Copy link
Contributor

coderabbitai bot commented Jun 17, 2024

Walkthrough

The updates primarily involve renaming components and functions related to middleware in the node-core package to maintain consistency with the new ABCI (Application Blockchain Interface) terminology. Additionally, validator updates are enhanced to manage duplicates and sorting, and new functionality is added to the BeaconState interface for improved blockchain state management.

Changes

Files Change Summary
middleware.go (node-core/pkg/components) Renamed ValidatorMiddlewareInput to ABCIMiddlewareInput and updated related functions and fields.
creator.go (node-core/pkg/builder) Replaced use of validatorMiddleware and finalizeBlockMiddleware with abciMiddleware in setting up components.
empty_components.go (node-core/pkg/builder) Renamed emptyValidatorMiddleware to emptyABCIMiddleware and removed emptyFinalizeBlockMiddleware.
extended_options.go (node-core/pkg/builder) Modified signatures of WithPrepareProposal and WithProcessProposal functions to add an extra argument.
defaults.go (node-core/pkg/components) Removed ProvideFinalizeBlockMiddleware and replaced ProvideValidatorMiddleware with ProvideABCIMiddleware.
module.go (node-core/pkg/components/module) Transitioned from FinalizeBlockMiddleware to ABCIMiddleware in AppModule and related methods.
validator_update.go (primitives/pkg/transition) Introduced functionality to remove duplicate validator updates and sort updates within ValidatorUpdates.
validator_update_test.go (primitives/pkg/transition) Added test functions for validating the removal of duplicates and sorting in ValidatorUpdates.
abci.go (runtime/pkg/middleware) Introduced with middleware logic for block processing stages, adding InitGenesis, PrepareProposal, ProcessProposal, PreBlock, and EndBlock methods.
middleware.go (runtime/pkg/middleware) Added imports, restructured ABCIMiddleware with new fields and methods, and introduced NewABCIMiddleware function.
types.go (runtime/pkg/middleware) Added GetBlockRootAtIndex and ValidatorIndexByCometBFTAddress methods to BeaconState interface.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant Middleware as ABCIMiddleware
    participant Chain as ChainService
    participant Validator as ValidatorService
    participant Metrics as TelemetrySink

    App->>Middleware: Initialize ABCIMiddleware
    Middleware->>Chain: Setup ChainService
    Middleware->>Validator: Setup ValidatorService
    Middleware->>Metrics: Setup TelemetrySink

    App->>Middleware: InitGenesis(ctx, bz)
    Middleware->>Chain: InitGenesis(ctx, bz)

    App->>Middleware: PrepareProposal(ctx, req)
    Middleware->>Chain: PrepareProposal(ctx, req)

    App->>Middleware: ProcessProposal(ctx, req)
    Middleware->>Chain: ProcessProposal(ctx, req)

    App->>Middleware: PreBlock(ctx, req)
    Middleware->>Chain: PreBlock(ctx, req)

    App->>Middleware: EndBlock(ctx)
    Middleware->>Chain: EndBlock(ctx)
Loading

Poem

In code's embrace, we dance anew,
Middleware shines in ABCI's hue,
Validators sorted, and duplicates flee,
Our blockchain hums in harmony.
Beacon's state, with fields so bright,
Together we'll scale new height.
🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

codecov bot commented Jun 17, 2024

Codecov Report

Attention: Patch coverage is 9.77011% with 157 lines in your changes missing coverage. Please review.

Project coverage is 24.62%. Comparing base (eb477fe) to head (2addf0c).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1511      +/-   ##
==========================================
+ Coverage   24.41%   24.62%   +0.20%     
==========================================
  Files         255      255              
  Lines       11360    11333      -27     
  Branches       18       18              
==========================================
+ Hits         2774     2791      +17     
+ Misses       8420     8376      -44     
  Partials      166      166              
Files Coverage Δ
mod/node-core/pkg/components/defaults.go 0.00% <ø> (ø)
mod/primitives/pkg/transition/validator_update.go 100.00% <100.00%> (ø)
mod/node-core/pkg/builder/empty_components.go 0.00% <0.00%> (ø)
mod/node-core/pkg/builder/extended_options.go 0.00% <0.00%> (ø)
mod/node-core/pkg/components/middleware.go 0.00% <0.00%> (ø)
mod/node-core/pkg/components/module/module.go 0.00% <0.00%> (ø)
mod/runtime/pkg/middleware/metrics.go 0.00% <0.00%> (ø)
mod/node-core/pkg/builder/creator.go 0.00% <0.00%> (ø)
mod/runtime/pkg/middleware/middleware.go 0.00% <0.00%> (ø)
mod/runtime/pkg/middleware/abci.go 0.00% <0.00%> (ø)

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

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 1abdb40 and 54a8b1f.

Files selected for processing (4)
  • mod/node-core/pkg/components/middleware.go (2 hunks)
  • mod/runtime/pkg/middleware/errors.go (1 hunks)
  • mod/runtime/pkg/middleware/finalize.go (4 hunks)
  • mod/runtime/pkg/middleware/helpers.go (1 hunks)
Additional comments not posted (5)
mod/runtime/pkg/middleware/errors.go (1)

30-33: The addition of ErrBadExtractBlockAndBlocks enhances error specificity for block extraction issues.

mod/runtime/pkg/middleware/helpers.go (1)

32-60: The function handleValUpdateConversion is well-implemented with deduplication, sorting, and conversion logic. However, ensure that the error handling in convertValidatorUpdate is robust, especially since it can return ErrUndefinedValidatorUpdate if an update is nil.

mod/node-core/pkg/components/middleware.go (1)

59-60: The simplification in FinalizeBlockMiddlewareInput by removing TelemetrySink is a positive change, reducing coupling and potential side effects. Ensure all dependencies are correctly adjusted throughout the application to accommodate this change.

mod/runtime/pkg/middleware/finalize.go (2)

120-141: The asynchronous implementation in PreBlock is robust, but ensure proper synchronization and error handling, especially when using channels for error and validator updates communication. Consider adding more detailed logging for debugging and monitoring these asynchronous operations.


150-163: In EndBlock, the handling of errors and the deduplication of validator updates are crucial. Ensure that the error handling logic is consistent and that potential issues with channel communication are addressed, particularly in high-load scenarios.

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

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 54a8b1f and d8e8f22.

Files ignored due to path filters (3)
  • beacond/go.sum is excluded by !**/*.sum
  • mod/cli/go.sum is excluded by !**/*.sum
  • mod/node-core/go.sum is excluded by !**/*.sum
Files selected for processing (3)
  • beacond/go.mod (2 hunks)
  • mod/cli/go.mod (2 hunks)
  • mod/node-core/go.mod (1 hunks)
Additional comments not posted (7)
mod/node-core/go.mod (1)

20-20: Updated dependency version for mod/cli aligns with project-wide updates.

mod/cli/go.mod (4)

21-21: Updated dependency version for mod/node-core aligns with project-wide updates.


22-22: Updated dependency version for mod/primitives aligns with project-wide updates.


61-61: Updated dependency version for mod/beacon aligns with project-wide updates.


63-63: Updated dependency version for mod/execution aligns with project-wide updates.

beacond/go.mod (2)

15-16: Ensure that the updated versions of github.com/berachain/beacon-kit/mod/cli and github.com/berachain/beacon-kit/mod/node-core are compatible with other project modules.


52-52: The updated versions of mod/async, mod/beacon, mod/execution, mod/primitives, and mod/runtime should be thoroughly tested to ensure they meet the new requirements introduced in this pull request.

Also applies to: 58-58, 63-63, 64-64

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: 4

Outside diff range comments (3)
mod/node-core/pkg/components/types.go (1)

[!TIP]
Codebase Verification

The review comment is correct. There are still references to FinalizeBlockMiddleware in the codebase, specifically in the files module.go and middleware.go. These references need to be updated to ensure consistency with the new middleware names.

  • module.go:
    • Line 49: // It is a wrapper around the FinalizeBlockMiddleware and ABCIMiddleware.
  • middleware.go:
    • Line 56: // FinalizeBlockMiddlewareInput is the input for the finalize block middleware.
    • Line 57: type FinalizeBlockMiddlewareInput struct {

Please update these references to align with the new middleware names.

Analysis chain

Line range hint 1-1: The type aliases in this file are correctly updated to reflect the new middleware names. Ensure that all references to these types across the project are updated to prevent any type mismatches.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all references to the types are updated across the project.

# Test: Search for old type names and ensure they are replaced.
rg --type go "ValidatorMiddleware|FinalizeBlockMiddleware"

Length of output: 389



Script:

#!/bin/bash
# Extract specific lines from module.go and middleware.go containing old type names

# Extract lines from module.go
rg --type go --line-number 'FinalizeBlockMiddleware' mod/node-core/pkg/components/module/module.go

# Extract lines from middleware.go
rg --type go --line-number 'FinalizeBlockMiddleware' mod/node-core/pkg/components/middleware.go

Length of output: 400

mod/runtime/pkg/middleware/validator.go (2)

Line range hint 97-148: ### Constructor Function NewABCIMiddleware
The constructor function for ABCIMiddleware is well-implemented. It correctly initializes all the fields including the new channels and the metrics. However, consider adding error handling or validation for the inputs to ensure they are not nil, which could lead to runtime panics.

func NewABCIMiddleware[...] (...) *ABCIMiddleware[...] {
+	if chainSpec == nil || validatorService == nil || chainService == nil || telemetrySink == nil {
+		return nil, errors.New("provided argument cannot be nil")
+	}
	return &ABCIMiddleware[...]{
		...
	}
}

Line range hint 154-211: ### Method Implementations: PrepareProposalHandler and ProcessProposalHandler
Both methods show appropriate use of the new asynchronous channels and error handling. However, there are repeated error checks in goroutines that could be simplified. Additionally, the logging context in ProcessProposalHandler has a typo in the service name.

	g.Go(func() error {
		sidecarsBz, localErr = h.blobGossiper.Publish(gCtx, blobs)
-		if localErr != nil {
-			logger.Error("failed to publish blobs", "error", err)
-		}
+		return localErr
	})
	g.Go(func() error {
		beaconBlockBz, localErr = h.beaconBlockGossiper.Publish(gCtx, blk)
-		if localErr != nil {
-			logger.Error("failed to publish beacon block", "error", err)
-		}
+		return localErr
	})
func (h *ABCIMiddleware[...]) ProcessProposalHandler(...) (...) {
	...
	logger := ctx.Logger().With(
-		"service", "prepare-proposal",
+		"service", "process-proposal",
	)
	...
}
Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between d8e8f22 and 8b3fb3f.

Files selected for processing (9)
  • mod/node-core/pkg/builder/creator.go (3 hunks)
  • mod/node-core/pkg/builder/empty_components.go (2 hunks)
  • mod/node-core/pkg/components/defaults.go (2 hunks)
  • mod/node-core/pkg/components/middleware.go (2 hunks)
  • mod/node-core/pkg/components/module/module.go (2 hunks)
  • mod/node-core/pkg/components/types.go (3 hunks)
  • mod/runtime/pkg/middleware/finalize.go (2 hunks)
  • mod/runtime/pkg/middleware/validator.go (6 hunks)
  • mod/runtime/pkg/middleware/validator_metrics.go (2 hunks)
Additional comments not posted (12)
mod/runtime/pkg/middleware/validator_metrics.go (4)

27-28: Renaming of the metrics struct aligns well with the overall middleware renaming strategy.


33-37: Constructor for ABCIMiddlewareMetrics is correctly implemented to initialize the struct with a telemetry sink.


43-43: Method for measuring proposal preparation duration is implemented correctly.

Also applies to: 43-43


52-52: Method for measuring proposal processing duration is implemented correctly.

Also applies to: 52-52

mod/node-core/pkg/components/middleware.go (1)

30-45: The ABCIMiddlewareInput struct and ProvideABCIMiddleware function are correctly implemented to reflect the new middleware nomenclature.

mod/node-core/pkg/builder/empty_components.go (1)

38-39: Function emptyABCIMiddleware correctly provides an empty instance of ABCIMiddleware.

mod/node-core/pkg/builder/creator.go (2)

53-53: Refactoring to use ABCIMiddleware is consistent with the project-wide changes. Ensure that all dependencies and references to ValidatorMiddleware are updated accordingly.


70-70: The integration of ABCIMiddleware into the application setup process appears correct. However, verify that the PrepareProposalHandler, ProcessProposalHandler, and PreBlock methods of ABCIMiddleware are fully implemented and tested.

Also applies to: 84-85

mod/node-core/pkg/components/module/module.go (1)

119-119: The usage of ABCIMiddleware in the InitGenesis and EndBlock methods is appropriate. Ensure that these methods in ABCIMiddleware handle all expected scenarios and edge cases effectively.

Also applies to: 126-126

mod/runtime/pkg/middleware/finalize.go (2)

30-30: Addition of new imports for error handling and mathematical operations is appropriate for the functionalities described in the modified methods.


113-126: The EndBlock method's implementation using channels for error and validator updates handling is innovative. However, ensure that the error handling logic does not inadvertently suppress important errors, especially in lines 121-123.

Verification successful

The investigation reveals that the error ErrBadExtractBlockAndBlocks is specifically designed to signal an error during the block extraction process and is conditionally suppressed in the EndBlock method. This suppression is intentional and limited to this specific error type, ensuring other errors are not inadvertently suppressed.

  • ErrBadExtractBlockAndBlocks is defined in mod/runtime/pkg/middleware/errors.go.
  • The error is conditionally set to nil in the EndBlock method if it matches ErrBadExtractBlockAndBlocks.

This handling appears to be appropriate and intentional.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify error handling logic in `EndBlock`.

# Test: Check if errors are logged before being suppressed.
rg --type go "log.*err" --glob "*finalize.go"

Length of output: 47



Script:

#!/bin/bash
# Searching the complete implementation of the EndBlock method
ast-grep --lang go --pattern 'func (h $_) EndBlock($_) ($_, $_) {
  $$$
}' 

Length of output: 1648



Script:

#!/bin/bash
# Find the definition and usage of ErrBadExtractBlockAndBlocks
rg 'ErrBadExtractBlockAndBlocks'

Length of output: 445

mod/runtime/pkg/middleware/validator.go (1)

Line range hint 41-94: ### Renaming and Structural Changes
The renaming from ValidatorMiddleware to ABCIMiddleware and the structural changes are consistent with the PR's objectives to transition middleware components. The addition of channels (valUpdatesChannel and errChannel) for asynchronous communication is a significant enhancement.

@@ -55,7 +54,7 @@ func DefaultComponentsWithStandardTypes() []any {
ProvideStorageBackend,
ProvideTelemetrySink,
ProvideTrustedSetup,
ProvideValidatorMiddleware,
ProvideABCIMiddleware,
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the redundant listing of ProvideABCIMiddleware in DefaultComponentsWithStandardTypes.

-		ProvideABCIMiddleware,

Committable suggestion was skipped due to low confidence.

@@ -46,7 +46,7 @@ var (
)

// AppModule implements an application module for the evm module.
// It is a wrapper around the FinalizeBlockMiddleware and ValidatorMiddleware.
// It is a wrapper around the FinalizeBlockMiddleware and ABCIMiddleware.
Copy link
Contributor

Choose a reason for hiding this comment

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

The AppModule struct's documentation should be updated to correctly describe its current functionality, especially since it no longer wraps around FinalizeBlockMiddleware.

Comment on lines +59 to +60
ChainService *ChainService
ChainSpec primitives.ChainSpec
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure that the FinalizeBlockMiddlewareInput struct is still required, as it is defined but not used anywhere in the codebase.

  • mod/node-core/pkg/components/middleware.go: Definition of FinalizeBlockMiddlewareInput
Analysis chain

Ensure that the FinalizeBlockMiddlewareInput struct is still required, as it's not mentioned in the PR changes summary.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Search for usage of `FinalizeBlockMiddlewareInput` to verify its necessity.

# Test: Search for the struct usage. Expect: Usage details or no occurrences.
rg --type go 'FinalizeBlockMiddlewareInput'

Length of output: 252



Script:

#!/bin/bash
# Description: Search for usage of `FinalizeBlockMiddlewareInput` to verify its necessity across the entire codebase.

# Test: Search for the struct usage. Expect: Usage details or no occurrences.
rg 'FinalizeBlockMiddlewareInput'

Length of output: 242

Comment on lines 70 to 100
func (h *ABCIMiddleware[
AvailabilityStoreT,
BeaconBlockT,
BeaconBlockBodyT,
BeaconStateT,
BlobSidecarsT,
]) PreBlock(
ctx sdk.Context, req *cometabci.FinalizeBlockRequest,
) error {
startTime := time.Now()
defer h.metrics.measureEndBlockDuration(startTime)
// Call the function asynchronously
go func() {
blk, blobs, err := encoding.
ExtractBlobsAndBlockFromRequest[BeaconBlockT, BlobSidecarsT](req,
BeaconBlockTxIndex,
BlobSidecarsTxIndex,
h.chainSpec.ActiveForkVersionForSlot(
math.Slot(req.Height),
))

blk, blobs, err := encoding.
ExtractBlobsAndBlockFromRequest[BeaconBlockT, BlobSidecarsT](req,
BeaconBlockTxIndex,
BlobSidecarsTxIndex,
h.chainSpec.ActiveForkVersionForSlot(
math.Slot(req.Height),
))
if err != nil {
h.errChannel <- errors.Join(err, ErrBadExtractBlockAndBlocks)
return
}

if err != nil {
// We want to return nil here to prevent the
// middleware from triggering a panic.
return nil
}
result, err := h.chainService.ProcessBlockAndBlobs(ctx, blk, blobs)
if err != nil {
h.errChannel <- err
} else {
h.valUpdatesChannel <- result
}
}()
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The implementation of asynchronous block processing in the PreBlock method lacks synchronization mechanisms around the errChannel and valUpdatesChannel. This could lead to race conditions.

  • Ensure proper synchronization using primitives like mutexes or wait groups around the usage of errChannel and valUpdatesChannel.
Analysis chain

The implementation of asynchronous block processing in PreBlock is a significant change. Ensure that error handling via errChannel and result handling via valUpdatesChannel are properly synchronized and that there are no race conditions.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify synchronization and absence of race conditions in `PreBlock`.

# Test: Search for synchronization primitives around `errChannel` and `valUpdatesChannel` usage.
rg --type go "(errChannel|valUpdatesChannel)" --context 5

Length of output: 3783

@@ -33,3 +38,26 @@ type ValidatorUpdate struct {
// EffectiveBalance is the effective balance of the validator.
EffectiveBalance math.Gwei
}

// RemoveDuplicates removes duplicate validator updates.
func (vu ValidatorUpdates) RemoveDuplicates() ValidatorUpdates {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@ocnc can you review, you did original work here

Copy link
Contributor

Choose a reason for hiding this comment

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

I see what you're doing but I think in the original logic, we were taking the latest occurrence of a val update (whatever was appended last to the val updates array is the update we want to retain), and this logic takes the first occurrence instead

Copy link
Contributor

Choose a reason for hiding this comment

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

Because of how the process multiple slots works => slot1, slot2, slot3, and the updates from slot3 should override slot1

Copy link
Contributor Author

Choose a reason for hiding this comment

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

addressed

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: 1

Outside diff range comments (3)
mod/runtime/pkg/middleware/proposal.go (3)

Line range hint 154-210: In PrepareProposalHandler, ensure error handling is consistent in the goroutines. Currently, the error localErr is logged but not returned, potentially leading to unhandled errors.

- return err
+ return localErr

Line range hint 210-257: In ProcessProposalHandler, the variable args is used for logging but could be optimized for clarity and performance. Consider using structured logging directly.

- args := []any{"beacon_block", true, "blob_sidecars", true}
- logger.Info("received proposal with", args...)
+ logger.Info("received proposal", "beacon_block", true, "blob_sidecars", true)

[!TIP]
Codebase Verification

The channels valUpdatesChannel and errChannel are instantiated but there is no evidence that they are being closed in the methods PrepareProposalHandler and ProcessProposalHandler. This can lead to potential memory leaks if the channels are not properly managed.

  • Ensure that valUpdatesChannel and errChannel are closed appropriately in the codebase to prevent memory leaks.
Analysis chain

Line range hint 41-92: Ensure that the newly introduced channels (valUpdatesChannel and errChannel) are properly closed to avoid memory leaks.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the channels are closed properly in all methods where they are used.

# Test: Search for channel usage and check for close operations. Expect: Close operations for each channel.
rg --type go $'close\(.*valUpdatesChannel.*\)'
rg --type go $'close\(.*errChannel.*\)'

Length of output: 88



Script:

#!/bin/bash
# Description: Verify usage of valUpdatesChannel and errChannel in methods of ABCIMiddleware.

# Test: Search for valUpdatesChannel usage.
rg --type go 'valUpdatesChannel' mod/runtime/pkg/middleware/proposal.go

# Test: Search for errChannel usage.
rg --type go 'errChannel' mod/runtime/pkg/middleware/proposal.go

Length of output: 380



Script:

#!/bin/bash
# Description: Verify usage of valUpdatesChannel and errChannel in methods of ABCIMiddleware.

# Test: Search for valUpdatesChannel usage in PrepareProposalHandler and ProcessProposalHandler.
rg --type go 'valUpdatesChannel' mod/runtime/pkg/middleware/proposal.go -A 10 -B 10

# Test: Search for errChannel usage in PrepareProposalHandler and ProcessProposalHandler.
rg --type go 'errChannel' mod/runtime/pkg/middleware/proposal.go -A 10 -B 10

Length of output: 2692

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 8b3fb3f and 243ee0e.

Files selected for processing (5)
  • mod/primitives/pkg/transition/validator_update.go (2 hunks)
  • mod/primitives/pkg/transition/validator_update_test.go (1 hunks)
  • mod/runtime/pkg/middleware/finalize.go (2 hunks)
  • mod/runtime/pkg/middleware/metrics.go (2 hunks)
  • mod/runtime/pkg/middleware/proposal.go (6 hunks)
Additional comments not posted (10)
mod/runtime/pkg/middleware/metrics.go (4)

27-28: Renamed struct ABCIMiddlewareMetrics aligns well with the renaming theme of the PR.


33-37: Function newABCIMiddlewareMetrics is well encapsulated and follows Go best practices for constructor functions.


52-52: Ensure the metric key beacon_kit.runtime.process_proposal_duration is registered and recognized in the telemetry system.


43-43: Ensure the metric key beacon_kit.runtime.prepare_proposal_duration is registered and recognized in the telemetry system.

mod/primitives/pkg/transition/validator_update_test.go (2)

12-29: The test TestValidatorUpdates_RemoveDuplicates is well-written and covers the functionality of removing duplicate validator updates.


31-50: The test TestValidatorUpdates_Sort is comprehensive and effectively tests the sorting functionality of validator updates.

mod/primitives/pkg/transition/validator_update.go (1)

57-63: The Sort method uses sort.SliceStable to maintain the order of elements that are equal. Verify that the comparison logic using Pubkey is consistent across other parts of the code.

Verification successful

The search results indicate that the comparison logic using Pubkey is only present in the Sort method of the validator_update.go file. Therefore, there are no other parts of the code where this logic needs to be verified for consistency.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify consistent use of Pubkey comparison logic.

# Test: Search for other usages of Pubkey comparison in sorting.
rg "Pubkey.*<" --type go

Length of output: 139

mod/runtime/pkg/middleware/finalize.go (2)

106-129: The EndBlock method correctly handles the deduplication and sorting of validator updates. Ensure that all error handling paths are thoroughly tested.


39-44: The implementation of asynchronous block processing in the PreBlock method uses goroutines and channels effectively. Ensure proper synchronization mechanisms are in place around errChannel and valUpdatesChannel to prevent race conditions.

Also applies to: 70-100

mod/runtime/pkg/middleware/proposal.go (1)

Line range hint 97-148: The constructor initializes all fields correctly, including the newly introduced channels. Good use of type parameters for generic type handling.

mod/primitives/pkg/transition/validator_update.go Outdated Show resolved Hide resolved
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: 4

Outside diff range comments (1)
mod/runtime/pkg/middleware/middleware.go (1)

Line range hint 35-86: The added fields in the ABCIMiddleware struct increase its responsibility. Consider modularizing this to adhere to the Single Responsibility Principle.

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 243ee0e and 2addf0c.

Files selected for processing (10)
  • mod/node-core/pkg/builder/creator.go (3 hunks)
  • mod/node-core/pkg/builder/empty_components.go (2 hunks)
  • mod/node-core/pkg/builder/extended_options.go (1 hunks)
  • mod/node-core/pkg/components/defaults.go (2 hunks)
  • mod/node-core/pkg/components/module/module.go (3 hunks)
  • mod/primitives/pkg/transition/validator_update.go (1 hunks)
  • mod/primitives/pkg/transition/validator_update_test.go (1 hunks)
  • mod/runtime/pkg/middleware/abci.go (1 hunks)
  • mod/runtime/pkg/middleware/middleware.go (2 hunks)
  • mod/runtime/pkg/middleware/types.go (1 hunks)
Additional comments not posted (15)
mod/node-core/pkg/components/defaults.go (1)

Line range hint 11-11: Ensure ProvideABCIMiddleware is not redundantly listed in DefaultComponentsWithStandardTypes.

mod/node-core/pkg/builder/empty_components.go (1)

37-39: The implementation of emptyABCIMiddleware correctly provides an empty instance of ABCIMiddleware, aligning with the middleware refactoring objectives.

mod/primitives/pkg/transition/validator_update.go (2)

59-65: The Sort method correctly uses sort.SliceStable to order validator updates by public key, ensuring stability in the sorting order.


41-57: Confirm the intended behavior for RemoveDuplicates—whether to keep the first or last occurrence of each validator update. Consider adding more comprehensive tests to ensure the method behaves as expected.

Verification successful

The test function TestValidatorUpdates_RemoveDuplicates confirms that the RemoveDuplicates method is intended to keep the last occurrence of each validator update. The test checks for duplicates and verifies that the last occurrence is retained.

  • mod/primitives/pkg/transition/validator_update_test.go:62-63: The test function TestValidatorUpdates_RemoveDuplicates ensures the method behaves as expected by comparing the result to the expected output.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the behavior of `RemoveDuplicates` and check for comprehensive tests.

# Test: Search for the `RemoveDuplicates` method and associated tests.
rg "RemoveDuplicates" mod/primitives/pkg/transition/validator_update.go --context 10

Length of output: 865



Script:

#!/bin/bash
# Description: Verify the behavior of `RemoveDuplicates` and check for comprehensive tests.

# Find all test files and search for tests related to the `RemoveDuplicates` method.
fd --type f --name '*.go' --exec rg "RemoveDuplicates" {}

Length of output: 310



Script:

#!/bin/bash
# Description: Verify the behavior of `RemoveDuplicates` and check for comprehensive tests.

# Find all Go test files and search for tests related to the `RemoveDuplicates` method.
fd --extension go | xargs rg "RemoveDuplicates"

Length of output: 575



Script:

#!/bin/bash
# Description: Extract the `TestValidatorUpdates_RemoveDuplicates` function to verify its comprehensiveness.

# Extract the `TestValidatorUpdates_RemoveDuplicates` function from the test file.
ast-grep --lang go --pattern 'func TestValidatorUpdates_RemoveDuplicates($$_) $$_' mod/primitives/pkg/transition/validator_update_test.go

Length of output: 2863

mod/node-core/pkg/builder/creator.go (2)

53-53: Correct use of emptyABCIMiddleware instead of emptyValidatorMiddleware aligns with the new middleware structure.


70-70: Ensure the new abciMiddleware methods are integrated properly with BeaconApp.

Also applies to: 83-85

mod/primitives/pkg/transition/validator_update_test.go (2)

32-64: The test for RemoveDuplicates appears to be comprehensive and correctly tests the functionality.


66-103: The test for Sort method is well-implemented and ensures that validator updates are sorted correctly.

mod/runtime/pkg/middleware/types.go (1)

38-46: The new methods added to the BeaconState interface are essential for enhanced interaction with the beacon state, such as retrieving validator indices by pubkey or CometBFT address.

mod/node-core/pkg/components/module/module.go (1)

Line range hint 48-126: The refactoring of AppModule to utilize ABCIMiddleware instead of FinalizeBlockMiddleware is correctly implemented. Ensure that the documentation is updated to reflect these changes.

mod/runtime/pkg/middleware/middleware.go (2)

88-140: The constructor NewABCIMiddleware has been significantly expanded with new parameters and initializations. Ensure that all parameters are validated before use to prevent runtime errors.


25-32: Please ensure that all newly added imports are used within the file to avoid unnecessary dependencies.

Verification successful

The current verification script only checks for the presence of import statements, not their actual usage in the code. To ensure that all imports are used, we need to search for references to each imported package within the file.

Let's generate a script to check for the actual usage of these imports within middleware.go.


The verification script has confirmed that all imports listed in middleware.go are indeed used within the file. Therefore, the concern about potentially unused imports does not apply in this case.

  • All imported packages are utilized in the file.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all imports in middleware.go are used.

# Test: List all imports and check their usage in the file.
ast-grep --lang go --pattern $'import $$$' mod/runtime/pkg/middleware/middleware.go

Length of output: 1100



Script:

#!/bin/bash
# Description: Verify the usage of each import in middleware.go.

# List of imports to verify
imports=(
  "github.com/berachain/beacon-kit/mod/consensus-types/pkg/types"
  "github.com/berachain/beacon-kit/mod/p2p"
  "github.com/berachain/beacon-kit/mod/primitives"
  "github.com/berachain/beacon-kit/mod/primitives/pkg/crypto"
  "github.com/berachain/beacon-kit/mod/primitives/pkg/math"
  "github.com/berachain/beacon-kit/mod/primitives/pkg/ssz"
  "github.com/berachain/beacon-kit/mod/primitives/pkg/transition"
  "github.com/berachain/beacon-kit/mod/runtime/pkg/encoding"
  "github.com/berachain/beacon-kit/mod/runtime/pkg/p2p"
)

# Check usage of each import
for import in "${imports[@]}"; do
  echo "Checking usage of $import"
  ast-grep --lang go --pattern "$import" mod/runtime/pkg/middleware/middleware.go
done

Length of output: 3326



Script:

#!/bin/bash
# Description: Verify the actual usage of each import in middleware.go.

# List of imports and their corresponding aliases if they exist
declare -A imports=(
  ["types"]="github.com/berachain/beacon-kit/mod/consensus-types/pkg/types"
  ["p2p"]="github.com/berachain/beacon-kit/mod/p2p"
  ["primitives"]="github.com/berachain/beacon-kit/mod/primitives"
  ["crypto"]="github.com/berachain/beacon-kit/mod/primitives/pkg/crypto"
  ["math"]="github.com/berachain/beacon-kit/mod/primitives/pkg/math"
  ["ssz"]="github.com/berachain/beacon-kit/mod/primitives/pkg/ssz"
  ["transition"]="github.com/berachain/beacon-kit/mod/primitives/pkg/transition"
  ["encoding"]="github.com/berachain/beacon-kit/mod/runtime/pkg/encoding"
  ["rp2p"]="github.com/berachain/beacon-kit/mod/runtime/pkg/p2p"
)

# Check usage of each import by searching for the alias or package name in the file
for alias in "${!imports[@]}"; do
  package="${imports[$alias]}"
  echo "Checking usage of $package (alias: $alias)"
  if ! grep -q "$alias" mod/runtime/pkg/middleware/middleware.go; then
    echo "No usage found for $package (alias: $alias)"
  fi
done

Length of output: 3694

mod/runtime/pkg/middleware/abci.go (3)

228-313: The PreBlock and EndBlock functions handle critical block processing steps. Ensure that all error paths are tested thoroughly to maintain blockchain integrity.


91-159: In PrepareProposal, ensure that error handling is consistent and that all errors are logged correctly to facilitate debugging. The use of goroutines requires careful management to avoid data races.


44-85: The InitGenesis function's implementation uses JSON unmarshalling which can fail with malformed input. Ensure that the input is validated before unmarshalling to prevent injection attacks.

mod/runtime/pkg/middleware/middleware.go Show resolved Hide resolved
mod/runtime/pkg/middleware/abci.go Show resolved Hide resolved
Comment on lines +52 to +53
handler sdk.ProcessProposalHandler,
) func(bApp *baseapp.BaseApp) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the trailing comma in the function parameter list of WithProcessProposal unless it's intended for future parameters.

- handler sdk.ProcessProposalHandler,
+ handler sdk.ProcessProposalHandler
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
handler sdk.ProcessProposalHandler,
) func(bApp *baseapp.BaseApp) {
handler sdk.ProcessProposalHandler
) func(bApp *baseapp.BaseApp) {

Comment on lines +43 to +44
handler sdk.PrepareProposalHandler,
) func(bApp *baseapp.BaseApp) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the trailing comma in the function parameter list of WithPrepareProposal unless it's intended for future parameters.

- handler sdk.PrepareProposalHandler,
+ handler sdk.PrepareProposalHandler
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
handler sdk.PrepareProposalHandler,
) func(bApp *baseapp.BaseApp) {
handler sdk.PrepareProposalHandler
) func(bApp *baseapp.BaseApp) {

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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 243ee0e and 2addf0c.

Files selected for processing (10)
  • mod/node-core/pkg/builder/creator.go (3 hunks)
  • mod/node-core/pkg/builder/empty_components.go (2 hunks)
  • mod/node-core/pkg/builder/extended_options.go (1 hunks)
  • mod/node-core/pkg/components/defaults.go (2 hunks)
  • mod/node-core/pkg/components/module/module.go (3 hunks)
  • mod/primitives/pkg/transition/validator_update.go (1 hunks)
  • mod/primitives/pkg/transition/validator_update_test.go (1 hunks)
  • mod/runtime/pkg/middleware/abci.go (1 hunks)
  • mod/runtime/pkg/middleware/middleware.go (2 hunks)
  • mod/runtime/pkg/middleware/types.go (1 hunks)
Additional comments not posted (19)
mod/node-core/pkg/components/defaults.go (1)

Line range hint 14-30: Changes align with the PR's objectives of restructuring middleware components. Good use of renaming to maintain consistency.

mod/node-core/pkg/builder/empty_components.go (1)

37-39: Renaming from emptyValidatorMiddleware to emptyABCIMiddleware is consistent with the PR's theme of renaming. The implementation correctly returns an address to an empty ABCIMiddleware.

mod/node-core/pkg/builder/extended_options.go (1)

43-44: The addition of a comma after the parameter in the function signatures of WithPrepareProposal and WithProcessProposal is a minor change and aligns with Go's style conventions.

Also applies to: 52-53

mod/primitives/pkg/transition/validator_update.go (1)

30-65: Introduction of ValidatorUpdates type and associated methods RemoveDuplicates and Sort enhances the handling of validator updates. The implementation uses standard Go idioms and is clear and efficient.

mod/node-core/pkg/builder/creator.go (2)

53-53: Renaming to emptyABCIMiddleware aligns with the new middleware naming convention.


83-85: Ensure that the WithPrepareProposal, WithProcessProposal, and WithPreBlocker methods are correctly implemented in the ABCIMiddleware to handle the new middleware logic.

mod/primitives/pkg/transition/validator_update_test.go (1)

66-103: The test for Sort method is well-implemented, verifying the sorting of ValidatorUpdates based on EffectiveBalance. Consider adding a test case to ensure stability when two entries have the same EffectiveBalance.

mod/runtime/pkg/middleware/types.go (3)

38-38: Method ValidatorIndexByPubkey is correctly added to the BeaconState interface, enhancing its functionality.


42-42: Method GetBlockRootAtIndex is a valuable addition for accessing specific block roots by index in the BeaconState.


46-46: Method ValidatorIndexByCometBFTAddress provides a necessary link between CometBFT addresses and validator indices, facilitating better integration with consensus mechanisms.

mod/node-core/pkg/components/module/module.go (2)

48-48: The documentation for AppModule should be updated to reflect its new functionality around ABCIMiddleware. This aligns with the previous comment suggesting an update to the documentation.


113-126: The InitGenesis and EndBlock methods correctly delegate to the ABCIMiddleware. This change is consistent with the structural update of the module.

mod/runtime/pkg/middleware/middleware.go (3)

88-140: The NewABCIMiddleware function correctly initializes the ABCIMiddleware struct. Ensure that the parameters provided align with the expected types and that error channels and other asynchronous mechanisms are initialized correctly to avoid potential deadlocks or leaks.


Line range hint 35-86: The expanded ABCIMiddleware struct includes several new fields and generics. Verify that these additions align with the intended functionality and check for potential data races, especially with channels valUpdatesCh and errCh.

Verification successful

The search results indicate that the valUpdatesCh and errCh channels are correctly utilized within the mod/runtime/pkg/middleware/abci.go file. The channels are being properly initialized and used for communication, which aligns with their intended purpose.

  • valUpdatesCh is used to send and receive validator updates.
  • errCh is used to communicate errors.

This confirms that the channels are handled correctly within the codebase.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the correct handling of channels in the ABCIMiddleware struct
ast-grep --lang go --pattern '$_.$valUpdatesCh<$$$>' mod/runtime/pkg/middleware/middleware.go
ast-grep --lang go --pattern '$_.$errCh<$$$>' mod/runtime/pkg/middleware/middleware.go

Length of output: 874



Script:

#!/bin/bash
# Search for the usage of `valUpdatesCh` channel in the codebase
rg 'valUpdatesCh' --glob '**/*.go'

# Search for the usage of `errCh` channel in the codebase
rg 'errCh' --glob '**/*.go'

Length of output: 2370


25-32: Ensure the newly added imports are used appropriately throughout the file. This includes p2p, crypto, math, ssz, transition, and encoding packages.

Verification successful

The newly added imports (p2p, crypto, math, ssz, transition, encoding) are indeed used within mod/runtime/pkg/middleware/middleware.go.

  • p2p and rp2p are used for PublisherReceiver and NewNoopBlobHandler.
  • crypto is used for BLSPubkey.
  • math is used for Slot and ValidatorIndex.
  • ssz is used for Marshallable.
  • transition is used for ValidatorUpdates.
  • encoding is used for ABCIRequest.

Thus, the imports are appropriately utilized in the file.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify usage of new imports in middleware.go
rg --type go --files-with-matches 'p2p|crypto|math|ssz|transition|encoding' mod/runtime/pkg/middleware/middleware.go

Length of output: 159



Script:

#!/bin/bash
# Verify usage of each new import in middleware.go
rg --type go 'p2p' mod/runtime/pkg/middleware/middleware.go
rg --type go 'crypto' mod/runtime/pkg/middleware/middleware.go
rg --type go 'math' mod/runtime/pkg/middleware/middleware.go
rg --type go 'ssz' mod/runtime/pkg/middleware/middleware.go
rg --type go 'transition' mod/runtime/pkg/middleware/middleware.go
rg --type go 'encoding' mod/runtime/pkg/middleware/middleware.go

Length of output: 1517

mod/runtime/pkg/middleware/abci.go (4)

44-85: The InitGenesis function delegates to initGenesis, which processes genesis data and handles errors robustly. Ensure that the error handling is consistent and that any failures in data processing do not compromise the integrity of the application state.


277-313: The EndBlock function handles asynchronous updates and errors. Ensure that the channel operations are safe and do not lead to deadlocks or race conditions. Consider adding more robust error handling or recovery mechanisms.


91-159: The prepareProposal function uses an error group for concurrent tasks, which is a robust pattern. However, ensure that the error handling within the goroutines is correct and that no errors are inadvertently swallowed or incorrectly propagated.


165-222: The processProposal function correctly logs and handles errors, using structured logging for better traceability. Verify that all error paths are tested and that the function's behavior aligns with the expected protocol operations.

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.

2 participants