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

Ensure find and indexOf perform splay #904

Merged
merged 4 commits into from
Sep 30, 2024
Merged

Conversation

m4ushold
Copy link
Contributor

@m4ushold m4ushold commented Sep 27, 2024

What this PR does / why we need it?

This PR addresses a critical issue in the splay tree implementation where the Find and IndexOf functions do not perform the necessary splay operation after locating a node. By ensuring that these functions splay the accessed node to the root, we maintain the amortized O(log n) time complexity for subsequent operations. This enhancement optimizes the overall efficiency and performance of the splay tree, ensuring that frequently accessed nodes remain close to the root and improving access times for future queries.

Any background context you want to provide?

Same PR as the Go repository
yorkie-team/yorkie#1017
image

What are the relevant tickets?

Fixes #903

Checklist

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

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced the SplayTree functionality for improved node access and manipulation.
    • Introduced a new benchmarking suite to evaluate the performance of the SplayTree under various conditions, including random access and stress tests.
  • Bug Fixes

    • Improved control flow in the getNodeAt and getIndexOfNode methods for more reliable node retrieval.

Added splay operation after locating the node in the Find function.
Simplified IndexOf() function by utilizing the splay operation,
reducing the need for additional traversal logic and ensuring
efficient access.
By incorporating splay in both functions, the tree maintains its
self-balancing property and ensures amortized O(log n) time
complexity for future operations.
The benchmarks include three tests: a stress test that randomly
performs insert, delete, find, and range delete operations; a skewed
tree test with 1000 random accesses; and a text editing benchmark
based on the editing-trace.json file.
@CLAassistant
Copy link

CLAassistant commented Sep 27, 2024

CLA assistant check
All committers have signed the CLA.

Copy link

coderabbitai bot commented Sep 27, 2024

Walkthrough

The changes introduce modifications to the SplayTree class in the splay_tree.ts file, ensuring that the splayNode(node) method is called in the getNodeAt and getIndexOfNode methods. A new benchmarking file, splay_tree.bench.ts, is also added, which includes tests for random access and stress testing of the SplayTree data structure, utilizing a custom StringNode class.

Changes

Files Change Summary
packages/sdk/src/util/splay_tree.ts Modifications to the SplayTree class, specifically in getNodeAt and getIndexOfNode methods to include splaying logic.
packages/sdk/test/bench/splay_tree.bench.ts New benchmarking tests for SplayTree, including a StringNode class and functions for random access and stress testing.

Assessment against linked issues

Objective Addressed Explanation
Ensure Find and IndexOf functions perform splay operation (903)

Poem

In the forest where trees sway,
A splay tree hops and plays,
With nodes that dance and gleam,
In benchmarks, they chase the dream.
Hooray for changes, let’s rejoice,
In code we trust, let’s raise our voice! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 13659f9 and 69808e3.

📒 Files selected for processing (1)
  • packages/sdk/test/bench/splay_tree.bench.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/sdk/test/bench/splay_tree.bench.ts

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

@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: 7

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4d5416f and f5b9466.

📒 Files selected for processing (2)
  • packages/sdk/src/util/splay_tree.ts (2 hunks)
  • packages/sdk/test/bench/splay_tree.bench.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/sdk/test/bench/splay_tree.bench.ts

[error] 7-9: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


[error] 6-6: Don't use 'Boolean' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'boolean' instead

(lint/complexity/noBannedTypes)

packages/sdk/test/bench/splay_tree.bench.ts Outdated Show resolved Hide resolved
packages/sdk/test/bench/splay_tree.bench.ts Outdated Show resolved Hide resolved
packages/sdk/test/bench/splay_tree.bench.ts Outdated Show resolved Hide resolved
packages/sdk/test/bench/splay_tree.bench.ts Outdated Show resolved Hide resolved
packages/sdk/test/bench/splay_tree.bench.ts Outdated Show resolved Hide resolved
packages/sdk/src/util/splay_tree.ts Show resolved Hide resolved
packages/sdk/src/util/splay_tree.ts Show resolved Hide resolved
Fixed a type error that occurred while reading the editing-trace.json
file.
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/test/bench/splay_tree.bench.ts (2)

58-77: Enhance benchmark documentation and expectations

The benchmark tests cover a good range of sizes for both stress testing and random access. However, there are a couple of areas where we could improve:

  1. Documentation: There's no explanation for why these specific sizes (10000, 20000, 30000) were chosen. Adding comments to explain the rationale behind these choices would be helpful for future maintainers.

  2. Performance Expectations: There are no baseline or expected performance metrics mentioned. Adding these would make it easier to identify performance regressions in the future.

Consider adding comments to explain the choice of sizes and include baseline performance expectations. For example:

describe('splay_tree.edit', () => {
  // We test with sizes 10000, 20000, and 30000 to cover small, medium, and large tree sizes
  // These sizes were chosen based on typical usage patterns in our application
  
  bench('splay_tree.stress 10000', () => {
    stressTest(10000);
  }, {
    // Add a comment explaining the expected performance
    // e.g., "Expected to complete in < 100ms on our CI environment"
  });
  
  // ... (repeat for other benchmarks)
});

Additionally, consider adding a comment at the top of the file explaining the overall purpose of these benchmarks and how they relate to the splay tree implementation improvements.


1-96: Overall assessment of the splay tree benchmarks

The benchmarks implemented in this file are comprehensive and cover various aspects of the SplayTree performance, which aligns well with the PR objectives of improving the splay tree operation. However, there are a few areas where the benchmarks could be enhanced to more directly address the specific issue mentioned in the PR (ensuring splay operation after find):

  1. Explicit testing of splay operation after find in both benchmarkRandomAccess and stressTest functions.
  2. Improving reproducibility of the stress test by using a seeded random number generator.
  3. Enhancing robustness of the editing-trace benchmark by replacing non-null assertions with proper null checks.
  4. Adding verification of the final tree state in the editing-trace benchmark.

Additionally, there are minor improvements to be made in terms of TypeScript best practices (using boolean instead of Boolean) and removing unnecessary code (the StringNode constructor).

Overall, with these suggested improvements, the benchmarks will provide a more targeted and robust way to verify the correct implementation of the splay tree operations, especially the critical splay-after-find behavior.

Consider adding a specific benchmark that focuses solely on the splay-after-find behavior. This could involve a series of find operations followed by checks to ensure the found node is at the root of the tree. This would directly address the main objective of the PR and provide a clear way to verify that the issue has been resolved.

🧰 Tools
🪛 Biome

[error] 7-9: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


[error] 6-6: Don't use 'Boolean' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'boolean' instead

(lint/complexity/noBannedTypes)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f5b9466 and 13659f9.

📒 Files selected for processing (1)
  • packages/sdk/test/bench/splay_tree.bench.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/sdk/test/bench/splay_tree.bench.ts

[error] 7-9: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


[error] 6-6: Don't use 'Boolean' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'boolean' instead

(lint/complexity/noBannedTypes)

🔇 Additional comments (1)
packages/sdk/test/bench/splay_tree.bench.ts (1)

23-31: Verify if the benchmark tests splay operation after find

The benchmarkRandomAccess function seems to be correctly implementing a random access benchmark. However, given the PR objectives to fix the splay tree operation, particularly ensuring that Find and IndexOf functions perform the necessary splay operation, it's not clear if this benchmark is effectively testing this aspect.

Could you verify if this benchmark is sufficient to test the splay operation after find? If not, consider modifying the benchmark to explicitly test this behavior. For example, you could add assertions to check if the found node is at the root of the tree after each find operation.

Comment on lines +33 to +56
const stressTest = (size: number) => {
const tree = new SplayTree<string>();
let treeSize = 1;
for (let i = 0; i < size; i++) {
const op = Math.floor(Math.random() * 3);
if (op == 0) {
const node = tree.find(Math.floor(Math.random() * treeSize))[0];
if (node != undefined) {
tree.insertAfter(node, StringNode.create('A'));
} else {
tree.insert(StringNode.create('A'));
}
treeSize++;
} else if (op == 1) {
tree.find(Math.floor(Math.random() * treeSize));
} else {
const node = tree.find(Math.floor(Math.random() * treeSize))[0];
if (node != undefined) {
tree.delete(node);
treeSize--;
}
}
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance stress test for splay operation and reproducibility

The stressTest function provides a comprehensive test of the SplayTree operations. However, there are two areas where it could be improved:

  1. Splay Operation Verification: Given the PR objectives, it would be beneficial to explicitly verify that the splay operation is performed after each find operation.

  2. Test Reproducibility: The use of Math.random() makes the test non-deterministic, which could lead to inconsistent results across different runs.

Consider the following improvements:

  1. Add checks to verify the splay operation after each find. For example, you could check if the found node is at the root of the tree after each find operation.

  2. Use a seeded random number generator to make the test deterministic and reproducible. You can use a library like seedrandom for this purpose.

Here's a sketch of how you might implement these changes:

import seedrandom from 'seedrandom';

const stressTest = (size: number, seed: string) => {
  const rng = seedrandom(seed);
  const tree = new SplayTree<string>();
  let treeSize = 1;
  for (let i = 0; i < size; i++) {
    const op = Math.floor(rng() * 3);
    if (op == 0) {
      // ... (insert operation)
    } else if (op == 1) {
      const index = Math.floor(rng() * treeSize);
      const [node] = tree.find(index);
      if (node) {
        // Verify splay operation
        expect(tree.root).toBe(node);
      }
    } else {
      // ... (delete operation)
    }
  }
};

// Usage
bench('splay_tree.stress 10000', () => {
  stressTest(10000, 'fixed-seed-for-reproducibility');
});

This approach will make your tests more targeted towards the PR objectives and more reliable across different runs.

packages/sdk/test/bench/splay_tree.bench.ts Outdated Show resolved Hide resolved
packages/sdk/test/bench/splay_tree.bench.ts Outdated Show resolved Hide resolved
Removed the redundant constructor that only called the super
constructor with the same parameters.
Changed the 'removed' property type from 'Boolean' to the lowercase
'boolean' type for consistency and clarity.
@m4ushold m4ushold self-assigned this Sep 29, 2024
@hackerwins hackerwins self-requested a review September 30, 2024 11:01
@hackerwins hackerwins changed the title Fix splay tree operation Ensure find and indexOf perform splay Sep 30, 2024
Copy link
Member

@hackerwins hackerwins left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution.

@hackerwins hackerwins merged commit 56ba2bb into main Sep 30, 2024
2 checks passed
@hackerwins hackerwins deleted the fix-splay-tree-operation branch September 30, 2024 11:05
@coderabbitai coderabbitai bot mentioned this pull request Oct 2, 2024
2 tasks
JOOHOJANG pushed a commit that referenced this pull request Oct 22, 2024
Enhance splay tree efficiency by incorporating splay operations after node
location in Find and IndexOf functions. This change maintains the tree's
self-balancing property and ensures amortized O(log n) time complexity for
future operations. Simplify IndexOf() by leveraging the splay operation,
reducing additional traversal logic and improving overall performance.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

Some Functions in Splay Tree does not performing splay operation
3 participants