Sub topic 9
Checking Saved State Against Reality
This chapter assumes you have read the earlier chapters on checkpoints, atomic writes, and the resume protocol. You should be comfortable with the save_checkpoint and load_checkpoint functions and with the completed list pattern. You also need basic Python and some familiarity with hashing files.
A checkpoint is a claim, not a fact
A checkpoint says "step transform finished." That sentence was true when it was written. Between that moment and the resume, other things may have happened:
- A person or another process deleted or edited the output.
- A disk was cleaned, or a temporary directory was wiped on reboot.
- The step was marked complete, but the work behind it was only partly done because of a bug.
- An external system changed, for example a remote file was removed or a database row was updated.
If a resume routine trusts the checkpoint blindly, it skips work that no longer holds. Every later step then builds on a missing or damaged input. The failure usually shows up far from the cause, which makes it hard to debug.
The rule for this chapter: on resume, treat saved state as a claim and check it against the real world before acting on it. The real world wins any disagreement.
What can drift
Different kinds of saved state go stale in different ways. Pick the cheapest check that would catch the likely failure.
| Saved claim | How it goes wrong | Cheap check |
|---|---|---|
| "Output file written" | File deleted, truncated, or edited | Exists, size matches, hash matches |
| "Rows loaded: 1200" | Rows deleted or loaded twice | Count query against the destination |
| "Uploaded to bucket" | Upload failed silently or object removed | Ask the remote system whether the object exists |
| "Branch `feature-x` ready" | Someone pushed or rebased | Compare the current commit id with the recorded one |
| "Config version 4 in use" | Config changed after the checkpoint | Compare a version or hash |
| "Step in progress" | Crash happened mid-step; the effect may be partial | Treat as not done and rely on idempotence |
The last row matters most. A step that started but never recorded completion is an unknown, not a failure. You cannot tell how much of its effect landed, so the step must be safe to repeat.
Record evidence when you finish a step
You can only verify what you recorded. When a step completes, store a small piece of evidence next to the completion mark. The evidence should be something you can recompute later without running the step again.
The code below stores the path, size, and SHA-256 hash of an output file, and defines a read-only check that compares the file on disk with that evidence. It includes compact versions of the checkpoint helpers so it runs on its own.
import hashlib
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 None
def sha256_of(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(65536), b""):
digest.update(block)
return digest.hexdigest()
def record_output(state, step, path):
state.setdefault("evidence", {})[step] = {
"path": path,
"bytes": os.path.getsize(path),
"sha256": sha256_of(path),
}
def check_output(state, step):
"""Return (ok, reason). Never modifies anything."""
evidence = state.get("evidence", {}).get(step)
if evidence is None:
return False, "no evidence recorded"
path = evidence["path"]
if not os.path.exists(path):
return False, f"{path} is missing"
if os.path.getsize(path) != evidence["bytes"]:
return False, f"{path} changed size"
if sha256_of(path) != evidence["sha256"]:
return False, f"{path} content differs"
return True, "ok"Comparing the size first is a cheap way to reject most damaged files before reading them. The hash is the stronger check, and it catches an edit that leaves the size unchanged.
Resume with verification
The resume routine from the earlier chapter skipped every step in completed. The version below first computes the longest prefix of completed steps that still holds, and discards the rest.
STEPS = ["fetch", "transform", "validate", "publish"]
def verified_prefix(state, checks):
"""Return completed steps that still hold, stopping at the first failure."""
valid = []
for name in STEPS:
if name not in state["completed"]:
break
ok, reason = checks[name](state, name)
if not ok:
print(f"step {name!r} no longer holds: {reason}")
break
valid.append(name)
return valid
def run(checkpoint_path, step_functions, checks):
state = load_checkpoint(checkpoint_path) or {"completed": [], "notes": []}
state["completed"] = verified_prefix(state, checks)
save_checkpoint(checkpoint_path, state)
for name in STEPS:
if name in state["completed"]:
continue
step_functions[name](state)
state["completed"].append(name)
save_checkpoint(checkpoint_path, state)
return stateTwo design choices are worth explaining.
The prefix stops at the first failure. Steps depend on earlier steps. If transform output is gone, a recorded validate result describes data that no longer exists. Keeping validate as completed would be wrong even if its own evidence still checks out. So everything after the first broken step is dropped and redone.
The corrected state is saved before work continues. If the process crashes again right after verification, the next resume starts from the corrected list and does not repeat the same diagnosis from a stale file.
Each name in checks maps to a function with the check_output signature. Steps with different evidence use different checks. A publish step might ask the destination system whether the object exists instead of reading a local file.
The decision path on resume
What to do on a mismatch
A failed check tells you the claim is wrong. It does not tell you what to do. Choose the response by the cause and the cost of redoing the step.
| Situation | Response |
|---|---|
| Output missing, step is idempotent | Redo the step and record fresh evidence |
| Output differs, nobody should have touched it | Redo, and write a note about the unexplained change |
| Output differs, a person may have edited it on purpose | Stop and ask. Redoing would erase their work |
| Step has an external side effect that cannot be repeated | Stop and inspect the destination before anything else |
| Evidence is missing from an old checkpoint | Treat as unverified and redo, or ask if redoing is risky |
The third and fourth rows are the reason to pause for a human or a decision rule. Automatic redo is only safe for steps that are idempotent and local. For steps that send email, charge a card, or publish to a public location, a mismatch means "investigate," not "try again."
Edge cases
Verification cost. Hashing a 50 GB output on every resume may take longer than redoing small steps. Options include checking size and modification time first, hashing only a sample of blocks, or storing a manifest hash written by the step itself. Whatever you choose, record the check's strength so you know what a pass means. A size match proves less than a hash match.
Time of check versus time of use. A pass tells you the state was correct at the moment of checking. Another process can change it a second later. If other writers exist, combine verification with the locking approach covered later in this tutorial, and keep the gap between check and use short.
Partial steps. Some steps produce many outputs, such as 500 files. Record a per-item manifest so verification can find which items are missing and redo only those. A single "done" flag for the whole step forces a full redo.
Checks that always pass. A check that tests only that the checkpoint file exists, or that compares the checkpoint with itself, verifies nothing. Each check should read something the step produced, from the place where the step produced it.
The progress file lies too. A progress file written by an agent may say "18 of 42 shortcodes converted." Treat that number the same way as a checkpoint count. Count the converted pages in the directory before continuing, and update the file if the numbers disagree.
Wrong environment. A checkpoint written on one machine may name paths, branches, or database hosts that differ on the machine doing the resume. Store an identifier for the target, such as a database name or repository path, and compare it first. If the target differs, stop. Verifying the right claims against the wrong system gives misleading passes or failures.
Verification and handoffs
When work passes to a new agent or person, verification matters more, because the reader has no memory of the work to compensate for gaps. A handoff note should separate what is verified from what is only claimed, as in the "Not yet verified" section of the earlier handoff example. The receiving agent runs the same checks, then moves items from claimed to verified as they pass.
Summary of the working model
- Write evidence alongside each completion mark.
- On resume, recompute the evidence from the real world, read-only.
- Keep only the longest valid prefix of completed steps.
- Save the corrected state before doing new work.
- On mismatch, redo only when the step is safe to repeat. Otherwise stop and look.
Exercise
A checkpoint lists fetch, transform, and validate as completed. On resume, the check for fetch passes, the check for transform fails because its output file is missing, and the check for validate would pass because its report file still exists. Which steps does verified_prefix return, and why is that the right answer?
Show answer
It returns only ["fetch"]. The loop stops at the first failure, so validate is dropped even though its own evidence is intact. The validation report describes the transform output, which no longer exists, so keeping validate would leave a result that doesn't match any current data. After the fix, transform and validate are rerun in order.
Exercise
Your publish step uploads a file to a public site. On resume, the check finds that the remote copy has a different hash from the one in the checkpoint. Should the routine simply rerun publish? Explain.
Show answer
No. The step has an external side effect, and the difference could have several causes: a person edited the remote file on purpose, a different process replaced it, or the earlier upload was partial. Rerunning would overwrite the remote copy and might erase someone's change. The routine should stop, report the mismatch with both hashes, and let a person or an explicit rule decide. Automatic redo is only right for local, idempotent steps.