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

refactor(server/v2): clean up storage use #22008

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

Conversation

kocubinski
Copy link
Member

@kocubinski kocubinski commented Oct 1, 2024

Description

Related to: #21678

This PR cleans up the dependency story for storage. After the merge of #21989 we no longer need to further bloat the AppI interface with GetStore() any, which is the core change in this PR.

--- a/server/v2/types.go
+++ b/server/v2/types.go
type AppI[T transaction.Tx] interface {
        InterfaceRegistry() server.InterfaceRegistry
        GetAppManager() *appmanager.AppManager[T]
        GetGPRCMethodsToMessageMap() map[string]func() gogoproto.Message
-       GetStore() any
 }

The store/v2.RootStore interface was also broken up slightly so that the dependency lines are cleaner for clients in server/v2.


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

    • Enhanced state management through the integration of a new store backend.
    • Improved command initialization process with updated parameters for better store handling.
    • Integration of store parameter in testnet command structure for better state management.
  • Bug Fixes

    • Minor grammatical corrections in comments for clarity.
  • Documentation

    • Updated comments to reflect changes in method signatures and functionality.
  • Refactor

    • Streamlined server and store structures by removing obsolete parameters and methods.
    • Unified snapshot management logic for improved flexibility.

Copy link
Contributor

coderabbitai bot commented Oct 1, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes involve significant modifications to the server's architecture, focusing on the integration of a new store field within the CometBFTServer and Server structs. The Store interface has been updated to embed the storev2.Backend interface, enhancing its functionality while removing certain methods. Additionally, various method signatures across multiple files have been simplified or altered to accommodate these changes, streamlining the server's initialization and configuration processes.

Changes

File Path Change Summary
server/v2/cometbft/server.go Updated CometBFTServer struct to include a new store field; modified constructor and Init method to utilize the new field.
server/v2/cometbft/types/store.go Modified Store interface to embed storev2.Backend; removed GetStateStorage and GetStateCommitment methods.
server/v2/commands.go Minor grammatical correction in a comment within the AddCommands function.
server/v2/server_test.go Updated comment for clarity regarding storeServer initialization.
server/v2/store/server.go Replaced appCreator field with store; simplified method signatures for Init, Start, and Stop.
server/v2/store/snapshot.go Updated RestoreSnapshotCmd and createSnapshotsManager signatures to accept storev2.Backend instead of AppCreator.
server/v2/types.go Removed GetStore method from AppI interface.
simapp/v2/simdv2/cmd/commands.go Updated initRootCmd to include a new store parameter; modified appExport function to ensure correct home directory configuration.
simapp/v2/simdv2/cmd/testnet.go Updated NewTestnetCmd and related functions to accept a cometbfttypes.Store parameter for better state management in the testnet environment.

Possibly related PRs

Suggested reviewers

  • facundomedica
  • sontrinh16
  • julienrbrt
  • tac0turtle

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

@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 and nitpick comments (4)
server/v2/cometbft/types/store.go (1)

Line range hint 9-36: Consider adding interface documentation

The Store interface seems to play a crucial role in the system. To improve code readability and maintainability, consider adding a comment block above the interface declaration explaining its purpose, responsibilities, and any important details about its usage.

For example:

// Store represents the main storage interface for the Cosmos SDK.
// It combines low-level storage operations with high-level state management,
// providing a unified interface for interacting with the blockchain state.
type Store interface {
    // ... existing code ...
}

This documentation will help developers understand the interface's role more quickly and use it correctly.

store/v2/store.go (1)

70-77: Well-structured Backend interface with clear method signatures

The new Backend interface is a great addition that improves the overall structure of the codebase. It effectively encapsulates methods for retrieving state storage and state commitment, which were previously part of the RootStore interface. This change:

  1. Enhances modularity and maintainability
  2. Adheres to the interface segregation principle
  3. Uses clear and descriptive method names, following Go conventions

Consider adding a brief comment above the Backend interface to explain its purpose and relationship with RootStore, similar to the comments for other interfaces in this file. For example:

// Backend defines the interface for accessing the underlying storage and commitment
// backends used by the RootStore.
type Backend interface {
    // ... (existing methods)
}
simapp/v2/simdv2/cmd/root_di.go (1)

88-89: LGTM: Updated initRootCmd call with store parameter

The modification to create a store using storeBuilder.Get() and pass it to initRootCmd is consistent with the PR objectives. This change reflects the restructuring of the store/v2.RootStore interface and aligns with the new storage management approach.

Consider renaming the store variable to something more descriptive, such as rootStore, to better reflect its purpose and type:

-store := storeBuilder.Get()
-initRootCmd(rootCmd, clientCtx.TxConfig, store, moduleManager)
+rootStore := storeBuilder.Get()
+initRootCmd(rootCmd, clientCtx.TxConfig, rootStore, moduleManager)
server/v2/store/snapshot.go (1)

79-79: Add a comment for the exported function RestoreSnapshotCmd.

According to the Uber Go Style Guide, all exported functions should have a comment explaining what the function does. Consider adding a comment for RestoreSnapshotCmd to improve code documentation.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 52d8b2e and 058248a.

📒 Files selected for processing (10)
  • server/v2/cometbft/server.go (3 hunks)
  • server/v2/cometbft/types/store.go (1 hunks)
  • server/v2/commands.go (1 hunks)
  • server/v2/server_test.go (1 hunks)
  • server/v2/store/server.go (4 hunks)
  • server/v2/store/snapshot.go (3 hunks)
  • server/v2/types.go (0 hunks)
  • simapp/v2/simdv2/cmd/commands.go (3 hunks)
  • simapp/v2/simdv2/cmd/root_di.go (3 hunks)
  • store/v2/store.go (2 hunks)
💤 Files with no reviewable changes (1)
  • server/v2/types.go
✅ Files skipped from review due to trivial changes (2)
  • server/v2/commands.go
  • server/v2/server_test.go
🧰 Additional context used
📓 Path-based instructions (7)
server/v2/cometbft/server.go (1)

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

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

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

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

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

server/v2/store/snapshot.go (1)

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

simapp/v2/simdv2/cmd/commands.go (1)

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

simapp/v2/simdv2/cmd/root_di.go (1)

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

store/v2/store.go (1)

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

🔇 Additional comments (19)
server/v2/cometbft/types/store.go (1)

10-11: Approved: Good use of interface embedding

The addition of storev2.Backend to the Store interface is a good refactoring decision. This change:

  1. Streamlines the interface by potentially reducing duplicate method declarations.
  2. Aligns with the PR objectives to simplify dependency management.
  3. Follows Go's composition over inheritance principle.
  4. Adheres to the Uber Golang style guide for interface composition.
server/v2/store/server.go (5)

12-12: LGTM: Import addition is appropriate.

The addition of the storev2 import is consistent with the changes made in the file, particularly the use of storev2.Backend. The import alias is clear and follows good naming conventions.


26-26: LGTM: Server struct update aligns with PR objectives.

The addition of the store field of type storev2.Backend to the Server struct is consistent with the PR's goal of streamlining storage-related dependency management. This change appropriately replaces the previous appCreator field.


29-30: LGTM: New function signature update is appropriate.

The New function has been correctly updated to accept a storev2.Backend parameter instead of an appCreator. This change is consistent with the modifications made to the Server struct and aligns with the PR objectives of streamlining storage-related dependencies.


66-66: LGTM: CLICommands method update is consistent.

The update to the RestoreSnapshotCmd call in the CLICommands method is appropriate. Using s.store instead of s.appCreator is consistent with the changes made to the Server struct and aligns with the PR objectives of removing the appCreator dependency.


33-33: Signature update looks good, but consider logger usage.

The Init method signature has been appropriately updated to reflect the changes in the Server struct and align with the PR objectives. The removal of the appI parameter usage is consistent with the goal of simplifying the interface.

However, I noticed that the logger parameter is now unused.

Could you please verify if the logger is intentionally unused now? If it's no longer needed, consider removing it from the method signature entirely. If it is still required elsewhere, please ensure it's properly utilized or document why it's kept as an unused parameter.

To help verify the logger usage, you can run the following command:

This will help us understand if there are any other implementations of the Init method that still use the logger parameter.

store/v2/store.go (2)

15-17: Excellent use of composition for RootStore interface

The addition of Pruner and Backend to the RootStore interface is a good design choice. This change:

  1. Improves separation of concerns
  2. Aligns with Go's preference for composition over inheritance
  3. Simplifies the RootStore interface, making it more modular and easier to maintain

This modification successfully achieves the PR objective of streamlining dependency management and simplifying the interface.


15-17: Verify removal of methods from RootStore

The AI summary mentions the removal of GetStateStorage() and GetStateCommitment() methods from the RootStore interface. This change is consistent with the addition of the Backend interface and aligns with the PR objectives of simplifying the RootStore interface.

To confirm this change, please run the following script:

If the script output shows the RootStore interface without these methods, it confirms their removal as mentioned in the AI summary.

simapp/v2/simdv2/cmd/root_di.go (3)

35-35: LGTM: Addition of storeBuilder variable

The introduction of storeBuilder runtime.StoreBuilder aligns with the PR objectives to streamline dependency management related to storage. This change is consistent with the removal of the GetStore() method from the AppI interface as mentioned in the PR summary.


55-55: LGTM: storeBuilder added to dependency injection

The addition of storeBuilder to the dependency injection is consistent with its introduction as a variable. This ensures that storeBuilder is properly initialized through the dependency injection process, which is in line with the PR's objective of refactoring storage usage.


Line range hint 1-153: Overall assessment: Changes align well with PR objectives

The modifications in this file successfully implement the intended refactoring of storage usage. The introduction of storeBuilder, its integration into the dependency injection process, and the updated initRootCmd call all contribute to streamlining the dependency management related to storage.

These changes are consistent with the PR objectives, particularly:

  1. The removal of the GetStore() method from the AppI interface.
  2. The restructuring of the store/v2.RootStore interface.

The code adheres to the Uber Golang style guide, maintaining good code quality and readability.

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

46-46: LGTM: Addition of store field to CometBFTServer struct

The addition of the store field of type types.Store to the CometBFTServer struct aligns with the PR objectives to streamline dependency management related to storage. This change is consistent with the removal of the GetStore() method from the AppI interface as mentioned in the PR summary.


52-57: LGTM: Updated New function signature

The addition of the store parameter to the New function signature is consistent with the changes made to the CometBFTServer struct. This update ensures that the store is properly initialized when creating a new CometBFTServer instance, which aligns with the PR objectives.


60-60: LGTM: Initialization of store field in CometBFTServer

The initialization of the store field in the CometBFTServer struct is consistent with the changes made to the struct definition and the New function signature. This ensures that the store is properly set when creating a new CometBFTServer instance.


115-115: LGTM: Updated Consensus initialization with store parameter

The addition of the store parameter to the NewConsensus function call in the Init method is consistent with the changes made to the CometBFTServer struct. This update ensures that the Consensus instance has access to the store for state management, which aligns with the PR objectives of streamlining storage dependency management.


127-128: LGTM: Updated snapshot management to use s.store

The changes to use s.store.GetStateStorage() and s.store.GetStateCommitment() instead of appI.GetStore() are consistent with the removal of the GetStore() method from the AppI interface as mentioned in the PR summary. This update aligns with the PR objectives of streamlining storage dependency management.

However, it's important to verify the type assertions .(snapshots.StorageSnapshotter) and .(snapshots.CommitSnapshotter) to ensure type safety. Consider adding runtime checks or using type switches to handle potential type mismatches gracefully.

To verify the type assertions, you can run the following script:

simapp/v2/simdv2/cmd/commands.go (3)

20-21: Imports are correctly organized and aliased

The new imports cometbfttypes and serverstore are properly added with clear aliases that improve code readability and prevent naming conflicts.


87-87: Validate the addition of serverstore.New[T](store) in serverv2.AddCommands

Including serverstore.New[T](store) as an argument to serverv2.AddCommands should match the expected parameters of the function. Verify that this addition is appropriate and that it integrates correctly with the rest of the application's initialization process.

Run the following script to examine the serverv2.AddCommands function signature:

#!/bin/bash
# Description: Check the parameters accepted by 'serverv2.AddCommands' to ensure compatibility.

# Test: Locate the definition of 'serverv2.AddCommands' and display its signature.
rg --type go -A 5 'func AddCommands\(' | grep -A 5 'func AddCommands('

82-85: Confirm store is correctly passed to cometbft.New

The addition of store as a parameter to cometbft.New should align with its expected function signature. Ensure that cometbft.New accepts store as an argument in this position and that the types are compatible.

Run the following script to check the definition of cometbft.New:

#!/bin/bash
# Description: Verify the function signature of 'cometbft.New' to confirm it accepts 'store' as a parameter.

# Test: Find the definition of 'cometbft.New' in the codebase.
rg --type go -A 5 'func New\(' | grep -A 5 'func New('

server/v2/cometbft/types/store.go Show resolved Hide resolved
simapp/v2/simdv2/cmd/commands.go Show resolved Hide resolved
Comment on lines +374 to +378
sm := snapshots.NewManager(
snapshotStore, snapshots.NewSnapshotOptions(interval, uint32(keepRecent)),
store.GetStateCommitment().(snapshots.CommitSnapshotter),
store.GetStateStorage().(snapshots.StorageSnapshotter),
nil, logger)
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

Handle type assertions to prevent potential panics.

At lines 376-377, the code uses unchecked type assertions. The Uber Go Style Guide recommends using the two-value form to handle cases where the assertion might fail, preventing runtime panics.

Modify the code to handle type assertion failures:

commitSnapshotter, ok := store.GetStateCommitment().(snapshots.CommitSnapshotter)
if !ok {
	return nil, fmt.Errorf("store does not implement snapshots.CommitSnapshotter")
}
storageSnapshotter, ok := store.GetStateStorage().(snapshots.StorageSnapshotter)
if !ok {
	return nil, fmt.Errorf("store does not implement snapshots.StorageSnapshotter")
}

sm := snapshots.NewManager(
	snapshotStore,
	snapshots.NewSnapshotOptions(interval, uint32(keepRecent)),
	commitSnapshotter,
	storageSnapshotter,
	nil,
	logger,
)

server/v2/store/snapshot.go 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: 2

🧹 Outside diff range and nitpick comments (3)
server/v2/store/server.go (1)

26-26: LGTM: Server struct update is appropriate.

The addition of the store field of type storev2.Backend aligns well with the PR objectives. It's a good step towards abstracting storage operations.

Consider adding a brief comment above the store field to describe its purpose, e.g.:

// store is the backend storage interface
store storev2.Backend
store/v2/store.go (1)

70-77: Well-structured Backend interface with room for minor improvement

The new Backend interface is a great addition that aligns with the PR objectives. It effectively separates the concerns of state storage and state commitment from the RootStore interface, enhancing modularity and clarity.

The interface is well-defined and follows good Go practices. However, to further improve documentation:

Consider adding a brief comment for each method to explain their purpose:

type Backend interface {
	// GetStateStorage returns the SS (State Storage) backend.
	GetStateStorage() VersionedDatabase

	// GetStateCommitment returns the SC (State Commitment) backend.
	GetStateCommitment() Committer
}

This addition would provide more context for developers working with this interface in the future.

simapp/v2/simdv2/cmd/root_di.go (1)

88-89: LGTM: Updated initRootCmd call with store parameter

The changes to the initRootCmd function call align well with the PR objectives. The addition of the store parameter, obtained from storeBuilder.Get(), reflects the removal of the GetStore() method from the AppI interface. This modification contributes to simplifying the interface and improving the overall code structure.

For improved clarity, consider adding a brief comment explaining the purpose of the store parameter:

// Get the store from the storeBuilder for use in initRootCmd
store := storeBuilder.Get()
initRootCmd(rootCmd, clientCtx.TxConfig, store, moduleManager)
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 52d8b2e and 058248a.

📒 Files selected for processing (10)
  • server/v2/cometbft/server.go (3 hunks)
  • server/v2/cometbft/types/store.go (1 hunks)
  • server/v2/commands.go (1 hunks)
  • server/v2/server_test.go (1 hunks)
  • server/v2/store/server.go (4 hunks)
  • server/v2/store/snapshot.go (3 hunks)
  • server/v2/types.go (0 hunks)
  • simapp/v2/simdv2/cmd/commands.go (3 hunks)
  • simapp/v2/simdv2/cmd/root_di.go (3 hunks)
  • store/v2/store.go (2 hunks)
💤 Files with no reviewable changes (1)
  • server/v2/types.go
✅ Files skipped from review due to trivial changes (2)
  • server/v2/commands.go
  • server/v2/server_test.go
🧰 Additional context used
📓 Path-based instructions (7)
server/v2/cometbft/server.go (1)

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

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

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

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

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

server/v2/store/snapshot.go (1)

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

simapp/v2/simdv2/cmd/commands.go (1)

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

simapp/v2/simdv2/cmd/root_di.go (1)

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

store/v2/store.go (1)

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

🔇 Additional comments (20)
server/v2/cometbft/types/store.go (2)

10-11: Approved: Interface simplification aligns with PR objectives

The changes to the Store interface, including embedding storev2.Backend and removing GetStateStorage() and GetStateCommitment() methods, effectively streamline the dependency management related to storage. This simplification aligns well with the PR objectives of reducing unnecessary complexity and improving the overall structure of the code.

The embedding of storev2.Backend is a good practice, as it allows the Store interface to inherit methods without explicitly declaring them, following the Uber Go Style Guide recommendation of preferring embedding to type aliases for interfaces.


Line range hint 1-38: Approved: Well-structured and documented interface

The overall structure and documentation of the Store interface are commendable:

  1. The imports are correctly organized and follow the Uber Go Style Guide.
  2. Each method has a descriptive comment, which is a good practice and enhances code readability.
  3. The method signatures are consistent and follow Go naming conventions.
  4. The interface is well-organized and focused on a single responsibility, adhering to good design principles.

These aspects contribute to the maintainability and clarity of the code, which aligns with the PR's goal of improving the overall structure of the codebase.

server/v2/store/server.go (4)

12-12: LGTM: Import statement addition is appropriate.

The addition of the storev2 import is consistent with the changes in the file and follows good naming conventions.


29-30: LGTM: New function update is appropriate.

The modification to accept store storev2.Backend instead of appCreator is consistent with the Server struct changes and aligns with the PR objectives. This change simplifies the initialization process and removes the dependency on AppI.GetStore().


66-66: LGTM: CLICommands method update is consistent.

The change to use s.store instead of s.appCreator in the RestoreSnapshotCmd call is consistent with the other modifications in this PR.

To ensure full compatibility, please verify that the RestoreSnapshotCmd function has been updated to accept a storev2.Backend parameter instead of an AppCreator. You can run the following command to check the function signature:

This will show the current signature of the RestoreSnapshotCmd function, which should now accept a storev2.Backend parameter.

✅ Verification successful

Verified: RestoreSnapshotCmd function signature correctly updated.

The RestoreSnapshotCmd function now accepts a storev2.Backend parameter as intended, ensuring compatibility with the recent changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

rg --type go -C 5 'func.*RestoreSnapshotCmd' server/v2/store/

Length of output: 723


33-33: LGTM with a minor concern: Init method signature update.

The change to ignore the appI parameter is consistent with the PR objectives. However, ignoring the logger parameter might lead to loss of logging capabilities in this method.

Could you please confirm if logging is no longer needed in the Init method? If logging is still required, consider keeping the logger parameter and using it within the method body.

To verify the usage of logging in the Init method, you can run the following command:

This will show if there were any logging statements in the Init method that might have been removed.

✅ Verification successful

logger parameter in Init method is safely removed.

No logging statements found in the Init method, so removing the logger parameter does not impact logging capabilities.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

rg --type go -C 5 'log(ger)?\.' server/v2/store/server.go

Length of output: 445

store/v2/store.go (3)

15-17: Excellent refactoring of the RootStore interface

The changes to the RootStore interface improve the code structure and align well with the PR objectives. By incorporating the Pruner and Backend interfaces, you've effectively segregated responsibilities and simplified the RootStore interface. This refactoring enhances maintainability and clarity of the codebase.

The removal of GetStateStorage() and GetStateCommitment() methods from RootStore (as indicated in the AI summary) further contributes to this simplification. These changes adhere to the interface segregation principle, which is consistent with good Go programming practices.


Line range hint 1-110: Summary of changes and their impact

The refactoring in this file significantly improves the structure and clarity of the RootStore interface and related components. Key improvements include:

  1. Simplification of the RootStore interface by embedding Pruner and Backend.
  2. Introduction of a new Backend interface to separate state storage and commitment concerns.
  3. Moving the Prune method to the Pruner interface, adhering to the interface segregation principle.

These changes align well with the PR objectives of streamlining dependency management and enhancing code maintainability. The refactoring follows good Go programming practices and the Uber Golang style guide.

Overall, this is a well-executed refactoring that should positively impact the codebase's organization and clarity.


15-15: Approve embedding of Pruner interface in RootStore

The embedding of the Pruner interface in RootStore is a positive change that aligns with the PR objectives. It streamlines dependency management and improves the overall structure of the code.

To ensure this change doesn't introduce any unintended consequences, let's verify the usage of the Prune method across the codebase:

This verification will help ensure that all usages of the Prune method are still valid after this refactoring.

✅ Verification successful

Pruner interface embedding in RootStore verified

The absence of direct calls to RootStore.Prune() and the presence of Prune implementations across the codebase confirm that embedding the Pruner interface in RootStore has been successfully implemented without introducing any issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any direct calls to RootStore.Prune() that might need updating

# Test: Search for direct calls to RootStore.Prune(). Expect: No results, as Prune is now part of the Pruner interface.
rg --type go 'RootStore.*\.Prune\('

# Test: Search for implementations of the Prune method. Expect: Implementations in concrete types that satisfy RootStore.
rg --type go 'func \(.*\) Prune\('

Length of output: 1576

simapp/v2/simdv2/cmd/root_di.go (1)

35-35: LGTM: Addition of storeBuilder variable

The introduction of the storeBuilder variable of type runtime.StoreBuilder aligns with the PR objectives to clean up storage use. This change appears to be part of the refactoring process to streamline dependency management related to storage.

simapp/v2/simdv2/cmd/commands.go (4)

20-21: Approved: Importing necessary packages

The addition of cometbfttypes and serverstore imports is appropriate and follows the Uber Golang style guide.


47-47: Approved: Added store parameter to initRootCmd

Including store cometbfttypes.Store in the initRootCmd function signature enhances dependency management and aligns with the refactoring objectives.


82-82: Approved: Passing store to cometbft.New

Passing the store variable to cometbft.New ensures proper initialization of the CometBFT component with the correct store configuration.


87-87: Approved: Initializing server store with store

Initializing the server store using serverstore.New[T](store) is appropriate and adheres to best practices for dependency injection.

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

46-46: Addition of store field to CometBFTServer struct

The store field is appropriately added to the CometBFTServer[T] struct to encapsulate the state management functionality. This change enhances encapsulation and reduces dependency on external interfaces.


52-57: Update to New function signature to include store parameter

The New function now accepts a store types.Store parameter, aligning with the addition of the store field in the struct. The parameter ordering is logical, and the variadic cfgOptions remains at the end, adhering to Go conventions.


60-60: Assignment of store field in struct initialization

The store field is correctly initialized within the CometBFTServer constructor, ensuring that the store is available throughout the instance's lifecycle.


115-115: Passing s.store to NewConsensus function

The s.store is appropriately passed as an argument to the NewConsensus function, replacing the previous dependency on the appI.GetStore() method. This modification simplifies the dependency chain and aligns with the PR objective of cleaning up storage use.

server/v2/store/snapshot.go (2)

79-79: Function signature updated appropriately

The RestoreSnapshotCmd function now accepts rootStore storev2.Backend as a parameter, aligning with the PR objectives to simplify dependency management and improve code structure.


351-353: Function signature updated for enhanced flexibility

Changing the createSnapshotsManager function to accept store storev2.Backend instead of storev2.RootStore enhances the flexibility of the snapshot management system and aligns with the refactoring goals.

Comment on lines +127 to +128
ss := s.store.GetStateStorage().(snapshots.StorageSnapshotter)
sc := s.store.GetStateCommitment().(snapshots.CommitSnapshotter)
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

Handle unchecked type assertions to prevent potential panics

The type assertions on s.store.GetStateStorage() and s.store.GetStateCommitment() are unchecked and could lead to a panic if the assertions fail. It is recommended to perform type assertion checks to handle potential failures gracefully.

Apply the following changes to handle potential type assertion failures:

- ss := s.store.GetStateStorage().(snapshots.StorageSnapshotter)
- sc := s.store.GetStateCommitment().(snapshots.CommitSnapshotter)
+ ssInterface := s.store.GetStateStorage()
+ ss, ok := ssInterface.(snapshots.StorageSnapshotter)
+ if !ok {
+     return fmt.Errorf("failed to assert s.store.GetStateStorage() to snapshots.StorageSnapshotter")
+ }
+ scInterface := s.store.GetStateCommitment()
+ sc, ok := scInterface.(snapshots.CommitSnapshotter)
+ if !ok {
+     return fmt.Errorf("failed to assert s.store.GetStateCommitment() to snapshots.CommitSnapshotter")
+ }

This change ensures that the type assertions are checked, and appropriate error handling is in place to prevent unexpected panics.

📝 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
ss := s.store.GetStateStorage().(snapshots.StorageSnapshotter)
sc := s.store.GetStateCommitment().(snapshots.CommitSnapshotter)
ssInterface := s.store.GetStateStorage()
ss, ok := ssInterface.(snapshots.StorageSnapshotter)
if !ok {
return fmt.Errorf("failed to assert s.store.GetStateStorage() to snapshots.StorageSnapshotter")
}
scInterface := s.store.GetStateCommitment()
sc, ok := scInterface.(snapshots.CommitSnapshotter)
if !ok {
return fmt.Errorf("failed to assert s.store.GetStateCommitment() to snapshots.CommitSnapshotter")
}

Comment on lines +374 to +378
sm := snapshots.NewManager(
snapshotStore, snapshots.NewSnapshotOptions(interval, uint32(keepRecent)),
store.GetStateCommitment().(snapshots.CommitSnapshotter),
store.GetStateStorage().(snapshots.StorageSnapshotter),
nil, logger)
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 runtime panic due to unchecked type assertions

In the call to snapshots.NewManager, the code performs unchecked type assertions:

store.GetStateCommitment().(snapshots.CommitSnapshotter),
store.GetStateStorage().(snapshots.StorageSnapshotter),

If store.GetStateCommitment() or store.GetStateStorage() do not return types that implement the expected interfaces, this will cause a runtime panic.

Consider using the comma-ok idiom to safely perform the type assertions and handle any errors appropriately. Here's how you can modify the code:

+	commitSnapshotter, ok := store.GetStateCommitment().(snapshots.CommitSnapshotter)
+	if !ok {
+		return nil, fmt.Errorf("store's state commitment does not implement snapshots.CommitSnapshotter")
+	}
+	storageSnapshotter, ok := store.GetStateStorage().(snapshots.StorageSnapshotter)
+	if !ok {
+		return nil, fmt.Errorf("store's state storage does not implement snapshots.StorageSnapshotter")
+	}
-	sm := snapshots.NewManager(
-		snapshotStore, snapshots.NewSnapshotOptions(interval, uint32(keepRecent)),
-		store.GetStateCommitment().(snapshots.CommitSnapshotter),
-		store.GetStateStorage().(snapshots.StorageSnapshotter),
-		nil, logger)
+	sm := snapshots.NewManager(
+		snapshotStore, snapshots.NewSnapshotOptions(interval, uint32(keepRecent)),
+		commitSnapshotter,
+		storageSnapshotter,
+		nil, logger)

This change ensures that if the type assertions fail, a meaningful error is returned instead of causing a panic.

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

looks better like this indeed. ACK.

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

🧹 Outside diff range and nitpick comments (3)
simapp/v2/simdv2/cmd/testnet.go (3)

91-91: Use consistent and descriptive parameter names for cometbfttypes.Store

The parameter is named rs in NewTestnetCmd and testnetInitFilesCmd, but it's called rootStore in initTestnetFiles. For better readability and consistency, consider using the same descriptive name, such as rootStore, across all functions.


106-106: Maintain consistent parameter naming across functions

In the function testnetInitFilesCmd, the parameter rs is used for cometbfttypes.Store. To enhance code clarity, consider renaming it to rootStore to match the naming in initTestnetFiles.


147-147: Ensure consistent naming when passing parameters

When calling initTestnetFiles, the variable rs is passed as rootStore. Using consistent parameter names across functions improves readability. Consider renaming rs to rootStore here as well.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 058248a and c8c207c.

📒 Files selected for processing (2)
  • simapp/v2/simdv2/cmd/commands.go (4 hunks)
  • simapp/v2/simdv2/cmd/testnet.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • simapp/v2/simdv2/cmd/commands.go
🧰 Additional context used
📓 Path-based instructions (1)
simapp/v2/simdv2/cmd/testnet.go (1)

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

🔇 Additional comments (2)
simapp/v2/simdv2/cmd/testnet.go (2)

344-344: Confirm the correct usage of rootStore in cometbft.New

Passing rootStore into cometbft.New aligns with the intended design to improve dependency management. Ensure that rootStore implements the necessary interfaces expected by cometbft.New.


348-348: Validate the initialization of storeServer

The creation of storeServer using store.New[T](rootStore) appears correct. Verify that rootStore meets the requirements of the store.New function to prevent potential runtime issues.

@kocubinski kocubinski added the S: DO NOT MERGE Status: DO NOT MERGE label Oct 1, 2024
@kocubinski
Copy link
Member Author

Added DNM, attending to it now.
There is a small bug in providers when running ❯ scripts/init-simapp-v2.sh
Surprised we don't have test coverage for this?

@julienrbrt
Copy link
Member

julienrbrt commented Oct 1, 2024

Added DNM, attending to it now. There is a small bug in providers when running ❯ scripts/init-simapp-v2.sh Surprised we don't have test coverage for this?

We do, system test is our coverage, as well as simapp-v2 tests: https://github.com/cosmos/cosmos-sdk/actions/runs/11131381060/job/30932833603?pr=22008

Personally, forgot to look at it, as I knew it was broken on other stuff.

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 C:Store S: DO NOT MERGE Status: DO NOT MERGE
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants