Sub topic 8
Resuming from Saved State
This chapter assumes you have read the previous chapters on checkpoints and progress files. You should know how to write a checkpoint atomically and what a progress file records. You also need basic Python and JSON.
A saved checkpoint does nothing until a restarted run knows how to use it. The routine that does this is the resume protocol. It answers one question: where does this run continue?
The resume protocol
A resume routine does the same few things each time it starts:
- Load the checkpoint. If none exists, start with empty state.
- Read the progress file for goal, decisions, and the next action.
- Skip every step the checkpoint lists as completed.
- Run the first unfinished step.
- Save a checkpoint after each step finishes.
The key design choice is that a fresh start and a restart use the same code path. A fresh start is just a restart with no checkpoint. You do not need a separate "recovery mode", and that removes a whole class of bugs.
A resumable runner
This script is complete. It saves checkpoints atomically, loads them, and runs the steps in order.
import json
import os
import tempfile
STEPS = ["fetch", "transform", "validate", "publish"]
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 None
def run(checkpoint_path, step_functions):
state = load_checkpoint(checkpoint_path) or {"completed": [], "notes": []}
for name in STEPS:
if name in state["completed"]:
continue
step_functions[name](state)
state["completed"].append(name)
save_checkpoint(checkpoint_path, state)
return state
def make_step(name):
def step(state):
print("running", name)
state["notes"].append(name + " done")
return step
if __name__ == "__main__":
functions = {name: make_step(name) for name in STEPS}
result = run("checkpoint.json", functions)
print("completed:", result["completed"])Run it once and all four steps print. Run it again and no step prints, because every name is already in completed. To test a real resume, make one step raise an exception on its first call, run the script, then fix the step and run it again. The second run starts at the step that failed.
The gap between a step and its checkpoint
The runner saves a checkpoint only after a step returns. If the process dies after publish finishes its work but before the save, the checkpoint does not list publish. On restart, the runner runs it again.
This gap cannot be closed completely, so the steps must tolerate it. Every step needs to be safe to repeat. A step that uploads a file should overwrite the same destination name, not append a new file each time. A step that cannot be made repeatable needs its own record, such as a marker written in the same place as the side effect.
Common resume errors
| Error | Symptom | Fix |
|---|---|---|
| Checkpoint saved before the step finishes | A crashed step is marked done and never runs again | Save only after the step returns |
| Step is not repeatable | Duplicate files or records after a restart | Make the step idempotent, or record the side effect |
| Step list changed between runs | Saved names no longer match `STEPS` | Store a version in the state and check it on load |
| Progress file disagrees with checkpoint | The notes say step 3 is next, the checkpoint says step 2 | Treat the checkpoint as the machine truth and update the notes |
Exercise
A run crashes after the transform step finishes its work but before save_checkpoint runs. What happens on restart, and what property must transform have for this to be safe?
Show answer
The checkpoint does not list transform as completed, so the runner runs it again. transform must be idempotent: running it twice on the same input must give the same result and no duplicated side effects.