Skip to content

perf: temporary cache for consequent calls of CDeterministicMNList for historical blocks #6734

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

knst
Copy link
Collaborator

@knst knst commented Jun 24, 2025

Issue being fixed or feature implemented

Each call of CDeterministicMNManager::GetListForBlock for historical block can require up to 575 diff applying from snapshot.
Consequent calls for close blocks repeat this calculation twice.

What was done?

This PR abuses mnListsCache by adding mini-snapshot each 32 blocks between snapshots in database (each 576 blocks).

Downside of this solution: extra RAM usage.
Though, this cache is cleaned every 10 seconds by CDeterministicMNManager::DoMaintenance, so, the RAM usage is temporary.

How Has This Been Tested?

It speeds up RPC protx diff up to 8x.
develop:

$ time ( for j in $(seq 500) ; do src/dash-cli protx diff $((2121000+$j)) $((2121000+$j+1)) ; done ) > /dev/null
real    0m47,743s
user    0m0,472s
sys     0m1,467s

PR:

$ time ( for j in $(seq 500) ; do src/dash-cli protx diff $((2121000+$j)) $((2121000+$j+1)) ; done ) > /dev/null
real    0m6,032s
user    0m0,423s
sys     0m1,300s

It speeds ups blocks's Undo up to 10x; measured by calling invalidateblock blockhash where blockhash is distant block, far from the tip (500+).

Breaking Changes

N/A

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation
  • I have assigned this pull request to a milestone

@knst knst added this to the 23 milestone Jun 24, 2025
Copy link

coderabbitai bot commented Jun 24, 2025

Walkthrough

A conditional block was added to the method CDeterministicMNManager::GetListForBlockInternal in src/evo/deterministicmns.cpp. After applying each cached diff to the snapshot, the code now caches the snapshot in mnListsCache if the snapshot's height is a multiple of 32. This caching is temporary and intended to optimize performance for queries of nearby blocks. No changes were made to the public interface or exported declarations; all modifications are internal to the method. The rest of the method’s logic, including loading and applying diffs and caching snapshots for the tip or quorums, remains unchanged.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4de63d1 and 30a9b2e.

📒 Files selected for processing (1)
  • src/evo/deterministicmns.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/evo/deterministicmns.cpp
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: linux64_tsan-build / Build source
  • GitHub Check: linux64_multiprocess-build / Build source
  • GitHub Check: mac-build / Build source
  • GitHub Check: linux64_nowallet-build / Build source
  • GitHub Check: win64-build / Build source
  • GitHub Check: linux64_fuzz-build / Build source
  • GitHub Check: linux64-build / Build source
  • GitHub Check: linux64_ubsan-build / Build source
  • GitHub Check: arm-linux-build / Build source
✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@knst
Copy link
Collaborator Author

knst commented Jun 24, 2025

@PastaPastaPasta

at first, I haven't planned to get this one merged, because I assumed that it improves only UndoBlock for several blocks; which maybe useful for reconsiderblock; and have very little benefits on mainnet; but actually it improves RPC performance for protx diff, especially for multiple calls for blocks that are close to each other. Also protx list is improved, if it's called multiple times for blocks that are close to each other in chain.

…r historical blocks

It speeds ups blocks's Undo up to 10x. It speeds up RPC `protx diff` up to 9x
@knst knst force-pushed the perf-rpc-protx-diff branch from 4de63d1 to 30a9b2e Compare June 24, 2025 20:47
@knst knst requested review from UdjinM6 and PastaPastaPasta July 1, 2025 15:20
Comment on lines +1072 to +1078
if (snapshot.GetHeight() % 32 == 0) {
// Add this temporary mini-snapshot to cache.
// This extra cached mn-list helps to improve performance of GetListForBlock
// for close blocks, because in the worst cases each of them requires to retrieve
// and apply up to 575 diffs
mnListsCache.emplace(snapshot.GetBlockHash(), snapshot);
}
Copy link
Member

Choose a reason for hiding this comment

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

  1. Consider Making Cache Interval Configurable
    - The hardcoded value 32 could be a named constant or configurable parameter
    static constexpr int MINI_SNAPSHOT_INTERVAL = 32;
    if (snapshot.GetHeight() % MINI_SNAPSHOT_INTERVAL == 0) {

@PastaPastaPasta
Copy link
Member

Consider:

  1. Add Test Coverage
    • The PR lacks unit tests verifying the caching behavior
    • Consider adding tests to ensure:
      • Snapshots are created at correct intervals
      • Cache hits improve performance
      • Cache cleanup doesn't remove actively used snapshots
  2. Documentation
    - The inline comment is good but could explain the "575 diffs" calculation more clearly
    - Consider adding a brief explanation of why 32 was chosen as the interval

@UdjinM6
Copy link

UdjinM6 commented Aug 15, 2025

  1. We should probably disable this extra cache while node is still reindexing e.g
diff --git a/src/evo/deterministicmns.cpp b/src/evo/deterministicmns.cpp
index 921a119642..3f2dab1d3e 100644
--- a/src/evo/deterministicmns.cpp
+++ b/src/evo/deterministicmns.cpp
@@ -16,6 +16,7 @@
 #include <consensus/validation.h>
 #include <deploymentstatus.h>
 #include <messagesigner.h>
+#include <node/blockstorage.h>
 #include <script/standard.h>
 #include <stats/client.h>
 #include <uint256.h>
@@ -26,6 +27,8 @@
 #include <optional>
 #include <memory>
 
+using node::fReindex;
+
 static const std::string DB_LIST_SNAPSHOT = "dmn_S3";
 static const std::string DB_LIST_DIFF = "dmn_D3";
 
@@ -780,7 +783,7 @@ CDeterministicMNList CDeterministicMNManager::GetListForBlockInternal(gsl::not_n
     for (const auto& diffIndex : listDiffIndexes) {
         const auto& diff = mnListDiffsCache.at(diffIndex->GetBlockHash());
         snapshot.ApplyDiff(diffIndex, diff);
-        if (snapshot.GetHeight() % 32 == 0) {
+        if (!fReindex && (snapshot.GetHeight() % 32 == 0)) {
             // Add this temporary mini-snapshot to cache.
             // This extra cached mn-list helps to improve performance of GetListForBlock
             // for close blocks, because in the worst cases each of them requires to retrieve
  1. Consider Making Cache Interval Configurable
    • The hardcoded value 32 could be a named constant or configurable parameter
      static constexpr int MINI_SNAPSHOT_INTERVAL = 32;
      if (snapshot.GetHeight() % MINI_SNAPSHOT_INTERVAL == 0) {

Agree

  1. Add Test Coverage

    • The PR lacks unit tests verifying the caching behavior

    • Consider adding tests to ensure:

      • Snapshots are created at correct intervals
      • Cache hits improve performance
      • Cache cleanup doesn't remove actively used snapshots

Adding unit tests here feels like an overkill tbh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants