Sub topic 3
Breaking Work into Resumable Steps
This chapter covers how to split a large task into steps that a restarted agent can skip, repeat, or continue from. It assumes you can read Python, JSON, and Markdown. It also assumes you know how an LLM agent calls tools in a loop, and that you have a basic picture of files and processes. Later chapters cover making steps safe to repeat, writing checkpoints, and resuming.
Why decomposition comes first
A long task fails somewhere in the middle. The process crashes, the context window fills, a network call times out, or a person closes the terminal. If the task is one large action, a failure means starting over. If the task is a list of small steps, a failure costs at most the step that was running.
Decomposition is the design decision that makes every later technique possible. A checkpoint records which steps are finished. A progress file describes the plan and what comes next. A resume routine skips completed work. None of these can work unless the task has named steps with clear boundaries.
What makes a step resumable
A step is resumable when a restarted run can answer three questions about it without guessing:
- Did this step finish?
- If it did, where is its output?
- If it did not, is it safe to run again from the start?
These questions lead to four properties.
- A name or identifier. The checkpoint needs a stable key to record.
"transform"works. "Step 3" breaks as soon as someone inserts a step before it. - A clear completion signal. The step either finished or it did not. "Mostly done" cannot be recorded.
- Declared inputs and outputs. The step reads known inputs and produces known outputs. A later step can then check that those outputs exist.
- Safe repetition. If a crash happens during the step, rerunning it must not corrupt anything. The next chapter treats this property in detail.
Choosing step size
Step size is a trade-off between two costs.
| Step size | Cost of a failure | Cost of bookkeeping |
|---|---|---|
| Very large (the whole job) | You lose all the work | Almost none |
| Medium (a stage such as "transform") | You lose one stage | Low |
| Very small (one record or one line) | You lose almost nothing | High: one checkpoint write per item |
A useful rule is to size a step by the work you are willing to lose and redo. If redoing ten minutes of work is acceptable, a step can take up to ten minutes. If a step calls a paid API or sends messages, make it smaller, because redoing it has a real cost.
Three other signals suggest where to cut:
- Natural boundaries. A step ends where its output becomes a durable artifact, such as a file written, a row committed, or a pull request opened.
- Side effects. Put each externally visible action, like sending an email or publishing a page, in its own step. Then a checkpoint can say exactly whether it happened.
- Context limits. For an LLM agent, a step should fit comfortably in one context window. If a step needs more than the agent can hold, split it, because a step that overflows the context cannot be resumed cleanly.
Two shapes of work: pipelines and batches
Most long tasks fall into one of two shapes, and the shape determines how you track progress.
A pipeline is a fixed sequence of different stages. Each stage depends on the one before it. The example later in this chapter is a pipeline of fetch, transform, validate, and publish. Progress is a list of completed stage names.
A batch applies the same operation to many items, such as converting 500 documents. Items are usually independent. Progress is a set of completed item identifiers, and a restart processes only the items not in the set.
Real tasks often combine both. A pipeline stage may itself be a batch, such as a "convert" stage that handles 500 files. In that case track progress at two levels: the stage, and the items inside it. A restart then skips finished stages, and inside an unfinished stage it skips finished items.
Dependencies between steps
Steps depend on each other in one of two ways, and you should write the dependency down.
- Data dependency. Step B reads a file that step A wrote. If A is marked complete but its output is missing, B will fail. The resume routine should check for the output, not only the checkpoint entry. Chapter 9 covers this check.
- Ordering dependency. Step B must happen after step A even though B reads nothing from A. For example, you must validate before you publish.
Independent steps can run in any order, and sometimes in parallel. But parallel steps bring concurrent writers, which need locking, covered in a later chapter. Until you need the speed, keep steps sequential. A sequential list is easier to checkpoint, easier to read, and easier to debug.
A worked example
Consider a job that fetches data, transforms it, validates it, and publishes it. Here is a first attempt written as one function.
def run_job():
data = fetch()
result = transform(data)
validate(result)
publish(result)If publish fails, the next run fetches and transforms everything again. If the process dies after a partial publish, nothing records how far it got. The function has no named steps and no durable record of progress.
Now split it into steps that read from and write to files. Each step takes a working directory, reads what it needs, and writes its output there.
import json
import os
WORKDIR = "work"
STEPS = ["fetch", "transform", "validate", "publish"]
def step_fetch(state):
os.makedirs(WORKDIR, exist_ok=True)
data = {"rows": [1, 2, 3, 4, 5]}
with open(os.path.join(WORKDIR, "raw.json"), "w") as f:
json.dump(data, f)
state["notes"].append("fetched 5 rows")
def step_transform(state):
with open(os.path.join(WORKDIR, "raw.json")) as f:
data = json.load(f)
out = {"rows": [n * 10 for n in data["rows"]]}
with open(os.path.join(WORKDIR, "clean.json"), "w") as f:
json.dump(out, f)
state["notes"].append("transformed rows")
def step_validate(state):
with open(os.path.join(WORKDIR, "clean.json")) as f:
out = json.load(f)
if not out["rows"]:
raise ValueError("no rows to publish")
state["notes"].append("validated")
def step_publish(state):
with open(os.path.join(WORKDIR, "clean.json")) as f:
out = json.load(f)
with open(os.path.join(WORKDIR, "published.json"), "w") as f:
json.dump(out, f)
state["notes"].append("published")
STEP_FUNCTIONS = {
"fetch": step_fetch,
"transform": step_transform,
"validate": step_validate,
"publish": step_publish,
}Each step now has a name, a defined input, and a defined output. The files in work/ act as the hand-off points between steps. A crash in validate leaves raw.json and clean.json on disk, so a restart does not need to redo the earlier work.
The state dictionary carries small facts between steps and into the checkpoint. Keep it small. Large data belongs in files, and the state should only point to them.
Driving the steps with a loop
With named steps, a simple loop can run them in order and record progress. This loop uses the checkpoint helpers save_checkpoint and load_checkpoint, which the next chapters build in full. Here is the driver.
def run(checkpoint_path, step_functions):
state = load_checkpoint(checkpoint_path) or {"completed": [], "notes": []}
for name in STEPS:
if name in state["completed"]:
continue
step_functions[name](state)
state["completed"].append(name)
save_checkpoint(checkpoint_path, state)
return stateThe loop has one rule: record a step as completed only after it returns. If the process dies inside a step, that step is not in completed, so the next run starts it again. This is why the step must be safe to repeat. The gap between "step finished" and "checkpoint saved" is small but real. If the process dies in that gap, the step ran but is not recorded, and it will run a second time.
Common mistakes in decomposition
- Steps that are too coupled. If step B only works with an in-memory object left by step A, a restart cannot resume at B. Pass data through files or other durable storage.
- Positional identifiers. Recording "completed up to step 3" breaks when the plan changes. Record names instead.
- Hidden side effects. A step that quietly sends a notification as well as transforming data cannot be repeated safely. Split the notification into its own step.
- One giant "do everything" step for an agent. An instruction such as "refactor the whole codebase" gives no boundary to checkpoint. Break it into one directory, one module, or one concern at a time.
- No definition of done. If a step has no testable end condition, you cannot tell on restart whether it finished. Write the condition down, such as "
clean.jsonexists and has at least one row."
Decomposition for LLM agents
An agent adds one complication. The planner is often the model itself, and its plan lives in the context window, which is exactly the memory you cannot rely on. So write the step list to a file at the start, in a form the agent and a person can both read. The next chapters show how a progress file holds that plan. For now the key point is that the plan must be fixed and durable before the work starts. If the agent regenerates the plan after each restart, the step names may drift, and the checkpoint entries will no longer match.
Exercise
A job converts 200 images and then uploads a zip of the results. Propose a decomposition that tracks progress at two levels, and say which step should be checked most carefully for repeat safety and why.
Show answer
Use two stages: "convert" and "upload". Treat "convert" as a batch whose progress is the set of image identifiers already converted, so a restart converts only the missing ones. Treat "upload" as a single step that runs only after every image is converted. The upload step needs the most care, because it has an external side effect. If the process crashes after the upload but before the checkpoint is saved, a restart uploads again, so the step must be safe to repeat, for example by overwriting the same file name instead of creating a new one.
Exercise
A checkpoint records "completed: 2" meaning two steps are done. Later, someone inserts a new step at the start of the plan. What goes wrong, and how do you prevent it?
Show answer
The number 2 now points at a different step, so the restarted run skips the wrong work or repeats finished work. Prevent it by recording step names, such as "fetch" and "transform", in the completed list instead of positions or counts. Names stay valid when the plan changes.