Skip to content

Fix tidy review write conflicts #130

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

Conversation

maoliver-amd
Copy link

@maoliver-amd maoliver-amd commented Dec 5, 2024

This fixes write failures when writing back the unmodified contents of files modified by clang-tidy.

Closes #129

Summary by CodeRabbit

  • New Features

    • Enhanced functionality for running clang-tidy with improved error handling during file operations.
    • Implemented a timeout mechanism for file accessibility checks.
  • Bug Fixes

    • Improved handling of file buffers to ensure the most recent changes are captured before processing.
  • Refactor

    • Organized the flow of execution in the _run_on_single_file function for better readability.

Comment on lines 264 to 269
timeout = time.monotonic_ns() + 1000000
# wait 1s for file to become accessible
success = False
while time.monotonic_ns() < timeout:
try:
src = open(filename, "r+b")
Copy link
Contributor

Choose a reason for hiding this comment

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

I guess this timeout idea works reliably?

Would really be great to have a reproducer.

Copy link
Author

Choose a reason for hiding this comment

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

It fixes the issue from the code base in the original issue ticket. I tried it several times with the header file changed to have tidy fixes found and with no tidy fixes to be found and all times the review output the correct information.
Not sure how easy it is to make a public reproducible test case, in theory anything with modified cpp files that all include the same header and that header has also been modified. Run it on a windows github action and see what it does. Im not familiar with your test suite so ill leave that to you

Co-authored-by: Brendan <2bndy5@gmail.com>
Copy link

codecov bot commented Dec 5, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (baee3c2) to head (b7e42a0).
Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #130   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           24        24           
  Lines         1837      1854   +17     
=========================================
+ Hits          1837      1854   +17     

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

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

@2bndy5 2bndy5 left a comment

Choose a reason for hiding this comment

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

Without a way to reproduce, our tests can't cover the lines specific to this problem. Instead I think some # pragma: no cover comments would suffice.

@2bndy5

This comment was marked as resolved.

@2bndy5 2bndy5 force-pushed the fix-tidy-review-write-conflicts branch from 5eaa197 to 30a0e34 Compare December 7, 2024 18:40
maoliver-amd and others added 2 commits December 9, 2024 15:09
@maoliver-amd
Copy link
Author

logger.error(
+                "Failed to write back contents of file: %s.%s)",
+                filename,
+                " timeout."
+                if not exception
+                else " {}: {}".format(
+                    exception.__class__.__name__, ", ".join(exception.args)
+                ),
+            )

Tested an seems to work correctly, updated the PR to match

@2bndy5 2bndy5 added the bug Something isn't working label Dec 10, 2024
Copy link

coderabbitai bot commented Dec 10, 2024

Walkthrough

The changes in this pull request involve modifications to the _run_on_single_file function in the cpp_linter/clang_tools/__init__.py file and enhancements to the run_clang_tidy function in the cpp_linter/clang_tools/clang_tidy.py file. The _run_on_single_file function's control flow is reorganized for clarity, while the run_clang_tidy function now includes improved error handling for file access, implementing a timeout mechanism to ensure files are accessible before reading or writing.

Changes

File Path Change Summary
cpp_linter/clang_tools/__init__.py Repositioned format_advice initialization before tidy_cmd check; removed previous logic.
cpp_linter/clang_tools/clang_tidy.py Added timeout mechanism for file access in run_clang_tidy; updated buffer reading logic.

Assessment against linked issues

Objective Addressed Explanation
Clang tidy review crashes when writing back file (#129)
Enhanced error handling for file access issues (#129)

Suggested labels

enhancement

Poem

🐰 In the land of code where bunnies play,
We fixed the linter, hip-hip-hooray!
With tidy and format now in their place,
No more crashes, just a happy face!
Hopping through files, with joy we glide,
Thanks to our changes, we take it in stride! 🌟


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.

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

🧹 Outside diff range and nitpick comments (1)
cpp_linter/clang_tools/clang_tidy.py (1)

285-285: Use write() instead of writelines() for writing byte content

Since original_buf is a bytes object containing the entire file content, using src.write(original_buf) is more appropriate than src.writelines([original_buf]), which is intended for writing a list of lines.

Apply this diff:

-src.writelines([original_buf])
+src.write(original_buf)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 96835b7 and 99efef7.

📒 Files selected for processing (2)
  • cpp_linter/clang_tools/__init__.py (1 hunks)
  • cpp_linter/clang_tools/clang_tidy.py (3 hunks)
🔇 Additional comments (3)
cpp_linter/clang_tools/clang_tidy.py (2)

8-8: Imports are correctly updated

The time module is imported to handle time-related functions used in the timeout mechanism.


250-250: Successfully stored original file content for restoration

Reading the original file content to original_buf ensures that the file can be restored after clang-tidy modifications.

cpp_linter/clang_tools/__init__.py (1)

49-60: Reordering formatting before tidying ensures code is formatted even if clang-tidy fails

By running clang-format before clang-tidy, the code will be formatted even if clang-tidy encounters an error. This change enhances the robustness of the formatting process.

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

🧹 Outside diff range and nitpick comments (1)
cpp_linter/clang_tools/clang_tidy.py (1)

273-274: Optimize busy-wait loops to reduce CPU usage.

The current implementation uses busy-wait loops that could consume unnecessary CPU cycles. Consider adding a small sleep to reduce CPU usage.

-                    while not src.readable() and time.monotonic_ns() < read_timeout:
-                        pass  # pragma: no cover
+                    while not src.readable() and time.monotonic_ns() < read_timeout:
+                        time.sleep(0.01)  # pragma: no cover
-                    while not src.writable() and time.monotonic_ns() < write_timeout:
-                        pass  # pragma: no cover
+                    while not src.writable() and time.monotonic_ns() < write_timeout:
+                        time.sleep(0.01)  # pragma: no cover

Also applies to: 282-283

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 99efef7 and 9627de3.

📒 Files selected for processing (1)
  • cpp_linter/clang_tools/clang_tidy.py (3 hunks)
🔇 Additional comments (2)
cpp_linter/clang_tools/clang_tidy.py (2)

8-8: LGTM!

The time module import is correctly placed and necessary for the new timeout functionality.


264-299: LGTM! Robust implementation of file access with timeouts.

The implementation correctly handles file access issues with proper timeouts and error handling. The use of context managers ensures proper resource cleanup, and the separate timeouts for different operations provide fine-grained control.

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 (1)
cpp_linter/clang_tools/clang_tidy.py (1)

264-299: Consider extracting file operations into helper functions.

The current implementation has complex nested structures. Consider extracting the file operations into helper functions to improve readability and maintainability.

Here's a suggested refactoring:

def _wait_for_file_operation(timeout_ns: int, check_fn) -> bool:
    while time.monotonic_ns() < timeout_ns:
        if check_fn():
            return True
    return False

def write_back_original_content(filename: str, original_buf: bytes, advice: TidyAdvice) -> bool:
    timeout = time.monotonic_ns() + 1_000_000_000
    try:
        with open(filename, "r+b") as src:
            if not _wait_for_file_operation(
                time.monotonic_ns() + 1_000_000_000,
                lambda: src.readable()
            ):
                return False
            
            advice.patched = b"".join(src.readlines())
            src.seek(0)
            
            if not _wait_for_file_operation(
                time.monotonic_ns() + 1_000_000_000,
                lambda: src.writable()
            ):
                return False
                
            src.write(original_buf)
            return True
    except OSError as exc:
        logger.error(
            "Failed to write back contents of file: %s. %s",
            filename,
            f"{exc.__class__.__name__}: {', '.join(exc.args)}",
        )
        return False

# Usage in run_clang_tidy:
if tidy_review:
    original_buf = Path(filename).read_bytes()
    cmds.append("--fix-errors")
    # ... rest of the code ...
    if not write_back_original_content(filename, original_buf, advice):
        logger.error("Failed to write back contents of file: %s. timeout.", filename)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9627de3 and b7e42a0.

📒 Files selected for processing (1)
  • cpp_linter/clang_tools/clang_tidy.py (3 hunks)
🔇 Additional comments (2)
cpp_linter/clang_tools/clang_tidy.py (2)

8-8: LGTM!

The time module import is correctly placed with other standard library imports and is necessary for the timeout implementation.


250-250: ⚠️ Potential issue

Add timeout and error handling for file read operation.

The file read operation should have similar timeout and error handling mechanisms as implemented for write operations to ensure consistency and robustness.

Apply this diff to implement consistent error handling:

-        original_buf = Path(filename).read_bytes()
+        timeout = time.monotonic_ns() + 1_000_000_000
+        success = False
+        exception = None
+        while not success and time.monotonic_ns() < timeout:
+            try:
+                original_buf = Path(filename).read_bytes()
+                success = True
+            except OSError as exc:
+                exception = exc
+        if not success:
+            error_msg = " timeout." if not exception else f" {exception.__class__.__name__}: {', '.join(exception.args)}"
+            logger.error("Failed to read contents of file: %s.%s", filename, error_msg)
+            return advice

Likely invalid or redundant comment.

2bndy5 added a commit that referenced this pull request Dec 10, 2024
Born from the discussion in #129 and continued in #130. This adds timeout-oriented functions for reading and writing to the scanned source files.

This supersedes #130 and resolves #129.
@2bndy5 2bndy5 mentioned this pull request Dec 10, 2024
@2bndy5
Copy link
Contributor

2bndy5 commented Dec 11, 2024

Superseded by #133.

In #133, I went with

  • abstracted read/write attempts into timeout-oriented FileObj functions
  • run clang-format before clang-tidy
  • reduce number file reads when parsing clang-format XML output

@maoliver-amd I'm sorry to have put you through all that and yet I went in a slightly different direction.

@2bndy5 2bndy5 closed this Dec 11, 2024
2bndy5 added a commit that referenced this pull request Dec 12, 2024
Born from the discussion in #129 and continued in #130. This adds timeout-oriented functions for reading and writing to the scanned source files.

This supersedes #130 and resolves #129.

* run clang-format before clang-tidy
* prevent busy waits and log errors
@maoliver-amd maoliver-amd deleted the fix-tidy-review-write-conflicts branch December 13, 2024 05:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Clang tidy review crashes when writing back file
2 participants