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(mempool)!: match server/v2/cometbft and sdk mempool interface #21744

Merged
merged 13 commits into from
Sep 18, 2024

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented Sep 16, 2024

Description

ref: #21741 (comment)

Make the server/v2/cometbft/mempool interface and sdk mempool interface match.

#21741 must be merged BEFORE.
I'll add changelog if this is accepted.


Author Checklist

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

I have...

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

Reviewers Checklist

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

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

I have...

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

Summary by CodeRabbit

  • New Features
    • Introduced a new framework for message handling to improve developer efficiency.
    • Added methods for selecting and counting transactions in the mempool.
  • Improvements
    • Updated transaction processing to accept decoded transactions directly, enhancing performance.
    • Enhanced error handling for transaction removal from the mempool.
    • Streamlined transaction selection processes in various mempool implementations.
  • Bug Fixes
    • Improved reliability of transaction decoding in test cases.
  • Chores
    • Updated dependency management to include a new package for type handling.

Copy link
Contributor

coderabbitai bot commented Sep 16, 2024

Walkthrough

Walkthrough

The pull request introduces significant updates to the Cosmos SDK, primarily focusing on the Mempool interface and transaction handling. Key changes include the introduction of a new framework, sims2, and modifications to the Mempool interface to accept decoded transactions directly, enhancing performance. Additionally, several methods across various files have been refactored to improve code clarity and efficiency, particularly in how transactions are selected and removed from the mempool.

Changes

Files Change Summary
CHANGELOG.md Updated to reflect the introduction of the sims2 framework and changes to the types/mempool.Mempool interface for accepting decoded transactions.
baseapp/abci_utils.go Refactored PrepareProposalHandler to decode transactions upfront, improving code clarity and performance.
baseapp/abci_utils_test.go Added mock expectations for transaction decoding in the TestDefaultProposalHandler_PriorityNonceMempoolTxSe test case.
server/v2/cometbft/abci.go Modified FinalizeBlock to remove transactions from the mempool individually, enhancing error reporting.
server/v2/cometbft/handlers/defaults.go Simplified error handling in PrepareHandler by directly passing transactions to the Remove method.
server/v2/cometbft/internal/mock/mock_mempool.go Added SelectBy method and modified Remove method to accept a single transaction in MockMempool.
server/v2/cometbft/mempool/mempool.go Updated Mempool interface methods to accept sdk.Tx instead of byte slices, added CountTx method, and modified Select method to indicate it is not thread-safe.
server/v2/cometbft/mempool/noop.go Added SelectBy method and modified Remove method in NoOpMempool to accept a single transaction.
simapp/v2/go.mod Added github.com/spf13/cast v1.7.0 as an indirect dependency.
simapp/v2/simdv2/cmd/config.go Updated mempool initialization to use sdkmempool.NewSenderNonceMempool.
types/mempool/mempool.go Modified Select and SelectBy methods to accept []sdk.Tx instead of [][]byte.
types/mempool/noop.go Updated Select and SelectBy methods to accept []sdk.Tx instead of [][]byte.
types/mempool/priority_nonce.go Changed Select, doSelect, and SelectBy methods to accept []sdk.Tx.
types/mempool/sender_nonce.go Modified Select, doSelect, and SelectBy methods to accept []sdk.Tx.

Possibly related PRs

Suggested labels

C:x/bank, C:x/tx


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 generate interesting stats about this repository and render them as a table.
    -- @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.

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Sep 16, 2024
@@ -14,10 +14,10 @@ type Mempool interface {

// Select returns an Iterator over the app-side mempool. If txs are specified,
// then they shall be incorporated into the Iterator. The Iterator is not thread-safe to use.
Select(context.Context, [][]byte) Iterator
Select(context.Context, []sdk.Tx) Iterator
Copy link
Member

Choose a reason for hiding this comment

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

why the change here?

Copy link
Member Author

Choose a reason for hiding this comment

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

As otherwise in server/v2 we would decode twice if the mempool implementation decodes the txs (ours do not, but we cannot know about users):

https://github.com/cosmos/cosmos-sdk/blob/95b8092/server/v2/cometbft/handlers/defaults.go#L52
https://github.com/cosmos/cosmos-sdk/blob/95b8092/server/v2/cometbft/handlers/defaults.go#L72

Copy link
Member

Choose a reason for hiding this comment

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

Should we use a generic instead of either []byte or sdk.Tx? if we use sdk.Tx how will this work with server/v2?

Copy link
Member

Choose a reason for hiding this comment

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

err.. this interface is only used for app v1 correct?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yea, the one of server/v2 is identical but use generic

baseapp/abci_utils.go Outdated Show resolved Hide resolved
Co-authored-by: Marko <marko@baricevic.me>
Co-authored-by: Marko <marko@baricevic.me>
@github-actions github-actions bot added C:server/v2 Issues related to server/v2 C:server/v2 cometbft labels Sep 16, 2024
baseapp/abci_utils.go Outdated Show resolved Hide resolved
Co-authored-by: Marko <marko@baricevic.me>
Base automatically changed from julien/wire-mempool to main September 16, 2024 18:50
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 and nitpick comments (4)
server/v2/cometbft/internal/mock/mock_mempool.go (1)

20-20: LGTM! Consider adding error handling.

The modification to the Remove function signature to accept a single transaction instead of a slice simplifies the removal process and enhances usability.

However, the function always returns nil, suggesting that it does not handle any errors that may occur during the removal process. Consider adding error handling to ensure that any failures during the removal process are properly propagated to the caller.

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

7-8: Remove the empty line between import statements.

To conform to the Uber Go Style Guide, group the import statements into two groups: standard library imports and external imports, with a single empty line between the two groups. Remove the empty line between the two external import statements.

Apply this diff to fix the issue:

 import (
 	"context"
 
-
 	sdk "github.com/cosmos/cosmos-sdk/types"
 )

23-24: Consider modifying the SelectBy method to return a slice of transactions.

The SelectBy method currently does not return anything, which deviates from the common practice of returning a slice of transactions that satisfy the predicate function. Consider modifying the method to return a slice of transactions of type T that satisfy the predicate function, for consistency with common practices and potential future use cases.

Apply this diff to modify the SelectBy method:

-func (NoOpMempool[T]) SelectBy(context.Context, []T, func(T) bool) {}
+func (NoOpMempool[T]) SelectBy(context.Context, []T, func(T) bool) []T { return nil }
CHANGELOG.md (1)

Line range hint 1-1: Consider adding more context.
The postHandler API change is described clearly, but it would help to also briefly mention:

  • The motivation for adding this new handler
  • How it impacts existing apps that don't utilize it
    This added context will help devs better assess the scope of this breaking change.
Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c9f0e2e and ee627c9.

Files selected for processing (14)
  • CHANGELOG.md (2 hunks)
  • baseapp/abci_utils.go (2 hunks)
  • baseapp/abci_utils_test.go (1 hunks)
  • server/v2/cometbft/abci.go (1 hunks)
  • server/v2/cometbft/handlers/defaults.go (1 hunks)
  • server/v2/cometbft/internal/mock/mock_mempool.go (1 hunks)
  • server/v2/cometbft/mempool/mempool.go (1 hunks)
  • server/v2/cometbft/mempool/noop.go (2 hunks)
  • simapp/v2/go.mod (1 hunks)
  • simapp/v2/simdv2/cmd/config.go (1 hunks)
  • types/mempool/mempool.go (1 hunks)
  • types/mempool/noop.go (1 hunks)
  • types/mempool/priority_nonce.go (2 hunks)
  • types/mempool/sender_nonce.go (2 hunks)
Files skipped from review due to trivial changes (1)
  • server/v2/cometbft/handlers/defaults.go
Additional context used
Path-based instructions (12)
server/v2/cometbft/internal/mock/mock_mempool.go (1)

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

types/mempool/noop.go (1)

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

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

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

types/mempool/mempool.go (1)

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

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

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

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

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

types/mempool/sender_nonce.go (1)

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

types/mempool/priority_nonce.go (1)

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

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

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

baseapp/abci_utils.go (1)

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

baseapp/abci_utils_test.go (2)

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


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

CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

Additional comments not posted (28)
types/mempool/noop.go (2)

20-20: LGTM!

The change in the Select method signature to accept []sdk.Tx instead of [][]byte aligns with the overall refactoring goal and improves type safety and code clarity. The no-op implementation still honors the Mempool interface contract.


21-21: LGTM!

The change in the SelectBy method signature to accept []sdk.Tx instead of [][]byte aligns with the overall refactoring goal and improves type safety and code clarity. The no-op implementation still honors the Mempool interface contract by accepting a filtering function.

server/v2/cometbft/mempool/noop.go (3)

11-11: LGTM!

The type assertions correctly verify that the NoOpMempool type implements the Mempool interface for both sdk.Tx and transaction.Tx types at compile time, preventing potential runtime errors.


22-22: LGTM!

The Insert method is correctly implemented as a no-op, returning nil without performing any action. This aligns with the purpose of the NoOpMempool type to discard and ignore transactions.


25-26: LGTM!

The CountTx and Remove methods are correctly implemented as no-ops, consistent with the purpose of the NoOpMempool type. The CountTx method always returns 0, indicating an empty mempool, and the Remove method returns nil, suggesting a successful removal operation, even though no actual removal takes place.

types/mempool/mempool.go (2)

17-17: Clarify the impact on server/v2 and the use of generics.

The change from [][]byte to []sdk.Tx improves type safety and clarity. However, please address the following:

  1. What is the impact of this change on server/v2? The past comments indicate concerns about decoding transactions twice.

  2. Should generics be used instead of sdk.Tx to align with server/v2's interface?

  3. Is this interface only used for app v1 as mentioned in the past comments?


20-20: Address the same concerns as the Select method.

The change from [][]byte to []sdk.Tx improves type safety and clarity, similar to the Select method. Please address the same concerns raised for the Select method regarding the impact on server/v2, the use of generics, and the applicability to app v1.

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

22-22: Excellent clarification about the thread-safety of the iterator.

The updated comment provides a clear warning that the returned iterator is not thread-safe. This information is crucial for developers to ensure they handle the iterator correctly in concurrent scenarios and avoid potential race conditions or unexpected behavior.


25-26: Great addition of the thread-safe SelectBy method.

The new SelectBy method is a valuable addition to the Mempool interface, providing a thread-safe way to iterate over the mempool using a callback function. This method addresses the thread-safety concerns of the Select method and offers developers a safer alternative for processing transactions concurrently.

The method signature is clear, follows the established naming convention, and the documentation adequately explains its functionality and thread-safety.


28-29: Useful addition of the CountTx method.

The new CountTx method is a handy addition to the Mempool interface, providing a simple way to retrieve the current number of transactions in the mempool. This method is particularly useful for monitoring purposes and making decisions based on the transaction count, such as triggering batch processing or adjusting resource allocation.

The method signature is clear, follows the established naming convention, and the documentation adequately explains its functionality.


33-33: Appropriate simplification of the Remove method signature.

The modification of the Remove method signature to accept a single transaction instead of a slice of transactions is a sensible change. This simplification aligns with the common use case of removing individual transactions from the mempool and makes the method more focused and easier to use.

The change maintains the original error handling behavior by returning an error upon failure, ensuring consistency with the previous implementation.

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

97-98: Mempool interface update looks good, but ensure it's well-tested.

The change to use sdkmempool.NewSenderNonceMempool for initializing the mempool aligns with the PR objective of matching the SDK mempool interface. This is a positive step towards consistency and resolving previous discrepancies.

However, given the potential impact on transaction processing, it's crucial to ensure that the new mempool implementation has been thoroughly tested and validated. Please confirm if adequate tests have been added to cover various scenarios and edge cases.

types/mempool/sender_nonce.go (3)

170-173: Approve the change in function signature.

The modification to accept []sdk.Tx instead of [][]byte improves type safety and code clarity by leveraging a more structured transaction type. This change enhances the robustness of the code while maintaining the existing locking mechanism and selection behavior.


Line range hint 176-197: Approve the change in function signature.

The modification to accept []sdk.Tx instead of [][]byte aligns with the change in the Select function and maintains consistency. The core logic of creating an ordered list of senders and initializing sender cursors remains unaltered. The function continues to return a senderNonceMempoolIterator instance with the same set of fields, preserving its original behavior.


Line range hint 205-212: Approve the change in function signature.

The modification to accept []sdk.Tx instead of [][]byte aligns with the changes in the Select and doSelect functions, maintaining consistency throughout the codebase. The function preserves its original behavior of iterating over the transactions using the obtained iterator and invoking the provided callback function for each transaction. The locking mechanism ensures thread safety during the selection and iteration process.

simapp/v2/go.mod (1)

38-38: LGTM!

Adding github.com/spf13/cast as an indirect dependency is fine. It's a well-known and widely used Go package for safe type casting.

types/mempool/priority_nonce.go (3)

364-367: LGTM!

The change in the parameter type from [][]byte to []sdk.Tx enhances type safety and clarity by ensuring that the method directly works with transaction objects rather than raw byte representations. The overall functionality remains intact.


Line range hint 370-382: LGTM!

The change in the parameter type from [][]byte to []sdk.Tx is consistent with the changes made to the Select method. The overall functionality remains intact, as the passed in parameters are ignored.


Line range hint 386-393: LGTM!

The change in the parameter type from [][]byte to []sdk.Tx is consistent with the changes made to the Select and doSelect methods. The overall functionality remains intact, as the method iterates over the selected transactions and invokes the callback function for each transaction.

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

470-473: LGTM, but consider adding a TODO for concurrent removal.

The changes to remove transactions one by one from the mempool look good and align with the types/mempool.Mempool interface from the SDK.

However, as mentioned in the previous review comments, removing transactions sequentially could potentially block. Consider adding a TODO comment to revisit this in the future and explore removing transactions concurrently to avoid blocking.

baseapp/abci_utils.go (3)

267-276: Refactoring to decode transactions before processing improves code clarity.

Decoding all transactions at the beginning and storing them in a decodedTxs slice enhances code clarity by separating the concerns of decoding transactions from their subsequent selection for proposals.


Line range hint 284-292: Using decoded transactions when mempool is nil or no-op reduces redundancy.

The updated logic iterates over the pre-decoded transactions (decodedTxs) instead of decoding them again when the mempool is nil or a no-op. This change reduces redundancy and improves performance by ensuring that each transaction is decoded only once.


Line range hint 300-369: Selecting transactions from mempool using decoded transactions streamlines the process.

The selection of transactions for proposals now uses the decoded transactions, which streamlines the process and maintains the integrity of the transaction data being processed.

baseapp/abci_utils_test.go (1)

694-694: LGTM!

The added mock expectation for the TxDecode method enhances the reliability of the test by simulating the transaction decoding process correctly. This ensures that the NewDefaultProposalHandler behavior is validated properly.

CHANGELOG.md (4)

Line range hint 1-1: Looks good! The unreleased improvements are documented clearly.


Line range hint 1-1: Breaking change documented well.
The x/gov state machine breaking change is captured with the right level of detail.


Line range hint 1-1: Bug fixes look good!
The entries clearly capture the bugs that were resolved, with good links to the PR for more details.


Line range hint 1-1: Deprecation notice is clear.
The deprecated function is called out with instructions on what to use instead. Looks good.

@@ -15,5 +15,6 @@ type MockMempool[T transaction.Tx] struct{}

func (MockMempool[T]) Insert(context.Context, T) error { return nil }
func (MockMempool[T]) Select(context.Context, []T) mempool.Iterator[T] { return nil }
func (MockMempool[T]) SelectBy(context.Context, []T, func(T) bool) {}
Copy link
Contributor

Choose a reason for hiding this comment

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

Complete the implementation of the SelectBy function.

The SelectBy function has been added to facilitate the selection of transactions based on a predicate. However, the current implementation is empty.

Please complete the function logic to ensure it behaves as expected when called. Consider iterating over the input transactions and applying the predicate to each transaction to determine which ones should be selected.

Copy link
Contributor

@testinginprod testinginprod left a comment

Choose a reason for hiding this comment

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

LGTM;

Although I think having the Remove step (or any other step) accept multiple txs might be a good idea to avoid locking the mempool multiple times.

It is also true that the mempool could implement its own batching mechanism for multiple txs to avoid multiple lokcs and remove txs in batches.

@julienrbrt julienrbrt added this pull request to the merge queue Sep 18, 2024
Merged via the queue into main with commit 356df96 Sep 18, 2024
73 checks passed
@julienrbrt julienrbrt deleted the julien/mempool-interface branch September 18, 2024 14:10
mergify bot pushed a commit that referenced this pull request Sep 18, 2024
#21744)

Co-authored-by: Marko <marko@baricevic.me>
(cherry picked from commit 356df96)

# Conflicts:
#	CHANGELOG.md
#	simapp/v2/go.mod
julienrbrt added a commit that referenced this pull request Sep 18, 2024
…e (backport #21744) (#21803)

Co-authored-by: Julien Robert <julien@rbrt.fr>
alpe added a commit that referenced this pull request Sep 18, 2024
* main:
  refactor(mempool)!: match server/v2/cometbft and sdk mempool interface (#21744)
  feat: make validator key injectable by application developers (#21608)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:server/v2 cometbft C:server/v2 Issues related to server/v2
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants