Sub topic 9
Checking Saved State Against Reality
A checkpoint records what the agent believed was true when it saved. Between the save and the resume, the world may have changed. This chapter shows how to compare saved state with the real system before you continue. It assumes you have read the chapters on checkpoints, progress files, and the resume protocol, and that you can read basic Python.
Why saved state can be wrong
A checkpoint is a claim, not a fact. It can disagree with reality in several ways:
- A person deleted or edited an output file after the step finished.
- A step wrote its checkpoint, but the output was later overwritten by another process.
- The checkpoint was saved before a side effect finished, so the step is marked done when it is not.
- The source data changed, so earlier results are out of date.
If the resume routine trusts the file blindly, it skips work that needs redoing. The error then shows up several steps later, far from its cause.
Trust, then verify
The rule is simple: treat saved state as a hint about where to look, and confirm it with a cheap check. Each completed step gets a check that inspects the real result, such as a file, a row count, or a remote record.
A verification routine
The code below attaches one check function to each step. If a check fails, the routine removes that step and every later step from the completed list. Later steps may depend on the failed one, so they cannot be trusted either.
import os
STEPS = ["fetch", "transform", "validate", "publish"]
def failed_checks(state, checks):
"""Return the completed steps whose check fails."""
failed = []
for name in state["completed"]:
check = checks.get(name)
if check is not None and not check(state):
failed.append(name)
return failed
def roll_back(state, checks):
failed = failed_checks(state, checks)
if failed:
first = min(STEPS.index(n) for n in failed)
state["completed"] = [
n for n in state["completed"] if STEPS.index(n) < first
]
state["notes"].append(
f"Re-running from {STEPS[first]}: check failed for {failed}"
)
return state
state = {"completed": ["fetch", "transform"], "notes": []}
checks = {
"fetch": lambda s: True,
"transform": lambda s: os.path.exists("transformed.csv"),
}
print(roll_back(state, checks))If transformed.csv does not exist, the output is:
{'completed': ['fetch'], 'notes': ["Re-running from transform: check failed for ['transform']"]}The transform step will run again. The note explains why, so the next reader of the progress file does not have to guess.
Choosing good checks
A check should be much cheaper than redoing the step, and it should test the result, not the record of the result.
| Step result | Weak check | Better check |
|---|---|---|
| Output file written | Checkpoint says "done" | File exists, size above zero, parses correctly |
| Rows exported | Counter in state | Row count matches the source query |
| Upload finished | Log line found | Remote listing contains the object |
| Test run passed | Saved "passed" flag | Run the fast test again |
Checks that can have side effects, such as an upload, do not belong here. Verification should only read.
What to do when reality and state disagree
- Prefer reality. Update the checkpoint to match what you observed.
- Roll back to the earliest failed step, as the code does.
- Write the disagreement into the progress file, with the time and the evidence.
- If you cannot tell which side is correct, stop and ask rather than guessing.
Exercise
A checkpoint lists "export" as completed, but the check finds the output file is empty. Steps "validate" and "publish" are also listed as completed. Which steps should the resume routine re-run, and why?
Show answer
It should re-run "export", "validate", and "publish". The export result is bad, and the later steps worked from that result, so their recorded completion cannot be trusted. The routine should also add a note explaining the rollback.