Skip to content

fix(file_io): write_json atomically (temp + os.replace) to survive interrupted writes#96

Open
gadievron wants to merge 1 commit into
masterfrom
fix/file-io-write-json-atomically-temp-os-replace
Open

fix(file_io): write_json atomically (temp + os.replace) to survive interrupted writes#96
gadievron wants to merge 1 commit into
masterfrom
fix/file-io-write-json-atomically-temp-os-replace

Conversation

@gadievron
Copy link
Copy Markdown
Collaborator

write_json opened the target in "w" (truncating it to 0 bytes) and then streamed json.dump.
A crash mid-serialization (SIGKILL / OOM / power loss) left the target partial or empty and
destroyed the prior good copy, so the next read_json raised JSONDecodeError -- e.g. a
corrupted checkpoint.json that breaks resume.

Serialize to a temp file in the same directory, flush + fsync, then os.replace onto the
target (atomic rename). An interrupted write leaves only the temp file (unlinked on a caught
error); the existing target is never truncated. All write_json call sites inherit the fix.
The temp uses a .tmp suffix (not .json) so a hard-crash leftover can't be miscounted by
directory scanners that do os.listdir + endswith(".json") (e.g. core/checkpoint.py).

Tests: tests/test_file_io_atomic_write.py (2 cases: interrupted write preserves the prior
file + no temp leak; normal round-trip incl. non-ASCII). RED 1 failed (JSONDecodeError) ->
GREEN 2 passed (venv py3.11). ruff clean.

Co-Authored-By: Claude Opus 4.7 (1M context) noreply@anthropic.com

…terrupted writes

write_json opened the target in "w" (truncating it to 0 bytes) and then streamed json.dump.
A crash mid-serialization (SIGKILL / OOM / power loss) left the target partial or empty and
destroyed the prior good copy, so the next read_json raised JSONDecodeError -- e.g. a
corrupted checkpoint.json that breaks resume.

Serialize to a temp file in the same directory, flush + fsync, then os.replace onto the
target (atomic rename). An interrupted write leaves only the temp file (unlinked on a caught
error); the existing target is never truncated. All write_json call sites inherit the fix.
The temp uses a `.tmp` suffix (not `.json`) so a hard-crash leftover can't be miscounted by
directory scanners that do os.listdir + endswith(".json") (e.g. core/checkpoint.py).

Tests: tests/test_file_io_atomic_write.py (2 cases: interrupted write preserves the prior
file + no temp leak; normal round-trip incl. non-ASCII). RED 1 failed (JSONDecodeError) ->
GREEN 2 passed (venv py3.11). ruff clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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.

1 participant