fix(state): atomically write StateManagerDisk .pkl files (#8063)

SH
3d ago
+127-12

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 in target.parent, calls flush() and os.fsync(), and atomically swaps it into place via os.replace().
    • Cleans up the temporary file on any exception before re-raising so no .tmp files are left behind and the previous .pkl remains intact.
  • tests/units/istate/manager/test_disk.py:
    • Added test_set_state_atomic_write_preserves_previous_file_on_failure.
  • 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 --check clean.

Note: This PR was developed with AI assistance and locally verified against the test suite and linter.