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(stf): change router service to extract the router at runtime rather than build time #20724

Merged
merged 15 commits into from
Jun 20, 2024

Conversation

testinginprod
Copy link
Contributor

@testinginprod testinginprod commented Jun 18, 2024

Description

Before: the router was being built and being passed to modules, this created a cyclic dependency in which modules to be be instantiated required the router, which in turn was created by STF that required all the modules.

After: the router is now extracted when needed by modules as they're executing a state transition, this makes it such that building logic is decocupled from execution logic.

Also closes: #20663


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

  • Refactor

    • Improved the internal architecture for message and query handling, making the system more modular and maintainable.
  • Tests

    • Added comprehensive test scenarios for block execution, transaction failures, and post-transaction failures to ensure robustness.
  • Chores

    • Removed unnecessary code and optimized existing functions to enhance performance and readability.

@testinginprod testinginprod requested a review from a team as a code owner June 18, 2024 21:20
Copy link
Contributor

coderabbitai bot commented Jun 18, 2024

Walkthrough

This update reengineers message and query handling within the STF struct. The primary changes involve transitioning from individual message and query handlers to the utilization of routers (msgRouter and queryRouter). The goal is to improve modularity and error handling, particularly addressing a nil dereference panic in deliverTx.

Changes

File(s) Change Summary
runtime/v2/builder.go Modified AppBuilder struct's Build method to construct stf object using msgRouterBuilder and queryRouterBuilder.
runtime/v2/module.go Updated ProvideEnvironment to revise initialization of QueryRouterService and MsgRouterService.
server/v2/stf/core_branch_service_test.go Removed handleMsg implementation and refactored test functions to add addMsgHandlerToSTF function.
server/v2/stf/core_router_service.go Refactored NewMsgRouterService and NewQueryRouterService to take an identity parameter and updated method signatures.
server/v2/stf/stf.go Refactored STF struct and NewSTF function; replaced handleMsg and handleQuery with router invocations.
server/v2/stf/stf_router.go Updated MsgRouterBuilder to return a Router struct implementing STF router functionality.
server/v2/stf/stf_router_test.go Added new file with TestMerge function for Router testing.
server/v2/stf/stf_test.go Added addMsgHandlerToSTF function for registering message handlers; refactored related functions and tests.
store/rootmulti/store_test.go Removed an empty line within a test function.

Assessment against linked issues

Objective Addressed Explanation
Prevent nil dereference panic in deliverTx (#20663)
Understand control flow changes for completing the new STF routing logic (#20439) Needs more refactoring specifics.

Possibly related issues


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>.
    • 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
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 (2)
server/v2/stf/core_branch_service_test.go (1)

Line range hint 19-44: Ensure comprehensive coverage and check for potential improvements in testing practices.

The additions to the test setup in TestBranchService function appear to cover new functionality. However, consider adding more detailed assertions to ensure that the state changes are as expected, and not just that no errors occur. Would you like assistance in enhancing these tests?

server/v2/stf/stf_router.go (1)

Line range hint 65-178: Review and refactor the Router implementation for optimization and error handling.

The Router struct and its methods are crucial for routing and handling messages. Consider optimizing the message handling logic to reduce duplication and improve performance. Additionally, ensure that error messages are clear and provide enough context to help diagnose issues quickly.

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 55821b3 and 25f5294.

Files selected for processing (8)
  • runtime/v2/builder.go (2 hunks)
  • runtime/v2/module.go (1 hunks)
  • server/v2/stf/core_branch_service_test.go (2 hunks)
  • server/v2/stf/core_router_service.go (1 hunks)
  • server/v2/stf/stf.go (11 hunks)
  • server/v2/stf/stf_router.go (4 hunks)
  • server/v2/stf/stf_test.go (4 hunks)
  • store/rootmulti/store_test.go (1 hunks)
Files skipped from review due to trivial changes (1)
  • store/rootmulti/store_test.go
Additional context used
Path-based instructions (7)
server/v2/stf/core_router_service.go (1)

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

server/v2/stf/core_branch_service_test.go (2)

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


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

server/v2/stf/stf_router.go (1)

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

runtime/v2/builder.go (1)

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

runtime/v2/module.go (1)

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

server/v2/stf/stf_test.go (2)

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


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

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

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

Additional comments not posted (7)
server/v2/stf/core_router_service.go (2)

44-54: Implementation of queryRouterService looks clean and follows the interface specifications.

The queryRouterService struct is implemented correctly according to the interface specifications, and there are no apparent issues with the methods provided.


27-40: Ensure type safety and error handling in msgRouterService methods.

These methods cast ctx to *executionContext without checking its actual type, which could lead to runtime panics if ctx is not of the expected type. Consider adding a type assertion and appropriate error handling to prevent potential runtime errors.

runtime/v2/builder.go (1)

Line range hint 101-116: Validate the integration of the STF setup in the Build method.

The integration of the STF using stf.NewSTF in the Build method appears correct, but ensure that all parameters passed are properly initialized and that the error handling is robust enough to catch and report any issues during the STF setup.

runtime/v2/module.go (1)

214-215: Refactored QueryRouterService and MsgRouterService initialization to be more modular and runtime-oriented.

server/v2/stf/stf_test.go (2)

23-54: Introduced addMsgHandlerToSTF to dynamically add message handlers, enhancing test flexibility and aligning with runtime message handling improvements.


90-93: Updated test scenarios to use addMsgHandlerToSTF, ensuring comprehensive testing of the new dynamic message handling capabilities.

Also applies to: 160-162, 203-205

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

47-79: Refactored NewSTF to accept dynamic router builders, enabling runtime router configuration and reducing build-time dependencies.

Comment on lines +13 to +23
func NewMsgRouterService(identity transaction.Identity) router.Service {
return msgRouterService{identity: identity}
}

var _ router.Service = (*msgRouterService)(nil)

type msgRouterService struct {
builder *MsgRouterBuilder
handler appmodulev2.Handler
// TODO(tip): the identity sits here for the purpose of disallowing modules to impersonate others (sudo).
// right now this is not used, but it serves the reminder of something that we should be eventually
// looking into.
identity []byte
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor suggestion for msgRouterService: Consider using the identity field in future implementations.

The identity field in the msgRouterService struct is currently unused. It's a good practice to avoid leaving unused code as it can lead to confusion and maintenance issues. If there are plans to use this field in the future, consider documenting the intended use more explicitly or implementing a placeholder functionality that can be expanded later.

server/v2/stf/core_router_service.go Show resolved Hide resolved
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.

utACK

@@ -42,29 +44,39 @@ type STF[T transaction.Tx] struct {

// NewSTF returns a new STF instance.
func NewSTF[T transaction.Tx](
handleMsg func(ctx context.Context, msg transaction.Msg) (transaction.Msg, error),
handleQuery func(ctx context.Context, req transaction.Msg) (transaction.Msg, error),
msgRouterBuilder *MsgRouterBuilder,
Copy link
Member

Choose a reason for hiding this comment

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

nit, can we add the logger here so it closes this as well: #20663

return &STF[T]{
handleMsg: handleMsg,
handleQuery: handleQuery,
logger: nil,
Copy link
Member

Choose a reason for hiding this comment

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

see above

if err != nil {
return err
}
gogoproto.Merge(resp, handlerResp)
Copy link
Member

@kocubinski kocubinski Jun 19, 2024

Choose a reason for hiding this comment

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

This will panic on custom typed gogo fields when the message is backed by a go struct, for example:

func Test_CoinMerge(t *testing.T) {
	src := sdk.NewInt64Coin("atom", 10)
	dst := &sdk.Coin{}
	require.Panics(t, func() {
		gogoproto.Merge(dst, &src)
	})
}

Previously I had (quite horrendous)

	reflect.Indirect(reflect.ValueOf(resp)).Set(reflect.Indirect(reflect.ValueOf(res)))

But I don't see any other alternatives on the table for a working implementation of InvokeTyped given the constraints of gogoproto and golang. We could remove InvokeTyped and just use InvokeUntyped, forcing callers to cast the returned type themselves.

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.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 25f5294 and b75456e.

Files selected for processing (2)
  • server/v2/stf/stf_router.go (4 hunks)
  • server/v2/stf/stf_router_test.go (1 hunks)
Files skipped from review due to trivial changes (1)
  • server/v2/stf/stf_router_test.go
Files skipped from review as they are similar to previous changes (1)
  • server/v2/stf/stf_router.go

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.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b75456e and 5ce7a41.

Files selected for processing (4)
  • runtime/v2/builder.go (2 hunks)
  • runtime/v2/module.go (1 hunks)
  • server/v2/stf/stf.go (11 hunks)
  • server/v2/stf/stf_router.go (4 hunks)
Files skipped from review as they are similar to previous changes (4)
  • runtime/v2/builder.go
  • runtime/v2/module.go
  • server/v2/stf/stf.go
  • server/v2/stf/stf_router.go

@@ -4,11 +4,13 @@
"context"
"errors"
"fmt"
"reflect"

Check notice

Code scanning / CodeQL

Sensitive package import Note

Certain system packages contain functions which may be a possible source of non-determinism
Copy link
Member

@kocubinski kocubinski left a comment

Choose a reason for hiding this comment

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

Big improvement ty 🙏

@testinginprod testinginprod added this pull request to the merge queue Jun 20, 2024
Merged via the queue into main with commit 11b8f11 Jun 20, 2024
69 of 70 checks passed
@testinginprod testinginprod deleted the tip/stf/change_routerservice branch June 20, 2024 13:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: server/v2/stf: nil deref panic in deliverTx
3 participants