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

cache first version for legacy versions #1018

Merged
merged 3 commits into from
Dec 16, 2024
Merged

Conversation

yihuang
Copy link
Collaborator

@yihuang yihuang commented Dec 14, 2024

fix performance regression after upgrade.

Context

We see higher cpu usage in rpc nodes when serving similar traffic of queries, we dump a golang trace and see following stacktrace appears frequently, we suspect this to be the issue.
The first version in ndb seems should be cached, but it's not in legacy version case, which cause an extra seek call to underlying db, and the extra call happens for each store and for each query request.

github.com/linxGnu/grocksdb._Cfunc_rocksdb_iter_seek:3593
--
github.com/linxGnu/grocksdb.(*Iterator).Seek.func1:108
github.com/linxGnu/grocksdb.(*Iterator).Seek:108
github.com/cosmos/cosmos-db.newRocksDBIterator:40
github.com/cosmos/cosmos-db.(*RocksDB).Iterator:215
github.com/cosmos/cosmos-db.(*PrefixDB).Iterator:112
cosmossdk.io/store/wrapper.(*DBWrapper).Iterator:29
github.com/cosmos/iavl.(*nodeDB).getPrefixIterator:1002
github.com/cosmos/iavl.(*nodeDB).getFirstVersion:735
github.com/cosmos/iavl.(*MutableTree).VersionExists:88
cosmossdk.io/store/iavl.(*Store).VersionExists:176
cosmossdk.io/store/iavl.(*Store).GetImmutable:109
cosmossdk.io/store/rootmulti.(*Store).CacheMultiStoreWithVersion:612
github.com/cosmos/cosmos-sdk/baseapp.(*BaseApp).CreateQueryContext:1270
github.com/cosmos/cosmos-sdk/baseapp.(*BaseApp).RegisterGRPCServer.func1:49
github.com/cosmos/cosmos-sdk/baseapp.(*BaseApp).RegisterGRPCServer.func2.ChainUnaryServer.2.1:48
github.com/grpc-ecosystem/go-grpc-middleware/recovery.UnaryServerInterceptor.func1:33
github.com/cosmos/cosmos-sdk/baseapp.(*BaseApp).RegisterGRPCServer.func2.ChainUnaryServer.2:53

We've verified this fix reduce the cpu usage on the nodes quite effective.

Summary by CodeRabbit

  • New Features

    • Introduced new APIs: DeleteVersionsFrom(int64) and GetLatestVersion.
  • Bug Fixes

    • Added extra check for reformatted root node in GetNode.
    • Fixed performance regression by caching the first version for legacy versions.
  • Improvements

    • Enhanced error handling for node retrieval methods.
    • Improved version management within the database.
  • Documentation

    • Updated changelog with new entries for bug fixes and improvements.

@yihuang yihuang requested a review from a team as a code owner December 14, 2024 02:26
Copy link

coderabbitai bot commented Dec 14, 2024

Walkthrough

The pull request introduces several updates primarily focused on the iavl package and the nodedb.go file. Key changes include the addition of new APIs for version management, specifically DeleteVersionsFrom(int64) and GetLatestVersion, along with improvements to error handling and method signatures. The changelog has been updated to reflect these changes, including bug fixes and the removal of dependencies. Overall, the modifications enhance version management and error clarity without altering the fundamental control flow.

Changes

File Change Summary
CHANGELOG.md Updated to include entries for bug fixes and improvements, detailing new APIs and changes in methods.
nodedb.go Updated getFirstVersion to reset firstVersion for legacy versions; refined error messages in GetNode and GetFastNode.

Possibly related PRs

Suggested reviewers

  • cool-develope
  • tac0turtle

🐇 In the code, we hop and play,
With new APIs brightening the way.
Errors refined, versions reset,
In the changelog, our changes are met.
A leap for clarity, a jump for fun,
In the world of code, we’ve only begun! 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bb624b8 and d550dcf.

📒 Files selected for processing (1)
  • nodedb.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • nodedb.go

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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

@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 (1)
nodedb.go (1)

741-741: Consider adding a comment explaining the caching behavior.

Add a comment explaining that this caches the first version for performance optimization when dealing with legacy versions.

+       // Cache the first version from legacy format to avoid repeated database queries
        ndb.resetFirstVersion(version)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d89d5d2 and bb624b8.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • nodedb.go (1 hunks)
🔇 Additional comments (2)
CHANGELOG.md (1)

17-17: LGTM: Clear and accurate changelog entry.

The changelog entry accurately describes the change and its impact.

nodedb.go (1)

741-741: LGTM: Good performance optimization, but verify thread safety.

The addition of caching the first version when found in legacy format is a good optimization that fixes the performance regression. The change is consistent with the changelog entry.

However, let's verify the thread safety of this caching mechanism:

✅ Verification successful

Let me gather more information about mutex usage patterns around firstVersion to ensure thread safety.


Let me check one final aspect about the getFirstVersion implementation to complete the thread safety analysis.


Thread safety verified for firstVersion caching

The implementation is thread-safe:

  • resetFirstVersion uses proper mutex locking with Lock() and defer Unlock()
  • getFirstVersion correctly locks during firstVersion read
  • All modifications to firstVersion are protected by mutex

The only minor concern is in orphans() method which reads firstVersion without a lock, but this is acceptable since:

  • It's used only for iteration bounds
  • Concurrent updates would not cause corruption, only potentially skip/include an extra version
  • The method appears to be used for maintenance/debugging purposes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential race conditions in version management

# Look for other concurrent access to firstVersion
rg -A 5 "firstVersion\s*=|firstVersion\s*==|firstVersion\s*!=|firstVersion\s*[<>]"

# Look for other calls to resetFirstVersion
rg "resetFirstVersion"

# Look for mutex usage patterns around firstVersion access
ast-grep --pattern 'ndb.mtx.Lock()
  $$$
  ndb.firstVersion
  $$$'

Length of output: 2411


Script:

#!/bin/bash
# Check mutex patterns around firstVersion access and modification

# Look for the firstVersion field declaration and surrounding context
rg -A 5 -B 5 "firstVersion.*int64"

# Look for all getFirstVersion method implementations
ast-grep --pattern 'func $_getFirstVersion() (int64, error) {
  $$$
}'

# Look for mutex patterns in resetFirstVersion
ast-grep --pattern 'func (ndb *nodeDB) resetFirstVersion($_) {
  $$$
}'

Length of output: 2489


Script:

#!/bin/bash
# Check getFirstVersion implementation for mutex patterns

# Look for getFirstVersion implementation
ast-grep --pattern 'func (ndb *nodeDB) getFirstVersion() (int64, error) {
  $$$
}'

# Look for all firstVersion reads
rg -A 3 -B 3 "ndb\.firstVersion"

Length of output: 2455

yihuang added a commit to crypto-org-chain/iavl that referenced this pull request Dec 16, 2024
cache first version for legacy versions (backport: cosmos#1018)
@tac0turtle tac0turtle merged commit e60601d into cosmos:master Dec 16, 2024
5 of 12 checks passed
@tac0turtle
Copy link
Member

@mergify backport release/v1.2.x

Copy link
Contributor

mergify bot commented Dec 16, 2024

backport release/v1.2.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Dec 16, 2024
(cherry picked from commit e60601d)

# Conflicts:
#	CHANGELOG.md
@tac0turtle
Copy link
Member

tac0turtle commented Dec 16, 2024

@Mergifyio backport release/v1.3.x

Copy link
Contributor

mergify bot commented Dec 16, 2024

release /v1.3.x

❌ Sorry but I didn't understand the command. Please consult the commands documentation 📚.

Copy link
Contributor

mergify bot commented Dec 16, 2024

backport release/v1.3.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Dec 16, 2024
(cherry picked from commit e60601d)

# Conflicts:
#	CHANGELOG.md
tac0turtle added a commit that referenced this pull request Dec 16, 2024
Co-authored-by: yihuang <huang@crypto.com>
Co-authored-by: Marko <marbar3778@yahoo.com>
tac0turtle added a commit that referenced this pull request Dec 16, 2024
Co-authored-by: yihuang <huang@crypto.com>
Co-authored-by: Marko Baricevic <marbar3778@yahoo.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants