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

Balancing Tree to Prevent Skewness #1025

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

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:

Description:
This pull request (PR) introduces an enhanced method for balancing a tree during insert operations to prevent skewness. The goal is to optimize performance by replacing the inefficient height-based splay operations with a more effective approach.

Changes Made:

  1. Linear Operation Detection and Balancing:

    • Detects sequences of linear insert operations that can cause the tree to become skewed.
    • Balances the tree by splaying the first node of the sequence when consecutive inserts originate from the root.
  2. Optimization of Splay Trigger Frequency:

    • Sets the splay operation to trigger every 500 linear insert operations. Through testing, it was determined that a threshold of 500 offers optimal performance among various alternatives.

Code Modifications:

  • Added linearCount and firstNode fields to the Tree structure to track consecutive insert operations.
  • Modified the InsertAfter method to conditionally perform a splay operation and reset linearCount.
// Additional fields in the Tree structure:
type Tree[V Value] struct {
    root        *Node[V]
    linearCount int
    firstNode   *Node[V]
}

// Changes in the InsertAfter method:
func (t *Tree[V]) InsertAfter(prev *Node[V], node *Node[V]) *Node[V] {
    if prev == t.root {
        t.linearCount++
        if t.linearCount == 1 {
            t.firstNode = node
        } else if t.linearCount > 500 {
            t.Splay(t.firstNode)
            t.linearCount = 0
        }
    } else {
        t.linearCount = 0
    }
    t.Splay(prev)
    t.root = node
    node.right = prev.right
}

Performance Improvements:

  • Tree height reduced by 80%.
  • Maximum rotations per operation decreased by 85%.
  • Total number of rotations reduced by 3%, significantly enhancing performance.
  • CRDT.Text benchmark(BenchmarkTextEditing) reduced by 42.53%(7.305 -> 4.198).
    image

For more details, you can check this

Which issue(s) this PR fixes:

Fixes #941

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


Additional documentation:


Checklist:

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

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 involve modifications to the Tree structure within the pkg/splay/splay.go file. Two new fields, linearCount and firstNode, have been added to track consecutive insertions at the root and reference the first inserted node, respectively. The NewTree constructor initializes linearCount to zero, and the InsertAfter method has been updated to manage linearCount, triggering a splay operation when it exceeds 500. These changes aim to enhance the performance of the Splay tree used in the crdt.Text data structure.

Changes

File Change Summary
pkg/splay/splay.go Added fields linearCount int and firstNode *Node[V] to Tree struct; updated NewTree and InsertAfter methods.

Assessment against linked issues

Objective Addressed Explanation
Improve performance of Splay Tree in crdt.Text data structure to prevent skewness (#941)

Possibly related issues

🐰 In the garden where trees sway,
A new count helps keep skewness at bay.
With nodes that dance and roots that play,
Performance blooms in a bright array!
🌳✨


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.

Copy link

codecov bot commented Oct 2, 2024

Codecov Report

Attention: Patch coverage is 46.15385% with 7 lines in your changes missing coverage. Please review.

Project coverage is 48.75%. Comparing base (fcf6fbf) to head (ca47fc7).

Files with missing lines Patch % Lines
pkg/splay/splay.go 46.15% 6 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1025      +/-   ##
==========================================
- Coverage   48.76%   48.75%   -0.01%     
==========================================
  Files          79       79              
  Lines       11343    11355      +12     
==========================================
+ Hits         5531     5536       +5     
- Misses       5269     5275       +6     
- Partials      543      544       +1     
Flag Coverage Δ
?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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 (3)
pkg/splay/splay.go (3)

96-97: Add documentation for new fields in Tree struct

To improve code readability and maintainability, please add comments explaining the purpose of the new fields linearCount and firstNode in the Tree struct. This will help other developers understand how these fields are used to prevent skewness in the splay tree.


126-126: Reset firstNode after splaying

After splaying firstNode and resetting linearCount, it's advisable to also reset firstNode to nil. This prevents holding a reference to a node that may have been altered or deleted later, which can help avoid potential memory leaks or unintended behavior.

Apply this diff:

        t.Splay(t.firstNode)
        t.linearCount = 0
+       t.firstNode = nil

124-126: Define splay threshold as a named constant

Using the magic number 500 as the splay threshold can reduce code clarity. Consider defining it as a named constant or making it configurable. This enhances readability and makes future adjustments easier.

Apply this diff:

+const splayThreshold = 500

...

        } else if t.linearCount > splayThreshold {
            t.Splay(t.firstNode)
            t.linearCount = 0
        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fcf6fbf and ca47fc7.

📒 Files selected for processing (1)
  • pkg/splay/splay.go (2 hunks)

Comment on lines +122 to +127
if t.linearCount == 1 {
t.firstNode = node
} else if t.linearCount > 500 {
t.Splay(t.firstNode)
t.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 valid before splaying

There's a potential risk that firstNode might have been modified or removed from the tree before the splay operation when linearCount exceeds the threshold. This could lead to unexpected behavior or runtime errors. Consider adding a check to ensure that firstNode is still a valid node in the tree before performing the splay operation.

Apply this diff to include a validity check:

        } else if t.linearCount > 500 {
+           if t.isValidNode(t.firstNode) {
                t.Splay(t.firstNode)
+           }
            t.linearCount = 0
        }

And implement the isValidNode method:

func (t *Tree[V]) isValidNode(node *Node[V]) bool {
    return node != nil && node.hasLinks()
}

@m4ushold m4ushold self-assigned this Oct 4, 2024
@m4ushold m4ushold added the enhancement 🌟 New feature or request label Oct 4, 2024
@m4ushold m4ushold changed the title optimize splay tree to prevent skewness Balancing Tree to Prevent Skewness Oct 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement 🌟 New feature or request
Projects
Status: Backlog
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