Skip to content

Conversation

alpe
Copy link
Contributor

@alpe alpe commented Apr 2, 2025

This is a rebased version of #23869 with some minor tweak and benchmark. All credits and bit thanks go to @ValarDragon for the original patch and idea!

Performance gains in the test setup to original code

Map key patch
((654391 - 435196) / 654391) * 100 ~= 33 %

Map value patch
((654391 - 421474) / 654391) * 100 ~= 35 %

Average

Original
(648741 + 649484 + 667771 + 651568) / 4 = 654391 ns/op
Map key patch
(433791 + 432525 + 432654 + 441817) / 4 = 435196 ns/op
Map value patch
(421966 + 422146 + 419467 + 422317) / 4 = 421474 ns/op

Benchmarks on my box

  • Original code
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    1789	    648741 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    1808	    649484 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    1755	    667771 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    1792	    651568 ns/op
  • With ValarDragon's patch to use non bech32 map key
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    2646	    433791 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    2608	    432525 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    2625	    432654 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    2661	    441817 ns/op
  • With my patch using int64 map value
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    2768	    421966 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    2654	    422146 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    2752	    419467 ns/op
BenchmarkApplyAndReturnValidatorSetUpdates-12    	    2703	    422317 ns/op




I did a quick microbenchmark in the beginning for marshal/unmarshal of `gogotypes.Int64Value` type. The unmarshal is ~41% faster so I refactored the index to use stdlib int64 instead. In the `BenchmarkApplyAndReturnValidatorSetUpdates` this brought ~2% performance gain.

BenchmarkMustMarshal
BenchmarkMustMarshal-12 60243637 19.92 ns/op
BenchmarkMustUnmarshal
BenchmarkMustUnmarshal-12 100000000 11.69 ns/op


<!-- Add a description of the changes that this PR introduces and the files that
are the most critical to review. -->

---

## 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](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title, you can find examples of the prefixes below:
    <!-- * `feat`: A new feature
    * `fix`: A bug fix
    * `docs`: Documentation only changes
    * `style`: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
    * `refactor`: A code change that neither fixes a bug nor adds a feature
    * `perf`: A code change that improves performance
    * `test`: Adding missing tests or correcting existing tests
    * `build`: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
    * `ci`: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
    * `chore`: Other changes that don't modify src or test files
    * `revert`: Reverts a previous commit -->
* [ ] confirmed `!` in the type prefix if API or client breaking change
* [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#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](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing)
* [ ] added a changelog entry to `CHANGELOG.md`
* [ ] updated the relevant documentation or specification, including comments for [documenting Go code](https://blog.golang.org/godoc)
* [ ] 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](../CONTRIBUTING.md#reviewer) for more information on how to review a pull request.

I have...

* [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) 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


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

- **Bug Fixes**
  - Prevented unexpected application interruptions in staking operations by ensuring clear, descriptive error messages during failures.

- **Refactor**
  - Streamlined the handling of validator state transitions and power updates for enhanced reliability and robustness.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

ValarDragon and others added 2 commits April 2, 2025 16:11
This change significantly improves the performance of staking endblock operations by:
1. Eliminating unnecessary Bech32 address conversions in getLastValidatorsByAddr and sortNoLongerBonded
2. Using string(byte[]) directly instead of codec.BytesToString
3. Updating error messages with more helpful context
4. Using AddRaw for better performance on integer addition

These optimizations are especially important for chains with many validators,
reducing the time spent in EndBlock which is a critical part of block processing.

Backport of commit cccdbd9

This comment has been minimized.

Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

📝 Walkthrough

Walkthrough

The changes update the ApplyAndReturnValidatorSetUpdates function in the staking keeper. The modifications improve error handling by wrapping and returning errors instead of panicking. The validator retrieval now uses a method that returns errors when a validator is not found. In addition, the logic for comparing and updating validator power has been simplified, and the type for storing validator power has been changed from a byte slice to an integer.

Changes

File Change Summary
x/staking/keeper/val_state_change.go Enhanced error handling in ApplyAndReturnValidatorSetUpdates with wrapped error messages; replaced mustGetValidator with GetValidator to handle missing validators gracefully; updated validator state checks to return errors instead of panicking; simplified power comparison logic; changed validatorsByAddr type from map[string][]byte to map[string]int64.

Sequence Diagram(s)

sequenceDiagram
  participant C as Caller
  participant A as ApplyAndReturnValidatorSetUpdates
  participant G as GetValidator
  participant S as StateCheck
  participant U as UpdatePower

  C->>A: Call ApplyAndReturnValidatorSetUpdates
  A->>G: Retrieve validator info
  G-->>A: Return validator object or error
  alt Error occurs during retrieval
    A->>C: Return wrapped error
  else Validator found
    A->>S: Check validator state (e.g., jailed, unexpected status)
    alt Invalid state
      A->>C: Return error with context
    else Valid state
      A->>U: Compare and update validator power if changed
      U-->>A: Updated validator power
      A->>C: Return validator set updates
    end
  end
Loading

📜 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 3ec128b and 308d4ba.

📒 Files selected for processing (1)
  • x/staking/keeper/val_state_change.go (12 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: test-system-legacy
  • GitHub Check: test-system
  • GitHub Check: tests (03)
  • GitHub Check: tests (02)
  • GitHub Check: tests (01)
  • GitHub Check: tests (00)
  • GitHub Check: test-sim-nondeterminism
  • GitHub Check: test-e2e
  • GitHub Check: test-integration
  • GitHub Check: build (arm64)
  • GitHub Check: build (amd64)
  • GitHub Check: Analyze
  • GitHub Check: dependency-review
  • GitHub Check: Gosec
  • GitHub Check: golangci-lint
  • GitHub Check: Summary
🔇 Additional comments (14)
x/staking/keeper/val_state_change.go (14)

6-6: Added import for errors package to use standard error types.

The errors package is now imported to replace panics with proper error handling throughout the code.


146-146: Improved error handling with context.

Good improvement - the error is now wrapped with additional context to help with debugging and troubleshooting.


152-152: Enhanced error message with context.

Similar to the previous change, this improvement provides better context when the iterator creation fails.


160-163: Replaced mustGetValidator with error handling approach.

This is a significant improvement in error handling. Rather than panicking when a validator is not found (as mustGetValidator would do), it now gracefully returns an error with context about which validator couldn't be found.


166-166: Changed panic to error return for jailed validator.

Good change - instead of panicking, the function now returns a descriptive error if a jailed validator is encountered in the power store.


192-192: Changed panic to error return for unexpected validator status.

Similar to the jailed validator check, this replaces a panic with a proper error return when an unexpected validator status is encountered.


195-196: Simplified power comparison using direct integer values.

The code now uses direct integer comparison instead of comparing bytes, making it cleaner and more efficient. The change is aligned with the type change from byte slices to integers for storing validator power.

Also applies to: 197-197, 201-201


212-212: Simplified power accumulation using raw integer value.

Using AddRaw with the integer power value is a cleaner approach than having to marshal/unmarshal the power value.


221-224: Consistent error handling for validator retrieval.

This change follows the same pattern as the earlier validator retrieval - replacing a potential panic with proper error handling.


231-231: Enhanced error message with context.

The error now provides more context about the failure, making debugging easier.


279-279: Improved error messages throughout validator state transitions.

All these state transition functions now provide better error messages with proper context about the failure.

Also applies to: 287-287, 295-295, 369-369, 393-393, 432-432


461-462: Changed validator power storage from byte slices to integers.

This optimization changes the map type from storing byte slices to storing integers directly, which should improve performance for power value comparisons and manipulations.


474-479: Optimized power value unmarshaling.

The function now uses direct integer values from Int64Value instead of dealing with byte slices, which aligns with the microbenchmark results mentioned in the PR description. This change should be more efficient for unmarshaling operations.


493-493: Simplified string to byte slice conversion.

This change simplifies the conversion from string to byte slice in the sortNoLongerBonded function.

✨ 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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

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

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.

@alpe alpe changed the title WIP: rebased #23869 + optimization perf(staking): optimize endblock by reducing bech32 conversions Apr 3, 2025
Copy link
Contributor

@aljo242 aljo242 left a comment

Choose a reason for hiding this comment

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

LGTM but let's keep the logic changes here minimal to what is needed for a performance improvement PR

Copy link
Contributor

@ValarDragon ValarDragon left a comment

Choose a reason for hiding this comment

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

Great! Really glad this is getting in

@aljo242 aljo242 enabled auto-merge April 3, 2025 20:44
@aljo242 aljo242 disabled auto-merge April 3, 2025 20:44
@aljo242 aljo242 added this pull request to the merge queue Apr 4, 2025
Merged via the queue into main with commit b49e864 Apr 4, 2025
46 checks passed
@aljo242 aljo242 deleted the alex/23869_ext branch April 4, 2025 18:59
julienrbrt pushed a commit to 01builders/cosmos-sdk that referenced this pull request Apr 8, 2025
thomas-nguy added a commit to crypto-org-chain/cosmos-sdk that referenced this pull request Aug 19, 2025
thomas-nguy added a commit to crypto-org-chain/cosmos-sdk that referenced this pull request Aug 20, 2025
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.

4 participants