-
Notifications
You must be signed in to change notification settings - Fork 273
fix: staking optimization #1907
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
base: main
Are you sure you want to change the base?
Conversation
This comment has been minimized.
This comment has been minimized.
WalkthroughApp.StoreKeys now returns MemoryStoreKeys; App stores and mounts memKeys and passes a mem-backed service to StakingKeeper. CI matrix adds the staking integration test. New integration test config and pytest suite exercise staking cache behaviors. go.mod/gomod2nix replacements and CHANGELOG entries updated. Changes
Sequence Diagram(s)sequenceDiagram
participant New as App.New
participant StoreKeys as StoreKeys()
participant Mount as MountMemoryStores
participant Staking as StakingKeeper
New->>StoreKeys: call
StoreKeys-->>New: return (keys, tkeys, okeys, memKeys)
New->>New: App.memKeys = memKeys
New->>Mount: MountMemoryStores(memKeys)
rect rgba(200,220,255,0.14)
note right of New: wire memory-backed cache into keepers
New->>Staking: runtime.NewMemStoreService(memKeys[stakingtypes.CacheStoreKey])
Staking-->>New: initialized with memstore
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
|
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
|
bab1a75 to
65fb87c
Compare
|
Lets change the target to v1.6.x is scheduled to be released soon and we do not have time to test this feature |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
app/app.go (1)
387-407: Consider validating feeBump range and documenting arithmetic assumptions.The TxReplacement calculation
np >= op*threshold/100wherethreshold = 100 + feeBumpcould overflow if bothop(old priority) andfeeBumpare very large. While priorities are typically bounded in practice, consider:
- Adding validation for feeBump (e.g.,
feeBump < 0 || feeBump > 10000)- Documenting the expected priority range assumptions
- Using safer arithmetic (e.g., rearranging to
np*100 >= op*thresholdwith overflow checks)Example validation:
feeBump := cast.ToInt64(appOpts.Get(FlagMempoolFeeBump)) + if feeBump < 0 || feeBump > 10000 { + logger.Error("Invalid feeBump value, must be between 0 and 10000", "feeBump", feeBump) + feeBump = 0 + } if mempoolMaxTxs >= 0 && feeBump >= 0 {
🧹 Nitpick comments (2)
CHANGELOG.md (1)
5-5: Grammar suggestion: Use hyphenated compound modifiers.As per static analysis hint, compound modifiers before nouns should be hyphenated:
- "in memory KV store" → "in-memory KV store"
- "staking related messages" → "staking-related messages"
Based on learnings
cmd/cronosd/opendb/opendb_rocksdb.go (1)
58-59: Based on the verification, here is the rewritten review comment:Verify AsyncIO support for multi-platform deployments and consider making readahead size configurable.
The AsyncIO and 16MB readahead settings are hardcoded performance optimizations. Based on verification:
AsyncIO platform support: AsyncIO in grocksdb v1.10.2 is experimental and platform/FS-dependent, with no guaranteed support on macOS or Windows. While AsyncIO was intentionally enabled in this codebase, it may not provide actual asynchronous I/O on all target platforms.
Hardcoded readahead size: The 16MB readahead is not configurable, yet different deployment scenarios (resource-constrained nodes vs. high-performance validators) may benefit from different values.
Consider making these tunable via configuration to allow operators to optimize for their specific hardware and platform:
func openRocksdb(dir string, readonly bool) (dbm.DB, error) { + readaheadSize := viper.GetInt64("rocksdb.readahead-size") + if readaheadSize == 0 { + readaheadSize = 16 * 1024 * 1024 // default 16MB + } + enableAsyncIO := viper.GetBool("rocksdb.async-io") + ro := grocksdb.NewDefaultReadOptions() - ro.SetAsyncIO(true) - ro.SetReadaheadSize(16 * 1024 * 1024) + ro.SetAsyncIO(enableAsyncIO) + ro.SetReadaheadSize(readaheadSize)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
go.sumis excluded by!**/*.sumversiondb/go.sumis excluded by!**/*.sum
📒 Files selected for processing (22)
.github/workflows/test.yml(1 hunks)CHANGELOG.md(1 hunks)app/app.go(11 hunks)app/block_address.go(2 hunks)cmd/cronosd/cmd/root.go(3 hunks)cmd/cronosd/cmd/versiondb.go(1 hunks)cmd/cronosd/config/config.go(1 hunks)cmd/cronosd/config/toml.go(1 hunks)cmd/cronosd/opendb/opendb_rocksdb.go(1 hunks)default.nix(1 hunks)go.mod(3 hunks)gomod2nix.toml(4 hunks)integration_tests/configs/default.jsonnet(2 hunks)integration_tests/configs/staking_cache.jsonnet(1 hunks)integration_tests/contracts/contracts/TestBlockTxProperties.sol(1 hunks)integration_tests/cosmoscli.py(4 hunks)integration_tests/test_basic.py(1 hunks)integration_tests/test_mempool.py(2 hunks)integration_tests/test_staking_cache.py(1 hunks)integration_tests/utils.py(1 hunks)nix/rocksdb.nix(1 hunks)versiondb/go.mod(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (8)
app/block_address.go (1)
testground/benchmark/benchmark/cosmostx.py (1)
MsgEthereumTx(80-86)
integration_tests/test_staking_cache.py (3)
integration_tests/network.py (1)
setup_custom_cronos(153-195)integration_tests/utils.py (1)
wait_for_new_blocks(127-135)integration_tests/cosmoscli.py (11)
address(303-313)validators(351-356)delegate_amount(460-477)get_delegated_amount(399-411)unbond_amount(480-497)get_unbonding_delegations(428-441)redelegate_amount(500-520)get_redelegations(443-458)get_delegations(413-426)validator(339-349)status(175-176)
app/app.go (2)
store/setup.go (1)
SetupMemIAVL(29-59)x/cronos/keeper/keeper.go (1)
NewKeeper(52-78)
integration_tests/test_mempool.py (2)
integration_tests/utils.py (4)
get_account_nonce(455-457)replace_transaction(466-470)send_transaction(460-463)wait_for_new_blocks(127-135)integration_tests/network.py (3)
w3(39-42)cosmos_cli(56-57)cosmos_cli(81-82)
integration_tests/test_basic.py (2)
integration_tests/network.py (1)
w3(39-42)integration_tests/utils.py (2)
deploy_contract(415-435)send_transaction(460-463)
cmd/cronosd/cmd/versiondb.go (1)
app/app.go (1)
StoreKeys(233-263)
integration_tests/cosmoscli.py (2)
testground/benchmark/benchmark/cli.py (1)
raw(9-21)integration_tests/network.py (2)
node_rpc(53-54)node_rpc(78-79)
cmd/cronosd/cmd/root.go (2)
cmd/cronosd/config/config.go (2)
CronosConfig(12-17)DefaultCronosConfig(19-24)cmd/cronosd/config/toml.go (1)
DefaultCronosConfigTemplate(4-16)
🪛 LanguageTool
CHANGELOG.md
[grammar] ~5-~5: Use a hyphen to join words.
Context: ...fix: Optimize staking endblocker with in memory KV store and fix gas consumption ...
(QB_NEW_EN_HYPHEN)
[grammar] ~5-~5: Use a hyphen to join words.
Context: ...tore and fix gas consumption for staking related messages Nov 30, 2025 ## v1....
(QB_NEW_EN_HYPHEN)
🪛 markdownlint-cli2 (0.18.1)
CHANGELOG.md
7-7: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
17-17: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
30-30: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
38-38: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
🪛 Ruff (0.14.4)
integration_tests/test_staking_cache.py
39-39: Unused function argument: node_index
(ARG001)
171-171: Do not catch blind exception: Exception
(BLE001)
217-217: Do not catch blind exception: Exception
(BLE001)
361-361: Do not catch blind exception: Exception
(BLE001)
409-409: Do not catch blind exception: Exception
(BLE001)
705-705: Do not catch blind exception: Exception
(BLE001)
749-749: Do not catch blind exception: Exception
(BLE001)
824-824: Do not catch blind exception: Exception
(BLE001)
844-844: Do not catch blind exception: Exception
(BLE001)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (22)
app/block_address.go (1)
7-7: LGTM!The import is necessary for EIP-7702 authorization validation.
default.nix (1)
14-14: LGTM!Version metadata updated correctly from v1.5.0 to v1.5.4.
versiondb/go.mod (1)
19-19: LGTM!Grocksdb dependency updated from pseudo-version to stable release v1.10.2, aligning with the root go.mod changes.
go.mod (2)
36-36: LGTM! Grocksdb version updated.The grocksdb dependency is updated to a stable release v1.10.2, which aligns with the RocksDB 10.4.2 upgrade in the Nix configuration.
300-300: Cometbft fork version b0e778b18408 is correct and properly maintained.Verification confirms the commit is a legitimate PR #10 merge (Oct 15, 2025) on the v0.38.x branch. The patch adds essential validation to BitArray structures in consensus messages, preventing state corruption through inconsistency checks between bit count and element array length. Changes include:
- New
ValidateBasic()method for BitArray consistency validation- Validation calls in three consensus message types
- Defensive bounds checking in bit operations
- Comprehensive test coverage for invalid states
The patch addresses a real correctness issue and is properly tested.
gomod2nix.toml (1)
197-199: LGTM! Dependency hashes updated correctly.The cometbft and grocksdb version updates with corresponding hash changes appear correct and align with the go.mod updates.
Also applies to: 517-518
cmd/cronosd/config/toml.go (1)
1-16: LGTM! CronosConfig struct correctly matches template.The TOML template and
CronosConfigstruct are in sync:
DisableTxReplacementandDisableOptimisticExecutionfields defined with matching mapstructure tags- TOML keys (
disable-tx-replacement,disable-optimistic-execution) properly mappednix/rocksdb.nix (1)
24-30: I need to gather more information to fully assess the upgrade concerns.Based on my verification, I can now address the review comment with confidence.
Backward compatibility is guaranteed by RocksDB for database format.
RocksDB's compatibility guarantee states that "newer version of RocksDB should be able to open DBs generated by all previous releases for normal configuration." RocksDB maintains backward compatibility by understanding all formats previously written to disk, which is central to its design for large-scale distributed systems.
The upgrade path from 9.11.2 to 10.4.2 is supported. The breaking changes in v10.0 (C++20 compiler requirement, cache defaults, API signatures) are at the application compilation level, not the database format level—they affect code that compiles against RocksDB headers, not existing persisted databases.
Since this is a Nix package update that provides the RocksDB binary, applications using existing 9.x databases will be able to read them with the 10.4.2 binary without migration. The upgrade is a normal major version bump with no special on-disk format migration required for the stated use case.
The original review's cautionary recommendations (test with actual data, keep backups) remain sensible operational practices, but are not blocking concerns for this version bump.
app/app.go (7)
115-115: LGTM!The new import and flag definitions are properly structured and follow existing conventions.
Also applies to: 177-182
293-293: LGTM!The memKeys field addition is consistent with other store key fields in the App struct.
428-442: LGTM! Clear concurrency-safety logic.The conditional memiavl cache and optimistic execution setup correctly handles concurrency constraints. The comment explaining why the cache is disabled for concurrent executors is helpful.
452-452: LGTM!The StoreKeys call and memKeys assignment are correctly updated to handle the new memory store keys.
Also applies to: 466-466
984-984: LGTM!Memory stores are correctly mounted following the same pattern as other store types.
233-263: All callers of StoreKeys() correctly handle the updated return signature.The search confirms both call sites already unpack all 4 return values:
cmd/cronosd/cmd/versiondb.go:17useskeys, _, _, _app/app.go:452useskeys, tkeys, okeys, memKeysThe breaking change has been properly handled throughout the codebase.
991-1006: Verify that ethermint'scache.NewAnteCache()correctly handles -1 to disable tx replacement caching.The code logic is correct: when
FlagDisableTxReplacementis set,mempoolCacheMaxTxsis set to -1 and passed through tocache.NewAnteCache(). However, the ethermint package (local forkv0.0.0-20251112055637-cce6d2501268) behavior with the -1 parameter could not be verified without access to its source. Confirm that the external package properly interprets -1 as a signal to disable caching, or verify the intended semantics align with the implementation.cmd/cronosd/cmd/versiondb.go (1)
17-17: LGTM!Correctly handles the updated StoreKeys signature by ignoring the memory keys return value, which is not needed for the versiondb command.
integration_tests/configs/default.jsonnet (1)
31-31: LGTM!The feebump configuration value of 10 (10% minimum increase) is reasonable for integration testing the new mempool transaction replacement feature.
.github/workflows/test.yml (1)
22-22: LGTM!Adding staking tests to the CI matrix is appropriate given the staking cache optimization introduced in this PR.
integration_tests/utils.py (1)
66-66: LGTM!The TestBlockTxProperties contract is properly registered following the existing TEST_CONTRACTS pattern.
cmd/cronosd/cmd/root.go (1)
15-15: LGTM!The CronosConfig is properly integrated into the application configuration structure, following the established pattern for other config sections.
Also applies to: 276-276, 285-285, 288-288
cmd/cronosd/config/config.go (1)
12-24: LGTM!The CronosConfig struct is well-defined with clear documentation and sensible defaults (both optimizations enabled by default).
integration_tests/contracts/contracts/TestBlockTxProperties.sol (1)
1-17: LGTM!The TestBlockTxProperties contract is well-structured for testing transaction properties, capturing relevant tx and msg globals in the emitted event.
go.mod
Outdated
| cosmossdk.io/store => github.com/crypto-org-chain/cosmos-sdk/store v0.0.0-20241217090828-cfbca9fe8254 | ||
| cosmossdk.io/x/tx => github.com/crypto-org-chain/cosmos-sdk/x/tx v0.0.0-20241217090828-cfbca9fe8254 | ||
| github.com/cosmos/cosmos-sdk => github.com/crypto-org-chain/cosmos-sdk v0.50.6-0.20250424063720-28ea58ae20d8 | ||
| github.com/cosmos/cosmos-sdk => github.com/randy-cro/cosmos-sdk v0.0.0-20251112055410-d2e10806c1d7 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Personal fork used for cosmos-sdk replacement.
The module replacement is pointing to github.com/randy-cro/cosmos-sdk, which appears to be a personal fork rather than an official or organization-owned repository. This raises several critical concerns:
- Security risk: Personal forks may not have the same security review process
- Maintenance risk: Personal accounts can be deleted or become unmaintained
- Trust chain: Validators and users need to trust official sources
- Code review: Changes in personal forks may not be properly reviewed
- Production readiness: As thomas-nguy commented, this PR targets main and affects imminent releases
For production releases, all module replacements should point to either:
- Official upstream repositories
- Organization-owned forks (e.g., github.com/crypto-org-chain/*)
- Tagged releases with documented changes
Recommended action:
- Merge necessary changes to official crypto-org-chain forks
- Tag proper releases
- Update go.mod to reference org-owned repositories
- If this is development work, retarget this PR to a development branch, not main
🤖 Prompt for AI Agents
In go.mod around line 287, the module replacement points to a personal fork
(github.com/randy-cro/cosmos-sdk) which is not acceptable for production;
replace this by merging the required changes into an organization-owned fork or
the official upstream, create and push a tagged release (semver) on that
org-owned repo, then update go.mod to reference the org-owned repository and the
new tag (or the official upstream tag); if these changes are only for
development, retarget the PR to a non-main development branch instead of main.
go.mod
Outdated
| // develop | ||
| github.com/evmos/ethermint => github.com/crypto-org-chain/ethermint v0.22.1-0.20250909102334-034803df81c7 | ||
| // release/v0.22.x | ||
| github.com/evmos/ethermint => github.com/randy-cro/ethermint v0.0.0-20251112055637-cce6d2501268 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Personal fork used for ethermint replacement.
Similar to the cosmos-sdk issue above, github.com/randy-cro/ethermint is a personal fork that should not be used in production releases targeting the main branch.
Replace with organization-owned fork:
- github.com/evmos/ethermint => github.com/randy-cro/ethermint v0.0.0-20251112055637-cce6d2501268
+ github.com/evmos/ethermint => github.com/crypto-org-chain/ethermint v0.22.x-cronos-vX.X.XWhere v0.22.x-cronos-vX.X.X is a proper tagged release in the official organization repository.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In go.mod at line 309 replace the personal fork dependency
"github.com/randy-cro/ethermint => github.com/randy-cro/ethermint
v0.0.0-20251112055637-cce6d2501268" with the organization-owned ethermint module
and a proper tagged release (e.g. "github.com/<org>/ethermint
v0.22.x-cronos-vX.X.X"); update the require/replace entry to point to that org
repo and tag, then run go mod tidy (or go get) to refresh go.sum and ensure the
module resolves to the official tagged release.
gomod2nix.toml
Outdated
| version = "v0.0.0-20251112055637-cce6d2501268" | ||
| hash = "sha256-rMg+s1tLVXItVNuSub6pmf8XVN9ehvqvXy8FGKYpyac=" | ||
| replaced = "github.com/randy-cro/ethermint" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Module replacement points to personal fork.
The ethermint replacement references github.com/randy-cro/ethermint, which should be an organization-owned fork for production.
See go.mod line 309 review for detailed recommendations.
🤖 Prompt for AI Agents
In gomod2nix.toml around lines 318 to 320, the module replacement points to a
personal fork (github.com/randy-cro/ethermint); replace it with the
organization-owned fork or the official upstream module (e.g.,
github.com/<org>/ethermint or the canonical repo) and update the version and
sha256 hash to match that repository. After changing the replacement, run your
dependency tooling (go mod tidy && go mod download or the project-specific
gomod2nix regeneration command) to refresh checksums and then update
gomod2nix.toml with the new version/hash before committing.
e53a31f to
65fb87c
Compare
65fb87c to
475ba9d
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
app/app.go (1)
654-658: Pass the Cronos memory store key, not a KV key.CronosKeeper.NewKeeper(cdc, storeKey, memKey, ...) should get a MemoryStoreKey. Passing keys[cronostypes.MemStoreKey] will be nil (not created) and of wrong type. Use memKeys instead (after adding it as suggested).
- app.CronosKeeper = *cronoskeeper.NewKeeper( - appCodec, - keys[cronostypes.StoreKey], - keys[cronostypes.MemStoreKey], + app.CronosKeeper = *cronoskeeper.NewKeeper( + appCodec, + keys[cronostypes.StoreKey], + memKeys[cronostypes.MemStoreKey],integration_tests/cosmoscli.py (1)
460-519: Fix gas_prices mismatch in staking methods to prevent test failures.DEFAULT_GAS_PRICE ("100000000000basetcro" = 1e11) is 50x below staking_cache.jsonnet's minimum-gas-prices ("5000000000000basetcro" = 5e12). Staking transactions using delegate_amount, unbond_amount, and redelegate_amount will be rejected during test_staking_cache.py tests. Either:
- Bump DEFAULT_GAS_PRICE to match or exceed the config minimum, or
- Override gas_prices in these methods when used with staking_cache configs
♻️ Duplicate comments (1)
gomod2nix.toml (1)
215-218: Critical: deps point to a personal fork; pin to org-owned or upstream tags.Replacing to github.com/randy-cro/{cosmos-sdk,ethermint} is risky for production. Use an organization-owned fork (e.g., crypto-org-chain/*) or upstream with immutable tags, and align go.mod replaces. Regenerate gomod2nix hashes afterward.
Run to locate and cross-check go.mod replaces and refresh nix data:
#!/bin/bash set -euo pipefail # Show relevant replaces in go.mod rg -nP '^\s*replace\s+.+\s+=>\s+.+(cosmos-sdk|ethermint)' go.mod || true # Verify gomod2nix entries point to same modules/versions rg -n 'github.com/(randy-cro|crypto-org-chain)/(cosmos-sdk|ethermint)' gomod2nix.toml # If you switch repos/tags, regenerate: # nix run .#gomod2nix -- -out gomod2nix.tomlAlso applies to: 315-317
🧹 Nitpick comments (3)
CHANGELOG.md (1)
5-5: Wording nit: hyphenate “in-memory”.Change “in memory KV store” to “in-memory KV store” for clarity.
-* fix: Optimize staking endblocker with in memory KV store and fix gas consumption for staking related messages +* fix: Optimize staking endblocker with in-memory KV store and fix gas consumption for staking-related messagesapp/app.go (1)
1222-1236: Expose memory store keys too (optional).GetStoreKeys() omits memKeys. Including them can help executors/diagnostics that consume the full set of stores.
- keys := make([]storetypes.StoreKey, 0, len(app.keys)+len(app.tkeys)+len(app.okeys)) + keys := make([]storetypes.StoreKey, 0, len(app.keys)+len(app.tkeys)+len(app.okeys)+len(app.memKeys)) ... for _, key := range app.okeys { keys are appended } + for _, key := range app.memKeys { + keys = append(keys, key) + }integration_tests/test_staking_cache.py (1)
39-47: Remove unused parameter.get_validator_address doesn’t use node_index. Drop it or rename to _ to appease linters.
-def get_validator_address(cli, node_index): +def get_validator_address(cli): """Get validator address for a specific node.""" return cli.address("validator", bech="val")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (9)
.github/workflows/test.yml(1 hunks)CHANGELOG.md(1 hunks)app/app.go(7 hunks)cmd/cronosd/cmd/versiondb.go(1 hunks)go.mod(2 hunks)gomod2nix.toml(2 hunks)integration_tests/configs/staking_cache.jsonnet(1 hunks)integration_tests/cosmoscli.py(4 hunks)integration_tests/test_staking_cache.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- go.mod
🧰 Additional context used
🧬 Code graph analysis (4)
cmd/cronosd/cmd/versiondb.go (1)
app/app.go (1)
StoreKeys(228-258)
integration_tests/test_staking_cache.py (3)
integration_tests/network.py (1)
setup_custom_cronos(155-197)integration_tests/utils.py (1)
wait_for_new_blocks(133-141)integration_tests/cosmoscli.py (11)
address(303-313)validators(351-356)delegate_amount(460-477)get_delegated_amount(399-411)unbond_amount(480-497)get_unbonding_delegations(428-441)redelegate_amount(500-520)get_redelegations(443-458)get_delegations(413-426)validator(339-349)status(175-176)
app/app.go (1)
x/cronos/keeper/keeper.go (1)
NewKeeper(52-78)
integration_tests/cosmoscli.py (2)
testground/benchmark/benchmark/cli.py (1)
raw(9-21)integration_tests/network.py (2)
node_rpc(55-56)node_rpc(80-81)
🪛 GitHub Check: Lint python
integration_tests/test_staking_cache.py
[failure] 92-92:
./integration_tests/test_staking_cache.py:92:56: BLK100 Black would make changes.
🪛 Ruff (0.14.4)
integration_tests/test_staking_cache.py
39-39: Unused function argument: node_index
(ARG001)
171-171: Do not catch blind exception: Exception
(BLE001)
217-217: Do not catch blind exception: Exception
(BLE001)
361-361: Do not catch blind exception: Exception
(BLE001)
409-409: Do not catch blind exception: Exception
(BLE001)
705-705: Do not catch blind exception: Exception
(BLE001)
749-749: Do not catch blind exception: Exception
(BLE001)
824-824: Do not catch blind exception: Exception
(BLE001)
844-844: Do not catch blind exception: Exception
(BLE001)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (22)
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (staking)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (ibc)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: gomod2nix
- GitHub Check: build (ubuntu-latest)
- GitHub Check: unittest
- GitHub Check: build (macos-14)
- GitHub Check: build (macos-latest)
- GitHub Check: Run golangci-lint
- GitHub Check: Socket Security: Pull Request Alerts
- GitHub Check: Analyze (go)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (6)
cmd/cronosd/cmd/versiondb.go (1)
16-16: Signature drift handled correctly.Ignoring the new 4th return from app.StoreKeys() is fine for this command. No action needed.
integration_tests/cosmoscli.py (2)
22-22: Add constant: good default for staking tx gas.STAKING_DEFAULT_GAS centralizes staking gas; makes tests predictable.
413-459: New staking query helpers look good.get_delegations / get_unbonding_delegations / get_redelegations simplify tests and return normalized lists.
.github/workflows/test.yml (1)
22-22: CI matrix updated to run staking tests.Good addition; ensures coverage of the new suite.
app/app.go (1)
504-515: Verify the custom cosmos-sdk fork definesserver.FlagStakingCacheSize.This codebase uses a custom fork (
github.com/randy-cro/cosmos-sdk v0.0.0-20251112055410-d2e10806c1d7via go.mod replace), andserver.FlagStakingCacheSizeis not a standard Cosmos SDK flag. The flag is used at line 504 but not defined in the current codebase—it must come from the fork.Confirm the fork revision includes this flag definition, or define it locally:
- stakingCacheSize := cast.ToInt(appOpts.Get(server.FlagStakingCacheSize)) + const flagStakingCacheSize = "staking-cache-size" + stakingCacheSize := cast.ToInt(appOpts.Get(flagStakingCacheSize))If the custom fork is known to define it, cite the fork commit/branch.
integration_tests/configs/staking_cache.jsonnet (1)
18-23: Config properly wired to pass cache-size through appOpts to StakingKeeper.The per-node staking cache-size values are correctly wired:
- jsonnet app-config → pystarport generates TOML config files
- App dynamically reads from appOpts via
server.FlagStakingCacheSize(not a hardcoded CLI flag)- Value passed directly to
stakingkeeper.NewKeeper()constructor- Integration tests validate different cache sizes (-1, 0, 1, 2, 3) produce expected results
The configuration flows from jsonnet through TOML into the app, ensuring per-validator cache settings take effect.
There was a problem hiding this 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
app/app.go (1)
654-663: Critical: Use memKeys for CronosKeeper's memory store parameter.Line 657 incorrectly passes
keys[cronostypes.MemStoreKey]as the memory store key parameter. This passes a KVStoreKey when a MemoryStoreKey is expected, causing the memory store to not be properly wired to the CronosKeeper.After adding
cronostypes.MemStoreKeyto thememKeysinitialization (line 254), you must also update this line to usememKeysinstead ofkeys.Apply this diff:
app.CronosKeeper = *cronoskeeper.NewKeeper( appCodec, keys[cronostypes.StoreKey], - keys[cronostypes.MemStoreKey], + memKeys[cronostypes.MemStoreKey], app.BankKeeper, app.TransferKeeper, app.EvmKeeper, app.AccountKeeper, authAddr, )
♻️ Duplicate comments (2)
app/app.go (2)
254-254: [Duplicate] Add cronostypes.MemStoreKey to memory store keys.This issue was already flagged in previous reviews. The CronosKeeper requires a memory store key (see line 657), but
cronostypes.MemStoreKeyis not included in thememKeysinitialization.
504-515: [Duplicate] FlagStakingCacheSize is undefined.This critical issue was already flagged in previous reviews. The
server.FlagStakingCacheSizeconstant does not exist and will cause a runtime error during app initialization.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
app/app.go(7 hunks)integration_tests/test_staking_cache.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
integration_tests/test_staking_cache.py (3)
integration_tests/network.py (1)
setup_custom_cronos(155-197)integration_tests/utils.py (1)
wait_for_new_blocks(133-141)integration_tests/cosmoscli.py (11)
address(303-313)validators(351-356)delegate_amount(460-477)get_delegated_amount(399-411)unbond_amount(480-497)get_unbonding_delegations(428-441)redelegate_amount(500-520)get_redelegations(443-458)get_delegations(413-426)validator(339-349)status(175-176)
app/app.go (1)
x/cronos/keeper/keeper.go (1)
NewKeeper(52-78)
🪛 Ruff (0.14.4)
integration_tests/test_staking_cache.py
39-39: Unused function argument: node_index
(ARG001)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
- GitHub Check: unittest
- GitHub Check: Analyze (go)
- GitHub Check: build (macos-latest)
- GitHub Check: build (macos-14)
- GitHub Check: gomod2nix
- GitHub Check: build (ubuntu-latest)
- GitHub Check: Run golangci-lint
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (staking)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (ibc)
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
app/app.go (3)
285-288: LGTM – Memory store keys field added correctly.The
memKeysfield is properly added to the App struct with the correct type to store memory store keys.
434-448: LGTM – Memory store keys properly unpacked and assigned.The code correctly unpacks the fourth return value from
StoreKeys()and assigns it toapp.memKeys.
966-966: LGTM – Memory stores properly mounted.The call to
MountMemoryStores(memKeys)is correctly placed with other store mounting operations and is necessary for the memory stores to function.
There was a problem hiding this 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
♻️ Duplicate comments (3)
integration_tests/test_staking_cache.py (3)
170-183: Drop the stale post-loop print.This print runs after the loop and only reports the last node’s numbers, which is misleading. Remove it (or move logging inside the loop) to avoid confusion.
465-569: Fail fast when the validator self-delegation lookup fails.If the CLI call returns nothing or omits the validator entry, the test silently skips the unbonding flow and still passes—exactly the regression we need to catch. Assert on the response and fail when the self-delegation isn’t present so the test surfaces real problems.
- if delegation_info and "delegation_responses" in delegation_info: - for del_resp in delegation_info["delegation_responses"]: - if del_resp["delegation"]["validator_address"] == val_addr: - self_delegation = del_resp["delegation"]["shares"] - print(f"Self-delegation shares: {self_delegation}") - ... - break + assert delegation_info and "delegation_responses" in delegation_info, ( + f"Failed to fetch self-delegations for {val_addr} before unbonding." + ) + for del_resp in delegation_info["delegation_responses"]: + if del_resp["delegation"]["validator_address"] == val_addr: + self_delegation = del_resp["delegation"]["shares"] + print(f"Self-delegation shares: {self_delegation}") + ... + break + else: + pytest.fail( + f"Validator self-delegation entry for {val_addr} missing in response." + )
478-486: Assert the self-unbond transaction succeeds.Continuing after a non-zero
codejust prints a warning and masks a failed unbond. Assert on the result so any failure stops the test with useful context.- if rsp["code"] == 0: - print("Unbonding transaction successful") - else: - msg = f"Warning: Unbonding returned code {rsp['code']}: " - msg += rsp.get("raw_log", "") - print(msg) + assert rsp["code"] == 0, ( + f"Validator self-unbond returned code {rsp['code']}: " + f"{rsp.get('raw_log', rsp)}" + ) + print("Unbonding transaction successful")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
integration_tests/configs/staking_cache.jsonnet(1 hunks)integration_tests/test_staking_cache.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- integration_tests/configs/staking_cache.jsonnet
🧰 Additional context used
🧬 Code graph analysis (1)
integration_tests/test_staking_cache.py (3)
integration_tests/network.py (1)
setup_custom_cronos(155-197)integration_tests/utils.py (1)
wait_for_new_blocks(133-141)integration_tests/cosmoscli.py (11)
address(303-313)validators(351-356)delegate_amount(460-477)get_delegated_amount(399-411)unbond_amount(480-497)get_unbonding_delegations(428-441)redelegate_amount(500-520)get_redelegations(443-458)get_delegations(413-426)validator(339-349)status(175-176)
🪛 Ruff (0.14.4)
integration_tests/test_staking_cache.py
39-39: Unused function argument: node_index
(ARG001)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
- GitHub Check: build (ubuntu-latest)
- GitHub Check: build (macos-14)
- GitHub Check: unittest
- GitHub Check: gomod2nix
- GitHub Check: build (macos-latest)
- GitHub Check: integration_tests (staking)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: integration_tests (ibc)
- GitHub Check: Run golangci-lint
- GitHub Check: Analyze (go)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
There was a problem hiding this 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
♻️ Duplicate comments (3)
integration_tests/test_staking_cache.py (3)
173-177: Remove the misleading post-loop print.This summary reuses
node_idx,cache_size, andtotal_countfrom the last iteration only, so the numbers don’t describe the cluster. It was already called out earlier—please drop it (or compute a real aggregate).- msg = ( - f"Node {node_idx} (cache-size={cache_size}): " - f"{total_count} total unbonding delegations" - ) - print(msg) + # Summary already asserted above; no redundant final print needed.
472-480: Fail the test when the self-unbond transaction fails.We’re still only printing a warning on non-zero codes, so the validator could fail to unbond and the test would keep going. Make it a hard assertion instead.
rsp = cli.unbond_amount(val_addr, unbond_amount, "validator") print(f"Unbonding response: {rsp}") - - if rsp["code"] == 0: - print("Unbonding transaction successful") - else: - msg = f"Warning: Unbonding returned code {rsp['code']}: " - msg += rsp.get("raw_log", "") - print(msg) + assert rsp.get("code") == 0, ( + f"Validator unbonding failed: {rsp.get('raw_log', rsp)}" + ) + print("Unbonding transaction successful")
491-509: Fail fast when any node can’t fetch the validator.If one node returns nothing, we just print “Validator not found,” skip appending a status, and the test can still pass if the remaining nodes agree. Please turn that into a failure so cache inconsistencies don’t slip through.
- if validator and "validator" in validator: - val_info = validator["validator"] - status = val_info.get("status", "unknown") - tokens = val_info.get("tokens", "0") - jailed = val_info.get("jailed", False) - unbonding_statuses.append(status) - print( - f"Node {node_idx} (cache-size={cache_size}): " - f"Status={status}, Tokens={tokens}, Jailed={jailed}" - ) - else: - print( - f"Node {node_idx} (cache-size={cache_size}): " - f"Validator not found" - ) + if not validator or "validator" not in validator: + pytest.fail( + f"Node {node_idx} (cache-size={cache_size}) " + f"failed to return validator {val_addr}" + ) + val_info = validator["validator"] + status = val_info.get("status", "unknown") + tokens = val_info.get("tokens", "0") + jailed = val_info.get("jailed", False) + unbonding_statuses.append(status) + print( + f"Node {node_idx} (cache-size={cache_size}): " + f"Status={status}, Tokens={tokens}, Jailed={jailed}" + )
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
integration_tests/test_staking_cache.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
integration_tests/test_staking_cache.py (3)
integration_tests/network.py (1)
setup_custom_cronos(155-197)integration_tests/utils.py (1)
wait_for_new_blocks(133-141)integration_tests/cosmoscli.py (11)
address(303-313)validators(351-356)delegate_amount(460-477)get_delegated_amount(399-411)unbond_amount(480-497)get_unbonding_delegations(428-441)redelegate_amount(500-520)get_redelegations(443-458)get_delegations(413-426)validator(339-349)status(175-176)
🪛 GitHub Check: Lint python
integration_tests/test_staking_cache.py
[failure] 38-38:
./integration_tests/test_staking_cache.py:38:1: E302 expected 2 blank lines, found 1
[failure] 38-38:
./integration_tests/test_staking_cache.py:38:1: BLK100 Black would make changes.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
- GitHub Check: integration_tests (staking)
- GitHub Check: build (macos-latest)
- GitHub Check: build (ubuntu-latest)
- GitHub Check: gomod2nix
- GitHub Check: unittest
- GitHub Check: build (macos-14)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: Run golangci-lint
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: integration_tests (ibc)
- GitHub Check: Analyze (go)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
There was a problem hiding this 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
🧹 Nitpick comments (1)
integration_tests/test_staking_cache.py (1)
174-178: Fix the post-assertion summary log.After the loop,
node_idx,cache_size, andtotal_countstill reference the last iteration, so the printed summary misreports the result. Emit a single consistent count derived from the list you just asserted instead.- msg = ( - f"Node {node_idx} (cache-size={cache_size}): " - f"{total_count} total unbonding delegations" - ) - print(msg) + consistent_count = total_unbonding_counts[0] + print(f"✓ All nodes consistent: {consistent_count} total unbonding delegations")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
integration_tests/test_staking_cache.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
integration_tests/test_staking_cache.py (3)
integration_tests/network.py (1)
setup_custom_cronos(155-197)integration_tests/utils.py (1)
wait_for_new_blocks(133-141)integration_tests/cosmoscli.py (11)
address(303-313)validators(351-356)delegate_amount(460-477)get_delegated_amount(399-411)unbond_amount(480-497)get_unbonding_delegations(428-441)redelegate_amount(500-520)get_redelegations(443-458)get_delegations(413-426)validator(339-349)status(175-176)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
- GitHub Check: build (macos-latest)
- GitHub Check: build (macos-14)
- GitHub Check: build (ubuntu-latest)
- GitHub Check: unittest
- GitHub Check: gomod2nix
- GitHub Check: Run golangci-lint
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (staking)
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: integration_tests (ibc)
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: Analyze (go)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
There was a problem hiding this 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
🧹 Nitpick comments (1)
CHANGELOG.md (1)
5-5: Fix hyphenation in compound adjectives.Two compound adjectives need hyphens: "in-memory" and "staking-related".
Apply this diff:
-* [#1907](https://github.com/crypto-org-chain/cronos/pull/1907) perf: Optimize staking endblocker with an in-memory KV store and standardize gas consumption for staking related messages +* [#1907](https://github.com/crypto-org-chain/cronos/pull/1907) perf: Optimize staking endblocker with an in-memory KV store and standardize gas consumption for staking-related messages
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
CHANGELOG.md(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (22)
- GitHub Check: Socket Security: Pull Request Alerts
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (staking)
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: integration_tests (ibc)
- GitHub Check: build (macos-14)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: build (ubuntu-latest)
- GitHub Check: build (macos-latest)
- GitHub Check: gomod2nix
- GitHub Check: unittest
- GitHub Check: Run golangci-lint
- GitHub Check: Analyze (go)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
CHANGELOG.md (1)
5-5: Staking optimization is confirmed present in this PR.The concern can be resolved:
- Memory store infrastructure is wired to StakingKeeper (app/app.go:508) with proper routing of
stakingtypes.CacheStoreKey- Cache size parameter is implemented (app/app.go:504) and passed during keeper initialization (app/app.go:514)
- Integration tests are included:
integration_tests/test_staking_cache.pywith corresponding configintegration_tests/configs/staking_cache.jsonnet- Git commit
475ba9dspecifically addresses this with message "fix: staking optimization, add integration tests for staking cache"The optimization has not been reverted and is fully functional in the current PR state.
da9e628 to
57f2da3
Compare
There was a problem hiding this 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
♻️ Duplicate comments (3)
go.mod (2)
284-284: Personal fork remains in go.mod — production risk persists.The cosmos-sdk replacement still points to
github.com/randy-cro/cosmos-sdk, a personal fork. This was flagged in previous reviews and remains unresolved. For a production-ready PR targeting the main branch (with v1.6.x release imminent per thomas-nguy's comment), all replacements must reference organization-owned repositories with proper tagged releases.
306-306: Personal fork remains in go.mod — production risk persists.The ethermint replacement still points to
github.com/randy-cro/ethermint, a personal fork. This was flagged in previous reviews and remains unresolved. Both the cosmos-sdk and ethermint dependencies should be migrated to organization-owned forks with proper version tags before merging to main.app/app.go (1)
504-515: Critical: FlagStakingCacheSize undefined — runtime error guaranteed.Line 504 references
server.FlagStakingCacheSize, which does not exist in the Cosmos SDK server package and was not found anywhere in the codebase (per previous review searches). This will cause a runtime panic during app initialization.You must either:
- Define this flag constant and register it in the CLI (e.g., in cmd/cronosd/cmd/root.go), or
- Use an alternative configuration mechanism (e.g., app.toml config value)
The integration test config at
integration_tests/configs/staking_cache.jsonnetshows the intended usage viaapp-config.staking.cache-size, suggesting this should be read from app config, not a server flag.Consider reading from app config instead:
-stakingCacheSize := cast.ToInt(appOpts.Get(server.FlagStakingCacheSize)) +stakingCacheSize := cast.ToInt(appOpts.Get("staking.cache-size"))
🧹 Nitpick comments (1)
CHANGELOG.md (1)
5-5: Minor grammar improvement for changelog entry.The changelog entry could be improved for clarity and grammar:
- "staking related messages" should be "staking-related messages" (hyphenated)
- Consider "fix gas consumption" instead of "standardize gas consumption" to be more explicit
Apply this diff:
-* [#1907](https://github.com/crypto-org-chain/cronos/pull/1907) fix: Optimize staking endblocker with an in-memory KV store and standardize gas consumption for staking related messages +* [#1907](https://github.com/crypto-org-chain/cronos/pull/1907) fix: Optimize staking endblocker with an in-memory KV store and fix gas consumption for staking-related messages
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (9)
.github/workflows/test.yml(1 hunks)CHANGELOG.md(1 hunks)app/app.go(7 hunks)cmd/cronosd/cmd/versiondb.go(1 hunks)go.mod(2 hunks)gomod2nix.toml(2 hunks)integration_tests/configs/staking_cache.jsonnet(1 hunks)integration_tests/cosmoscli.py(4 hunks)integration_tests/test_staking_cache.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- integration_tests/cosmoscli.py
- gomod2nix.toml
- integration_tests/test_staking_cache.py
🧰 Additional context used
🧬 Code graph analysis (2)
cmd/cronosd/cmd/versiondb.go (1)
app/app.go (1)
StoreKeys(228-258)
app/app.go (1)
x/cronos/keeper/keeper.go (1)
NewKeeper(52-78)
🪛 GitHub Actions: Run Gosec
.github/workflows/test.yml
[error] CodeQL Action version v2 is deprecated. Please update all occurrences of the CodeQL Action in your workflow files to v3. Reference: github/codeql-action/upload-sarif@v3
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: build (macos-14)
- GitHub Check: build (ubuntu-latest)
- GitHub Check: build (macos-latest)
- GitHub Check: gomod2nix
- GitHub Check: unittest
- GitHub Check: Run golangci-lint
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (staking)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: integration_tests (ibc)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: Analyze (go)
🔇 Additional comments (5)
integration_tests/configs/staking_cache.jsonnet (1)
1-246: Excellent test configuration for staking cache validation.This test configuration systematically covers different cache size scenarios:
- Disabled cache (-1)
- Unlimited cache (0)
- Size-limited caches (1, 2, 3)
The consistent validator setup and clear inline comments make this a well-designed integration test. The comprehensive genesis configuration ensures thorough testing of the staking optimization feature.
.github/workflows/test.yml (1)
22-22: LGTM - enables staking cache integration tests.The addition of "staking" to the test matrix properly wires the new integration tests into CI, ensuring the staking optimization is validated in automated testing.
app/app.go (2)
434-448: Memory store integration properly implemented.The memory store wiring is correctly implemented:
- Line 434: StoreKeys() returns memKeys as 4th value
- Line 448: App stores memKeys reference
- Line 966: Memory stores are mounted before initialization
The integration follows the expected pattern for adding memory-backed stores to the Cosmos SDK app.
Also applies to: 966-966
228-233: All StoreKeys() callers properly updated to handle 4 return values.The ripgrep results confirm both callers have been correctly updated:
- app/app.go:434 unpacks all 4 return values
- cmd/cronosd/cmd/versiondb.go:16 captures all 4 with blank identifiers for unused values
The breaking API change is consistently implemented throughout the codebase.
cmd/cronosd/cmd/versiondb.go (1)
16-16: LGTM! Correctly adapts to the new StoreKeys() signature.The change properly unpacks all four return values from
app.StoreKeys(), discarding the newly added memory store keys (fourth return value) which is appropriate sinceChangeSetCmdoperates on persisted database stores, not ephemeral in-memory caches.
e677e38 to
73f1631
Compare
73f1631 to
0bd11b5
Compare
There was a problem hiding this 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
🧹 Nitpick comments (1)
integration_tests/test_staking_cache.py (1)
462-482: Consider deriving unbond amount from self-delegation balance.The hard-coded unbond amount
"1000000000000000000stake"at line 470 may cause test brittleness if genesis configurations or validator initial stakes change. Deriving the amount from the queried self-delegation balance (available at line 466 asdel_resp["balance"]) would make the test more resilient.Apply this pattern to derive the unbond amount:
if del_resp["delegation"]["validator_address"] == val_addr: self_delegation = del_resp["delegation"]["shares"] print(f"Self-delegation shares: {self_delegation}") - # Unbond all self-delegation - unbond_amount = "1000000000000000000stake" + # Unbond the full self-delegation + balance = del_resp.get("balance", {}) + assert balance and "amount" in balance and "denom" in balance, ( + f"Missing balance info for validator {val_addr}: {del_resp}" + ) + unbond_amount = f"{balance['amount']}{balance['denom']}"The same pattern should be applied at lines 764-766 in
test_staking_cache_consistency.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (9)
.github/workflows/test.yml(1 hunks)CHANGELOG.md(1 hunks)app/app.go(7 hunks)cmd/cronosd/cmd/versiondb.go(1 hunks)go.mod(5 hunks)gomod2nix.toml(4 hunks)integration_tests/configs/staking_cache.jsonnet(1 hunks)integration_tests/cosmoscli.py(4 hunks)integration_tests/test_staking_cache.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- go.mod
- CHANGELOG.md
- integration_tests/configs/staking_cache.jsonnet
🧰 Additional context used
🧬 Code graph analysis (4)
app/app.go (2)
x/cronos/types/keys.go (2)
MemStoreKey(18-18)StoreKey(12-12)x/cronos/keeper/keeper.go (1)
NewKeeper(52-78)
integration_tests/test_staking_cache.py (3)
integration_tests/network.py (1)
setup_custom_cronos(155-197)integration_tests/utils.py (1)
wait_for_new_blocks(133-141)integration_tests/cosmoscli.py (11)
address(303-313)validators(351-356)delegate_amount(460-477)get_delegated_amount(399-411)unbond_amount(480-497)get_unbonding_delegations(428-441)redelegate_amount(500-520)get_redelegations(443-458)get_delegations(413-426)validator(339-349)status(175-176)
integration_tests/cosmoscli.py (2)
testground/benchmark/benchmark/cli.py (1)
raw(9-21)integration_tests/network.py (2)
node_rpc(55-56)node_rpc(80-81)
cmd/cronosd/cmd/versiondb.go (1)
app/app.go (1)
StoreKeys(228-258)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (22)
- GitHub Check: Socket Security: Pull Request Alerts
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (staking)
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: integration_tests (ibc)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: unittest
- GitHub Check: Run golangci-lint
- GitHub Check: gomod2nix
- GitHub Check: build (macos-latest)
- GitHub Check: build (macos-14)
- GitHub Check: build (ubuntu-latest)
- GitHub Check: Analyze (go)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (12)
.github/workflows/test.yml (1)
22-22: LGTM: Staking test added to CI matrix.The addition of "staking" to the integration test matrix correctly enables the new staking cache tests in the CI pipeline.
cmd/cronosd/cmd/versiondb.go (1)
16-16: LGTM: Correctly handles updated StoreKeys signature.The unpacking correctly accommodates the new fourth return value (memKeys) from
app.StoreKeys()by ignoring it with_, which is appropriate since this command only needs the KV store keys.gomod2nix.toml (1)
140-144: Version bumps look correct.The btcd and btcd/btcec/v2 version updates with corresponding hash changes are properly formatted.
app/app.go (2)
228-258: LGTM: Memory store keys correctly integrated.The
StoreKeys()function now properly returnsmemKeysas the fourth value, including bothstakingtypes.CacheStoreKeyandcronostypes.MemStoreKey. The memory stores are correctly mounted at line 966 viaapp.MountMemoryStores(memKeys).
504-514: Cannot locate FlagStakingCacheSize definition—verification required.The code at line 504 references
server.FlagStakingCacheSize, which is not defined in this codebase or in the official cosmos-sdk. While a custom cosmos-sdk fork (randy-cro/cosmos-sdk v0.0.0-20251117070127-bfb2785e993e) is being used, the flag cannot be verified as existing in that fork without direct inspection. Confirm this flag is defined in the custom fork or add it locally before merge.integration_tests/cosmoscli.py (3)
22-22: LGTM: Fixed gas constant for staking operations.The
STAKING_DEFAULT_GASconstant aligns with the PR objective to implement fixed gas consumption for staking-related messages to ensure consistent gas usage across nodes.
413-458: LGTM: New staking query methods.The three new methods (
get_delegations,get_unbonding_delegations,get_redelegations) provide the necessary query interfaces for the staking cache tests. They correctly call the respective CLI commands and parse the responses.
460-520: LGTM: Consistent fixed gas applied to staking operations.The staking transaction methods (
delegate_amount,unbond_amount,redelegate_amount) now consistently useSTAKING_DEFAULT_GASandDEFAULT_GAS_PRICE, ensuring deterministic gas consumption across nodes as intended.integration_tests/test_staking_cache.py (4)
26-41: LGTM: Fixture and helper setup.The
cronos_staking_cachefixture correctly provisions a test cluster with the staking cache configuration, and theget_delegator_addresshelper provides a clean interface for retrieving delegator addresses.
44-225: LGTM: Comprehensive unbonding test with cross-node verification.The test properly exercises multiple unbonding operations from different delegators and validates consistency across all nodes (with different cache sizes) both before and after the unbonding period matures. The phased approach with explicit wait_for_new_blocks calls ensures state propagation.
227-408: LGTM: Thorough redelegation test.The test correctly validates redelegation operations across nodes with different cache configurations, checking both active redelegations and their maturation. The handling of "not found" errors during maturation verification (lines 376-388) is appropriate.
576-873: LGTM: Comprehensive consistency test covering full lifecycle.This test successfully combines delegations, redelegations, unbonding delegations, and validator unbonding with thorough cross-node consistency checks at each phase. The verification after maturation (Phase 6) ensures all transient staking state is properly cleaned up across all cache configurations.
0bd11b5 to
e920e8a
Compare
e920e8a to
8a5aad4
Compare
There was a problem hiding this 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
♻️ Duplicate comments (5)
go.mod (2)
284-284: Critical: Personal fork used for cosmos-sdk replacement.This issue was already flagged in previous reviews. The personal fork should be replaced with an organization-owned repository before merging to main.
306-306: Critical: Personal fork used for ethermint replacement.This issue was already flagged in previous reviews. The personal fork should be replaced with an organization-owned repository before merging to main.
gomod2nix.toml (2)
216-218: Critical: Module replacement points to personal fork.This issue was already flagged in previous reviews. The cosmos-sdk replacement should point to an organization-owned repository.
315-317: Critical: Module replacement points to personal fork.This issue was already flagged in previous reviews. The ethermint replacement should point to an organization-owned repository.
app/app.go (1)
504-514: FlagStakingCacheSize is not defined — critical runtime error.This issue was already flagged in previous reviews. The flag
server.FlagStakingCacheSizedoes not exist and will cause a runtime error during app initialization.
🧹 Nitpick comments (2)
integration_tests/cosmoscli.py (2)
413-426: Clarify distinction between get_delegations and get_delegated_amount.The new
get_delegationsmethod (lines 413-426) is nearly identical to the existingget_delegated_amountmethod (lines 399-411). Both query the same data butget_delegationsreturns the raw JSON response whileget_delegated_amountreturns it as well. This duplication may cause confusion.Consider either:
- Deprecating
get_delegated_amountin favor ofget_delegations- Renaming one method to clarify their different purposes
- Documenting the difference more clearly
460-477: Consider allowing gas parameter overrides.The delegate_amount method now uses fixed gas values (DEFAULT_GAS_PRICE and STAKING_DEFAULT_GAS), which ensures consistent gas consumption. However, this removes flexibility for callers who may need to customize gas settings for specific scenarios.
Consider adding optional **kwargs parameter to allow gas overrides when needed:
-def delegate_amount(self, to_addr, amount, from_addr): +def delegate_amount(self, to_addr, amount, from_addr, **kwargs): + kwargs.setdefault("gas_prices", DEFAULT_GAS_PRICE) + kwargs.setdefault("gas", STAKING_DEFAULT_GAS) return json.loads( self.raw( "tx", "staking", "delegate", to_addr, amount, "-y", home=self.data_dir, from_=from_addr, keyring_backend="test", chain_id=self.chain_id, node=self.node_rpc, - gas_prices=DEFAULT_GAS_PRICE, - gas=STAKING_DEFAULT_GAS, + **kwargs, ) )Apply similar changes to unbond_amount and redelegate_amount.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (9)
.github/workflows/test.yml(1 hunks)CHANGELOG.md(1 hunks)app/app.go(7 hunks)cmd/cronosd/cmd/versiondb.go(1 hunks)go.mod(5 hunks)gomod2nix.toml(4 hunks)integration_tests/configs/staking_cache.jsonnet(1 hunks)integration_tests/cosmoscli.py(4 hunks)integration_tests/test_staking_cache.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- .github/workflows/test.yml
- cmd/cronosd/cmd/versiondb.go
- CHANGELOG.md
- integration_tests/test_staking_cache.py
🧰 Additional context used
🧬 Code graph analysis (2)
integration_tests/cosmoscli.py (2)
testground/benchmark/benchmark/cli.py (1)
raw(9-21)integration_tests/network.py (2)
node_rpc(55-56)node_rpc(80-81)
app/app.go (2)
x/cronos/types/keys.go (2)
MemStoreKey(18-18)StoreKey(12-12)x/cronos/keeper/keeper.go (1)
NewKeeper(52-78)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: integration_tests (upgrade)
- GitHub Check: integration_tests (gov)
- GitHub Check: integration_tests (gas)
- GitHub Check: integration_tests (slow)
- GitHub Check: integration_tests (staking)
- GitHub Check: integration_tests (ibc_timeout)
- GitHub Check: integration_tests (ibc_update_client)
- GitHub Check: integration_tests (ica)
- GitHub Check: integration_tests (ibc_rly_evm)
- GitHub Check: integration_tests (unmarked)
- GitHub Check: integration_tests (ibc_rly_gas)
- GitHub Check: integration_tests (ibc)
- GitHub Check: gomod2nix
- GitHub Check: build (macos-latest)
- GitHub Check: build (macos-14)
- GitHub Check: build (ubuntu-latest)
- GitHub Check: unittest
- GitHub Check: Run golangci-lint
- GitHub Check: Analyze (go)
Description
To address the issue of slow nodes due to heavy i/o in staking endblocker, two key changes were introduced:
Use of an in-memory KV store to manage staking caches.
Reference
Implementation of fixed gas consumption for staking-related messages to ensure consistent gas usage.
Reference
PR Checklist:
make)make test)go fmt)golangci-lint run)go list -json -m all | nancy sleuth)Thank you for your code, it's appreciated! :)
Summary by CodeRabbit
Bug Fixes
New Features
Tests
Chores
Improvements