Replacing a Generated File After a Complete Write

A generated output can be written to a temporary file and then moved into place with an atomic replacement operation on a supported filesystem.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a failed generation
  2. State the filesystem assumptions
  3. Build and validate a complete replacement beside its destination
  4. Distinguish visibility from persistence of the rename

Trace a failed generation

An old report remains readable while a new report is written elsewhere. If generation fails half through, there is no need to present a partial report. File write modes explain why opening the final file for ordinary writing differs.

State the filesystem assumptions

A replacement typically needs the temporary and final paths on the same filesystem. Visibility and persistence after a crash have distinct guarantees. Add integration tests for the actual platform and document sync requirements if necessary.[1]

Build and validate a complete replacement beside its destination

Suppose readers serve a report from one stable path. The writer can save a proposed revision to a nearby temporary file, close and validate it, and replace the destination via an atomic rename where the filesystem supports that operation. A failure while generating then leaves the earlier report available. See temporary file lifetime.

Destination has version A
Temporary file receives version B
Validate B and close its writer
Replace destination entry → future opens see B under the stated atomic semantics

Distinguish visibility from persistence of the rename

An already open handle can continue reading an older object. Sync requirements for persistence depend on platform and filesystem. Test an interrupted writer before replacement and a successful reader afterwards, using one filesystem as required by the rename contract.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩