Skip to content

Conversation

@randy-cro
Copy link
Contributor

@randy-cro randy-cro commented Nov 12, 2025

Description

Previous staking optimizations were causing AppHash mismatches across nodes.
To address this issue, two key changes were introduced:

  1. Use of an in-memory KV store to manage staking caches.
    Reference

  2. Implementation of fixed gas consumption for staking-related messages to ensure consistent gas usage.
    Reference

PR Checklist:

  • Have you read the CONTRIBUTING.md?
  • Does your PR follow the C4 patch requirements?
  • Have you rebased your work on top of the latest master?
  • Have you checked your code compiles? (make)
  • Have you included tests for any non-trivial functionality?
  • Have you checked your code passes the unit tests? (make test)
  • Have you checked your code formatting is correct? (go fmt)
  • Have you checked your basic code style is fine? (golangci-lint run)
  • If you added any dependencies, have you checked they do not contain any known vulnerabilities? (go list -json -m all | nancy sleuth)
  • If your changes affect the client infrastructure, have you run the integration test?
  • If your changes affect public APIs, does your PR follow the C4 evolution of public contracts?
  • If your code changes public APIs, have you incremented the crate version numbers and documented your changes in the CHANGELOG.md?
  • If you are contributing for the first time, please read the agreement in CONTRIBUTING.md now and add a comment to this pull request stating that your PR is in accordance with the Developer's Certificate of Origin.

Thank you for your code, it's appreciated! :)

Summary by CodeRabbit

  • Bug Fixes

    • Optimized staking performance and standardized gas consumption for staking operations
    • Applied security patch for Comet BFT
  • New Features

    • End-to-end staking cache integration tests validating per-node cache sizes and cross-node consistency
    • In-memory store support integrated to improve staking performance and memory-backed behavior
  • Improvements

    • Changelog updated with unreleased entries and date marker
  • Chores

    • CI now runs staking tests in the integration test matrix

@randy-cro randy-cro requested a review from a team as a code owner November 12, 2025 10:39
@randy-cro randy-cro requested review from calvinaco and songgaoye and removed request for a team November 12, 2025 10:39
@github-actions

This comment has been minimized.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 12, 2025

Walkthrough

App StoreKeys now returns MemoryStoreKeys and App stores/mounts memKeys; a memory-backed service is passed into StakingKeeper. Staking integration tests, CLI helpers, and CI matrix updated; go.mod/gomod2nix replace directives and CHANGELOG entries adjusted.

Changes

Cohort / File(s) Summary
In-memory store infra
app/app.go, cmd/cronosd/cmd/versiondb.go
StoreKeys() extended to return map[string]*storetypes.MemoryStoreKey; App gains memKeys field and assigns it during New; MountMemoryStores(memKeys) invoked; callers updated to unpack the extra return; versiondb command updated to accept the extra value (ignored).
Staking keeper integration
app/app.go
StakingKeeper constructed with runtime.NewMemStoreService(memKeys[stakingtypes.CacheStoreKey]) so staking uses the memory-backed cache.
Integration tests: staking cache config & tests
integration_tests/configs/staking_cache.jsonnet, integration_tests/test_staking_cache.py
New Jsonnet describing a 5-node cluster with per-node staking.cache-size (-1,0,1,2,3); new pytest suite exercising delegations, redelegations, unbonding, validator unbonding and cross-node consistency before/after unbonding maturation.
Integration tests: CLI changes
integration_tests/cosmoscli.py
Added STAKING_DEFAULT_GAS, moved staking tx calls to fixed gas/gas_price usage; added get_delegations, get_unbonding_delegations, get_redelegations; updated delegate/unbond/redelegate signatures to use explicit gas and gas_prices.
CI matrix
.github/workflows/test.yml
Added "staking" to the integration_tests matrix (TESTS_TO_RUN includes staking).
Dependency & build metadata
go.mod, gomod2nix.toml
Updated replace directives to new upstreams (github.com/randy-cro/cosmos-sdk, github.com/randy-cro/ethermint) with updated pseudo-versions and hashes; gomod2nix entries updated accordingly.
Changelog
CHANGELOG.md
Added/expanded UNRELEASED entries (including PR #1907 and others) and added a date marker.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Reviewers should focus on:
    • All call sites of StoreKeys() for correct unpacking and handling of the added return.
    • Correct memKey names and that MountMemoryStores(memKeys) is invoked in the appropriate lifecycle phase.
    • StakingKeeper initialization uses the proper CacheStoreKey memKey.
    • Integration test stability: timing, ports, and cross-node assertions in staking_cache.jsonnet and tests.
    • go.mod / gomod2nix replace entries for reproducibility.

Possibly related PRs

Suggested reviewers

  • thomas-nguy

Poem

🐰 I nibble keys in mem so light,

Caches hum through day and night,
Five nodes hop, their states to share,
Tests bound, then clear the air,
A happy rabbit guards the byte 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'fix: staking optimization' is vague and generic, using non-descriptive terms that don't convey the specific nature of the optimization or the changes involved. Consider a more specific title that captures the key aspect, such as 'fix: optimize staking with in-memory KV store' or 'fix: standardize staking message gas consumption'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/staking-optimization

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@socket-security
Copy link

socket-security bot commented Nov 12, 2025

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedgolang/​github.com/​randy-cro/​ethermint@​v0.0.0-20251113080751-200a3fa212867510010010070
Addedgolang/​github.com/​randy-cro/​cosmos-sdk@​v0.0.0-20251113072857-fbecd698368d76100100100100

View full report

@thomas-nguy
Copy link
Collaborator

Lets change the target to main

v1.6.x is scheduled to be released soon and we do not have time to test this feature

@randy-cro randy-cro changed the base branch from release/v1.6.x to main November 13, 2025 03:22
@github-actions github-actions bot added the nix label Nov 13, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 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/100 where threshold = 100 + feeBump could overflow if both op (old priority) and feeBump are very large. While priorities are typically bounded in practice, consider:

  1. Adding validation for feeBump (e.g., feeBump < 0 || feeBump > 10000)
  2. Documenting the expected priority range assumptions
  3. Using safer arithmetic (e.g., rearranging to np*100 >= op*threshold with 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:

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between ae678b5 and e53a31f.

⛔ Files ignored due to path filters (2)
  • go.sum is excluded by !**/*.sum
  • versiondb/go.sum is 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 CronosConfig struct are in sync:

  • DisableTxReplacement and DisableOptimisticExecution fields defined with matching mapstructure tags
  • TOML keys (disable-tx-replacement, disable-optimistic-execution) properly mapped
nix/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:17 uses keys, _, _, _
  • app/app.go:452 uses keys, tkeys, okeys, memKeys

The breaking change has been properly handled throughout the codebase.


991-1006: Verify that ethermint's cache.NewAnteCache() correctly handles -1 to disable tx replacement caching.

The code logic is correct: when FlagDisableTxReplacement is set, mempoolCacheMaxTxs is set to -1 and passed through to cache.NewAnteCache(). However, the ethermint package (local fork v0.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
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

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:

  1. Security risk: Personal forks may not have the same security review process
  2. Maintenance risk: Personal accounts can be deleted or become unmaintained
  3. Trust chain: Validators and users need to trust official sources
  4. Code review: Changes in personal forks may not be properly reviewed
  5. 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:

  1. Merge necessary changes to official crypto-org-chain forks
  2. Tag proper releases
  3. Update go.mod to reference org-owned repositories
  4. 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
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

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

Where 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
Comment on lines 219 to 218
version = "v0.0.0-20251112055410-d2e10806c1d7"
hash = "sha256-vm19U7gZ6eaDgwnr1CurpBPCyZtDUv7UBFrfotHI+/c="
replaced = "github.com/randy-cro/cosmos-sdk"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical: Module replacement points to personal fork.

Consistent with the go.mod concern, the cosmos-sdk replacement is pointing to github.com/randy-cro/cosmos-sdk. This should reference an official organization-owned repository for production releases.

See the detailed concern raised in go.mod review (line 287). The same recommendation applies: use organization-owned forks with proper tagged releases.

🤖 Prompt for AI Agents
In gomod2nix.toml around lines 219 to 221, the module replacement points at a
personal fork ("github.com/randy-cro/cosmos-sdk"); replace this with the
official organization-owned repository (or an organization-maintained fork) and
a proper tagged release, update the corresponding version and sha256 hash to the
tag you choose, and keep it consistent with the change made in go.mod (see line
287); after updating, regenerate/validate modules (go mod tidy / regenerate
lockfile or run your gomod2nix workflow) so the version/hash are correct.

gomod2nix.toml Outdated
Comment on lines 318 to 320
version = "v0.0.0-20251112055637-cce6d2501268"
hash = "sha256-rMg+s1tLVXItVNuSub6pmf8XVN9ehvqvXy8FGKYpyac="
replaced = "github.com/randy-cro/ethermint"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

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.

@randy-cro randy-cro changed the base branch from main to release/v1.6.x November 13, 2025 04:01
@randy-cro randy-cro force-pushed the fix/staking-optimization branch from e53a31f to 65fb87c Compare November 13, 2025 04:02
@github-actions github-actions bot removed the nix label Nov 13, 2025
@randy-cro randy-cro changed the base branch from release/v1.6.x to main November 13, 2025 04:06
@randy-cro randy-cro force-pushed the fix/staking-optimization branch from 65fb87c to 475ba9d Compare November 13, 2025 04:07
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 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.toml

Also 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 messages
app/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

📥 Commits

Reviewing files that changed from the base of the PR and between e53a31f and 475ba9d.

⛔ Files ignored due to path filters (1)
  • go.sum is 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 defines server.FlagStakingCacheSize.

This codebase uses a custom fork (github.com/randy-cro/cosmos-sdk v0.0.0-20251112055410-d2e10806c1d7 via go.mod replace), and server.FlagStakingCacheSize is 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:

  1. jsonnet app-config → pystarport generates TOML config files
  2. App dynamically reads from appOpts via server.FlagStakingCacheSize (not a hardcoded CLI flag)
  3. Value passed directly to stakingkeeper.NewKeeper() constructor
  4. 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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.MemStoreKey to the memKeys initialization (line 254), you must also update this line to use memKeys instead of keys.

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.MemStoreKey is not included in the memKeys initialization.


504-515: [Duplicate] FlagStakingCacheSize is undefined.

This critical issue was already flagged in previous reviews. The server.FlagStakingCacheSize constant does not exist and will cause a runtime error during app initialization.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 475ba9d and 69b6498.

📒 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 memKeys field 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 to app.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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ 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 code just 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

📥 Commits

Reviewing files that changed from the base of the PR and between 69b6498 and 77e4f42.

📒 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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ 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, and total_count from 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

📥 Commits

Reviewing files that changed from the base of the PR and between 77e4f42 and ca0225d.

📒 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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 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, and total_count still 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

📥 Commits

Reviewing files that changed from the base of the PR and between ca0225d and 47420b2.

📒 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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between 47420b2 and 180b362.

📒 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.py with corresponding config integration_tests/configs/staking_cache.jsonnet
  • Git commit 475ba9d specifically 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.

@randy-cro randy-cro force-pushed the fix/staking-optimization branch from da9e628 to 57f2da3 Compare November 13, 2025 07:35
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ 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:

  1. Define this flag constant and register it in the CLI (e.g., in cmd/cronosd/cmd/root.go), or
  2. Use an alternative configuration mechanism (e.g., app.toml config value)

The integration test config at integration_tests/configs/staking_cache.jsonnet shows the intended usage via app-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

📥 Commits

Reviewing files that changed from the base of the PR and between 180b362 and 57f2da3.

⛔ Files ignored due to path filters (1)
  • go.sum is 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 since ChangeSetCmd operates on persisted database stores, not ephemeral in-memory caches.

@randy-cro randy-cro force-pushed the fix/staking-optimization branch from 57f2da3 to e677e38 Compare November 13, 2025 07:50
@randy-cro randy-cro force-pushed the fix/staking-optimization branch from e677e38 to 73f1631 Compare November 13, 2025 08:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants