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

Fix: (Renderer) splitChannels memory leak #3959

Merged
merged 1 commit into from
Dec 13, 2024

Conversation

rjett1
Copy link
Contributor

@rjett1 rjett1 commented Dec 13, 2024

Short description

When using wavesurfer's splitChannels option there is a memory leak that occurs when zooming the waveforms. The code does not properly clean up scroll event handlers which can eventually lead to the page crashing.

Implementation details

The original code stores an unsubscribe function for a scroll event handler that gets created when an audio channel is rendered. When multiple channels are rendered the previous unsubscribe functions get overwritten and their references are never properly cleaned up.

To fix the issue I've updated the unsubscribeOnScroll variable to be an array, so that it can store the unsubscribe function for each audio channel that gets rendered.

How to test it

You can observe this behavior on the Zoom Plugin example page if you set the splitChannels option to true. As you zoom in and out the page will use more and more memory.

Screenshots

Before:
before

After:
after

Checklist

  • This PR is covered by e2e tests
  • It introduces no breaking API changes

Summary by CodeRabbit

  • New Features

    • Enhanced management of scroll event subscriptions, allowing multiple unsubscribe callbacks.
  • Bug Fixes

    • Improved reliability of the unsubscribe mechanism for scroll events.

Copy link

coderabbitai bot commented Dec 13, 2024

Walkthrough

The changes in this pull request modify the Renderer class in src/renderer.ts to enhance the management of scroll event subscriptions. The unsubscribeOnScroll property is updated from an optional function to an array of functions, allowing for multiple unsubscribe callbacks. This adjustment affects the constructor, destroy, and reRender methods, which now iterate over the array to invoke callbacks. The property is also initialized as an empty array, improving the reliability of the unsubscribe mechanism.

Changes

File Change Summary
src/renderer.ts Updated unsubscribeOnScroll from an optional function to an array of functions; modified constructor, destroy, and reRender methods to handle multiple unsubscribe callbacks; initialized unsubscribeOnScroll as an empty array.

Possibly related PRs

Suggested reviewers

  • katspaugh

Poem

In the land of code where rabbits hop,
The Renderer’s changes make scrolling stop!
Unsubscribe with ease, no more a chore,
Multiple callbacks, we’ll manage galore!
With each little hop, our code will sing,
A dance of functions, oh what joy they bring! 🐇✨


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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.

@rjett1 rjett1 changed the title Fix: (Renderer) splitChannel memory leak Fix: (Renderer) splitChannels memory leak Dec 13, 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: 0

🧹 Outside diff range and nitpick comments (3)
src/renderer.ts (3)

296-297: Remove unnecessary optional chaining

Since unsubscribeOnScroll is initialized as an empty array and can never be undefined, the optional chaining (?.) is unnecessary.

-    this.unsubscribeOnScroll?.forEach((unsubscribe) => unsubscribe())
+    this.unsubscribeOnScroll.forEach((unsubscribe) => unsubscribe())

588-597: LGTM: Proper storage of scroll event handler

The implementation correctly stores the unsubscribe handler in the array, fixing the memory leak by preventing handler overwrite.

Fix indentation

The indentation of the empty line and the array push operation seems incorrect.

      const unsubscribe = this.on('scroll', () => {
        const { scrollLeft } = this.scrollContainer
        const canvasIndex = Math.floor((scrollLeft / totalWidth) * numCanvases)
        clearCanvases()
        draw(canvasIndex - 1)
        draw(canvasIndex)
        draw(canvasIndex + 1)
      })
-
-      this.unsubscribeOnScroll.push(unsubscribe)
+      
+      this.unsubscribeOnScroll.push(unsubscribe)

683-684: LGTM with minor refinement

The cleanup of scroll handlers before re-rendering is correct and necessary. However, like in the destroy method, the optional chaining is unnecessary since unsubscribeOnScroll is an array.

-    this.unsubscribeOnScroll?.forEach((unsubscribe) => unsubscribe())
+    this.unsubscribeOnScroll.forEach((unsubscribe) => unsubscribe())
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ac6b678 and 7c79f70.

📒 Files selected for processing (1)
  • src/renderer.ts (4 hunks)
🔇 Additional comments (2)
src/renderer.ts (2)

34-34: LGTM: Property type change addresses the memory leak

The change from optional function to array of functions is correct and addresses the core issue by preventing overwrite of unsubscribe handlers.


34-34: Verify complete cleanup of scroll handlers

The implementation looks correct, but let's verify there are no remaining scroll handler references that could cause memory leaks.

Also applies to: 296-297, 588-597, 683-684

✅ Verification successful

Based on the search results, I can now verify the scroll handler cleanup implementation. The code shows:

  1. The scroll event listener is properly added in the renderer.ts file with a clear cleanup mechanism through the unsubscribeOnScroll array.
  2. All scroll-related event handlers are managed through the subscription system:
    • In regions.ts: scroll handlers are added to subscriptions and cleaned up when regions are removed
    • In timeline.ts: scroll subscriptions are managed through the subscriptions array
    • In minimap.ts: scroll handlers are part of the main subscription system
  3. The main renderer properly cleans up subscriptions in the destroy method.

Let's verify the cleanup implementation with one final check:


Scroll handler cleanup implementation is correct and complete

The verification confirms proper cleanup of scroll handlers:

  • The unsubscribeOnScroll array is properly initialized and managed
  • Cleanup is performed in both destroy() and reRender() methods
  • All scroll handlers are properly unsubscribed by calling each cleanup function
  • The array is reset after cleanup to prevent memory leaks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any scroll-related event handlers that might not be properly cleaned up
rg -A 5 "scroll.*event.*listener" 
rg -A 5 "on.*scroll"

Length of output: 19397


Script:

#!/bin/bash
# Check the cleanup implementations in renderer.ts
ast-grep --pattern 'destroy() {
  $$$
}'

# Check for any reRender cleanup
ast-grep --pattern 'reRender() {
  $$$
}'

Length of output: 86


Script:

#!/bin/bash
# Let's try a different approach to find the cleanup implementations
rg -A 10 "destroy\(\)" src/renderer.ts
rg -A 10 "reRender\(\)" src/renderer.ts

# Also check for unsubscribe usage
rg "unsubscribeOnScroll" src/renderer.ts

Length of output: 2012

Copy link
Owner

@katspaugh katspaugh left a comment

Choose a reason for hiding this comment

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

Thank you, great catch!

@katspaugh katspaugh merged commit d7161f5 into katspaugh:main Dec 13, 2024
4 checks passed
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.

2 participants