Skip to content

🧹 [code health improvement] Refactor broad exception handling in _atomic_write_json_sync#372

Merged
sheepdestroyer merged 2 commits into
masterfrom
fix-atomic-write-json-exception-16094635891453368834
Jul 24, 2026
Merged

🧹 [code health improvement] Refactor broad exception handling in _atomic_write_json_sync#372
sheepdestroyer merged 2 commits into
masterfrom
fix-atomic-write-json-exception-16094635891453368834

Conversation

@sheepdestroyer

@sheepdestroyer sheepdestroyer commented Jul 24, 2026

Copy link
Copy Markdown
Owner

🎯 What: Replaced broad Exception catches 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:

  • Replace broad Exception catches with targeted OSError, TypeError, and ValueError handling in _atomic_write_json_sync to improve robustness and readability.

@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 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 @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@sourcery-ai

sourcery-ai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Refactors _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_sync

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

File-Level Changes

Change Details Files
Narrowed broad exception handling in _atomic_write_json_sync to specific OS and serialization-related exceptions.
  • Changed inner fdopen failure handler to catch only OSError and explicitly close the file descriptor before re-raising.
  • Updated main try/except around JSON dumping and os.replace to catch only OSError, TypeError, and ValueError, corresponding to filesystem and JSON serialization issues.
  • Restricted cleanup unlink failure handler to catch only OSError and ignore it, instead of swallowing all exceptions.
router/main.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

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

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread router/main.py Outdated
try:
f = os.fdopen(fd, "w", encoding="utf-8")
except Exception:
except OSError:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@sheepdestroyer
sheepdestroyer force-pushed the fix-atomic-write-json-exception-16094635891453368834 branch from 2663eb8 to f24e70a Compare July 24, 2026 10:36
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@sheepdestroyer, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 51 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 185af8fa-0c07-43ea-ac5b-3fcecf44f704

📥 Commits

Reviewing files that changed from the base of the PR and between da14ac0 and 483039f.

📒 Files selected for processing (2)
  • router/main.py
  • tests/test_atomic_write.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-atomic-write-json-exception-16094635891453368834

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.

@github-actions github-actions Bot added the tests label Jul 24, 2026
google-labs-jules Bot and others added 2 commits July 24, 2026 12:43
…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.
@sheepdestroyer
sheepdestroyer force-pushed the fix-atomic-write-json-exception-16094635891453368834 branch from 6f21f63 to 483039f Compare July 24, 2026 10:43
@sheepdestroyer
sheepdestroyer merged commit a3683d9 into master Jul 24, 2026
8 checks passed
@sheepdestroyer
sheepdestroyer deleted the fix-atomic-write-json-exception-16094635891453368834 branch July 24, 2026 10:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant