Skip to content

Conversation

dsarno
Copy link
Owner

@dsarno dsarno commented Aug 17, 2025

Summary

  • make RefreshDebounce.Schedule thread-safe and enforce debounce window
  • defer refresh until debounce window passes and coalesce duplicate requests

Testing

  • pytest -q

https://chatgpt.com/codex/tasks/task_e_68a1f53683d483279a293aeade114dbf

Copy link

coderabbitai bot commented Aug 17, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/fix-debouncing-logic-in-refreshdebounce

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Summary

This PR addresses a critical race condition in the RefreshDebounce class within the Unity MCP Bridge's script management system. The RefreshDebounce class is responsible for coalescing multiple asset refresh requests within a specified time window to prevent excessive Unity asset database operations that can impact editor performance.

The original implementation had a fundamental flaw in its debouncing logic where rapid successive requests could bypass the intended debounce window. This happened because the timing check (now - _last) < window could be evaluated before the window had fully elapsed, particularly in multi-threaded scenarios or when multiple script changes occurred in quick succession.

The new implementation completely restructures the debouncing mechanism to use a continuous "ticking" approach. Instead of immediately scheduling work when the window appears to have elapsed, it now:

  1. Records all incoming requests with proper thread synchronization using locks and atomic operations
  2. Tracks the timestamp of the most recent request (_lastRequest)
  3. Uses a recursive EditorApplication.delayCall mechanism that continuously checks if the full debounce window has elapsed from the last request
  4. Only executes the accumulated refresh work once the window has completely passed

This change is particularly important in the Unity MCP context because the system handles rapid script modifications and asset imports that need to be batched efficiently. The ManageScript.cs file appears to be a core component of the MCP bridge that manages Unity script assets, and proper debouncing ensures that compilation and asset database operations don't overwhelm the editor during active development sessions.

Important Files Changed
Filename Score Overview
UnityMcpBridge/Editor/Tools/ManageScript.cs 5/5 Fixed race condition in RefreshDebounce class by implementing proper thread-safe debouncing with continuous ticking mechanism

Confidence score: 5/5

  • This PR is safe to merge with minimal risk as it addresses a clear race condition with a well-structured solution
  • Score reflects the focused nature of the change, proper thread safety implementation, and clear improvement to existing flawed logic
  • No files require special attention as the change is isolated to a single method with clear threading and timing improvements

Sequence Diagram

sequenceDiagram
    participant User
    participant ManageScript
    participant RefreshDebounce
    participant EditorApplication
    participant AssetDatabase
    participant CompilationPipeline

    User->>ManageScript: "HandleCommand (create/update/edit script)"
    ManageScript->>ManageScript: "Write script to disk"
    ManageScript->>ManageScriptRefreshHelpers: "ScheduleScriptRefresh(relativePath)"
    ManageScriptRefreshHelpers->>RefreshDebounce: "Schedule(relPath, 200ms window)"
    
    RefreshDebounce->>RefreshDebounce: "Set _pending = 1, add path to _paths"
    RefreshDebounce->>RefreshDebounce: "Update _lastRequest timestamp"
    
    alt First schedule call
        RefreshDebounce->>RefreshDebounce: "Set _scheduled = true"
        RefreshDebounce->>EditorApplication: "delayCall += Tick(window)"
    else Subsequent calls during window
        RefreshDebounce->>RefreshDebounce: "Update _lastRequest only"
    end
    
    ManageScript-->>User: "Return success response"
    
    loop Until debounce window elapsed
        EditorApplication->>RefreshDebounce: "Execute Tick(window)"
        RefreshDebounce->>RefreshDebounce: "Check if (UtcNow - _lastRequest) >= window"
        alt Window not elapsed
            RefreshDebounce->>EditorApplication: "delayCall += Tick(window) again"
        end
    end
    
    EditorApplication->>RefreshDebounce: "Execute Tick(window) - window elapsed"
    RefreshDebounce->>RefreshDebounce: "Set _scheduled = false"
    RefreshDebounce->>RefreshDebounce: "Exchange _pending to 0"
    RefreshDebounce->>RefreshDebounce: "Get all paths from _paths, clear set"
    
    loop For each path
        RefreshDebounce->>AssetDatabase: "ImportAsset(path, ForceUpdate)"
    end
    
    RefreshDebounce->>CompilationPipeline: "RequestScriptCompilation()"
Loading

1 file reviewed, no comments

Edit Code Review Bot Settings | Greptile

@dsarno dsarno merged commit fb0f464 into protocol-framing Aug 17, 2025
2 checks passed
@dsarno dsarno deleted the codex/fix-debouncing-logic-in-refreshdebounce branch August 19, 2025 09:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant