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 socket closes #4879

Merged
merged 6 commits into from
Oct 3, 2024
Merged

Ensure socket closes #4879

merged 6 commits into from
Oct 3, 2024

Conversation

kaixi-wang
Copy link
Contributor

@kaixi-wang kaixi-wang commented Oct 2, 2024

What changes are proposed in this pull request?

  • call send_request using a context manager to ensure the socket always closes
  • currently, terminating the server results in a ResourceWarning:
Object allocated at (most recent call last):
  File "../fiftyone/service/ipc.py", lineno 112
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py:1070: ResourceWarning: subprocess 19806 is still running

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

  • add unit test and passes

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

  • New Features

    • Enhanced inter-process communication (IPC) testing with a new test case for socket closure on exceptions.
  • Bug Fixes

    • Improved resource management by ensuring sockets are automatically closed after use.
  • Chores

    • Updated the version constraints for the open3d package in the testing requirements.
    • Updated the version of the werkzeug package in the testing requirements.

@kaixi-wang kaixi-wang self-assigned this Oct 2, 2024
Copy link
Contributor

coderabbitai bot commented Oct 2, 2024

Warning

Rate limit exceeded

@kaixi-wang has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 31060be and c8c81dd.

Walkthrough

The changes involve modifications to the send_request function in the fiftyone/service/ipc.py file, where a context manager is now used for socket management. This adjustment ensures that the socket is automatically closed after use, preventing resource leaks. Additionally, the version of the open3d package in requirements/test.txt has been updated to include an upper limit, and the werkzeug package has been downgraded from 3.0.3 to 2.0.3. The test suite in tests/ipc_tests.py has been enhanced with a new test case to verify socket closure on exceptions, improving overall test coverage for inter-process communication functionality.

Changes

File Change Summary
fiftyone/service/ipc.py Modified send_request to use a context manager for socket creation, ensuring automatic closure.
requirements/test.txt Updated open3d version from open3d>=0.16.0 to open3d>=0.16.0,<0.18.0; downgraded werkzeug from 3.0.3 to 2.0.3.
tests/ipc_tests.py Added test_socket_closes_on_exception to verify socket closure on exceptions; enhanced IPC tests.

Poem

In the burrow where the sockets play,
A change was made to save the day.
With a context snug and tight,
Resources close, all feels just right.
Hopping through tests, we cheer with glee,
For a safer code, oh what a spree! 🐇✨


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.

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

🧹 Outside diff range and nitpick comments (2)
fiftyone/service/ipc.py (1)

112-115: Excellent use of context manager for socket handling

The implementation of the context manager (with statement) for socket handling is a significant improvement. It ensures that the socket is properly closed after use, addressing the ResourceWarning issue mentioned in the PR objectives. This change follows Python best practices for resource management and maintains the existing functionality.

Consider adding explicit error handling within the context manager to manage potential network-related exceptions. Here's a suggested improvement:

def send_request(port, message):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect(("localhost", port))
            pickle.dump(message, s.makefile("wb"))
            return pickle.load(s.makefile("rb"))
    except (socket.error, pickle.PickleError) as e:
        # Log the error or handle it as appropriate for your application
        raise ConnectionError(f"Failed to communicate with IPC server: {e}")

This addition will provide more informative error messages and allow for graceful error handling in the calling code.

tests/ipc_tests.py (1)

126-150: LGTM: Well-structured test for socket closure on exception.

This test function effectively verifies that the socket is properly closed when an exception occurs during send_request. It aligns well with the PR objective and uses mocking appropriately to simulate the behavior without actual network operations.

A minor suggestion for improvement:

Consider adding an assertion to verify that mock_socket_instance.close() is called. This would provide an extra layer of certainty that the socket is explicitly closed. You can add this assertion just before the existing assertions:

mock_socket_instance.close.assert_called_once()

This addition would make the test even more robust in ensuring proper resource management.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 77f664c and 88c5871.

📒 Files selected for processing (3)
  • fiftyone/service/ipc.py (1 hunks)
  • requirements/test.txt (1 hunks)
  • tests/ipc_tests.py (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • requirements/test.txt
🔇 Additional comments (2)
tests/ipc_tests.py (2)

16-18: LGTM: New imports are appropriate for the added test.

The new imports (unittest, BytesIO, and MagicMock) are correctly added and are necessary for the new test function. These are standard Python libraries, which is good for maintaining minimal external dependencies.


Line range hint 1-150: Summary: Excellent addition to improve test coverage for socket closure.

The changes in this file effectively address the PR objective of ensuring proper socket closure. The new test function test_socket_closes_on_exception is well-implemented and uses appropriate mocking techniques to verify the behavior without actual network operations.

Key points:

  1. The new test aligns perfectly with the goal of eliminating ResourceWarnings due to unclosed sockets.
  2. The implementation follows good testing practices, including the use of mocking and specific assertions.
  3. Existing tests remain unchanged, maintaining the integrity of previous test coverage.

These changes contribute to the overall robustness of the IPC functionality in FiftyOne by ensuring that edge cases related to exception handling and resource management are properly tested.

itsdangerous==2.0.1
werkzeug==3.0.3
werkzeug==2.0.3
Copy link
Contributor Author

@kaixi-wang kaixi-wang Oct 3, 2024

Choose a reason for hiding this comment

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

attempting to run any tests locally with python v3.9 fails with

ImportError: cannot import name 'BaseResponse' from 'werkzeug.wrappers' (/Users/kacey/.pyenv/versions/3.9.14/envs/fo/lib/python3.9/site-packages/werkzeug/wrappers/__init__.py)

unless 2.0.3 specified (with open3d 0.16.1)

@kaixi-wang kaixi-wang requested a review from a team October 3, 2024 01:48
Copy link
Contributor

@minhtuev minhtuev left a comment

Choose a reason for hiding this comment

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

Small comment otherwise LGTM :)

Copy link
Contributor

@minhtuev minhtuev left a comment

Choose a reason for hiding this comment

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

LGTM 🚀

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.

nice fix ✨

@kaixi-wang kaixi-wang merged commit 9102e84 into develop Oct 3, 2024
13 checks passed
@kaixi-wang kaixi-wang deleted the kacey/ensure-socket-closes branch October 3, 2024 23:34
benjaminpkane pushed a commit that referenced this pull request Oct 4, 2024
* ensure socket closes

* fmt

* fix test dependency

* fix test dependency

* fix open3d dep

* try resolve dep
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.

3 participants