Skip to content

Module 05 · Lesson 5.5

Managing Long-Running Tasks and Checkpoints

40 minUpdated 18 Nov 2026Part of Planning and Agent Execution Patterns · AI Agent Development
On this page
  1. What you will learn
  2. Why long-running agent tasks fail half-way
  3. What is a checkpoint, and what should it save?
  4. How to resume a task from a checkpoint
  5. Set budgets and a clear status for long tasks
  6. Why a write step needs fresh approval after a resume
  7. Save and resume a task with a checkpoint in Python
  8. Conclusion and your next step
  9. Common errors and fixes
  10. Validation checklist
  11. Hands-on exercise
  12. Knowledge check
  13. Frequently asked questions
  14. References

Imagine you are moving house and the van breaks down halfway. If you kept a tick-list on the fridge with a tick next to every box already delivered, you can carry on from box 12. If you kept nothing in writing, you start again and you may carry some boxes twice.

A long-running AI agent faces the same risk. It may take many steps, and something can stop it at any moment. This lesson shows how to save progress in a checkpoint, how to resume from it, and how to limit how long a task may run. Most of it needs no coding. One short Python example at the end crashes on purpose and then finishes the job.

What you will learn

  • Explain why long tasks stop half-way and what a checkpoint is.
  • Decide what a checkpoint should contain and what it must never contain.
  • Resume a task by loading a checkpoint and skipping the finished steps.
  • Set step and time budgets, and require a fresh approval for any write after a resume.

Before you start

Why long-running agent tasks fail half-way

A one-question chat is over in seconds. A research task may read many documents, wait for a person and take minutes or hours. The longer a task runs, the more chances there are for something to go wrong.

  • Timeouts. A tool or a service takes too long to answer, so the call gives up.
  • Crashes. The program hits a bug, or the computer restarts.
  • Rate limits. A service says "too many requests, wait", and the task has to pause.
  • People. The approver closes the laptop, and the agent is left waiting.

Without saved progress, every stop means starting from step 1. That wastes time and money. Worse, it can repeat steps that already had an effect. Tool Errors, Retries, Timeouts and Idempotency covered what to do when one tool call fails. This lesson covers a whole task that stops.

What is a checkpoint, and what should it save?

A checkpoint is saved progress: a small file or record that says what the task is, what the plan is and which steps are already finished. It is the tick-list on the fridge. After a stop, the agent reads the list and carries on.

Checkpoint
A saved copy of a task's progress, written after each finished step.
Resume
Starting a stopped task again from its checkpoint, skipping the steps that are already done.
Budget
A limit on how much a task may use, such as the number of steps or the total time.
Status
A short, clear word that tells a person where the task is, such as running, waiting, stopped or complete.

What to save

  • The goal. The question the task is trying to answer.
  • The plan. The list of steps, so the same plan continues after a restart.
  • Each finished step's result. So the agent does not read or fetch it again.
  • The status. Which steps are done and where the task stands.

In this module's research scenario, a checkpoint is one file called checkpoint.json. It holds the goal, the plan and a done section with one entry per finished step. The key is the step number, written as text, because JSON object keys are always text.

JSONcheckpoint.json
{
  "goal": "Which battery should Quillfeather Cycles stock next season?",
  "plan": {"goal": "...", "steps": ["...four steps..."]},
  "done": {
    "1": "Alpha: 500 Wh, price 420",
    "2": "Beta: 420 Wh, price 360"
  }
}

A checkpoint after two finished steps. The plan is shortened here.

What never to save

  • Secrets. Never write an API key or a password into a checkpoint. Files get copied, shared and left on disks.
  • Personal data you do not need. Save only what the task needs to resume. A customer's address does not belong in a research checkpoint.

How to resume a task from a checkpoint

Resuming is simple, and that is why checkpoints are worth the effort. The agent loads the file and goes through the plan from the top. If a step's number is already in done, it skips that step. Otherwise it runs the step and saves again.

Run, crash, resume
  1. Load checkpoint

    If none exists, start fresh

  2. Next step done?

    Yes: skip it. No: run it.

  3. Run the step

    Safe to repeat, if needed

  4. Save checkpoint

    Write the result and the step number

  5. All steps done

    Finish, then delete the checkpoint

The checkpoint is written after every step, so a stop loses at most one step of work.

Make steps safe to repeat

There is one awkward moment. A step can finish, and then the program crashes before the checkpoint is written. On resume, the agent does not know the step is done, so it runs it again. This is why steps should be safe to repeat: running the step twice gives the same result as running it once. That property is called idempotency, covered in the Module 3 lesson linked above.

Reading a document is naturally safe to repeat. A write needs more care, such as an idempotency key like the one in the Module 3 lab. With a key, a repeated request is spotted and not saved twice.

Set budgets and a clear status for long tasks

A task that never ends is as bad as a task that crashes. A model can loop, a service can be slow, or a plan can grow. Set two limits for the whole task, not only for one step.

  • A maximum number of steps. You met this idea as MAX_ROUNDS in the Module 3 lab. The plan rules in this module also allow at most 8 steps.
  • A maximum total time. For example, 10 minutes for the whole task. When time is up, the task stops cleanly.

When a budget runs out, do not just disappear. Save the checkpoint, set a clear status and tell the person. They can then decide to resume, raise the limit or stop.

StatusWhat it tells a personWhat happens next
runningThe agent is working through the steps.Nothing needed.
waiting for approvalA write step is ready and needs a yes.A person decides.
stopped: step limitThe step budget ran out.Resume with a higher limit, or end the task.
stopped: time limitThe time budget ran out.Resume, or end the task.
failedA step failed and could not be repeated safely.A person looks at the error.
completeAll steps are done.Delete the checkpoint.
A status is a word a person can read in one second. Avoid vague words such as "processing".

Why a write step needs fresh approval after a resume

Suppose the task asked a person to approve save_report, and then crashed. When it resumes an hour later, can it use the old yes? No. An old approval does not carry over.

Think of a signature on a cheque. It was meant for one payment at one moment. If the facts change, or the cheque is found a day later, you do not treat it as permission to pay again. The same applies here. The evidence may have changed, a different person may now be in charge, and the person may no longer agree.

  • Do not store "approved" in the checkpoint as a standing permission.
  • When a write step comes up after a resume, build a new approval request and ask again, as in Human-in-the-Loop Approval and Escalation.
  • Record the new decision in the audit list. The old one stays as history.

This keeps the approval gate in code, where it belongs. The checkpoint remembers the work. It does not remember anyone's permission.

Save and resume a task with a checkpoint in Python

The script below runs a three-step plan: read RS-01, RS-02 and RS-04. It saves checkpoint.json after every step. On the first run it crashes on purpose when step 3 starts. On the second run it loads the checkpoint, skips the finished steps, completes and prints a short summary. The script uses no AI model and the standard library only.

The summary at the end is plain Python, not a plan step, so the plan follows this module's plan rules exactly. The script leaves out save_report on purpose, because a write needs approval.

Pythoncheckpoint_demo.py
import json
from pathlib import Path

FILE = Path(__file__).parent / "checkpoint.json"  # saved next to this script
DOCS = {"RS-01": "Alpha: 500 Wh, price 420", "RS-02": "Beta: 420 Wh, price 360",
        "RS-04": "Returns: Beta 6%, Alpha 2%"}
PLAN = {"goal": "Which battery should Quillfeather Cycles stock next season?", "steps": [
    {"id": 1, "tool": "read_doc", "args": {"doc_id": "RS-01"}, "after": []},
    {"id": 2, "tool": "read_doc", "args": {"doc_id": "RS-02"}, "after": []},
    {"id": 3, "tool": "read_doc", "args": {"doc_id": "RS-04"}, "after": []},
]}


def do_step(step):
    return DOCS[step["args"]["doc_id"]]  # every step in this plan is a read_doc


def run(crash_at=None):
    if FILE.exists():
        state = json.loads(FILE.read_text())  # resume: load saved progress
    else:
        state = {"goal": PLAN["goal"], "plan": PLAN, "done": {}}
    for step in state["plan"]["steps"]:
        key = str(step["id"])  # JSON object keys are strings
        if key in state["done"]:
            print("skip step", key, "(already done)")
            continue
        if step["id"] == crash_at:
            raise RuntimeError(f"simulated crash at step {crash_at}")
        state["done"][key] = do_step(step)
        FILE.write_text(json.dumps(state, indent=2))  # save after every step
        print("finished step", key, "->", state["done"][key])
    print("summary:", " | ".join(state["done"][key] for key in sorted(state["done"])))
    FILE.unlink()  # success: remove the checkpoint so the demo can repeat
    print("Run complete. Checkpoint deleted.")


try:
    run(crash_at=3)
except RuntimeError as error:
    print("Run stopped:", error)
print("Saved steps:", list(json.loads(FILE.read_text())["done"]))
print("--- second run ---")
run()

Runs offline with any Python 3.10 or later. It writes checkpoint.json in its own folder and deletes it at the end.

What each part does

  • FILE = Path(__file__).parent / "checkpoint.json" points to a file in the same folder as the script. pathlib is Python's built-in tool for file paths.
  • DOCS holds three short fake documents, and PLAN is the plan in this module's format: a goal and a list of steps, each with id, tool, args and after.
  • do_step runs one read_doc step and returns the document text.
  • In run, FILE.exists() decides between resume (load the saved state) and a fresh start with an empty done.
  • key = str(step["id"]) turns the number into text, because JSON saves object keys as text.
  • if key in state["done"] is the skip. A finished step is never run again.
  • raise RuntimeError(...) simulates a crash when step 3 starts on the first run.
  • FILE.write_text(json.dumps(...)) saves the checkpoint after every step.
  • After the loop, the summary line joins every saved result. It runs only once all steps are done, whether they were done on this run or an earlier one.
  • FILE.unlink() deletes the checkpoint after a successful run, so you can run the demo again from the start.
  • try and except catch the fake crash and print that the run stopped. The last lines run again and resume.
OutputCaptured from a real run
finished step 1 -> Alpha: 500 Wh, price 420
finished step 2 -> Beta: 420 Wh, price 360
Run stopped: simulated crash at step 3
Saved steps: ['1', '2']
--- second run ---
skip step 1 (already done)
skip step 2 (already done)
finished step 3 -> Returns: Beta 6%, Alpha 2%
summary: Alpha: 500 Wh, price 420 | Beta: 420 Wh, price 360 | Returns: Beta 6%, Alpha 2%
Run complete. Checkpoint deleted.

The second run did not read RS-01 or RS-02 again. It picked up at step 3, exactly where the first run stopped.

Conclusion and your next step

Long tasks stop for ordinary reasons, so plan for it. Save the goal, the plan and each finished result after every step. Resume by skipping what is done. Make steps safe to repeat, set step and time budgets, and show a clear status. Never save secrets, and ask for a fresh approval before any write after a resume.

Your next step: take the plan from the previous lessons and decide where the checkpoint would be written, what it holds and which status words you would show. Then build it in Practical Lab: Build a Multi-Step Research Agent, where you combine planning, parallel reads, approval and checkpoints in one agent.

For more on keeping data tidy, revisit Conversation State vs. Persistent Memory. Before you launch any agent, run through the Agent Launch Safety Checklist.

Common errors and how to fix them

After a resume, finished steps run again.

Why it happens: The step numbers were saved as numbers but compared with text keys, or the checkpoint was never loaded.

Fix: JSON object keys are text. Convert the id with str(...) when saving and when checking, and load the file before the loop.

A write happened twice after a crash.

Why it happens: The step finished, the crash came before the checkpoint was saved, and the step was not safe to repeat.

Fix: Make writes idempotent with a key, so a repeat is spotted, and keep the approval gate in code.

A resumed task saved a report without asking anyone.

Why it happens: The checkpoint stored an old approval as a standing yes.

Fix: Never store approval in the checkpoint. Ask again for every write after a resume.

The checkpoint file contains an API key or customer details.

Why it happens: The whole program state was dumped to disk.

Fix: Save only the goal, the plan and the step results. Keep secrets in environment variables, and keep the file out of git.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Add a step budget and a status to the checkpoint demo

Extend checkpoint_demo.py. Add a MAX_STEPS = 2 budget for one run. When the budget is reached, stop cleanly with the status "stopped: step limit", keep the checkpoint, and let a second run finish the task.

You will need

  • Your working copy of checkpoint_demo.py from this lesson.
  • Remove the simulated crash: call run() with no crash_at.
  • The status words from the table in this lesson.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Keep a counter that starts at 0 in each call to run, and add 1 after each step that actually runs.
  • Check the counter before running the next step, so a third step does not start.
  • Return from run early, before FILE.unlink(), when the budget is reached.
Show a model answer

A strong answer adds ran = 0 at the top of run. Inside the loop, after the skip check, it adds if ran == MAX_STEPS: print("stopped: step limit"); return, and after each completed step it adds ran += 1. The early return happens before FILE.unlink(), so the checkpoint stays on disk. The second call to run() loads it, skips steps 1 and 2, runs step 3 as the only new step (so ran is 1, below the limit), prints the summary, and then reaches FILE.unlink() and says the run is complete. Counting only steps that really run matters. If skipped steps counted, a resumed task could hit its budget before doing any new work.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.A task finished steps 1 and 2, then crashed. What should the resumed run do?
    Show the answer and explanation

    Answer: B. The checkpoint is the record of what is done, so the run skips those steps. Starting again feels safe, but it wastes time and may repeat steps that had effects. A model's memory is not a reliable record.

  2. 2.A task asked for approval to save a report, then crashed. After the resume, what happens at the save step?
    Show the answer and explanation

    Answer: B. Approval belongs to one moment and one set of facts, so it does not carry over. Reusing the old yes is tempting because it saves the person's time, but things may have changed.

  3. 3.Which of these should never be saved in a checkpoint?
    Show the answer and explanation

    Answer: C. Secrets must not be written into files that can be copied or shared. The goal, the plan and the results are what a resume needs. A key is tempting to save if the program needs it later, but it should come from a safe place such as an environment variable.

Frequently asked questions

What is a checkpoint in an AI agent?

A checkpoint is saved progress. It is a small file or record with the goal, the plan and the result of every finished step. If the task stops, the agent can load it and continue, instead of starting again.

How do I resume an AI agent task after a crash?

Load the saved checkpoint, then go through the plan again. Skip every step already marked as done and run the rest. Make the steps safe to repeat, in case one finished but was not saved before the crash.

How long should an AI agent be allowed to run?

Set a limit for the whole task, such as a maximum number of steps and a maximum total time. The right numbers depend on your task. When a limit is reached, the agent should stop, save its progress and show a clear status.

Can an agent keep using an old approval after it resumes?

No. An approval is for one moment and one request. After a resume, ask again before any write step, and record the new decision. Never store approval in the checkpoint as a standing permission.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.