fix(state): atomically write StateManagerDisk .pkl files (#8063)
SH
3d ago+127+127+012345678901234567890123456789-12-12-01234567890123456789
Fixes #8063
Summary
StateManagerDisk.set_state_for_substate() previously persisted .pkl files in place via Path.write_bytes(), which opens the destination with O_TRUNC and can wipe or corrupt previously committed state if the process crashes or is killed mid-write.
Changes
reflex/istate/manager/disk.py(_atomic_write_bytes,StateManagerDisk.set_state_for_substate):- Added
_atomic_write_bytes(target, data)which writes to a sibling temporary file intarget.parent, callsflush()andos.fsync(), and atomically swaps it into place viaos.replace(). - Cleans up the temporary file on any exception before re-raising so no
.tmpfiles are left behind and the previous.pklremains intact.
- Added
tests/units/istate/manager/test_disk.py:- Added
test_set_state_atomic_write_preserves_previous_file_on_failure.
- Added
news/+atomic-disk-state-write.bugfix.md:- Added news fragment.
Testing
pytest tests/units/istate/manager/test_disk.py(all passed)ruff check&ruff format --checkclean.
Note: This PR was developed with AI assistance and locally verified against the test suite and linter.