Skip to content

Conversation

@smypmsa
Copy link
Member

@smypmsa smypmsa commented Nov 2, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved WebSocket resource cleanup and error recovery during connection termination with more robust handling of edge cases.
  • Chores

    • Enhanced logging for better diagnostics in connection lifecycle management.

@smypmsa smypmsa self-assigned this Nov 2, 2025
@smypmsa smypmsa added the enhancement New feature or request label Nov 2, 2025
@vercel
Copy link

vercel bot commented Nov 2, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
chainstack-rpc-dashboard-germany Ready Ready Preview Comment Nov 2, 2025 4:24pm
chainstack-rpc-dashboard-japan Ready Ready Preview Comment Nov 2, 2025 4:24pm
chainstack-rpc-dashboard-singapore Ready Ready Preview Comment Nov 2, 2025 4:24pm
chainstack-rpc-dashboard-us-west Ready Ready Preview Comment Nov 2, 2025 4:24pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 2, 2025

Walkthrough

Enhances error handling and logging in WebSocket resource cleanup within the finally block of metric collection. Adds explicit handling for asyncio.CancelledError during unsubscribe and websocket.close operations, replaces single broad error log with granular non-critical logging for each operation.

Changes

Cohort / File(s) Summary
WebSocket cleanup error handling
common/metric_types.py
Enhanced finally block cleanup: added explicit asyncio.CancelledError handling with informational logging during unsubscribe; added general exception handler for unsubscribe failures; wrapped websocket.close() in shield with separate CancelledError and exception handlers; replaced single error log with granular non-fatal logging per operation

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Verify exception handling patterns are consistent across both unsubscribe and websocket.close operations
  • Confirm logging levels (info vs. warning) are appropriate for non-critical cleanup issues
  • Check that shield context manager is correctly applied to websocket.close()

Poem

🐰 Through WebSocket tunnels, errors might creep,
But now our cleanup runs deep and steep,
With shields and handlers, graceful and kind,
We catch what's lost and log what we find,
No socket left behind! ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "fix: log error as warning during WebSocket unsubscribe and close operations" is directly related to the actual changes made in the pull request. The summary confirms that the code modifications enhance cleanup of WebSocket resources by replacing single error logs with more granular, non-fatal logging for unsubscribe and close failures. The title accurately captures this logging improvement aspect, which is a significant and clearly identifiable part of the changes. The title is specific enough to convey the primary logging-focused modification and is not misleading or off-topic.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/websocket-metric-closing

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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)
common/metric_types.py (2)

94-99: Clarify the log message for CancelledError handling.

The message "Unsubscribe completed despite cancellation" is misleading. When asyncio.shield() raises CancelledError here, it indicates that the outer task was cancelled but the shielded unsubscribe operation completed successfully. The current wording suggests the operation was cancelled but somehow finished anyway, which isn't accurate.

Consider revising the message to be more precise:

 try:
     await asyncio.shield(self.unsubscribe(websocket))
 except asyncio.CancelledError:
-    logging.info("Unsubscribe completed despite cancellation")
+    logging.debug("Unsubscribe completed (outer task was cancelled)")
 except Exception as e:
     logging.warning(f"Error during unsubscribe (non-critical): {e!s}")

Also consider using logging.debug() instead of info() since this is expected behavior during task cancellation rather than something that needs to be highlighted at the info level.


101-106: Clarify the log message for CancelledError handling.

The same issue with the log message applies here as with the unsubscribe operation (lines 96-97). The message "WebSocket close completed despite cancellation" is misleading when asyncio.shield() raises CancelledError to indicate the outer task was cancelled.

Apply a similar revision for consistency:

 try:
     await asyncio.shield(websocket.close())
 except asyncio.CancelledError:
-    logging.info("WebSocket close completed despite cancellation")
+    logging.debug("WebSocket close completed (outer task was cancelled)")
 except Exception as e:
     logging.warning(f"Error closing websocket (non-critical): {e!s}")
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fc73dfc and 29a0d3c.

📒 Files selected for processing (1)
  • common/metric_types.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Follow PEP 8 style guidelines
Use type hints for all function parameters and return values
Include Google-style docstrings for all functions and classes
Keep cyclomatic complexity below 10 (enforced by Ruff)

Files:

  • common/metric_types.py
common/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

/common directory should contain shared utilities and base classes

Files:

  • common/metric_types.py
🪛 Ruff (0.14.2)
common/metric_types.py

98-98: Do not catch blind exception: Exception

(BLE001)


105-105: Do not catch blind exception: Exception

(BLE001)

🔇 Additional comments (2)
common/metric_types.py (2)

98-98: The broad exception catches are appropriate here (Ruff false positives).

Ruff flags these lines for catching blind Exception, but in cleanup code within a finally block, this is actually the correct pattern. These catches ensure that:

  1. Errors during cleanup are logged but don't prevent the remaining cleanup operations from executing
  2. The "non-critical" labeling accurately reflects that these are best-effort cleanup operations
  3. Unexpected exceptions from the websockets library don't cause the cleanup to fail entirely

The current implementation is pragmatic and follows established patterns for resource cleanup in async contexts.

Also applies to: 105-105


94-106: Good enhancement to cleanup error handling.

The changes improve the robustness and debuggability of WebSocket resource cleanup by:

  1. Adding explicit asyncio.CancelledError handling to acknowledge task cancellation scenarios
  2. Separating error handling for unsubscribe and close operations for better granularity
  3. Using asyncio.shield() to ensure cleanup completes even when the outer task is cancelled
  4. Logging errors as warnings with "non-critical" labels to reflect their nature

This approach correctly handles the edge cases where task cancellation occurs during cleanup while ensuring resources are properly released.

@smypmsa smypmsa merged commit b7d9abc into master Nov 2, 2025
6 checks passed
@smypmsa smypmsa deleted the fix/websocket-metric-closing branch November 2, 2025 16:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants