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): port simappv2 changes #20587

Merged
merged 1 commit into from
Jun 10, 2024
Merged

feat(stf): port simappv2 changes #20587

merged 1 commit into from
Jun 10, 2024

Conversation

testinginprod
Copy link
Contributor

@testinginprod testinginprod commented Jun 6, 2024

Description

This PR ports simappv2 changes related to STF to main


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

    • Added functionality to retrieve and handle state changes for all actors.
    • Introduced lazy initialization for improved performance.
  • Refactor

    • Improved context creation and header information handling.
    • Enhanced message processing logic.

@testinginprod testinginprod requested a review from a team as a code owner June 6, 2024 17:15
Copy link
Contributor

coderabbitai bot commented Jun 6, 2024

Walkthrough

Walkthrough

The recent updates introduce significant enhancements to the WriterMap struct, core_router_service, and stf package in the server's version 2. These changes primarily focus on improving state management, lazy initialization of handlers, and context creation. New methods have been added to handle state changes recursively and process messages more efficiently, alongside refactoring existing functions for better performance and maintainability.

Changes

Files/Paths Change Summary
server/v2/stf/branch/writer_map.go Added GetStateChanges and recurseStateChanges methods to handle state changes for all actors.
server/v2/stf/core_router_service.go Introduced reflect import, removed handler initialization in NewQueryRouterService, added lazy initialization in InvokeTyped.
server/v2/stf/stf.go Added corecontext import, Identity variable, modified beginBlock logic, updated headerInfoPrefix, refactored setHeaderInfo and getHeaderInfo, and changed makeContext function.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant Client
    participant CoreRouterService
    participant Handler
    participant WriterMap
    participant STF

    Client->>CoreRouterService: InvokeTyped(Request)
    CoreRouterService->>CoreRouterService: Lazy initialize handler
    CoreRouterService->>Handler: Process message
    Handler->>WriterMap: GetStateChanges()
    WriterMap->>WriterMap: Recurse state changes
    WriterMap->>Handler: Return state changes
    Handler->>CoreRouterService: Return response
    CoreRouterService->>Client: Send response
Loading
sequenceDiagram
    participant STF
    participant Store
    participant Context

    STF->>Store: setHeaderInfo()
    Store-->>STF: Acknowledge
    STF->>Store: getHeaderInfo()
    Store-->>STF: Return header info
    STF->>Context: makeContext()
    Context-->>STF: Return execution context
Loading

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

github-actions bot commented Jun 6, 2024

@testinginprod your pull request is missing a changelog!

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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 439f2f9 and 93ec87c.

Files selected for processing (3)
  • server/v2/stf/branch/writer_map.go (1 hunks)
  • server/v2/stf/core_router_service.go (3 hunks)
  • server/v2/stf/stf.go (6 hunks)
Additional context used
Path-based instructions (3)
server/v2/stf/branch/writer_map.go (1)

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

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/stf.go (1)

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

golangci-lint
server/v2/stf/core_router_service.go

32-32: undefined: MsgRouterBuilder (typecheck)


73-73: undefined: MsgRouterBuilder (typecheck)


17-17: undefined: MsgRouterBuilder (typecheck)


64-64: undefined: MsgRouterBuilder (typecheck)

server/v2/stf/stf.go

38-38: undefined: branchFn (typecheck)


39-39: undefined: makeGasMeterFn (typecheck)


40-40: undefined: makeGasMeteredStateFn (typecheck)


558-558: undefined: branchFn (typecheck)


559-559: undefined: makeGasMeterFn (typecheck)


560-560: undefined: makeGasMeteredStateFn (typecheck)


606-606: undefined: makeGasMeterFn (typecheck)


607-607: undefined: makeGasMeteredStateFn (typecheck)


608-608: undefined: branchFn (typecheck)

Additional comments not posted (1)
server/v2/stf/stf.go (1)

593-598: Simplify context creation in makeContext.
[REFACTOR_SUGGESTion]
The method makeContext is frequently called and involves multiple steps. Consider optimizing this method by caching frequently used values or reducing the complexity of the context creation process to improve performance.

Comment on lines +56 to +71
// GetStateChanges returns the state changes for all actors in the WriterMap, including all direct
// ancesotors from which this WriterMap was derived.
// See WriterMap.recurseStateChanges for more details.
// Subject to possible renaming to ensure a developer can retrieve only changes in *this* branch
// context (not ancestors) if that is desired.
// see: https://github.com/cosmos/cosmos-sdk/pull/20412#discussion_r1618771230
func (b WriterMap) GetStateChanges() ([]store.StateChanges, error) {
sc := make([]store.StateChanges, len(b.branchedWriterState))
for account, stateChange := range b.branchedWriterState {
kvChanges, err := stateChange.ChangeSets()
if err != nil {
return nil, err
}
var (
changes = make(map[string][]store.KVPair)
sc []store.StateChanges
)
if err := b.recurseStateChanges(changes); err != nil {
return nil, err
}

for account, kvPairs := range changes {
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider renaming GetStateChanges to reflect its functionality more accurately.

The method name GetStateChanges might imply that it only retrieves changes from the current branch, but it also includes ancestor changes. Consider renaming it to GetAllStateChanges or similar to avoid confusion.

Comment on lines +80 to +95
func (b WriterMap) recurseStateChanges(changes map[string][]store.KVPair) error {
// depth first
if wr, ok := b.state.(WriterMap); ok {
if err := wr.recurseStateChanges(changes); err != nil {
return err
}
}
for account, stateChange := range b.branchedWriterState {
kvChanges, err := stateChange.ChangeSets()
if err != nil {
return err
}
changes[account] = append(changes[account], kvChanges...)
}
return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize the recursion in recurseStateChanges.

The recursive approach in recurseStateChanges could lead to performance issues with deep recursion. Consider using an iterative approach with a stack to manage state changes, which can be more efficient and easier to understand.

Comment on lines +98 to +112
// TODO lazy initialization is ugly and not thread safe. we don't want to check a mutex on every InvokeTyped either.
if m.handler == nil {
var err error
m.handler, err = m.builder.Build()
if err != nil {
return fmt.Errorf("cannot create queryRouter: %w", err)
}
}
// reflection is required, see https://github.com/cosmos/cosmos-sdk/pull/20349
res, err := m.handler(ctx, req)
if err != nil {
return err
}
reflect.Indirect(reflect.ValueOf(resp)).Set(reflect.Indirect(reflect.ValueOf(res)))
return nil
Copy link
Contributor

Choose a reason for hiding this comment

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

Address thread safety and performance concerns in InvokeTyped.

The lazy initialization of m.handler in InvokeTyped is not thread-safe. This could lead to race conditions in a multi-threaded environment. Consider initializing m.handler in the constructor or using synchronization mechanisms like mutexes to ensure thread safety.

Comment on lines +413 to +419
const headerInfoPrefix = 0x37

// setHeaderInfo sets the header info in the state to be used by queries in the future.
func (s STF[T]) setHeaderInfo(state store.WriterMap, headerInfo header.Info) error {
runtimeStore, err := state.GetWriter(appmanager.RuntimeIdentity)
// TODO storing header info is too low level here, stf should be stateless.
// We should have a keeper that does this.
runtimeStore, err := state.GetWriter(Identity)
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor setHeaderInfo to separate concerns.

The method setHeaderInfo is performing low-level operations that might be better handled by a dedicated component. Consider introducing a HeaderKeeper that encapsulates the logic for storing and retrieving header information, which would make STF more focused on its primary responsibilities.

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.

Breaks out the stf code from #20412, LGTM. Something needs to provision an stf store key, but I guess it's OK to leave that to follow on PRs too.

runtimeStore, err := state.GetWriter(appmanager.RuntimeIdentity)
// TODO storing header info is too low level here, stf should be stateless.
// We should have a keeper that does this.
runtimeStore, err := state.GetWriter(Identity)
Copy link
Member

Choose a reason for hiding this comment

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

Like we talked about, this GetWriter("stf") will err unless an "stf" storekey is provided, probably by runtime/v2 if we don't want depinject infra code in stf.

server/v2/stf/core_router_service.go Dismissed Show dismissed Hide dismissed
@tac0turtle tac0turtle added this pull request to the merge queue Jun 10, 2024
Merged via the queue into main with commit e799965 Jun 10, 2024
64 of 66 checks passed
@tac0turtle tac0turtle deleted the tip/simappv2/stf branch June 10, 2024 07:59
@testinginprod testinginprod restored the tip/simappv2/stf branch June 10, 2024 12:49
alpe added a commit that referenced this pull request Jun 12, 2024
* main:
  refactor(x/auth): Fix system test (#20531)
  feat(crypto): add blst (#20296)
  docs: Update high level overview and introduction (#20535)
  refactor(x/core): remove test (#20624)
  feat(x/mint)!: Replace InflationCalculationFn with MintFn + simple epoch minting (#20363)
  docs: remove duplicate words (#20622)
  feat: prep for errors v2 (#20539)
  chore: reduce default inflation (#20606)
  refactor(store): add miss defer (#20602)
  chore: use comet api pkg instead of comet alias (#20614)
  chore: write gentx info to cmd.ErrOrStderr (#20616)
  docs: ADR 073: update to accepted and add to README.md (#20619)
  chore(proto): change future extracted modules version from v1.0.0 to v0.2.0 (#20600)
  fix: remove some duplicate words (#20605)
  feat(stf): port simappv2 changes (#20587)
  chore: bring patch changelogs to main (#20599)
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.

4 participants