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

clean overlays in detach function and not during reconciliation #5337

Merged
merged 6 commits into from
Jan 3, 2025

Conversation

sashankaryal
Copy link
Contributor

@sashankaryal sashankaryal commented Jan 2, 2025

What changes are proposed in this pull request?

  • Cleanup overlays in looker's detach as opposed to reconciliation function
  • For single channel masks, modify buffer in-place instead of allocating another UInt8 array
  • Set targets to null in overlay cleanup. They should already be garbage collected, but this is just a safety mechanism to reduce ref to the buffer by one in case overaly refs are maintained somewhere.
  • Reuse offscreen canvas. I did micro-benchmarking with creating new offscreen canvas vs reusing it. I noticed a difference of 2ms at most, so this is kind of a useless change. Resizing the canvas probably offsets the cost of allocating a new canvas and destroying it.

How is this patch tested? If it is not, please explain why.

(Details)

Release Notes

Is this a user-facing change that should be mentioned in the release notes?

  • No. You can skip the rest of this section.
  • Yes. Give a description of this change to be included in the release
    notes for FiftyOne users.

(Details in 1-2 sentences. You can just refer to another PR with a description
if this PR is part of a larger change.)

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other

Summary by CodeRabbit

  • Performance Improvements

    • Enhanced memory management for overlays by implementing cleanup mechanisms
    • Optimized image processing in canvas decoding with off-screen canvas and efficient data handling
  • Bug Fixes

    • Improved resource cleanup for looker and scroll reader components
    • Added safeguards to prevent potential memory leaks during object destruction
  • New Features

    • Introduced more robust overlay processing for heatmap and segmentation overlays

@sashankaryal sashankaryal self-assigned this Jan 2, 2025
Copy link
Contributor

coderabbitai bot commented Jan 2, 2025

Walkthrough

This pull request focuses on improving resource management and cleanup processes across multiple components in the Looker and Spotlight packages. The changes primarily involve enhancing the destruction and cleanup methods in various classes, including AbstractLooker, HeatmapOverlay, and SegmentationOverlay. Additionally, the changes include optimizations in the canvas decoding process and scroll reader functionality, with a particular emphasis on properly releasing resources and managing memory more efficiently.

Changes

File Change Summary
app/packages/looker/src/lookers/abstract.ts Modified destroy() method to clean up overlays by calling cleanup() on each overlay
app/packages/looker/src/overlays/heatmap.ts Updated cleanup() method to set targets to null
app/packages/looker/src/overlays/segmentation.ts Updated cleanup() method to set targets to null
app/packages/looker/src/processOverlays.ts Added imports for HeatmapOverlay and SegmentationOverlay, added conditional checks for processing these overlay types
app/packages/looker/src/worker/canvas-decoder.ts Introduced off-screen canvas for image processing, optimized grayscale conversion
app/packages/spotlight/src/createScrollReader.ts Added animationFrameId to manage animation frame lifecycle

Sequence Diagram

sequenceDiagram
    participant AbstractLooker
    participant Overlay
    
    AbstractLooker->>Overlay: destroy()
    Overlay->>Overlay: cleanup()
    Overlay-->>AbstractLooker: resources released
Loading

Possibly related PRs

Suggested labels

bug, app

Suggested reviewers

  • benjaminpkane
  • ritch

Poem

🐰 Cleanup dance, resources free,
Overlays vanish, memory's glee!
Canvases spin, frames take flight,
Efficient code shines ever bright!
A rabbit's code, lean and clean! 🧹✨


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. (Beta)
  • @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.

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.

@sashankaryal sashankaryal added the app Issues related to App features label Jan 2, 2025
Copy link
Contributor

@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

🧹 Nitpick comments (2)
app/packages/looker/src/overlays/segmentation.ts (1)

266-266: Enhance clarity on setting this.targets to null
This update properly clears the reference to this.targets, aiding garbage collection. However, consider adding a brief JSDoc or inline comment explaining that this is an intentional release of resources.

 public cleanup(): void {
   this.label.mask?.bitmap?.close();
+  // Intentionally nullifying references for garbage collection
   this.targets = null;
 }
app/packages/looker/src/lookers/abstract.ts (1)

607-607: Good practice to clean up overlay resources upon destruction
Invoking cleanup on every overlay helps avoid potential memory leaks and prevents retaining references to stale objects. Ensure that all overlays, especially newly introduced or specialized ones, implement their cleanup method properly.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86eb964 and e9e749e.

📒 Files selected for processing (6)
  • app/packages/looker/src/lookers/abstract.ts (1 hunks)
  • app/packages/looker/src/overlays/heatmap.ts (1 hunks)
  • app/packages/looker/src/overlays/segmentation.ts (1 hunks)
  • app/packages/looker/src/processOverlays.ts (2 hunks)
  • app/packages/looker/src/worker/canvas-decoder.ts (2 hunks)
  • app/packages/spotlight/src/createScrollReader.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
app/packages/looker/src/overlays/segmentation.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/spotlight/src/createScrollReader.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/overlays/heatmap.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/processOverlays.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/canvas-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/abstract.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (12)
app/packages/spotlight/src/createScrollReader.ts (3)

12-12: Storing animation frame ID helps manage rendering loop
Good approach to store the requestAnimationFrame ID for easier cleanup. No immediate concerns.


67-67: Assigning requestAnimationFrame to animationFrameId
This ensures that the animation frame handle is correctly captured for use in cleanup. Looks good.


77-84: Properly canceling animation frame and clearing timeout
This block effectively prevents resource leaks by canceling the animation frame and clearing the timeout. These steps complement the destroyed flag, ensuring that the component no longer processes rendering tasks after destruction.

app/packages/looker/src/processOverlays.ts (4)

7-7: Introducing HeatmapOverlay import
Adding the HeatmapOverlay import is appropriate for handling heatmap feature logic.


8-8: Introducing SegmentationOverlay import
Adding the SegmentationOverlay import is appropriate for efficiently managing segmentation overlays.


35-45: Improved condition for SegmentationOverlay
Skipping overlays that do not have the required mask data is consistent with defensive programming, ensuring only valid overlays proceed.


46-52: Refinement for HeatmapOverlay
Similar to the segmentation check, the early continue avoids invalid heatmap overlays. This helps prevent exceptions or undefined behavior.

app/packages/looker/src/worker/canvas-decoder.ts (4)

3-7: Offscreen canvas initialization
Defining a single offScreenCanvas and context at the module level improves efficiency by reusing these resources instead of allocating them repeatedly.


61-65: Dynamically setting canvas dimensions
Resizing the off-screen canvas to match the image dimensions is a more efficient approach than creating new canvases each time.


68-68: Extracting ImageData
Grabbing the image data in one step is straightforward and avoids additional overhead.


72-85: Optimizing grayscale conversion
Modifying the buffer in-place and slicing the data for grayscale improves performance by minimizing allocations. The loop logic appears correct and effectively handles skipping the G, B, and A channels.

app/packages/looker/src/overlays/heatmap.ts (1)

211-211: Clearing references in cleanup
Setting this.targets to null supports garbage collection. Good addition to ensure extended memory is freed when no longer needed.

@sashankaryal sashankaryal changed the title clean overlays in detach function and during reconciliation clean overlays in detach function and not during reconciliation Jan 2, 2025
Copy link
Contributor

@benjaminpkane benjaminpkane left a comment

Choose a reason for hiding this comment

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

LGTM 🐎

@@ -30,6 +32,25 @@ const processOverlays = <State extends BaseState>(

if (!(overlay.field && overlay.field in bins)) continue;

// todo: find a better approach / place for this.
// for instance, this won't work in detection overlay, where
// we might want the bounding boxes but masks might not have been loaded
Copy link
Contributor

Choose a reason for hiding this comment

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

I think these instances can be filtered out during overlay creation. But this is a good place for now 👍

Comment on lines +78 to +84
if (timeout) {
clearTimeout(timeout);
}

if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

It seems like there is redundancy here. I would be surprised if the closure here is causing a memory leak. But it doesn't hurt 👍

@sashankaryal sashankaryal merged commit 74642e5 into develop Jan 3, 2025
12 checks passed
@sashankaryal sashankaryal deleted the feat/improv-overlays branch January 3, 2025 17:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
app Issues related to App features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants