Sub topic 14
A checklist for designing long-running tasks
This chapter collects the earlier chapters into one design review. It assumes you can read Python, JSON, and Markdown, and that you know how an agent calls tools in a loop. It also assumes you have read the chapters on checkpoints, progress files, resuming, and handoffs. Each item below points back to one of those ideas and says what to check.
How to use the checklist
Run the checklist twice. Run it before you build the task, to shape the design. Run it again before you trust the task with real work, to catch what the design missed.
Each item is a question you can answer with yes or no, and a "no" means there is work to do. Some items need a test rather than a judgment. For those, the test is to kill the process at an awkward moment and see what happens.
The diagram shows the order of the review. Earlier items shape later ones, so a weak decomposition makes every later item harder.
1. Decomposition
- Is every step small enough that you can afford to redo it from the beginning?
- Does each step have a clear start condition and a clear finish condition?
- Can you tell from outside the process whether a step finished?
- Is the step order written down in one place, such as a
STEPSlist, instead of being implied by the code?
A step that takes two hours and produces nothing until the end is a risk. If it fails at minute 119, you lose all of it. Split it so that partial results are saved along the way. A good size is one where the cost of repeating a step is lower than the cost of building recovery logic for it.
2. Repeatable steps
- If a step runs twice, is the result the same as running it once?
- Does every step that has a side effect (a send, an upload, a payment, a delete) have a way to detect that it already happened?
- Do you use stable identifiers, such as a deterministic file name or an idempotency key, instead of random or time-based ones?
- Is the checkpoint written after the step, and can the step safely repeat in the gap between the step finishing and the checkpoint landing?
The last question is the one people miss. A crash can happen after the side effect and before the checkpoint. On restart, the checkpoint says the step is not done, so it runs again. If the step is not safe to repeat, you get duplicates. The handoff example in this tutorial warns that re-running an upload "creates duplicate files." That is a design bug, and a warning note only works around it. Fix it by making the upload check for an existing file first, or by naming the file after its content.
3. State
- Have you listed everything the next run needs to continue, and is all of it outside the agent's memory?
- Is each piece of state stored in exactly one place?
- Is machine state (the checkpoint) kept apart from human-readable explanation (the progress file)?
- Does the state contain only what is needed, with no secrets and no large copies of data you can regenerate?
Agent memory includes the context window, local variables, and anything "remembered" in a conversation. Treat all of it as lost on interruption. A useful test is to start a fresh process with an empty context and only the files on disk. If it cannot continue, some state lives in the wrong place.
4. Checkpoints and atomic writes
- Is a checkpoint saved after every completed step, not just at the end?
- Is each checkpoint written to a temporary file in the same directory, flushed, synced, and swapped in with
os.replace? - Does
load_checkpointhandle a missing file by returningNone? - Does the checkpoint include a version number, so a newer program can read or reject an older file?
- Is a corrupt or unreadable checkpoint treated as an error that stops the run, instead of being silently ignored?
The last item matters because the lenient choice is often the wrong one. If the loader returns an empty state when the file is corrupt, the task starts over and repeats side effects. Stopping is safer. Add a version field when you first create the file, because adding one later is awkward.
CHECKPOINT_VERSION = 2
def load_checked(path):
state = load_checkpoint(path)
if state is None:
return {"version": CHECKPOINT_VERSION, "completed": [], "notes": []}
if state.get("version") != CHECKPOINT_VERSION:
raise RuntimeError(
f"Checkpoint version {state.get('version')} is not supported"
)
return stateThis helper uses load_checkpoint from the earlier chapter. A json.JSONDecodeError from a corrupt file is left to propagate, which is the behavior the checklist asks for.
5. Progress file
- Does it state the goal in one or two sentences?
- Does it list steps with their status, with counts for steps that are partly done?
- Does it record decisions together with the reason?
- Does it name a single next action?
- Does it list open problems that need a decision?
- Is it updated at the same moments as the checkpoint, so the two files do not drift apart?
Reading the progress file should answer "what do I do now?" in under a minute. If the next action says "continue the work," it is too vague. Name the file, the step, and the command.
6. Resume and verification
- Does startup always begin by loading saved state, with no special "first run" path?
- Does it skip steps recorded as complete?
- Before skipping, does it check that the results of those steps still exist?
- If the check fails, does the run stop, or redo the step, according to a rule you chose in advance?
- Does it write down what it verified, and what it did not?
Saved state is a claim about the past. Files may have been deleted, a remote service may have changed, or a different process may have edited the output since. Check the claims that are cheap to check and that a wrong answer would make expensive.
import os
def verify_completed(state, out_dir):
"""Return a list of problems found in the saved state."""
problems = []
for step, files in state.get("outputs", {}).items():
if step not in state["completed"]:
continue
for name in files:
full = os.path.join(out_dir, name)
if not os.path.exists(full):
problems.append(f"{step}: missing output {name}")
elif os.path.getsize(full) == 0:
problems.append(f"{step}: empty output {name}")
return problemsCall it right after loading and before running any step. If it returns problems, either remove the affected steps from completed so they run again, or stop and report. Which one you pick depends on item 2. Redoing is only safe for repeatable steps.
7. Handoffs
- Can a reader with no prior context act on the note alone?
- Does it separate finished work from unverified work?
- Does it name steps that must not be repeated?
- Does it give one next action?
- Does it say where the full state lives?
- Does it give a time, so the reader knows how old it is?
Write the note at the end of every session, not only when you expect a handoff. Interruptions are rarely announced. Then test it: give the note to someone, or to a fresh agent, and watch where they hesitate. Each hesitation is a missing sentence.
8. Concurrent writers
- Can two runs of this task ever overlap, for example a retry that starts while the first run is still alive?
- Is there a lock that one run must hold before it writes?
- Is a stale lock detectable, using an owner, a process ID, and a timestamp?
- Do you check whether you still hold the lock before each checkpoint write?
An atomic write protects a file from a crash, but it does not protect it from a second writer. Two runs can each write a valid checkpoint, and the later one silently discards the earlier one's progress. A lock file created with an exclusive flag is the simplest fix.
import json
import os
import time
def acquire_lock(lock_path, owner):
try:
fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
return False
with os.fdopen(fd, "w") as f:
json.dump({"owner": owner, "pid": os.getpid(), "time": time.time()}, f)
return True
def release_lock(lock_path):
try:
os.unlink(lock_path)
except FileNotFoundError:
passO_EXCL makes creation fail if the file exists, so only one caller wins. If a run crashes, the lock file stays behind. Whoever finds it must decide whether the owner is still alive, using the stored PID and time, before removing it by hand.
Mapping failure modes to checklist items
When something goes wrong in production, this table points you to the item that should have prevented it.
| Symptom | Likely cause | Checklist item |
|---|---|---|
| Duplicate uploads after a restart | Crash between side effect and checkpoint | 2 |
| Task restarts from the beginning | Corrupt checkpoint treated as empty | 4 |
| Run skips a step whose output is gone | Saved state trusted without checking | 6 |
| New agent repeats finished work | Handoff lacks "do not repeat" | 7 |
| Progress disappears after a retry | Two writers, no lock | 8 |
| Next person does not know what to do | Vague next action | 5 |
Putting it into practice
You do not need every item at full strength for every task. A ten-minute script that you can rerun from scratch needs little more than items 1 and 2. A multi-day job that moves money needs all of them, plus tests. Scale the effort to the cost of a mistake.
Exercise
A task uploads a report and then saves a checkpoint. The process is killed after the upload finishes but before the checkpoint is written. On restart, the report is uploaded a second time. Which checklist items did the design fail, and what is one fix for each?
Show answer
It failed item 2, because the upload is not safe to repeat, and item 6, because the resume logic did not check whether the upload already happened. Fix item 2 by giving the upload a deterministic name or an idempotency key, so a second upload replaces or is ignored in place of creating a duplicate. Fix item 6 by checking the destination for an existing report before uploading, and recording what was found in the progress file.
Exercise
Your resume routine loads a checkpoint, and the file contains invalid JSON because someone edited it by hand. The loader catches the error and returns an empty state. Why does this break the checklist, and what should happen instead?
Show answer
It breaks item 4. An empty state makes the task start over and repeat steps that already had side effects. The loader should let the error stop the run and report which file is unreadable. A person can then repair or restore the file, and the run can continue with its real history.
Exercise
Two copies of a job start at the same time because a scheduler retried a slow run. Both write valid checkpoints with atomic replaces. Why can progress still be lost, and which mechanism prevents it?
Show answer
Atomic replace only guarantees that each file is complete, not that one writer does not overwrite the other. The slower writer can replace a newer checkpoint with an older view of the state. A lock file created with an exclusive flag, held for the whole run and checked before each write, ensures that only one run writes at a time.