Sub topic 6
Writing Checkpoints Atomically
This chapter assumes you can read basic Python, know what JSON is, and understand that a process can be killed at any moment. It covers how to write a checkpoint file so that a crash never leaves a corrupt one.
The problem with writing in place
A checkpoint is only useful if you can read it after a crash. The obvious way to save one is to open the file and overwrite it:
import json
def save_checkpoint_unsafe(path, state):
with open(path, "w") as f:
json.dump(state, f)Opening a file with mode "w" truncates it to zero bytes first. If the process dies, the machine loses power, or the agent is killed halfway through json.dump, the file holds either nothing or a partial JSON document. The old checkpoint is gone and the new one is not complete. The task has lost its progress, which is the thing the checkpoint was meant to protect.
An operation is atomic when other observers see it as either not started or fully finished, with no state in between. We want checkpoint writes to behave that way.
The write-then-swap pattern
The standard solution has three parts:
- Write the new state to a temporary file in the same directory as the target.
- Flush the data to disk.
- Replace the target with the temporary file in a single rename operation.
os.replace performs the rename. On the same filesystem, the operating system swaps the name in one step. A reader sees either the old file or the new one.
The implementation
import json
import os
import tempfile
def save_checkpoint(path, state):
directory = os.path.dirname(os.path.abspath(path))
fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(state, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
except BaseException:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
raise
def load_checkpoint(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return NoneEach detail has a reason:
dir=directory: A rename is only atomic within one filesystem. A temp file in/tmpmay sit on a different filesystem, and the move could become a copy followed by a delete, which is not atomic.f.flush()andos.fsync:flushmoves Python's buffer to the operating system.fsyncasks the operating system to write it to the storage device. Without them, a power loss after the rename can leave a correctly named but empty file.except BaseException: This also catchesKeyboardInterrupt, so an interrupted save does not leave stray.tmpfiles.load_checkpointreturnsNone: A missing file means a fresh start, and the caller can tell that apart from a real checkpoint.
What atomic does not cover
Atomic replacement protects the file from being half-written. It does not make the contents correct.
- It does not stop two processes from overwriting each other's checkpoints. The last writer wins. A later chapter covers locking.
- It does not guarantee the saved state matches the real world. A step may have changed something after the last save.
- For full durability, you can also
fsyncthe directory after the rename. This protects the rename itself against power loss. Many tasks skip it, because the worst case is losing the newest checkpoint, and the old one is still valid.
Exercise
A teammate saves checkpoints with tempfile.mkstemp() using the default directory (usually /tmp), then calls os.replace to move the file into the project folder. Tests pass, but in production, which runs with the project folder on a separate mounted volume, checkpoints are occasionally corrupt after crashes. What is the likely cause, and what is the fix?
Show answer
A rename across filesystems cannot be done in a single step, so os.replace fails with an error or, in other tools, falls back to copy-then-delete, which a crash can interrupt. Pass dir=directory to mkstemp so the temp file is created in the same directory as the checkpoint, keeping the swap atomic.