Skip to content

perf: avoid heavy object copy during ApplyDiff for CDeterministicMNList#6680

Merged
PastaPastaPasta merged 1 commit intodashpay:developfrom
knst:perf-GetListForBlockInternal
May 27, 2025
Merged

perf: avoid heavy object copy during ApplyDiff for CDeterministicMNList#6680
PastaPastaPasta merged 1 commit intodashpay:developfrom
knst:perf-GetListForBlockInternal

Conversation

@knst
Copy link
Collaborator

@knst knst commented May 22, 2025

Issue being fixed or feature implemented

The function ApplyDiff for CDeterministicMNList creates copy of current object and return it.
It is not efficient in case of applying several diffs one after one.
In case if UndoBlock and in case of calculating Quorum Members for old blocks (without caches) up to 576 temporary copies of CDeterministicMNList may be created and destroyed.

What was done?

ApplyDiff now changes current object, not returning a copy.

It speed ups calculation of GetDeterministicMNListInternal for ~10%; this helper is most hot function during:

  • block undo
  • RPC quorum info for distant quorums (when it's not in cache).
  • RPC quorum verify for distant quorums (when it's not in cache)

How Has This Been Tested?

Run unit / functional tests

Collected perf stats for block-undo.

develop:
image

PR:
image

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

@coderabbitai
Copy link

coderabbitai bot commented May 22, 2025

Walkthrough

The changes update the method CDeterministicMNList::ApplyDiff to perform in-place modifications on the current object instead of returning a new modified copy. The method's signature is changed from returning a CDeterministicMNList to returning void, and it is no longer marked as const. All usages of ApplyDiff throughout the codebase, including in CDeterministicMNManager and related tests, are updated to reflect this new in-place behavior. Additionally, a clarifying comment is added to the method declaration, and variable naming in the tests is corrected for consistency. No other exported or public entity signatures are altered.


📜 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 0de700400af3db43bdfb45ea40942dd86381d34d and 73b68fe.

📒 Files selected for processing (3)
  • src/evo/deterministicmns.cpp (3 hunks)
  • src/evo/deterministicmns.h (1 hunks)
  • src/test/evo_deterministicmns_tests.cpp (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/evo/deterministicmns.h
  • src/test/evo_deterministicmns_tests.cpp
🔇 Additional comments (2)
src/evo/deterministicmns.cpp (2)

708-709: Correctly adapted to new in-place ApplyDiff semantics

The change properly implements the new usage pattern:

  1. Creates an explicit copy of prevList (line 708)
  2. Modifies the copy in-place using ApplyDiff (line 709)

This maintains the same logical behavior while leveraging the performance optimization.


1097-1097: Correct usage of in-place ApplyDiff

This correctly uses the new in-place ApplyDiff method to modify the snapshot object directly. This sequential application of diffs without creating temporary copies aligns with the performance optimization goals of the PR.

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

Copy link

@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 (2)
src/evo/deterministicmns.h (1)

370-375: Polish the new doc-comment

Nice to see the explanatory comment, but there are two minor nits that may cause confusion:

  1. Typo: duplicated words “up to up to”.
  2. {DISK_SNAPSHOT_PERIOD} is a literal placeholder, so anyone reading the header (e.g. in an IDE) will not immediately know the magnitude you’re referring to. Either spell out the constant or add a short note.
- * Calculating for old block may take up to up to {DISK_SNAPSHOT_PERIOD} object copying and destroying.
+ * Calculating for old blocks may take up to DISK_SNAPSHOT_PERIOD object copies and destructions.
src/evo/deterministicmns.cpp (1)

1095-1098: Minor optimisation opportunity for empty diffs

GetListForBlockInternal now always calls ApplyDiff, even when diff.HasChanges()==false.
Given the added assert/early-return proposal in ApplyDiff, the overhead is negligible, but if you prefer to avoid the extra function call entirely you could keep the previous short-circuit.

Purely optional; feel free to ignore.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between da8a475 and 0de700400af3db43bdfb45ea40942dd86381d34d.

📒 Files selected for processing (3)
  • src/evo/deterministicmns.cpp (3 hunks)
  • src/evo/deterministicmns.h (1 hunks)
  • src/test/evo_deterministicmns_tests.cpp (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/evo/deterministicmns.cpp (1)
src/evo/deterministicmns.h (9)
  • pindex (375-375)
  • pindex (592-592)
  • pindex (594-594)
  • pindex (603-603)
  • pindex (616-616)
  • dmn (304-304)
  • dmn (305-305)
  • dmn (367-367)
  • dmn (377-377)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: x86_64-apple-darwin / Build depends
  • GitHub Check: x86_64-w64-mingw32 / Build depends
  • GitHub Check: x86_64-pc-linux-gnu_nowallet / Build depends
  • GitHub Check: arm-linux-gnueabihf / Build depends
  • GitHub Check: x86_64-pc-linux-gnu_multiprocess / Build depends
  • GitHub Check: x86_64-pc-linux-gnu / Build depends
🔇 Additional comments (2)
src/evo/deterministicmns.cpp (1)

708-710: Verify diff direction in UndoBlock

UndoBlock now reconstructs curList by copying prevList and applying the forward diff from prev → cur.
That produces the state being undone, which is what we later use to build the inverse diff, so the logic is sound.

Just double-check that the diff read from disk is always prev → cur; if at some point it’s stored inverted, the new call pattern will silently generate a corrupt list.

src/test/evo_deterministicmns_tests.cpp (1)

372-376: Good adaptation to in-place ApplyDiff

The test update mirrors the production change correctly: copying base_list and mutating it in-place preserves the original object for later assertions.

Comment on lines 426 to 448
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add consistency guards inside ApplyDiff

The in-place variant looks solid, but a few inexpensive assertions would harden it even more:

  1. assert(diff.nHeight == pindex->nHeight);
    – Helps detect accidental mismatches when we pass the wrong diff/pindex pair.

  2. Early exit when the diff is empty to skip hash/height updates in the no-op case (micro-optimisation but costs nothing).

 void CDeterministicMNList::ApplyDiff(gsl::not_null<const CBlockIndex*> pindex, const CDeterministicMNListDiff& diff)
 {
+    // Sanity: the diff we’re applying must belong to the same block.
+    assert(diff.nHeight == -1 || diff.nHeight == pindex->nHeight);
+    if (!diff.HasChanges()) {
+        blockHash = pindex->GetBlockHash();
+        nHeight   = pindex->nHeight;
+        return;
+    }

Those checks catch logical errors early without any runtime penalty in production builds (asserts are stripped in -DNDEBUG).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void CDeterministicMNList::ApplyDiff(gsl::not_null<const CBlockIndex*> pindex, const CDeterministicMNListDiff& diff)
{
CDeterministicMNList result = *this;
result.blockHash = pindex->GetBlockHash();
result.nHeight = pindex->nHeight;
blockHash = pindex->GetBlockHash();
nHeight = pindex->nHeight;
for (const auto& id : diff.removedMns) {
auto dmn = result.GetMNByInternalId(id);
auto dmn = GetMNByInternalId(id);
if (!dmn) {
throw std::runtime_error(strprintf("%s: can't find a removed masternode, id=%d", __func__, id));
}
result.RemoveMN(dmn->proTxHash);
RemoveMN(dmn->proTxHash);
}
for (const auto& dmn : diff.addedMNs) {
result.AddMN(dmn);
AddMN(dmn);
}
for (const auto& p : diff.updatedMNs) {
auto dmn = result.GetMNByInternalId(p.first);
auto dmn = GetMNByInternalId(p.first);
if (!dmn) {
throw std::runtime_error(strprintf("%s: can't find an updated masternode, id=%d", __func__, p.first));
}
result.UpdateMN(*dmn, p.second);
UpdateMN(*dmn, p.second);
}
return result;
}
void CDeterministicMNList::ApplyDiff(gsl::not_null<const CBlockIndex*> pindex, const CDeterministicMNListDiff& diff)
{
// Sanity: the diff we’re applying must belong to the same block.
assert(diff.nHeight == -1 || diff.nHeight == pindex->nHeight);
if (!diff.HasChanges()) {
blockHash = pindex->GetBlockHash();
nHeight = pindex->nHeight;
return;
}
blockHash = pindex->GetBlockHash();
nHeight = pindex->nHeight;
for (const auto& id : diff.removedMns) {
auto dmn = GetMNByInternalId(id);
if (!dmn) {
throw std::runtime_error(strprintf("%s: can't find a removed masternode, id=%d", __func__, id));
}
RemoveMN(dmn->proTxHash);
}
for (const auto& dmn : diff.addedMNs) {
AddMN(dmn);
}
for (const auto& p : diff.updatedMNs) {
auto dmn = GetMNByInternalId(p.first);
if (!dmn) {
throw std::runtime_error(strprintf("%s: can't find an updated masternode, id=%d", __func__, p.first));
}
UpdateMN(*dmn, p.second);
}
}
🤖 Prompt for AI Agents
In src/evo/deterministicmns.cpp around lines 426 to 448, add an assertion at the
start of ApplyDiff to verify that diff.nHeight equals pindex->nHeight to ensure
consistency between the diff and block index. Also, add an early return if the
diff is empty (no removed, added, or updated masternodes) to avoid unnecessary
updates to blockHash and nHeight. These changes improve robustness and
efficiency without affecting production performance due to asserts being
disabled in release builds.

@knst knst marked this pull request as draft May 22, 2025 13:01
@knst knst force-pushed the perf-GetListForBlockInternal branch from 0de7004 to 73b68fe Compare May 22, 2025 13:04
@knst knst marked this pull request as ready for review May 25, 2025 21:15
@knst knst requested review from PastaPastaPasta and UdjinM6 May 25, 2025 21:15
@knst knst added this to the 23 milestone May 25, 2025
Copy link

@UdjinM6 UdjinM6 left a comment

Choose a reason for hiding this comment

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

ACK 73b68fe

snapshot.SetBlockHash(diffIndex->GetBlockHash());
snapshot.SetHeight(diffIndex->nHeight);
}
snapshot.ApplyDiff(diffIndex, diff);
Copy link
Member

Choose a reason for hiding this comment

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

Am I correct that this is the only place we have a performance improvement right? All other instances, just now have an explicit copy instead of implicit copy. This change does seem worth it, but only this specific one in GetListForBlockInternal has any perf improvement

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

not counting unit tests, there are only 2 usages of ApplyDiff: GetListForBlockInternal and in UndoBlock. GetListForBlockInternal will be benefitial from this optimisation; undo block - doesn't become slower either faster.

Copy link
Member

@PastaPastaPasta PastaPastaPasta left a comment

Choose a reason for hiding this comment

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

utACK 73b68fe

@PastaPastaPasta PastaPastaPasta merged commit e626133 into dashpay:develop May 27, 2025
39 of 47 checks passed
@knst knst deleted the perf-GetListForBlockInternal branch May 27, 2025 14:14
knst pushed a commit to knst/dash that referenced this pull request Sep 17, 2025
…r CDeterministicMNList

73b68fe perf: avoid heavy object copy during ApplyDiff for CDeterministicMNList (Konstantin Akimov)

Pull request description:

  ## Issue being fixed or feature implemented
  The function `ApplyDiff` for CDeterministicMNList creates copy of current object and return it.
  It is not efficient in case of applying several diffs one after one.
  In case if `UndoBlock` and in case of calculating Quorum Members for old blocks (without caches) up to 576 temporary copies of CDeterministicMNList may be created and destroyed.

  ## What was done?
  `ApplyDiff` now changes current object, not returning a copy.

  It speed ups calculation of GetDeterministicMNListInternal for ~10%; this helper is most hot function during:
   - block undo
   - RPC `quorum info` for distant quorums (when it's not in cache).
   - RPC `quorum verify` for distant quorums (when it's not in cache)

  ## How Has This Been Tested?
  Run unit / functional tests

  Collected `perf` stats for block-undo.

  develop:
  <img width="772" alt="image" src="https://github.com/user-attachments/assets/a74e5dbb-314e-4067-b0dc-372235d37fb5" />

  PR:
  <img width="772" alt="image" src="https://github.com/user-attachments/assets/a587cb6d-96f1-4932-9143-90b7a08b2751" />

  ## Breaking Changes
  n/a

  ## Checklist:
  - [x] 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
  - [x] I have assigned this pull request to a milestone

ACKs for top commit:
  UdjinM6:
    ACK 73b68fe
  PastaPastaPasta:
    utACK 73b68fe

Tree-SHA512: cd82e35bdef6793d5bb0ea2189a66b01e50f318dbefd0283dab2973f6df8d99a731cef7b49aed5e8f9ca54c2282ab5570a35224e34c6d10447caeb9e097a31e5
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