Skip to content
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

optimize splay tree #907

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

optimize splay tree #907

wants to merge 2 commits into from

Conversation

m4ushold
Copy link
Contributor

@m4ushold m4ushold commented Oct 2, 2024

To prevent the tree from becoming skewed, I balanced it by splaying the first node of the sequence every 500 linear insert operations. The value 500 was determined experimentally.

What this PR does / why we need it:

Previous

  • This is the result of benchmarking in the current implementation.
    image
    image

  • previous pr(max height splay)
    In previous PR, we chose to balance the deepest node by splaying it whenever the tree was heightened, but the optimization was not good.
    image

  • The cost of reproducing the height and the overhead of checking the height for each operation and performing the splay operation seem to be larger than expected.

  • By triggering balancing based on height, the splay operation seems to occur more often than is required for balancing, resulting in performance degradation.

In this PR

  • block continuous linear opeartion
    The main idea is that the cause of the skew tree is a linear insert operation, so if such an operation is repeatedly entered, balancing is performed.

  • In insertAfter, the count is increased when the previous node is root, and the first node of the linear operation is splayed when the count is n or more.

Below is the result of experimenting with $n$, and the performance was the best when $n$ was 500.

  • n = 100

image

image

  • n = 500

image

image

  • n = 1000

image

image

  • n = 5000
    image

image

go test

image

C++ benchmark (based on a modified version of @justiceHui's code):

  • Tree height reduced by 20%.
  • Maximum rotations per operation reduced by 15%.
  • Total rotations reduced by 97%.
    Data used: editing-trace.json.
    Experimental code is available here.
    image

Which issue(s) this PR fixes:

Fixes #906

Special notes for your reviewer:
same pr as yorkie-team/yorkie#1025

Does this PR introduce a user-facing change?:


Additional documentation:


Checklist:

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Enhanced tree structure to track consecutive insertions and manage node references effectively.
    • Implemented a mechanism to trigger specific actions based on insertion counts, improving performance and functionality.

To prevent the tree from becoming skewed, I balanced it by splaying
the first node of the sequence every 500 linear insert operations.
The value 500 was determined experimentally.
Copy link

coderabbitai bot commented Oct 2, 2024

Walkthrough

The changes in this pull request modify the SplayTree class in splay_tree.ts by introducing a new static property SPLAY_THRESHOLD and two private properties, linearCount and firstNode. The constructor initializes linearCount to zero. The insertAfter method is updated to manage these properties, incrementing linearCount for root insertions, tracking the first node, and triggering a splay operation when the threshold is exceeded. These modifications aim to enhance the performance of the Splay Tree in the context of the crdt.Text data structure.

Changes

Files Change Summary
packages/sdk/src/util/splay_tree.ts Added properties SPLAY_THRESHOLD, linearCount, and firstNode; modified constructor and insertAfter method logic.

Assessment against linked issues

Objective Addressed Explanation
Improve performance of Splay Tree to prevent skewness (#906)

Possibly related PRs

  • Ensure find and indexOf perform splay #904: This PR modifies the SplayTree class in the same file (splay_tree.ts) and introduces changes to the getNodeAt and getIndexOfNode methods, which are relevant to the control flow and operations of the SplayTree, similar to the changes made in the main PR regarding the insertAfter method.

Poem

🐇 In the forest where trees sway,
A splay tree finds its way.
With counts and nodes, it takes a leap,
To keep its roots from falling deep.
Performance shines, no more to stray,
Hooray for changes made today! 🌳


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai 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.

@m4ushold m4ushold self-assigned this Oct 2, 2024
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: 3

🧹 Outside diff range and nitpick comments (2)
packages/sdk/src/util/splay_tree.ts (2)

173-174: Consider initializing firstNode in the constructor

While firstNode is optional, explicitly initializing it in the constructor enhances code clarity and prevents potential undefined issues.

Apply this diff to initialize firstNode:

 constructor(root?: SplayNode<V>) {
   this.root = root;
   this.linearCount = 0;
+  this.firstNode = undefined;
 }

263-274: Add comments to clarify the splaying logic for linear insertions

Adding descriptive comments helps others understand how linearCount and firstNode work together to prevent tree skewness due to sequential insertions.

Consider adding comments like this:

 if (target === this.root) {
+  // Increment linearCount when inserting after the root node
   this.linearCount++;
   if (this.linearCount == 1) {
+    // Store the first node of the linear insertion sequence
     this.firstNode = newNode;
   } else if (this.linearCount > 500) {
+    // Splay the first node to rebalance the tree after 500 insertions
     this.splayNode(this.firstNode);
     this.linearCount = 0;
   }
 } else {
+  // Reset linearCount if insertion is not after the root
   this.linearCount = 0;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 56ba2bb and 539490b.

📒 Files selected for processing (1)
  • packages/sdk/src/util/splay_tree.ts (2 hunks)

Comment on lines +268 to +269
this.splayNode(this.firstNode);
this.linearCount = 0;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure firstNode is defined before splaying

Although firstNode should be defined when linearCount > 500, adding a safety check can prevent unexpected errors if the state changes in the future.

Apply this diff to add a null check:

   } else if (this.linearCount > 500) {
+    if (this.firstNode) {
       this.splayNode(this.firstNode);
+    }
     this.linearCount = 0;

Committable suggestion was skipped due to low confidence.

Comment on lines 263 to 274
if (target == this.root) {
this.linearCount++;
if (this.linearCount==1) {
this.firstNode = newNode;
} else if (this.linearCount > 500) {
this.splayNode(this.firstNode);
this.linearCount = 0;
}
} else {
this.linearCount = 0;
}

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Make the splay threshold configurable

Hardcoding the value 500 limits flexibility. Defining it as a constant or making it configurable allows for easier tuning based on different use cases.

Define a constant at the top of the class:

 export class SplayTree<V> {
   private root?: SplayNode<V>;
+  private static readonly SPLAY_THRESHOLD = 500;
   private linearCount: number;
   private firstNode?: SplayNode<V>;

Update the code to use the constant:

-  } else if (this.linearCount > 500) {
+  } else if (this.linearCount > SplayTree.SPLAY_THRESHOLD) {

Committable suggestion was skipped due to low confidence.

Comment on lines 263 to 271
if (target == this.root) {
this.linearCount++;
if (this.linearCount==1) {
this.firstNode = newNode;
} else if (this.linearCount > 500) {
this.splayNode(this.firstNode);
this.linearCount = 0;
}
} else {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use strict equality === instead of ==

Using strict equality ensures both value and type are compared, preventing potential bugs with type coercion.

Apply this diff to use strict equality:

-if (target == this.root) {
+if (target === this.root) {
📝 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
if (target == this.root) {
this.linearCount++;
if (this.linearCount==1) {
this.firstNode = newNode;
} else if (this.linearCount > 500) {
this.splayNode(this.firstNode);
this.linearCount = 0;
}
} else {
if (target === this.root) {
this.linearCount++;
if (this.linearCount==1) {
this.firstNode = newNode;
} else if (this.linearCount > 500) {
this.splayNode(this.firstNode);
this.linearCount = 0;
}
} else {

Move hardcoded constant to readonly attribute in Splay Tree
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

🧹 Outside diff range and nitpick comments (1)
packages/sdk/src/util/splay_tree.ts (1)

173-175: LGTM! Consider making SPLAY_THRESHOLD configurable.

The new properties align well with the PR objectives for optimizing the splay tree performance. The static SPLAY_THRESHOLD effectively implements the proposed solution of splaying every 500 linear insert operations.

To enhance flexibility, consider making SPLAY_THRESHOLD configurable:

-  private static readonly SPLAY_THRESHOLD = 500;
+  private static SPLAY_THRESHOLD = 500;
+
+  public static setSplayThreshold(threshold: number): void {
+    if (threshold > 0) {
+      SplayTree.SPLAY_THRESHOLD = threshold;
+    }
+  }

This allows for easier tuning based on different use cases or performance requirements.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 539490b and 0329ccd.

📒 Files selected for processing (1)
  • packages/sdk/src/util/splay_tree.ts (4 hunks)
🔇 Additional comments (2)
packages/sdk/src/util/splay_tree.ts (2)

179-179: LGTM! Proper initialization of linearCount.

Initializing linearCount to 0 in the constructor is correct and aligns with the new balancing strategy. This ensures that each new SplayTree instance starts with a fresh count for linear insertions.


218-218: Consider the impact of splaying after find operations.

While splaying after find operations can improve amortized performance in typical splay trees, it might interfere with the new balancing strategy for linear insertions. Splaying nodes found by the find method could potentially break linear sequences that the new strategy is trying to manage.

To assess the impact, let's analyze the usage of the find method:

Consider whether splaying after find operations is necessary given the new balancing strategy, and evaluate its potential impact on the overall performance objectives of this PR.

Comment on lines +264 to +275
if (target == this.root) {
this.linearCount++;
if (this.linearCount == 1) {
this.firstNode = newNode;
} else if (this.linearCount > SplayTree.SPLAY_THRESHOLD) {
this.splayNode(this.firstNode);
this.linearCount = 0;
}
} else {
this.linearCount = 0;
}

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement the new balancing strategy with some improvements.

The new logic effectively implements the proposed balancing strategy for linear insertions, aligning well with the PR objectives. However, there are a few points to address:

  1. Use strict equality (===) instead of loose equality (==) for comparisons.
  2. Add a null check before splaying firstNode.
  3. Consider resetting firstNode after splaying.

Apply this diff to address the points mentioned:

-    if (target == this.root) {
+    if (target === this.root) {
       this.linearCount++;
-      if (this.linearCount == 1) {
+      if (this.linearCount === 1) {
         this.firstNode = newNode;
       } else if (this.linearCount > SplayTree.SPLAY_THRESHOLD) {
-        this.splayNode(this.firstNode);
+        if (this.firstNode) {
+          this.splayNode(this.firstNode);
+          this.firstNode = undefined;
+        }
         this.linearCount = 0;
       }
     } else {
       this.linearCount = 0;
+      this.firstNode = undefined;
     }

These changes improve type safety, prevent potential null pointer exceptions, and ensure proper reset of the firstNode reference.

📝 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
if (target == this.root) {
this.linearCount++;
if (this.linearCount == 1) {
this.firstNode = newNode;
} else if (this.linearCount > SplayTree.SPLAY_THRESHOLD) {
this.splayNode(this.firstNode);
this.linearCount = 0;
}
} else {
this.linearCount = 0;
}
if (target === this.root) {
this.linearCount++;
if (this.linearCount === 1) {
this.firstNode = newNode;
} else if (this.linearCount > SplayTree.SPLAY_THRESHOLD) {
if (this.firstNode) {
this.splayNode(this.firstNode);
this.firstNode = undefined;
}
this.linearCount = 0;
}
} else {
this.linearCount = 0;
this.firstNode = undefined;
}

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.

Improve performance of Splay Tree in crdt.Text data structure to prevent skewness
1 participant