Sub topic 13
Common Failure Modes and How to Spot Them
This chapter assumes you can read basic Python, know how an LLM agent calls tools in a loop, and have seen the checkpoint, progress file, and handoff patterns from earlier chapters. Here the focus is on how those patterns break and how to notice the break before it costs you work.
Why failure modes deserve their own chapter
Checkpoints and progress files give you a recovery path. They also give you new ways to go wrong. A saved state can be old, wrong, half-written, or written by two workers at once. A resumed run can repeat a side effect that already happened. A handoff note can omit the one fact the next reader needed.
Most of these failures share one trait. They are silent. The run continues, the output looks plausible, and the damage shows up later. So each failure below comes with a symptom you can check for and a defense you can build in.
Stale state
Stale state means the saved record no longer matches the world. The checkpoint says a step is complete, but something changed after it was written.
Common causes:
- Someone edited or deleted the output files by hand.
- An upstream data source changed after the step ran.
- A checkpoint from an older run was loaded for a newer task.
- A progress file was updated by the agent's memory of events instead of by observing the result.
Symptoms:
- A later step fails on input that "must exist" according to the checkpoint.
- The final result is missing pieces that the log says were produced.
- Two runs of the same task disagree about what is done.
Defenses:
- Check saved state against reality before trusting it (see the chapter on verification). For each step marked complete, confirm that its output exists and has the expected shape.
- Store a task identifier and an input fingerprint in the checkpoint. Refuse to resume when they do not match.
- Record timestamps so a reader can judge how old a claim is.
The following sketch adds a task identifier and a check of output files to the resume routine. It assumes the load_checkpoint and save_checkpoint functions from the earlier chapter.
import os
def validate_state(state, task_id, output_dir):
"""Return a list of problems found. An empty list means the state looks usable."""
problems = []
if state.get("task_id") != task_id:
problems.append(
f"checkpoint belongs to task {state.get('task_id')!r}, expected {task_id!r}"
)
for name in state.get("completed", []):
expected = os.path.join(output_dir, name + ".out")
if not os.path.exists(expected):
problems.append(f"step {name!r} is marked complete but {expected} is missing")
return problems
if __name__ == "__main__":
state = {"task_id": "export-42", "completed": ["fetch", "transform"]}
for problem in validate_state(state, "export-43", "out"):
print(problem)Running this prints three lines: one task mismatch and one missing file for each completed step. A real resume routine would stop, or re-run the affected steps, instead of printing.
Duplicated side effects
A side effect is any action that changes something outside the task's own files: sending an email, uploading a file, charging a card, posting a message. Repeating a side effect is usually worse than repeating a computation.
The classic gap looks like this:
- The step performs the side effect.
- The process crashes.
- The checkpoint, which would have recorded the step, is never written.
- On resume, the step runs again.
Symptoms:
- Duplicate files, messages, or records after a restart.
- Counts at the destination that are higher than counts at the source.
Defenses:
- Make the step idempotent, meaning running it twice has the same result as running it once. Use an idempotency key, or write to a name derived from the input so a second write replaces the first.
- Where you cannot make a step idempotent, write an "intent" entry before the action and a "done" entry after. On resume, an intent without a done entry means "unknown, check the destination first."
- Put a "Do not repeat" section in the handoff note for steps that are not safe to run again.
The next example records intent before an action and refuses to blindly repeat it.
def run_upload(state, upload, already_uploaded, save):
"""Upload once. If a previous attempt may have succeeded, check first."""
if "upload" in state["completed"]:
return
if state.get("upload_started"):
# A previous run began the upload but never recorded completion.
if already_uploaded():
state["completed"].append("upload")
save(state)
return
state["upload_started"] = True
save(state)
upload()
state["completed"].append("upload")
save(state)The already_uploaded function asks the destination, not the checkpoint, whether the file is there. The destination is the source of truth.
Corrupt or partial checkpoints
If a process dies while writing a checkpoint file in place, the file can end up truncated. The next json.load raises an error, and the task has lost its memory.
Symptoms:
JSONDecodeErroron startup.- A checkpoint file of zero bytes, or one that ends mid-line.
Defenses:
- Write to a temporary file in the same directory, flush, call
fsync, then useos.replace. This is the atomic write pattern from the earlier chapter. - Decide what to do when a checkpoint is unreadable. Do not silently treat it as "no checkpoint" and start over if earlier steps had side effects. Stop and report instead.
The difference between "file not found" and "file unreadable" matters. A missing file means a fresh start. A corrupt file means something went wrong, and a person or a recovery step should look at it.
import json
def load_checkpoint_strict(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return None
except json.JSONDecodeError as exc:
raise RuntimeError(
f"checkpoint {path} is unreadable ({exc}); refusing to start over"
) from excConcurrent writers
Two workers that write the same checkpoint or progress file will overwrite each other. Each reads the state, changes its own part, and writes the whole file back. The second write erases the first worker's change.
How it happens in practice:
- A supervisor restarts a task that was only slow, not dead, so two copies run.
- Two agents are given the same progress file for different parts of a task.
- A person edits the progress file while an agent is writing it.
Symptoms:
- Steps that were finished reappear as pending.
- The progress file shows decisions that contradict one another.
- Intermittent failures that no single run explains.
Defenses:
- Use one writer per state file. Give each worker its own file and merge afterward.
- Take a lock before running. A lock file created with exclusive mode fails if it already exists.
- Store the owner and a start time in the lock so a stale lock can be recognized.
import os
def acquire_lock(lock_path, owner):
try:
fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
with open(lock_path) as f:
holder = f.read().strip()
raise RuntimeError(f"task is locked by {holder}")
with os.fdopen(fd, "w") as f:
f.write(owner)
def release_lock(lock_path):
os.unlink(lock_path)A lock left behind by a crashed process blocks every later run. That is the price of this simple design. Decide in advance who may remove a stale lock and how they confirm the old holder is gone.
Plausible but wrong progress notes
Progress files are written by agents, and agents can write confident text that is wrong. A note such as "all links fixed" may reflect intent, not a check.
Symptoms:
- A status line claims completion but no command output backs it up.
- Counts in the notes are round numbers or never change.
- The "Next action" repeats the same text across several sessions.
Defenses:
- Tie each "done" claim to evidence: a command, a count, a file path.
- Separate "done" from "verified" in the notes, as the handoff example does with "Not yet verified."
- Make the final step of every unit of work a check that produces a number, then write that number down.
Lost context in handoffs
A handoff fails when the reader cannot act without asking the author. The author is often gone, so the question cannot be answered.
Typical omissions:
- The reason behind a decision, which leads the next agent to reverse it.
- Steps that are unsafe to repeat.
- The location of the full state.
- Facts that the author considered obvious, such as which environment or account the task runs against.
Symptoms:
- The new agent starts by redoing work.
- The new agent makes a choice the previous agent had ruled out.
- The first message from the reader is a question.
Defense: test the note. Give it to a reader with no other context and ask what they would do first. If the answer is not the stated next action, rewrite the note.
Unbounded growth and drift
Long tasks accumulate text. Logs grow, progress files collect old notes, and the checkpoint embeds large outputs. Two problems follow.
- Reading the state costs more each session, until it crowds out the actual work in the agent's context window.
- Important lines get buried under old ones, so the reader misses the current status.
Defenses:
- Keep large outputs in separate files and store only their paths in the checkpoint.
- Keep the progress file short and current. Move history to a separate log.
- Put the status and next action near the top.
A quick reference
| Failure mode | Typical symptom | First defense |
|---|---|---|
| Stale state | Later step fails on input the checkpoint says exists | Validate saved state against reality on resume |
| Duplicated side effects | Duplicate uploads or messages after a restart | Idempotent steps, or intent and done entries |
| Corrupt checkpoint | JSON error on startup | Atomic writes, and stop on unreadable state |
| Concurrent writers | Finished steps reappear as pending | One writer per file, or a lock |
| Wrong progress notes | "Done" claims with no evidence | Attach a command, count, or path to each claim |
| Lost handoff context | New agent redoes or reverses work | Test the note with a cold reader |
| Unbounded growth | State files crowd the context window | Store paths, keep the progress file short |
Spotting failures early
You do not have to wait for a symptom. A few cheap habits surface problems sooner:
- Log every resume: which checkpoint was loaded, its age, and which steps were skipped.
- Compare counts at the source and destination at the end of each unit of work.
- Run a deliberate crash test. Kill the process at a random point, restart, and confirm the result matches an uninterrupted run.
- Review the progress file as if you were the next reader, after every session.
Exercises
Exercise
A task uploads a file, then saves a checkpoint. The process crashes between the two. After restart, two copies of the file appear at the destination. Name the failure mode and give two ways to prevent it.
Show answer
This is a duplicated side effect caused by a crash between the action and the checkpoint write. Prevent it by making the upload idempotent (for example, write to a name derived from the input so a repeat overwrites), or by recording an intent entry before the upload and, on resume, checking the destination before repeating it.
Exercise
On startup, load_checkpoint raises a JSONDecodeError. A teammate suggests catching the error and starting from scratch. Why is that risky, and what should the code do instead?
Show answer
Earlier steps may already have caused side effects, such as uploads or sent messages, and a fresh start would repeat them. The code should stop with a clear error that names the file, so a person or a recovery step can inspect it. Only a missing file should mean a fresh start.
Exercise
Two copies of a task run at once because a supervisor restarted a slow run. Describe one symptom you would see in the progress file and one mechanism that prevents it.
Show answer
Symptom: steps that were finished show up as pending again, because one writer overwrote the other's update. Prevention: acquire an exclusive lock file (created with OCREAT | OEXCL) before running, so the second copy fails to start, or give each worker its own state file.