Sub topic 1
Why Long-Running Tasks Break
A long-running agent task is work that takes more time, more steps, or more tokens than one uninterrupted run can hold. Examples include migrating hundreds of documents, exporting months of records, or refactoring a large codebase. This chapter explains why such tasks fail and what has to be saved so that a failure costs minutes instead of the whole job. Later chapters cover the techniques in detail: decomposition, checkpoints, progress files, resuming, and handoffs.
Prerequisites
This chapter assumes you have:
- Basic Python or comparable scripting experience.
- Familiarity with how an LLM-based agent calls tools in a loop: the model proposes an action, a tool runs it, and the result goes back into the model's context.
- Comfort reading JSON and Markdown files.
- A basic understanding of files and processes. You should know that a process has its own memory and that this memory disappears when the process exits.
The core problem: the task outlives its container
A short task fits inside one run. The agent starts, works, and finishes, and everything it knows sits in memory the whole time. A long task does not fit. It has to survive at least one of these boundaries:
- A context window. The model can only read a limited amount of text at once. When the conversation grows past that limit, older content is truncated or summarized, and details are lost.
- A process. The program running the agent can crash, be killed, run out of memory, or be restarted by a deploy. Everything held in variables is gone.
- A session. A user closes a terminal, a job hits a time limit, or a scheduler stops the run. The next run starts with no memory of the previous one.
- An actor. A different agent or a person takes over, and they were not present for earlier decisions.
If the only place the task's state lives is inside one of these containers, then the state dies when the container does. The fix is the same in every case. State that matters must live outside the agent, in a place that outlasts the run.
Common ways long tasks fail
Most failures fall into a small number of patterns. Learning to name them helps you design against them.
Context loss
As an agent works, its context fills with tool output, intermediate reasoning, and earlier instructions. When the window fills, something has to go. The agent may then forget a constraint stated at the start, such as "keep the old URLs", and quietly violate it. It may also forget which items it already handled and redo them.
The failure is hard to notice because the agent keeps working fluently. Nothing raises an error. The output simply drifts away from the original intent.
Process interruption
A process can stop at any line. A network call times out and the exception is not handled. The machine reboots. A container is evicted. If the program kept its progress in a Python list or a counter variable, that progress disappears.
The important detail is that the interruption can land between two actions that belong together. Consider this sequence:
- Upload a file to storage.
- Record in a database that the upload happened.
If the process dies between step 1 and step 2, the world now contains an upload that nothing remembers. Restarting from "nothing recorded" uploads it again.
Duplicated side effects
A side effect is a change to something outside the program: sending an email, charging a card, uploading a file, writing a row. Side effects are the dangerous part of restarting. Re-running a pure calculation is harmless. Re-running "send the invoice" sends it twice.
Naive recovery, which means "start over from the top", turns an interruption into duplicated work or duplicated damage. This is why a later chapter treats making steps safe to repeat as its own topic.
Stale or corrupt state
Saving state is not enough. The saved copy can be wrong in two ways:
- Corrupt. The program crashed while writing the state file, leaving half a JSON document. The next run cannot parse it, or worse, parses a truncated version.
- Stale. The file is valid but no longer matches reality. The checkpoint says the export is finished, but someone deleted the output directory. The checkpoint says a branch exists, but it was force-pushed away.
Corruption is solved by writing atomically. Staleness is solved by checking saved state against the real world before trusting it. Both get their own chapters.
Lost intent at handoffs
When another agent or person takes over, they see the files and the current state of the world. They do not see why things were done that way. Without a record of decisions, the new actor may undo a deliberate choice or repeat a step that was supposed to run only once.
Silent drift and false completion
A long task has many chances to go slightly wrong. An agent may report "done" after finishing 18 of 42 items because its picture of the task has blurred. Without an explicit record of what "done" means and how much is done, nobody can tell.
| Failure | What causes it | What it looks like | Typical defense |
|---|---|---|---|
| Context loss | Window fills, early details dropped | Constraints forgotten, work redone | Progress file re-read at the start of each session |
| Process interruption | Crash, kill, timeout | Run ends mid-task with no record | Checkpoints after each step |
| Duplicated side effects | Restart repeats completed actions | Duplicate emails, files, charges | Idempotent steps, recorded completions |
| Corrupt state | Crash during a write | Unparseable or truncated state file | Atomic writes |
| Stale state | Reality changed after the save | Resume skips work that is not actually done | Verify before trusting |
| Lost intent | New actor lacks history | Decisions reversed, steps repeated | Decisions log and handoff note |
What has to survive
Not everything needs saving. Saving too much creates a large state file that nobody reads and that goes stale quickly. A useful way to choose is to ask what a stranger would need in order to continue. Five kinds of information usually qualify.
- The goal. What the finished task looks like, stated so that completion can be checked.
- The plan and status. The list of steps and which are done, in progress, or not started.
- Decisions and reasons. Choices made along the way and why, so they are not reversed by accident.
- The next action. One concrete thing to do first when work resumes.
- Open problems. Questions that are unresolved or results that are unverified.
There is also information that should not be treated as state. Raw tool output, long reasoning traces, and anything that can be cheaply recomputed from the real world are poor candidates. If a value can be looked up again reliably, store a pointer to where to look rather than a copy.
Machine-readable state and human-readable state serve different readers. A JSON checkpoint is easy for a script to load and compare. A Markdown progress file is easy for a person, or for a fresh model reading with an empty context, to understand. Most robust designs keep both, with clearly separate jobs.
A first look at the fix
You do not need the full design yet. The smallest useful version has three parts: break the work into steps, record each completed step, and skip recorded steps on restart. This sketch shows the shape.
import json
import os
STEPS = ["fetch", "transform", "validate", "publish"]
def load_done(path):
try:
with open(path) as f:
return json.load(f)["completed"]
except FileNotFoundError:
return []
def record_done(path, completed):
with open(path, "w") as f:
json.dump({"completed": completed}, f)
def run(path, actions):
completed = load_done(path)
for name in STEPS:
if name in completed:
print(f"skip {name}")
continue
actions[name]()
completed.append(name)
record_done(path, completed)
print(f"done {name}")
if __name__ == "__main__":
calls = {name: (lambda n=name: print(f"running {n}")) for name in STEPS}
run("checkpoint.json", calls)Run it once and all four steps execute. Run it again and every step is skipped. If you stop it halfway, the next run continues from the first unfinished step.
This sketch is deliberately weak. record_done writes directly to the file, so a crash during the write can leave a corrupt checkpoint. A crash between actions[name]() and record_done repeats a step that already ran. The sketch also trusts the file without checking it against reality. Each weakness corresponds to a failure in the table above, and each is fixed in a later chapter.
Where interruptions land
Interruptions are not evenly spread. They are most damaging at the moments when the program is changing something external. The timeline of a single step shows three places where a crash can occur.
The gap between "side effect succeeded" and "checkpoint saved" cannot be removed. It can only be made safe. You make it safe by designing the step so that running it a second time causes no harm. That property is called idempotence, and it is the reason decomposition and checkpoints work together instead of separately.
Why more memory is not the answer
A common first reaction is to give the agent a bigger context window or more RAM. This helps with some failures, but not the ones that matter most.
- A larger window delays context loss. It does not remove it, and it does nothing for a crash or a handoff.
- A larger window does not survive a process exit.
- Long contexts can degrade attention to details placed far back, so a fact being present in the window does not guarantee it is used.
- Memory cannot be shared with the next actor.
External, explicit, small state is more reliable than large implicit state. A short file that says "next action: convert shortcodes starting at setup.md" is worth more than a hundred thousand tokens of history that nobody can summarize.
Designing with failure in mind
The mindset for the rest of this tutorial is to assume the task will be interrupted, and decide in advance what happens when it is. Ask these questions about any long task:
- If the process died right now, what would be lost?
- If it died between any two lines, could a step run twice with harm?
- If a stranger opened the working directory tomorrow, could they tell what to do next?
- If the saved state were wrong, how would we find out?
The answers define the work for the remaining chapters. Decomposition gives you units to record. Idempotent steps make repeats safe. Checkpoints and atomic writes keep the record trustworthy. Progress files carry intent. A resume protocol, verification, and handoff notes put it all to use.
Exercise
An agent exports 12 monthly reports and uploads each one. It keeps a list of finished months only in a Python variable. The process is killed after uploading month 7 but before the variable would have been saved anywhere. Name two things that can go wrong on the restart, and say which failure pattern each belongs to.
Show answer
First, the restart has no record of progress, so it begins at month 1 and repeats the uploads for months 1 to 7. This is a duplicated side effect caused by process interruption. Second, if the agent relied on its conversation to remember what was done, that history may be gone or truncated too, so it cannot tell which months were handled. This is context loss. The shared fix is to store completed months in a file outside the process.
Exercise
A checkpoint file says the "publish" step is complete. On resume, the agent skips publishing. Later you find the published site is missing. Is this a corrupt-state or a stale-state failure, and what should the resume routine have done?
Show answer
It is a stale-state failure. The file was valid and accurately recorded what happened at the time, but the real world changed afterward (the published output was removed). The resume routine should have verified the saved claim against reality, for example by checking that the published site exists, before skipping the step.
Exercise
List the five kinds of information a stranger needs in order to continue a task, and say which of them a Markdown progress file is better suited to hold than a JSON checkpoint.
Show answer
The goal, the plan and status, decisions and reasons, the next action, and open problems. A Markdown progress file suits the goal, decisions and reasons, the next action, and open problems best, because they are written for a human or a fresh model to read. A JSON checkpoint suits the machine-readable status, such as the list of completed steps.