Skip to content

Fix atomic writes replacing destinations after command failures - #1918

Open
wterrr wants to merge 1 commit into
fastapi:masterfrom
wterrr:fix/atomic-write-rollback
Open

Fix atomic writes replacing destinations after command failures#1918
wterrr wants to merge 1 commit into
fastapi:masterfrom
wterrr:fix/atomic-write-rollback

Conversation

@wterrr

@wterrr wterrr commented Aug 2, 2026

Copy link
Copy Markdown

Summary

  • register atomic file parameters as exception-aware context resources
  • forward callback exceptions through lazy atomic files
  • discard temporary output instead of replacing the destination after failures
  • add regression tests for lazy and eager files

Problem

File parameters configured with atomic=True replace the destination even
when the command callback raises an exception after writing partial content.

This defeats the purpose of atomic output and can replace an existing valid
file with incomplete data.

The issue affects both lazy=True and lazy=False.

Fix

Atomic files are now registered with Context.with_resource() so their
context managers receive the active exception.

LazyFile forwards the exception information to its underlying atomic
stream, and _AtomicFile.close(delete=True) removes the temporary file
instead of replacing the destination.

Non-atomic file cleanup behavior is unchanged.

Tests

Regression coverage verifies both lazy modes when:

  • the destination already exists
  • the destination does not exist
  • the command writes and flushes partial content before raising
  • the original callback exception is preserved
  • no temporary file is leaked

Validation results:

  • atomic file tests: 10 passed
  • full test suite: 1390 passed, 12 skipped, 2 xfailed
  • Ruff lint and formatting checks passed

Related upstream report: pallets/click#3221

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.

2 participants