08C.3 Checkpoint, Resume and Durable Execution (without LangGraph)

Agents & multimodalLesson 3 of 37,613 words8 parts
Module 08C · 0 of 3 lessons done
  1. 1
  2. 2
  3. 3

An agent that runs for ten minutes will be killed at minute nine. A deploy restarts the server, a spot instance disappears, a provider times out, or a person takes three days to approve a step. If the only copy of the agent's progress is in memory, that progress is gone and the agent starts again, possibly repeating a refund. This lesson teaches how to make a run survive: what to save (a checkpoint), how to save it safely, how to continue (resume), why continuing must not repeat side effects, and how the idea scales up into durable execution engines such as Temporal and AWS Step Functions. You build the idea in plain Python first, with real output, then see how the two engines do it.

It follows 08C.1 (the plan as data) and 08C.2 (recovery and constraints). The LangGraph version of durable execution is already taught in 08F.11, Part 4. Here it is one implementation among several. The related topic of agents that run in the background for a long time is 08A.13.

What you'll learn

  • What a checkpoint contains, and what must stay out of it
  • Atomic writes: why a crash while saving must never corrupt the previous checkpoint
  • Idempotent resume: continuing without repeating side effects, using idempotency keys
  • Replay vs resume: restoring a saved snapshot versus re-running code against a recorded history
  • Workflow-as-code durable execution: workflows, activities, event history, determinism, timers, signals, retries
  • How Temporal and AWS Step Functions do it, checked against their official documentation on 1 December 2026
  • When to use plain files, LangGraph, Temporal or Step Functions
  • What to measure when you evaluate resumable agents

What you don't need

  • API keys. Both runnable samples use plain Python, the standard library only (a JSON file and an embedded SQLite file in a temporary folder), and fake tools.
  • Docker, a Temporal server, an AWS account, or any service. The Temporal and Step Functions snippets are illustrative and were not run.
  • LangGraph. See 08F.11 if you use it.

Setup

As of 1 December 2026. Python 3.11 or newer. The runnable code uses only the standard library (json, os, tempfile, sqlite3), so there is nothing to install. To try the engines for real you would install temporalio (Temporal's Python SDK) or use the AWS console or CLI, which this lesson does not require.

Each code block starts with a comment giving its file name. Save the files and run with python <file>. The running example is the support assistant: load an order, refund it, email the customer.


What you must be able to do after this lesson#

  • List what a checkpoint must contain and what must stay out of it
  • Write a checkpoint atomically (temporary file, fsync, os.replace) so a crash never destroys the last good one
  • Resume a run without repeating side effects by deriving idempotency keys from the run and the step
  • Explain the difference between resuming from a snapshot and replaying code against a recorded history
  • Describe how Temporal and AWS Step Functions keep progress after a crash, and when to pick each over plain files
  • Test resume by killing a run at chosen points and counting side effects

Why this matters for an AI engineer#

Anything that talks to a model for minutes, waits for a human, or does money-moving work needs to survive restarts. The cost of getting it wrong is concrete: lost work, duplicate refunds, duplicate emails, and runs that can never be explained afterwards. The ideas here are older than LLMs (workflow engines, write-ahead logs, idempotency keys) and they transfer directly.

You'll hear... You'll understand it after...
"Checkpoint after every step." Part 2: Checkpoints in plain Python
"Write to a temp file and rename." 2.2 Atomic writes
"Resume must be idempotent." 2.3 Idempotent resume
"Replay, not restore." Part 3: Replay versus resume
"Workflows must be deterministic." 3.3 Determinism
"Why not just use Temporal?" Part 5: How Temporal does it
"Step Functions can wait for a human for a year." Part 6: How AWS Step Functions does it
"Does checkpointing in the eval lesson mean this?" The terminology note above

Part 1: What to save and why#

08A.9, 6.2 gives the durability checklist and 08A.14, 5.3 lists a checkpoint in three bullets. This part goes field by field: what a checkpoint holds, what must stay out and when to save.

1.1 What goes wrong in long runs#

Failure How often Example
Process killed Routine Deploy, autoscaling, out-of-memory, spot interruption
Dependency down Routine Provider 503, rate limit (08C.2 retries these)
Wait for a human By design Approval takes hours or days (08A.12)
Budget or deadline hit By design Stop now, continue tomorrow with more budget
Bug in your code Eventually Fix it, then continue the stuck runs

For the first and last rows a checkpoint is the only way not to start over.

1.2 What a checkpoint contains#

A checkpoint is a saved copy of everything the run needs to continue as if it had never stopped. A good checkpoint is small, plain data (JSON), versioned, and sufficient.

Field Why Example
run_id Identify the run and derive idempotency keys run-42
schema_version Refuse or migrate checkpoints written by old code 1
Plan and step statuses Where the run is (08C.1) next: 1, or plan.json
Step results Inputs for later steps {"load": {...}}
Conversation state Messages or a summary, if later steps need them list of messages, or a compacted summary
Budget used Tokens, cost and time already spent (08C.2) tokens_used: 5200
Side-effect ledger Which writes were already done, with their keys refund:A17 -> r1
Pending approvals What a human has yet to decide approval_id
Timestamps and attempt counts Debugging and retry caps attempt: 2

What must not go into a checkpoint:

  • Secrets (API keys, tokens). Keep them in your secret store and re-read them on resume.
  • Live objects (HTTP clients, open files, database connections, thread handles). They cannot be saved and must be rebuilt on resume.
  • Huge blobs. Store large files elsewhere and keep a reference (a path or id) in the checkpoint.
  • Sensitive personal data you do not need. A checkpoint is a copy of user data that lives as long as you keep it. Treat it under your retention rules (08F.11, 6.2 discusses what a LangGraph checkpoint stores and what that means for privacy).

1.3 When to checkpoint#

Checkpoint at boundaries where state is consistent, usually:

  • after each step completes (the simplest and most common rule),
  • before a risky or irreversible action (so a crash right after it can be recognised), and
  • before a long wait (a human approval, a timer).

Do not checkpoint in the middle of a step's internal loop unless the step itself is long enough to need it. Finer checkpoints cost more writes and bring more states to reason about.


Part 2: Checkpoints in plain Python#

08A.9, 6.3 is a minimal durable runner: a state file and a set of finished steps. This part extends it with atomic writes, the crash between an action and its save, and idempotent resume with keys and a ledger.

2.1 Snapshot after every step#

The simplest durable agent: a loop that loads the latest checkpoint on start, runs the next step, saves, repeats. If the process is killed, starting it again continues from the last saved step.

2.2 Atomic writes#

A naive path.write_text(...) first truncates the file and then writes. If the process dies in between, you have a half-written file and no valid checkpoint at all. The fix is the standard atomic write:

  1. write the new content to a temporary file in the same directory,
  2. flush and fsync it so the bytes are really on disk,
  3. rename the temporary file over the real one with os.replace, which swaps atomically.

A reader then sees either the whole old file or the whole new file, never half of one. The temporary file must be on the same filesystem as the target, or the rename is not atomic.

2.3 Idempotent resume#

There is a second, subtler problem. Look at the order of events in a step that issues a refund:

  1. call the payment system (the refund happens),
  2. save the checkpoint saying "refund done".

If the process dies between 1 and 2, the checkpoint still says "refund not done", and the resumed run will refund again. No ordering of those two lines fixes this: you cannot make "do the thing" and "write it down" one atomic action across two systems.

The fix is idempotency: make repeating the call harmless. The standard tool is an idempotency key: a stable string that identifies the logical operation (run-42:refund:A17). The receiving system remembers the key and returns the first result when it sees it again. The key must be derived from the run and the step (not random per attempt), so a resumed attempt sends the same key as the crashed one. 08A.7 teaches idempotency in the tool layer and 08A.2, 6.3 covers the same rule in the raw loop. If the system you call has no idempotency support, keep a ledger of your own (write "about to refund A17" first, and on resume check the other system for the result before acting).

The code below shows all three ideas: atomic save, resume after a crash, and what idempotency keys change. A Payments fake honours keys the way real payment APIs do. The crash is simulated by raising an exception right after the refund and before the checkpoint.

python
# checkpoint.py: snapshot checkpoints with atomic writes, and idempotent resume after a crash
from __future__ import annotations

import json
import os
import tempfile
from pathlib import Path

SCHEMA_VERSION = 1


def save_checkpoint(path: Path, state: dict) -> None:
    """Write state so a reader sees either the old file or the new one, never half of one."""
    state = dict(state, schema_version=SCHEMA_VERSION)
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
    with os.fdopen(fd, "w") as f:
        json.dump(state, f)
        f.flush()
        os.fsync(f.fileno())         # force the bytes to disk before the swap
    os.replace(tmp, path)            # atomic on POSIX and Windows when on the same filesystem


def load_checkpoint(path: Path) -> dict | None:
    if not path.exists():
        return None
    state = json.loads(path.read_text())
    if state.get("schema_version") != SCHEMA_VERSION:
        raise RuntimeError(f"checkpoint schema {state.get('schema_version')} != {SCHEMA_VERSION}: migrate or restart")
    return state


# --- A fake payment system that DOES honour idempotency keys (like Stripe-style APIs) -------------
class Payments:
    def __init__(self) -> None:
        self.refunds: list[tuple[str, float]] = []
        self.seen: dict[str, dict] = {}

    def refund(self, order: str, amount: float, idempotency_key: str | None) -> dict:
        if idempotency_key and idempotency_key in self.seen:
            return self.seen[idempotency_key]            # same key: return the first result, do nothing
        self.refunds.append((order, amount))
        result = {"refund_id": f"r{len(self.refunds)}", "amount": amount}
        if idempotency_key:
            self.seen[idempotency_key] = result
        return result


class Crash(Exception): ...


STEPS = ["load", "refund", "notify"]


def run(path: Path, payments: Payments, *, use_keys: bool, crash_after_refund: bool) -> dict:
    state = load_checkpoint(path) or {"run_id": "run-42", "next": 0, "results": {}}
    print(f"  start: next step = {STEPS[state['next']] if state['next'] < len(STEPS) else 'none'}")
    while state["next"] < len(STEPS):
        step = STEPS[state["next"]]
        if step == "load":
            out = {"order": "A17", "total": 42.0}
        elif step == "refund":
            key = f"{state['run_id']}:refund:A17" if use_keys else None   # derived from the run, stable across restarts
            out = payments.refund("A17", 42.0, key)
            if crash_after_refund:
                raise Crash("process killed after the refund, before the checkpoint")
        else:
            out = {"emailed": True}
        state["results"][step] = out
        state["next"] += 1
        save_checkpoint(path, state)                    # checkpoint AFTER each step completes
    return state


for use_keys in (False, True):
    print(f"== idempotency keys: {use_keys}")
    d = Path(tempfile.mkdtemp(prefix="ckpt_"))
    pay = Payments()
    try:
        run(d / "run.json", pay, use_keys=use_keys, crash_after_refund=True)
    except Crash as c:
        print("  crashed:", c)
    final = run(d / "run.json", pay, use_keys=use_keys, crash_after_refund=False)   # the resume
    print("  finished:", sorted(final["results"]))
    print("  refunds actually made:", pay.refunds)

# --- Why atomic writes: a torn write --------------------------------------------------------------
print("== torn write")
d = Path(tempfile.mkdtemp(prefix="torn_"))
p = d / "run.json"
save_checkpoint(p, {"run_id": "run-42", "next": 1, "results": {}})
good = p.read_text()
p.write_text(good[:20])                                  # naive write killed halfway
try:
    load_checkpoint(p)
except json.JSONDecodeError as e:
    print("  naive overwrite, then crash ->", type(e).__name__)
save_checkpoint(p, {"run_id": "run-42", "next": 1, "results": {}})
(d / "run.json.tmp").write_text(good[:20])               # crash while writing the temp file
print("  atomic writer, crash mid-temp-write -> still loads:", load_checkpoint(p)["next"])
Output · real, run with Python 3.14 on 1 December 202615 lines
== idempotency keys: False
  start: next step = load
  crashed: process killed after the refund, before the checkpoint
  start: next step = refund
  finished: ['load', 'notify', 'refund']
  refunds actually made: [('A17', 42.0), ('A17', 42.0)]
== idempotency keys: True
  start: next step = load
  crashed: process killed after the refund, before the checkpoint
  start: next step = refund
  finished: ['load', 'notify', 'refund']
  refunds actually made: [('A17', 42.0)]
== torn write
  naive overwrite, then crash -> JSONDecodeError
  atomic writer, crash mid-temp-write -> still loads: 1

Read the output:

  • Without idempotency keys, the crash after the refund and before the checkpoint makes the resume issue the refund again: refunds actually made lists two refunds. Resume worked and the system was still wrong.
  • With keys, the second call carries the same key as the first, the fake payment system returns the stored result, and exactly one refund exists.
  • Torn write: a plain overwrite that dies halfway leaves unparseable JSON (JSONDecodeError). The atomic writer's checkpoint still loads, because a crash while writing the temporary file cannot touch the real file. (The demo imitates the crash by leaving a partial file with the temporary-file name next to the good checkpoint.)

Two more details in the code are easy to miss. schema_version is checked on load: a checkpoint written by an older version of your code should be refused or migrated, never guessed at. And save_checkpoint runs after each step completes, so a checkpoint always describes a finished step, never a half-done one.


Part 3: Replay versus resume#

Deep-dive

3.1 Two ways to continue#

Resume from a snapshot Replay from a history
What is saved The latest state (a picture) The ordered list of events (a diary): each completed activity and its result
How it continues Load state, jump to the next step Re-run the code from line 1, feeding back recorded results instead of repeating the work
Code layout A step loop with explicit next Ordinary straight-line code (a = f(); b = g(a))
Strength Simple; no restrictions on your code You write normal code; the engine reconstructs variables, loops and branches for you
Cost You design the state shape Code must be deterministic (3.3)
Used by Plain files, LangGraph checkpoints Temporal, Azure Durable Functions, many workflow engines

Both give "the work already done is not done again". The difference is where the knowledge of "where was I?" lives: in saved variables (snapshot) or in re-executing the code against a log (replay). 08F.11, 4.2 explains the LangGraph flavour: a node that was half done is run again from its first line, which is why idempotency matters there too.

3.2 A 40-line replay engine#

To understand replay, build a tiny one. The history is an append-only table of (sequence number, step name, result). The workflow is ordinary Python. Every call that touches the outside world goes through ctx.activity(name, fn, *args). That function asks: "is there already a recorded result at this position?" If yes, it returns the recorded result and does not call fn. If no, it calls fn, records the result, then moves on.

python
# replay_engine.py: a 40-line "workflow as code" engine: an event history, replay on restart, non-determinism detection
from __future__ import annotations

import json
import sqlite3
import tempfile
from pathlib import Path


class NonDeterminismError(Exception): ...
class Crash(Exception): ...


class History:
    """Append-only list of (seq, name, result) in sqlite. This is the durable truth."""

    def __init__(self, path: Path) -> None:
        self.db = sqlite3.connect(path)
        self.db.execute("create table if not exists events (seq integer primary key, name text, result text)")

    def get(self, seq: int):
        return self.db.execute("select name, result from events where seq=?", (seq,)).fetchone()

    def append(self, seq: int, name: str, result) -> None:
        with self.db:
            self.db.execute("insert into events values (?,?,?)", (seq, name, json.dumps(result)))

    def count(self) -> int:
        return self.db.execute("select count(*) from events").fetchone()[0]


class Ctx:
    def __init__(self, history: History) -> None:
        self.h, self.seq, self.executed, self.replayed = history, 0, [], []

    def activity(self, name: str, fn, *args):
        """Run fn once ever. On replay return the recorded result without calling fn."""
        seq, self.seq = self.seq, self.seq + 1
        row = self.h.get(seq)
        if row:
            recorded_name, result = row
            if recorded_name != name:                        # the code no longer matches the history
                raise NonDeterminismError(f"step {seq}: history has {recorded_name!r}, code now asks for {name!r}")
            self.replayed.append(name)
            return json.loads(result)
        result = fn(*args)
        self.h.append(seq, name, result)                     # persist BEFORE moving on
        self.executed.append(name)
        return result


SIDE_EFFECTS: list[str] = []


def load_order(oid):    SIDE_EFFECTS.append("load");   return {"id": oid, "total": 42.0}
def issue_refund(amt):  SIDE_EFFECTS.append("refund"); return {"refund_id": "r1", "amount": amt}
def send_email(text):   SIDE_EFFECTS.append("email");  return {"sent": True}


def workflow(ctx: Ctx, order_id: str, crash_at: str | None = None):
    order = ctx.activity("load_order", load_order, order_id)
    if crash_at == "before_refund":
        raise Crash("worker died")
    refund = ctx.activity("issue_refund", issue_refund, order["total"])
    if crash_at == "before_email":
        raise Crash("worker died")
    ctx.activity("send_email", send_email, f"refunded {refund['amount']}")
    return "done"


db_path = Path(tempfile.mkdtemp(prefix="hist_")) / "history.db"

print("== run 1 (crashes after the refund)")
ctx = Ctx(History(db_path))
try:
    workflow(ctx, "A17", crash_at="before_email")
except Crash as c:
    print("  crash:", c, "| executed:", ctx.executed)

print("== run 2 (restart: the code runs again from line 1)")
ctx = Ctx(History(db_path))
print("  result:", workflow(ctx, "A17"))
print("  replayed from history:", ctx.replayed)
print("  executed for real:   ", ctx.executed)
print("  side effects in total:", SIDE_EFFECTS)

print("== run 3 (a developer changed the code while the history exists)")
def workflow_v2(ctx: Ctx, order_id: str):
    ctx.activity("load_order", load_order, order_id)
    ctx.activity("check_fraud", lambda: "ok")             # NEW step inserted before the refund
    ctx.activity("issue_refund", issue_refund, 42.0)

try:
    workflow_v2(Ctx(History(db_path)), "A17")
except NonDeterminismError as e:
    print("  NonDeterminismError:", e)
Output · real9 lines
== run 1 (crashes after the refund)
  crash: worker died | executed: ['load_order', 'issue_refund']
== run 2 (restart: the code runs again from line 1)
  result: done
  replayed from history: ['load_order', 'issue_refund']
  executed for real:    ['send_email']
  side effects in total: ['load', 'refund', 'email']
== run 3 (a developer changed the code while the history exists)
  NonDeterminismError: step 1: history has 'issue_refund', code now asks for 'check_fraud'

Step by step:

  • Run 1 executes load_order and issue_refund, then the worker "dies" before sending the email. Both results are in the history.
  • Run 2 starts the same function from line 1. The first two ctx.activity calls find recorded results and return them without running anything (replayed from history). Only send_email runs for real. Across both runs the side effects list shows each action once.
  • Run 3 shows the catch. A developer inserted a check_fraud step before the refund while a run is in flight. Replay now asks for check_fraud at position 1 where the history has issue_refund, and the engine raises NonDeterminismError rather than silently doing the wrong thing.

3.3 Determinism, and changing code in flight#

Replay only works if the workflow code makes the same sequence of decisions every time it runs against the same history. That is the determinism requirement. In practice, workflow code must not read the clock, generate random numbers, read files or call the network directly, because those give different answers on replay. Anything like that belongs inside an activity (whose result is recorded), or goes through the engine's replay-safe helpers. Temporal's Python documentation, for example, tells you to use workflow.now(), workflow.random() and workflow.uuid4() instead of datetime.now(), random and uuid.uuid4() (docs.temporal.io, read 1 December 2026).

The model call is the classic case. A model call is not deterministic, so in an agent built this way, the model call is an activity: its result is recorded in the history, and on replay the recorded reply is returned instead of calling the model again. This also means replay never pays for the same tokens twice.

Changing code while runs are in flight is the other consequence. Run 3 above shows why: the old history no longer matches the new code. Engines give you tools for this (Temporal calls them versioning or patching; Step Functions publishes numbered versions and aliases of a state machine, and a redriven execution keeps using the definition it started with, per its docs). The plain-Python equivalent is: keep schema_version in checkpoints, finish or drain old runs before changing step order, or start new runs on the new code and let old ones complete on the old.

3.4 Activities are at-least-once, so keep them idempotent#

Look at the replay engine again: ctx.activity runs fn first and then appends to the history. If the process dies in between, the work happened but the history does not know it, so the next run executes it again. Replay engines give you "each recorded activity is not repeated", which in practice means at-least-once execution of activities. Therefore everything in 2.3 still applies: give side-effecting activities an idempotency key. Durable execution removes most duplicate work and nearly all the bookkeeping, and it does not remove the need for idempotent writes.


Part 4: Workflow-as-code durable execution, the concepts#

Deep-dive

08A.9, 6.4 compares the engine families in one table. This part names the concepts they share (workflow, activity, event history, signal, timer) and ties each to the code you wrote in Part 3.

"Durable execution" platforms package the ideas from Parts 2 and 3. The vocabulary below is shared across most of them.

Concept Meaning In the plain-Python lessons
Workflow The durable, long-lived orchestration logic. Deterministic. workflow() in replay_engine.py
Activity (or task) One unit of side-effecting work with its own timeout and retry policy. Its result is recorded. ctx.activity(...)
Event history Append-only record of everything that happened in one workflow run The events table
Worker A process that runs workflow and activity code and polls the engine for work Your Python process
Replay Re-running workflow code against the history to rebuild its state Run 2
Timer A durable sleep: survives restarts and costs no worker while waiting Not built here
Signal / callback A message sent into a waiting workflow from outside (a human approved) Not built here
Retry policy How and how often a failed activity is retried 08C.2 retry
Timeout Time limits for an activity attempt, for the whole activity, and for the workflow 08C.2 budgets
Idempotency Making a repeated activity harmless 2.3

Why this fits agents well:

  • An agent loop is a long, branching sequence of side-effecting calls (model, tools) with waits (humans, rate limits). That is exactly what a workflow is.
  • The model call as an activity gives free retries with backoff, timeouts, recorded replies and a full audit history of what the agent saw and decided.
  • Human approval becomes a durable wait (08A.12): the workflow sleeps for days at no cost and wakes on a signal or callback.
  • The history is the trace: you can see exactly what happened and replay a failed run against a fixed bug.

The costs: you run (or rent) another system, you accept the determinism rules, large payloads must be kept out of the history, and a long-running loop needs a way to keep its history from growing forever (Part 5 and Part 6 show how each engine handles that).


Part 5: How Temporal does it#

Deep-dive

What it is. Temporal is an open-source durable execution platform (docs.temporal.io). A Workflow Execution is described in its docs as "a durable, reliable, and scalable function execution". It stores everything as an Event History, and on failure a Worker resumes by replay: it re-runs the workflow code from the start and uses the Event History to rebuild state, while Activities are not re-executed, because their recorded results are reused. These descriptions come from the Temporal pages "Workflow Execution" and "Workflows", read on 1 December 2026.

The pieces, in Temporal's words (same pages):

  • Workflow Definition: code in a general-purpose language (Go, Java, TypeScript, Python and others). It must be deterministic. Work that touches the outside world (API calls, database queries, file I/O) goes in Activities.
  • Activity: the way a Workflow interacts with the outside environment. Starting one is an awaitable: the workflow waits until it returns.
  • Worker: runs your Workflow and Activity code and talks to the Temporal Service.
  • Retry Policy: for Activities, the default is an initial interval of 1 second, a backoff coefficient of 2.0, a maximum interval of 100 times the initial interval, and unlimited attempts; a Workflow has no retry policy by default. Errors marked non-retryable in code are never retried (docs.temporal.io "Retry Policies", read 1 December 2026).
  • Timeouts: Schedule-To-Close (whole activity execution), Start-To-Close (one attempt) and a Heartbeat timeout. An activity that calls activity.heartbeat(details) tells the service it is alive, and the heartbeat details are stored, so a retried attempt can read where the failed attempt got to and continue (docs.temporal.io Python "Activity timeouts", read 1 December 2026).
  • Signals, Queries, Updates: Signals are asynchronous messages into a running workflow; Queries read workflow state synchronously; Updates call a handler synchronously and can return a result (docs.temporal.io "Sending messages").
  • Continue-As-New: a workflow can checkpoint its latest state and start a new execution with the same Workflow Id and a new Run Id and a fresh Event History. It exists because a very long Event History slows a workflow and can hit history limits, and because it limits how many code versions a long run spans. The docs describe a "Continue-As-New Suggested" signal that tells the workflow when to do it (docs.temporal.io "Continue-As-New", read 1 December 2026; the page lists no numeric limits, so check the current limits page before you design around them).

An agent in Temporal (illustrative, not run). The structure is: the loop is the workflow; each model call and each tool call is an activity; approval is a signal. The decorator and call names below are those shown in Temporal's Python documentation (@workflow.defn, @workflow.run, @activity.defn, workflow.execute_activity with start_to_close_timeout and retry_policy). @workflow.signal and workflow.wait_condition are the documented Python names for signals and waiting, but check the current Python docs before relying on exact signatures.

python
# temporal_agent_sketch.py: ILLUSTRATIVE, requires `temporalio` and a Temporal service; not run in this lesson
from datetime import timedelta

from temporalio import activity, workflow
from temporalio.common import RetryPolicy


@activity.defn
async def call_model(messages: list[dict]) -> dict:
    """Calls OpenAI or Anthropic. The reply is recorded in the history on success."""
    ...


@activity.defn
async def run_tool(name: str, args: dict, idempotency_key: str) -> str:
    """Runs one tool. Side-effecting tools must honour idempotency_key (Part 2.3)."""
    ...


@workflow.defn
class SupportAgent:
    def __init__(self) -> None:
        self._approved: bool | None = None

    @workflow.signal
    def approve(self, ok: bool) -> None:           # a human sends this from outside
        self._approved = ok

    @workflow.run
    async def run(self, goal: str) -> str:
        messages = [{"role": "user", "content": goal}]
        for step in range(20):                      # a loop budget, as in 08A.3
            reply = await workflow.execute_activity(
                call_model, messages,
                start_to_close_timeout=timedelta(seconds=60),
                retry_policy=RetryPolicy(maximum_attempts=3),
            )
            if not reply.get("tool_calls"):
                return reply["text"]
            for call in reply["tool_calls"]:
                if call["needs_approval"]:
                    await workflow.wait_condition(lambda: self._approved is not None)
                    if not self._approved:
                        return "stopped: approval denied"
                result = await workflow.execute_activity(
                    run_tool, args=[call["name"], call["args"], f"{workflow.info().run_id}:{step}:{call['name']}"],
                    start_to_close_timeout=timedelta(seconds=30),
                    retry_policy=RetryPolicy(maximum_attempts=3),
                )
                messages.append({"role": "tool", "content": result})
        return "stopped: step budget used"

Notice what is not in this code: no checkpoint file, no next counter, no resume logic. A worker crash at any line means another worker replays this function against the recorded history and continues. That is what you pay the engine for. Notice also what is there: the idempotency key passed to run_tool, because activities are at-least-once.

Temporal and agent frameworks. Temporal documents an integration with the OpenAI Agents SDK for Python, in which the agent loop runs in a Workflow and model calls run as Activities. According to Temporal's docs it became generally available on 23 March 2026. Its install instructions differ between Temporal doc pages as of 1 December 2026 (one shows an extra on temporalio, another a separate package), so follow the page for the SDK version you install. Temporal's own pages also note that its durability does not extend to external MCP servers, which run outside the Workflow (each MCP operation becomes an Activity). Verify the current state of this integration in the Temporal docs before depending on it.


Part 6: How AWS Step Functions does it#

Deep-dive

What it is. AWS Step Functions lets you define workflows, also called state machines, in Amazon States Language (JSON), made of states; a running instance is an execution (docs.aws.amazon.com/step-functions, "What is Step Functions?", read 1 December 2026). The design differs from Temporal in a way that matters: the workflow is configuration, not code. The engine, not your code, holds the control flow, and your code lives in the tasks (Lambda functions, containers, other AWS services). There is therefore no replay and no determinism rule for your orchestration logic: the engine persists the execution's state between transitions.

Standard vs Express (docs "Choosing workflow type", read 1 December 2026):

Standard Express
Max duration 1 year 5 minutes
Execution semantics Exactly-once workflow execution (a task or state is not run more than once unless you configured Retry) Asynchronous: at-least-once. Synchronous: at-most-once
State persisted between transitions Yes No
Execution history Available through the API for 90 days after the execution closes Only through CloudWatch Logs
Wait for a callback or job .waitForTaskToken and .sync patterns supported Not supported

For agents that wait for humans or run long, Standard is the one that matters. Docs note that Standard's exactly-once model suits non-idempotent actions, which still does not mean you can stop thinking about idempotency inside your Lambda functions: a Lambda or task that times out may already have done its work, and a Retry will call it again.

Error handling is declarative. Task, Parallel and Map states take a Retry array (fields ErrorEquals, IntervalSeconds default 1, MaxAttempts default 3, BackoffRate default 2.0, optional MaxDelaySeconds and JitterStrategy) and a Catch array (ErrorEquals, Next, ResultPath). Retries run first. When they are used up, the matching catcher routes to a fallback state. States.ALL, States.Timeout and States.TaskFailed are built-in error names (docs "Handling errors", read 1 December 2026). This is the failure classification of 08C.2 written as configuration: retry transient errors, and send the rest to a Catch state that replans or escalates.

Human approval is a callback. A task with the .waitForTaskToken suffix passes a task token to an external system and pauses until that system calls SendTaskSuccess or SendTaskFailure with the token. The docs say the execution can wait up to the one-year quota, and recommend HeartbeatSeconds so a lost callback does not leave an execution stuck (the task fails with States.Timeout if no heartbeat or token arrives in time).

Redrive. For a Standard execution that failed, was aborted or timed out, redrive continues it from the unsuccessful step with the same input and execution ARN, keeping the results of steps that already succeeded. It is eligible for 14 days after the execution closes, requires fewer than 24,999 history events, and uses the state machine definition the execution started with (docs "Redrive", read 1 December 2026). It is the managed version of "resume from checkpoint after a bug fix".

Limits that shape agent design (docs "Service quotas", read 1 December 2026): a Standard execution history is capped at 25,000 events (the execution fails at the limit; the docs advise starting new executions to avoid it) and the input or output of a task, state or execution is capped at 256 KiB. The practical consequence is a design rule, not a quote from the docs: do not pass a growing message history through the state machine. Keep the conversation in S3 or a database and pass a reference (an id) between states. A loop that runs hundreds of iterations should start a fresh execution every so often, the Step Functions version of Temporal's Continue-As-New.

An agent step in Step Functions (illustrative, not run). One model call with retry and a catch, then a human approval with a task token. State names and field names follow the docs pages cited above; the function name, queue URL and the shape of the payload are made up.

json
{
  "Comment": "ILLUSTRATIVE: not deployed or run. One agent step, then a human approval.",
  "StartAt": "CallModel",
  "States": {
    "CallModel": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "call-model", "Payload.$": "$" },
      "TimeoutSeconds": 60,
      "Retry": [{
        "ErrorEquals": ["States.Timeout", "Lambda.ServiceException", "Lambda.TooManyRequestsException"],
        "IntervalSeconds": 2, "MaxAttempts": 3, "BackoffRate": 2.0, "JitterStrategy": "FULL"
      }],
      "Catch": [{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "Escalate" }],
      "Next": "WaitForApproval"
    },
    "WaitForApproval": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
      "HeartbeatSeconds": 3600,
      "Parameters": {
        "QueueUrl": "https://sqs.us-east-1.amazonaws.com/123456789012/approvals",
        "MessageBody": { "plan.$": "$.plan", "TaskToken.$": "$$.Task.Token" }
      },
      "Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "Escalate" }],
      "End": true
    },
    "Escalate": { "Type": "Fail", "Error": "NeedsHuman", "Cause": "Step failed or approval lost" }
  }
}

A person (or a small service) later calls SendTaskSuccess with the token to continue, or SendTaskFailure to stop. The Step Functions integration table in the docs also lists Amazon Bedrock as an optimized integration for Standard workflows with both .sync and .waitForTaskToken patterns. Calling OpenAI or Anthropic from a state machine is done through a Lambda function or a container task, like any other API.


Part 7: Choosing#

The closing summary of 08A.9, 6.4 picks an engine by workload. This part adds plain files, Step Functions and provider-managed runtimes to the comparison and gives the order in which to adopt them.

Option Good for Costs Resume model
Plain files or SQLite (Parts 2 and 3) One service, short or medium runs, learning, tests You write and test the resume logic and the idempotency Snapshot, or your own history
LangGraph checkpointers (08F.11) You already use LangGraph; graph-shaped agents; human-in-the-loop interrupts A framework dependency; its replay rules (a node re-runs from its first line) Snapshot per super-step, with pending writes
Temporal Long, branching, code-shaped agents; very long waits; strict audit; polyglot teams Run or rent a Temporal service; determinism rules; workers to operate Replay from event history
AWS Step Functions (Standard) You are on AWS; orchestration between AWS services and Lambda; approvals and audits; low operational burden Workflow lives in JSON (ASL), not your code; 256 KiB and 25,000-event limits; AWS lock-in Engine-persisted state; redrive from failure
Provider-managed agent runtimes and background modes Offloading a long run to the provider Less control over state and retention Provider's design; see 08A.13

Rules of thumb:

  1. Start plain (checkpoint file or SQLite, atomic writes, idempotency keys). It teaches you what any engine will ask of you anyway.
  2. Move to an engine when you need waits longer than a process lifetime, many concurrent long runs, per-step retries and timeouts you do not want to write, or an audit history you can show.
  3. Choose replay-style code (Temporal) when your control flow is complex and best expressed as code, and declarative (Step Functions) when you mostly glue managed services together and want the visual graph.
  4. In every case, idempotent side effects, small state, and no secrets in the saved state.

For the broader decision of when to build an agent at all, see the workflow-versus-agent decision in 13A.8, 11.1.


Part 8: Evaluate it#

A resumable agent has a property that a final-answer eval will never see: what happens when you kill it. You have to test that on purpose.

Concept lessons first.

DeepEval lessons (required track).

  • 10B.2 and 10B.4 for basics and built-in metrics.
  • 10B.5 for tracing a run and scoring its trajectory, which is how you would score a resumed trajectory.
  • 10B.6 for turning crash scenarios into a dataset, and 10B.7 for running them in CI.

Inspect AI lessons (optional).

8.1 What to measure#

Measure Question How
Resume correctness After a kill at point k, does the finished run equal an uninterrupted run? Compare end-state of killed-and-resumed vs clean runs
Exactly-once effects Is each side effect present exactly once? Count rows, refunds and emails in the fake world
Work not repeated Did resume skip finished steps? Count executed activities and model calls per step; compare with the clean run
Recovery from torn writes Does a crash mid-save leave a loadable checkpoint? Kill during the write; load; expect the previous version
Replay safety Does a code change break in-flight runs? Run the old history against the new code and expect either success or a clear NonDeterminismError
Resume cost What does a crash cost in tokens and time? Tokens and seconds from kill to completion

8.2 A tiny eval design#

  • Inputs: the 3-step refund workflow from checkpoint.py, killed at each of 6 points: before step 1, after step 1, between the refund and its checkpoint, after the refund checkpoint, after step 3, and during a checkpoint write.
  • Metric 1 (code): end-state equals the clean run's end-state for all 6 kill points. Pass rule: 6 of 6.
  • Metric 2 (code): refund count is exactly 1 at every kill point. Pass rule: 6 of 6. Run the same table with idempotency keys turned off and confirm it fails at the "between refund and checkpoint" point, which proves the test can detect the bug.
  • Metric 3 (code): executed steps after resume equal the steps not yet checkpointed. Pass rule: no step repeated except the one that was in flight.
  • Metric 4 (with a model in the loop, optional): kill a real agent run at a random turn 10 times, resume, and grade the final outcome with the end-state grader from 10A.7. Report resume success rate and tokens spent after resume.

Like the fault table in 08C.2, the first three metrics need no model and belong in your normal unit tests. As the last paragraph of 10B.15 section 10.8 puts it for eval checkpoints, a checkpoint feature you have never restored is a hope, not a control.


Common misconceptions#

  • "Checkpointing in the eval lesson is the same as durable execution." It is not. 10B.15 section 10.8 resumes an interrupted eval run. This lesson resumes a production agent.
  • "If I save a checkpoint, resume is safe." Only if side effects are idempotent. A crash between the action and the save repeats the action.
  • "Overwriting the checkpoint file is fine." A crash during the write destroys it. Write to a temporary file, fsync, then os.replace.
  • "Durable execution means exactly-once everything." Engines give exactly-once for recorded progress. Activities and Lambda tasks may still run more than once, so keep them idempotent.
  • "Replay re-calls the model." In a replay engine the recorded result is returned. That only works because the model call is an activity with a recorded result.
  • "A workflow can read the clock or call an API directly." Not in a replay engine: it breaks determinism. Use activities or the engine's replay-safe helpers.
  • "Resume undoes what the agent did." A checkpoint restores the agent's state, not the outside world.
  • "Step Functions is just Temporal in JSON." The model differs: Step Functions keeps orchestration state in the engine and has no replay of your code, while Temporal replays your code against a history.

Key takeaways#

  • A checkpoint is small, versioned, plain data: ids, plan and step state, results, budget used and a side-effect ledger. No secrets, no live objects.
  • Save at consistent boundaries, after each step and before long waits or irreversible actions.
  • Write checkpoints atomically: temporary file, fsync, os.replace.
  • Resume must be idempotent. Derive idempotency keys from the run and step, not from the attempt.
  • Snapshot resume restores a picture of state. Replay re-runs deterministic code against a recorded history. Both avoid repeating finished work.
  • In replay engines the model call is an activity, which makes it recorded, retryable and free to replay.
  • Temporal gives code-based workflows, activities, event history, retry policies, heartbeats, signals and Continue-As-New. Step Functions gives declarative state machines, Retry and Catch, callback tokens and redrive, with 256 KiB and 25,000-event limits.
  • "Checkpointing" in 10B.15 section 10.8 means resuming an eval run. Do not confuse it with durable execution.
  • Test resume by killing runs on purpose at every interesting point.

Terms introduced in this lesson#

Term Meaning
Checkpoint A saved copy of the state a run needs in order to continue after a stop
Resume Loading the latest checkpoint and continuing from there
Snapshot A copy of state at one moment
Atomic write Writing so a reader sees either the whole old file or the whole new one, never a mix
Torn write A write interrupted halfway, leaving a corrupt file
fsync An operating-system call that forces buffered file data to disk
Idempotency Property of an operation that makes repeating it have the same effect as doing it once
Idempotency key A stable string that identifies one logical operation so repeats can be recognised
Side-effect ledger A record of which external actions were already done, with their keys
Schema version A number stored in a checkpoint so code can refuse or migrate old formats
Durable execution Running code so that it survives crashes and restarts without losing completed work or repeating it
Replay Re-running workflow code against a recorded history to rebuild its state
Event history The append-only record of everything that happened in one workflow run
Workflow The long-lived, durable orchestration logic
Activity One side-effecting unit of work inside a workflow, with its own timeout and retries
Determinism requirement The rule that workflow code must make the same decisions every time it replays
Non-determinism error The failure raised when code no longer matches the recorded history
Worker A process that runs workflow and activity code for an engine
Signal An asynchronous message sent into a running workflow, such as a human approval
Heartbeat A periodic "still alive" message from a long-running activity or task
Continue-As-New Temporal's way to end a long workflow run and start a new one with carried-over state and a fresh history
State machine (Step Functions) A workflow defined as states and transitions in Amazon States Language
Task token A token a Step Functions task hands to an external system, which must return it to continue the workflow
Redrive Continuing a failed Standard Step Functions execution from the failed step, keeping completed results
At-least-once A guarantee that an operation runs one or more times, so duplicates are possible
Eval-run checkpointing Saving state so an interrupted evaluation run can resume; not durable execution of an agent

Exercises#

  1. Kill-point table. Wrap run() in checkpoint.py so you can raise Crash at any of six places, and write a loop that runs every kill point and asserts exactly one refund. Hint: pass a crash_at string and check it before and after each step and around save_checkpoint; compare the final results with a clean run.
  2. Make the ledger the source of truth. Add a ledger list to the checkpoint recording "refund:A17" before calling the payment fake, and on resume check the fake's records first. Does this work for a payment system with no idempotency keys? Hint: it narrows the window but cannot close it without a way to query the other system; say what you would do for a refund API that has no lookup.
  3. SQLite checkpoint. Replace the JSON file by one SQLite row per run, saved in a transaction together with the side-effect ledger. Hint: with conn: gives a transaction; put the checkpoint update and ledger insert inside one with block, and test a crash between them by raising inside the block.
  4. Record the model call. In replay_engine.py, add a scripted "model call" activity that returns canned text and counts calls. Kill and resume, and assert the model was called once per step across both runs. Hint: a counter in the fake model is enough; the point is that replay returns the recorded text.
  5. Version a workflow. Give History a workflow_version and make run 3 start a new history instead of failing when the version changes. What happens to runs already in flight? Hint: store the version in a small meta table and refuse to mix versions; decide whether old runs drain or are migrated.
  6. Read the docs. Open the Temporal "Workflow Execution" page and the Step Functions "Choosing workflow type" page. Write five lines comparing how each engine keeps progress after a crash, and note one fact that changed since this lesson's date. Hint: check the duration limits, the retry defaults and the history limits first.

Check yourself#

  1. List four things a checkpoint should contain and three things that must stay out.
  2. Why is path.write_text() unsafe for checkpoints, and what does the atomic pattern do instead?
  3. Why does a crash between "refund done" and "checkpoint saved" cause a duplicate refund?
  4. How should an idempotency key be derived, and why must it not be random per attempt?
  5. Explain the difference between resume-from-snapshot and replay-from-history.
  6. Why must workflow code in a replay engine be deterministic?
  7. Why is the model call an activity in a replay-style agent, and what does that give you?
  8. Name two ways a Step Functions Standard workflow differs from a Temporal workflow in how it keeps progress.
  9. What does Step Functions redrive do, and what are its eligibility limits?
  10. What does "checkpointing" mean in lesson 10B.15 section 10.8, and how does it differ from this lesson?

Further resources#


← 08C.2 — Dynamic Replanning and Constraint-Aware Planning | Module 08C overview | Module 08D: Multi-Agent Systems →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close