Sub topic 8
Resuming from Saved State
This chapter covers the resume routine: what an agent does when it starts and finds state left by an earlier run. It assumes you can read Python, JSON, and Markdown, and that you know how an agent loop calls tools. It also assumes you have seen checkpoints and progress files from earlier chapters. Here we put them to work.
Why resuming needs its own design
Saving state is only half of the job. A run that restarts must decide three things before it does any work:
- Is there saved state at all?
- Can that state be believed?
- Which step comes next?
Many agents get the first and third right and skip the second. They read a checkpoint, see "transform: done", and move on. If the checkpoint is older than the real world, that choice causes duplicate work or lost work.
A resume routine is the code (or the written instructions to an agent) that answers those three questions in a fixed order. Writing it down once means every restart behaves the same way.
The resume protocol
A resume protocol is a short, ordered procedure. A reliable version has five stages.
- Locate. Look for the checkpoint and the progress file in known paths. If neither exists, this is a fresh start.
- Load. Parse the checkpoint. If parsing fails, treat the file as damaged and fall back to the progress file or to a fresh start. Do not guess.
- Verify. Compare what the state claims with what actually exists, such as output files or database rows. The next chapter treats this in depth. Here we only place it in the sequence.
- Select. Choose the first step that is not recorded as complete.
- Continue. Run that step, and save a checkpoint after it.
Notice that the fresh start and the resumed run join at the same stage. A fresh start is simply a resume with an empty list of completed steps. Sharing one code path means you test resuming every time you run, not only after a crash.
A resume loop in code
The loop below uses the save_checkpoint and load_checkpoint functions from the checkpoint chapter. It is repeated here in a form that runs on its own, with a simple verification hook added.
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
except json.JSONDecodeError:
return None
def first_unfinished(state):
for name in STEPS:
if name not in state["completed"]:
return name
return None
def run(checkpoint_path, step_functions, verifiers=None):
verifiers = verifiers or {}
state = load_checkpoint(checkpoint_path) or {"completed": [], "notes": []}
# Verify: drop any step whose claimed result is missing.
for name in list(state["completed"]):
check = verifiers.get(name)
if check is not None and not check(state):
state["notes"].append(f"{name} was marked done but failed verification")
state["completed"].remove(name)
while True:
name = first_unfinished(state)
if name is None:
break
step_functions[name](state)
state["completed"].append(name)
save_checkpoint(checkpoint_path, state)
return state
if __name__ == "__main__":
def make_step(label):
def step(state):
print("running", label)
return step
funcs = {n: make_step(n) for n in STEPS}
result = run("demo_checkpoint.json", funcs)
print("completed:", result["completed"])Run it twice. The first run executes all four steps. The second run prints only the final line, because every step is already recorded.
One detail matters here. If verification removes a step from completed, every later step may depend on it. The simple loop above re-runs from the first unfinished step in STEPS order, so it re-runs the removed step and everything after it that is not still marked complete. For strict pipelines, also remove all steps after the failed one.
The window between work and checkpoint
The most important edge case in resuming is the gap between finishing a step's work and saving its checkpoint. A crash in that gap leaves a step that did its work but is not recorded as done.
On resume, the checkpoint does not mention publish, so the routine runs it again. What happens next depends on the step:
- If the step is idempotent (running it twice gives the same result as once), nothing breaks.
- If it is not, you get a duplicate upload, a second email, or a double charge.
You cannot remove this window. You can only handle it. There are three common approaches:
| Approach | How it works | Cost |
|---|---|---|
| Make the step idempotent | Use a stable key, such as an output file name derived from the input, and overwrite instead of append. | Needs design effort per step. |
| Record intent first | Save "publish: started" before the work, then check the real system on resume if you find "started" without "done". | Adds a state and a check. |
| Verify the effect | On resume, look at the target system to see whether the work already happened. | Needs a read path to the target. |
The best designs combine the first and third. The step is safe to repeat, and the resume routine still checks.
Recording "started" separately from "done"
A two-state record lets the resume routine notice an unfinished step instead of silently treating it as untouched.
def begin_step(state, name, path):
state.setdefault("started", [])
if name not in state["started"]:
state["started"].append(name)
save_checkpoint(path, state)
def finish_step(state, name, path):
state["completed"].append(name)
if name in state["started"]:
state["started"].remove(name)
save_checkpoint(path, state)
def interrupted_steps(state):
return [n for n in state.get("started", []) if n not in state["completed"]]On resume, interrupted_steps(state) returns steps that began and never finished. Those are the ones to inspect before running again. For a step that only writes a local file, you can just redo it. For a step that calls an outside service, check that service first.
Using the progress file when resuming
The checkpoint is for code. The progress file is for the reader, whether that is a person or an agent that has lost its context. On resume, an agent should read the progress file as well as the checkpoint, because the checkpoint says what finished and the progress file says why and what to do next.
When the two disagree, decide which one wins by what each is good at:
- For which steps finished, trust the checkpoint, after verifying it against reality.
- For intent, decisions, and the next action, trust the progress file.
A mismatch is worth recording. If the progress file says "Convert shortcodes (18 of 42 done)" but the output folder holds 21 converted files, write that difference into the notes and resolve it. Do not silently pick one number.
A practical start-up message for an agent looks like this:
## Resume check (session 4)
- Checkpoint lists: fetch, transform
- Progress file next action: validate
- Output files found: matches checkpoint
- Decision: continue at validateWriting the check down gives the next session evidence of what you saw, not just a conclusion.
Common resume errors
- Trusting a stale checkpoint. The state is old, and the world changed. The input data was updated, or someone deleted the output. Verify before you skip.
- Resuming into changed code. If the step list or step meaning changed between runs, the saved names may no longer match. Store a version number in the state and refuse to resume across an incompatible one.
- Treating a parse error as an empty state. In the code above, a damaged checkpoint starts a fresh run. That is fine for cheap, idempotent work. For expensive or side-effecting work, stop and ask instead, since a fresh start may repeat everything.
- Resuming silently. Always print or log what was found and which step is next. A silent resume hides bugs.
- Skipping the last step's check. The step that was running at the time of the crash is the one most likely to be half done. Look at it first.
Summary of the design
A sound resume routine is short. It locates state, loads it defensively, verifies it, picks the first unfinished step, and logs what it decided. It treats the gap between work and checkpoint as real, and it handles that gap through idempotent steps, a "started" marker, or a check against the target system.
Exercise
A run crashes after uploading a file in the "publish" step but before saving the checkpoint. The upload step is not idempotent. Name two things you could add so the resume routine avoids a duplicate upload.
Show answer
Any two of: record "publish: started" before the upload and check the target for the file when resuming finds "started" without "done"; make the upload idempotent by using a stable file name derived from the input so a repeat overwrites instead of duplicating; query the target system on resume to see whether the file already exists and skip the upload if it does.
Exercise
The checkpoint lists "transform" as complete, but the transform output file is missing. Which of the two records do you trust for which steps are done, and what should the routine do?
Show answer
Do not trust the checkpoint alone. Verification against reality shows the claim is false, so the routine removes "transform" (and any later steps that depend on it) from the completed list, notes the mismatch, and re-runs transform.
Exercise
Why does the resume code treat a fresh start and a resumed run through the same loop?
Show answer
A fresh start is a resume with no completed steps. Sharing one code path means the resume logic runs on every execution, so it is tested constantly and not only after a rare crash.