🧹 [code health improvement] Refactor broad exception handling in _atomic_write_json_sync#372
Conversation
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
Reviewer's guide (collapsed on small PRs)Reviewer's GuideRefactors _atomic_write_json_sync to replace broad Exception handlers with more specific OS and JSON serialization-related exceptions, making error handling clearer and safer while preserving overall behavior of temporary-file writes and cleanup. Flow diagram for refined exception handling in _atomic_write_json_syncflowchart TD
A[start _atomic_write_json_sync] --> B[os.fdopen fd]
B -->|success| C[with f: json.dump data]
B -->|OSError| D[os.close fd]
D --> E[raise]
C --> F[os.replace tmp_path path]
F --> G[end]
C -. may raise .-> H[(OSError or TypeError or ValueError)]
F -. may raise .-> H
H --> I[os.unlink tmp_path]
I -->|success| J[raise]
I -->|OSError| K[pass]
K --> J
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 1 issue, and left some high level feedback:
- Narrowing the outer
exceptto(OSError, TypeError, ValueError)changes behavior for other unexpected exceptions (e.g.OverflowError,RecursionError) which will now leave the temp file behind; confirm this is acceptable or consider a fallback cleanup path for truly unexpected errors. - Similarly, the inner
except OSErroraroundos.fdopenassumes onlyOSErroris relevant; if any other exception type here should still triggeros.close(fd), you may want a broader catch that closes the FD before re-raising.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Narrowing the outer `except` to `(OSError, TypeError, ValueError)` changes behavior for other unexpected exceptions (e.g. `OverflowError`, `RecursionError`) which will now leave the temp file behind; confirm this is acceptable or consider a fallback cleanup path for truly unexpected errors.
- Similarly, the inner `except OSError` around `os.fdopen` assumes only `OSError` is relevant; if any other exception type here should still trigger `os.close(fd)`, you may want a broader catch that closes the FD before re-raising.
## Individual Comments
### Comment 1
<location path="router/main.py" line_range="629" />
<code_context>
try:
f = os.fdopen(fd, "w", encoding="utf-8")
- except Exception:
+ except OSError:
os.close(fd)
raise
</code_context>
<issue_to_address>
**issue (bug_risk):** Non-OSError exceptions from os.fdopen can now leak the file descriptor.
With this change, failures in `os.fdopen` that aren't `OSError` will leave `fd` open and leak the descriptor. If you want narrower error handling, you can still ensure `fd` is always closed on any `fdopen` failure by using a broader `except` solely to close the fd, or by wrapping `fdopen` in a helper that guarantees cleanup on error.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| try: | ||
| f = os.fdopen(fd, "w", encoding="utf-8") | ||
| except Exception: | ||
| except OSError: |
There was a problem hiding this comment.
issue (bug_risk): Non-OSError exceptions from os.fdopen can now leak the file descriptor.
With this change, failures in os.fdopen that aren't OSError will leave fd open and leak the descriptor. If you want narrower error handling, you can still ensure fd is always closed on any fdopen failure by using a broader except solely to close the fd, or by wrapping fdopen in a helper that guarantees cleanup on error.
2663eb8 to
f24e70a
Compare
|
Warning Review limit reached
Next review available in: 51 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
…mic_write_json_sync Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@users.noreply.github.com>
… atomic JSON write - Use try/finally pattern in _atomic_write_json_sync to guarantee temp file unlinking on any exception. - Catch all exception types during os.fdopen to close raw file descriptor prior to re-raising. - Add unit tests for non-OSError fdopen failures and unexpected dump exceptions.
6f21f63 to
483039f
Compare
🎯 What: Replaced broad
Exceptioncatches with specific exceptions (OSError,TypeError,ValueError) in_atomic_write_json_sync.💡 Why: Broad exception handling makes debugging difficult. Catching specific file-related and serialization exceptions improves maintainability and readability.
✅ Verification: Verified by running the existing test suite.
✨ Result: Improved code health and safer exception handling.
PR created automatically by Jules for task 16094635891453368834 started by @sheepdestroyer
Summary by Sourcery
Enhancements:
Exceptioncatches with targetedOSError,TypeError, andValueErrorhandling in_atomic_write_json_syncto improve robustness and readability.