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

perf: add cache to address codec #20122

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

Conversation

JulianToledano
Copy link
Contributor

@JulianToledano JulianToledano commented Apr 22, 2024

Description

ref:
#13140
#7448


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
  • 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.

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 address caching in the Bech32 codec to enhance performance.
    • Added new testing functionalities for Bech32 codec creation and concurrency.
  • Enhancements
    • Updated the initialization of address codecs in the NewSimApp function to use specific prefixes.
  • Documentation
    • Updated CHANGELOG to reflect new features and enhancements in the system.

@JulianToledano JulianToledano requested a review from a team as a code owner April 22, 2024 08:26
Copy link
Contributor

coderabbitai bot commented Apr 22, 2024

Warning

Rate Limit Exceeded

@JulianToledano has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 29 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.

Commits Files that changed from the base of the PR and between 469ac79 and a608650.

Walkthrough

The update primarily introduces caching for Bech32 address conversions in the codec module, enhancing performance. It also involves adding new tests for these codecs, ensuring robustness in concurrent scenarios. Other significant changes include modifications in the app.go file for initializing codecs with specific prefixes and several updates across different modules like server and telemetry for better customization and metric handling.

Changes

Files Changes Summary
.../bech32_codec.go Introduced caching mechanisms for address conversions, added new types and methods for cached address handling.
.../bech32_codec_test.go Added tests for Bech32 codecs, addressing different prefixes, conversions, and concurrency.
simapp/app.go Updated initialization of address codecs with specific prefixes.
CHANGELOG.md Documented new features and changes such as caching in address codec, updates in server customization, and telemetry enhancements.

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.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

This comment has been minimized.

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

Comment on lines 134 to 167
func (cbc cachedBech32Codec) BytesToString(bz []byte) (string, error) {
key := conv.UnsafeBytesToStr(bz)
cbc.mu.Lock()
defer cbc.mu.Unlock()

if addr, ok := cbc.cache.Get(key); ok {
return addr.(string), nil
}

addr, err := cbc.codec.BytesToString(bz)
if err != nil {
return "", err
}
cbc.cache.Add(key, addr)

return addr, nil
}

func (cbc cachedBech32Codec) StringToBytes(text string) ([]byte, error) {
cbc.mu.Lock()
defer cbc.mu.Unlock()

if addr, ok := cbc.cache.Get(text); ok {
return addr.([]byte), nil
}

addr, err := cbc.codec.StringToBytes(text)
if err != nil {
return nil, err
}
cbc.cache.Add(text, addr)

return addr, 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 locking strategy in cachedBech32Codec methods.

The current implementation locks the entire method, which could lead to performance bottlenecks. Consider using a more granular locking strategy or other synchronization techniques like sync.Map which is optimized for the use case where the entry for a given key is only written once but read many times.

codec/address/bech32_codec.go Outdated Show resolved Hide resolved
codec/address/bech32_codec.go Outdated Show resolved Hide resolved
Copy link
Contributor

@alpe alpe left a comment

Choose a reason for hiding this comment

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

Good start! 🏃
I added some thoughts and ideas although I have only limited context on this feature.

When it comes to caching, I also have telemetry on my list to learn about the utilization. This may be overkill but just sharing this collector as example.

}
if valAddrCache, err = simplelru.NewLRU(500, nil); err != nil {
panic(err)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🤔 do we need 3 different cache types? I was wondering if this is for sharding or pinning maybe? The LRU should keep the frequently used ones in cache anyway? WDYT?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The bytes of the addresses are the same, but there are three possible outputs (AccAddress, ValAddress, ConsAddress). I see three options here:

  1. Use three different caches.
  2. Add the prefix of the address codec to the key
  3. Store a map in the LRU with prefix as keys (e.g., map["cosmos"] = "cosmos1dr3...")

I've chosen the first option to maintain consistency with how things were done before.

cosmos-sdk/types/address.go

Lines 100 to 111 in 8e60f3b

var (
// AccAddress.String() is expensive and if unoptimized dominantly showed up in profiles,
// yet has no mechanisms to trivially cache the result given that AccAddress is a []byte type.
accAddrMu sync.Mutex
accAddrCache *simplelru.LRU
consAddrMu sync.Mutex
consAddrCache *simplelru.LRU
valAddrMu sync.Mutex
valAddrCache *simplelru.LRU
isCachingEnabled atomic.Bool
)


// in total the cache size is 61k entries. Key is 32 bytes and value is around 50-70 bytes.
// That will make around 92 * 61k * 2 (LRU) bytes ~ 11 MB
if accAddrCache, err = simplelru.NewLRU(60000, nil); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

personal preference: it would be great to have this configurable so people can trade CPU for memory or not.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Agreed. I'm not sure what the best approach is to solve this, as LRUs are currently shared between codecs and defined as globals.


func init() {
var err error
isCachingEnabled.Store(true)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: this is always true

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, followed the same style as in address.go, although I think it doesn't make much sense.


addr, err := cbc.codec.StringToBytes(text)
if err != nil {
return nil, err
Copy link
Contributor

Choose a reason for hiding this comment

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

🤔 it can be worth to cache failures, too. Some benchmarks would be interesting.

codec/address/bech32_codec.go Show resolved Hide resolved
cbc.mu.Lock()
defer cbc.mu.Unlock()

if addr, ok := cbc.cache.Get(key); ok {
Copy link
Contributor

Choose a reason for hiding this comment

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

Not sure if this is possible but in case the bytes match an existing bech32 address, it can create some trouble. Adding key prefixes may solve this or not sharing the same cache.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

See first comment. Currently, there are three different caches, but adding key prefixes may be a solution if we prefer just one.

codec/address/bech32_codec_test.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

Out of diff range and nitpick comments (1)
codec/address/bech32_codec.go (1)

39-54: Consider consolidating cache types or making cache configuration more flexible, as multiple cache types might not be necessary and could complicate maintenance.

codec/address/bech32_codec.go Outdated Show resolved Hide resolved
codec/address/bech32_codec.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: 1

CHANGELOG.md 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: 1

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 7ffa4a7 and 37bf7f5.
Files selected for processing (2)
  • codec/address/bech32_codec.go (2 hunks)
  • codec/address/bech32_codec_test.go (1 hunks)
Additional Context Used
Path-based Instructions (2)
codec/address/bech32_codec_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"

codec/address/bech32_codec.go (1)

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

Additional comments not posted (6)
codec/address/bech32_codec_test.go (2)

17-66: The unit tests in TestNewBech32Codec effectively validate the caching mechanism and address conversions. Good coverage of different prefixes and cache interactions.


70-92: The tests in TestMultipleBech32Codec correctly ensure that separate caches for different codecs do not interfere with each other and validate the caching behavior.

codec/address/bech32_codec.go (4)

39-53: Initialization of caches and mutexes is correctly implemented, ensuring separate caches for different address types and appropriate error handling.


69-91: The NewBech32Codec function is well-implemented, correctly handling the selection of caches and mutexes based on the prefix and the caching condition.


Line range hint 91-133: Methods StringToBytes and BytesToString in Bech32Codec are correctly implemented with comprehensive error handling and validation.


134-168: Methods in cachedBech32Codec are correctly implemented with thread safety and caching. Consider optimizing the locking strategy to improve performance, as discussed in previous comments.

codec/address/bech32_codec_test.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: 0

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 37bf7f5 and 469ac79.
Files selected for processing (1)
  • codec/address/bech32_codec_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • codec/address/bech32_codec_test.go

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.

None yet

5 participants