Skip to content

Conversation

SpicyLemon
Copy link
Contributor

@SpicyLemon SpicyLemon commented Mar 26, 2025

Description

This PR improves the performance of GetAllBalances and GetAccountsBalances. They were using Coins.Add in a loop, which becomes prohibitively expensive as the number of denoms grows. Since the info is coming directly out of state, though, we know there are no duplicated denoms, and they'll be in the correct order already. So we can use append instead of Coins.Add and bypass a whole lot of copying, comparisons and processing.


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 N/A
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification N/A
  • 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

This update enhances the performance of account balance queries, resulting in faster and more efficient balance retrieval.

  • Performance Improvements
    • Optimized balance queries for quicker account information retrieval.
    • Streamlined the process of consolidating balance data to reduce processing time.
    • Delivers a smoother and more responsive experience when checking account balances.

Copy link
Contributor

coderabbitai bot commented Mar 26, 2025

📝 Walkthrough

Walkthrough

The changes introduce performance improvements in the Cosmos SDK’s bank module. Specifically, the keeper methods GetAllBalances and GetAccountsBalances in the x/bank module have been refactored. The modifications include using slice append instead of the sdk.Coins addition method, simplifying duplicate address checking logic, and removing an unnecessary sorting operation. These changes streamline balance aggregation and improve query efficiency without altering the underlying functional behavior.

Changes

File(s) Change Summary
CHANGELOG.md Added a changelog entry summarizing the performance improvements for balance queries in the bank module.
x/bank/keeper/view.go Modified GetAllBalances to use slice append instead of sdk.Coins.Add, removed sorting, and updated GetAccountsBalances to simplify duplicate address handling by replacing map-based index tracking with a check on the last entry in the slice.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant BaseViewKeeper
    Client->>BaseViewKeeper: Call GetAllBalances(account)
    BaseViewKeeper->>BaseViewKeeper: Iterate over balances
    BaseViewKeeper->>BaseViewKeeper: Append each balance using slice append
    BaseViewKeeper-->>Client: Return unsorted balance slice
Loading
sequenceDiagram
    participant Client
    participant BaseViewKeeper
    Client->>BaseViewKeeper: Call GetAccountsBalances(accounts)
    loop For each account transaction
        BaseViewKeeper->>BaseViewKeeper: Check if last entry matches current address
        alt Same address
            BaseViewKeeper->>BaseViewKeeper: Append new balance to existing account's Coins slice
        else New address
            BaseViewKeeper->>BaseViewKeeper: Create new accountBalance entry
        end
    end
    BaseViewKeeper-->>Client: Return consolidated account balances
Loading

Suggested reviewers

  • tac0turtle
  • alpe
  • facundomedica
  • julienrbrt

📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between da5a74d and 76dd017.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • x/bank/keeper/view.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.go`: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

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

  • x/bank/keeper/view.go
`**/*.md`: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

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

  • CHANGELOG.md
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze
  • GitHub Check: Summary
🔇 Additional comments (5)
CHANGELOG.md (1)

53-53: Well-formatted entry with no issues.

The changelog entry is clear, concise, and correctly formatted with the appropriate module prefix, PR reference, and description of the performance improvement.

x/bank/keeper/view.go (4)

101-110: Performance improvement through direct slice append

The change replaces Coins.Add with slice append for collecting balances, which is a good performance optimization since:

  1. Data coming from the state doesn't have duplicate denoms
  2. It eliminates unnecessary sorting, validation, and copying operations
  3. Directly returns the accumulated coins without sorting

These changes align perfectly with the PR objective to improve performance for accounts with many denominations.


121-124: Efficient simplification of duplicate address handling

This change optimizes the logic for handling duplicate addresses by checking if the current address matches the last entry instead of using a map for tracking indices. This works because:

  1. The iteration pattern guarantees consecutive entries for the same address
  2. It eliminates map lookups and additional memory usage
  3. The comment clearly explains the intention

This is a clean optimization that maintains the same functionality while reducing complexity.


127-133: Clear comment addition for new address entries

The added comment and logic handling for new address entries is clear and maintains the original functionality while being more efficient. The creation of new accountBalance entries only happens when necessary.


101-137:

❓ Verification inconclusive

Verify iteration ordering remains consistent

The optimizations in both GetAllBalances and GetAccountsBalances rely on the assumption that balances are iterated in a consistent way that clusters entries by address. This appears valid based on the implementation of IterateAllBalances, but it's worth verifying that no future changes to the iteration order would break this assumption.


🏁 Script executed:

#!/bin/bash
# Check if the iterator in IterateAllBalances preserves ordering by address

echo "Examining the Balances.Walk implementation to verify iteration order:"
rg -A 5 -B 5 "Walk.*Pair\[sdk\.AccAddress, string\]" --glob="**/*.go"

echo "Checking if there are tests that verify the iteration order behavior:"
rg -A 3 "TestIterate.*Balances" --glob="**/*_test.go"

Length of output: 1995


Iteration Order Validation Needed

The current implementation in x/bank/keeper/view.go relies on the assumption that Balances.Walk (used in both IterateAccountBalances and IterateAllBalances) returns balances grouped by address. The shell script output confirms the use of Walk for iteration but shows no dedicated tests verifying the ordering behavior. Please ensure that:

  • The underlying collection guarantees that iteration order clusters balances by address.
  • Robust tests are added to validate that this ordering assumption holds, preventing potential regressions if future changes affect the iteration order.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@SpicyLemon
Copy link
Contributor Author

I discovered the need for this because of an account that has over 10k different coins. The Coins.Add method has a bunch of overhead which is compounded when calling it in a loop like that. Our queries that utilize GetAllBalances would time out before returning.

@SpicyLemon SpicyLemon marked this pull request as ready for review March 26, 2025 17:27
@SpicyLemon SpicyLemon requested a review from a team March 26, 2025 17:27
@aljo242
Copy link
Contributor

aljo242 commented Mar 26, 2025

Do we have tests that ensure that these queries are still deterministic (in terms of ordering?)

@SpicyLemon
Copy link
Contributor Author

Do we have tests that ensure that these queries are still deterministic (in terms of ordering?)

I don't see any unit tests that test these methods specifically. However, GetAccountsBalances is used in many unit tests (to check account balances after doing stuff), and GetAllBalances is used to generate the bank genesis file which looks to only be tested in the sims.

They use the collection iterators, though, so the only way they'd be non-deterministic is if those iterators aren't deterministic. The balances key is <address> <denom>, so the iterator will go over all denoms for an address, then move on to the next, and the denoms will also be in alphabetical order for any given address.

The AllBalances query endpoint also builds the Coins this way. So if these aren't deterministic, then that query isn't either.

@SpicyLemon
Copy link
Contributor Author

SpicyLemon commented Apr 16, 2025

It appears that I no longer have the ability to push to this branch, so I cannot update it with recent changes. I'm not complaining, just pointing out that that's why this is still out of date.

@aljo242
Copy link
Contributor

aljo242 commented Apr 30, 2025

Hey @SpicyLemon - could you re-target this PR against main? The branches have drifted a lot but we'd love to get this in

@SpicyLemon
Copy link
Contributor Author

Hey @SpicyLemon - could you re-target this PR against main? The branches have drifted a lot but we'd love to get this in

My ability to push to the repo has been removed so I'll have to recreate this from a fork in order to be able to update it. I'll close this one once I've done that.

@SpicyLemon
Copy link
Contributor Author

I recreated this PR so that I could update the branch:

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