Crash, Resume, Compare
Kill a checkpointing support agent with SIGKILL before and after every side effect, resume it from its last checkpoint, and compare its tickets and emails with an uninterrupted run; then break idempotency and checkpoint granularity on purpose and watch the same harness catch the duplicates and the extra model calls.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: The outside world
- Step 2: An agent that checkpoints and can crash
- Step 3: An uninterrupted run
- Step 4: One crash, by hand
- Step 5: Every crash point
- Step 6: Break idempotency and watch the test fail
- Step 7: Checkpoint only at the end
- Check your understanding
- Apply it
- Review prompt
Lessons of Durable Agent Execution
- What Breaks in Long-Running Agents Concept · 15 min
- Checkpointers Versus Workflow Engines Concept · 15 min
- Idempotent Side Effects Worked example · 20 min
- Lab: Background Runs with Retries and Cancellation Lab · 25 min
- Crash, Resume, Compare Lab · 25 min
- Check: Failure and Recovery Scenarios Knowledge check · 8 questions
What you will learn
- Resume an interrupted run from its last checkpoint and verify that the outcome matches an uninterrupted run.
Prerequisites: Agent Loops & ReAct
01. Goal and setup
Saying "our agent resumes after a crash" is a claim. This lab turns it into a test. You will build a five-step support agent that saves a checkpoint (a saved copy of its state) after every step, then a chaos harness that kills it at every interesting point, resumes it, and compares the result with a run that was never interrupted.
The comparison is the core of the lab, so decide first what "the same result" means. It cannot mean the same text: real model output changes from call to call, and the fake model here picks its greeting at random to make that visible. It means the same outcome: the same tickets and emails in the outside world, linked the same way, and a run that reached its end. Those are the things a customer would notice.
You need: Python 3.10 or newer (tested with 3.12) and nothing to install. The "outside world" is a separate SQLite file, remote.sqlite, that the agent writes through two small functions; it survives the agent's crashes just as a real ticket system would. Create a folder crash-lab and run every command inside it.
crash-lab/
├── remote.py step 1: ticket and email services, idempotent by key
├── agent_run.py step 2: the agent, with checkpoints and crash points
├── show.py step 3: prints the remote state and the checkpoints
└── chaos.py step 4: crash at every point, resume, compare02. Step 1: The outside world
create_ticket and send_email each take an idempotency key, as in Idempotent Side Effects. A second call with a known key returns the first result. Setting REMOTE_IDEMPOTENT=0 makes both services ignore keys, so you can see later what the harness reports when a tool is not safe to repeat. The connection uses autocommit, so every write is committed the moment it happens, before the agent has any chance to record it.
"""Stand-ins for external systems. Their state lives in remote.sqlite and survives
an agent crash, exactly like a real ticket system or mail provider would."""
import os
import sqlite3
IDEMPOTENT = os.environ.get("REMOTE_IDEMPOTENT", "1") == "1"
db = sqlite3.connect("remote.sqlite", isolation_level=None) # autocommit
db.executescript("""
CREATE TABLE IF NOT EXISTS tickets (id INTEGER PRIMARY KEY, key TEXT, title TEXT);
CREATE TABLE IF NOT EXISTS emails (id INTEGER PRIMARY KEY, key TEXT, to_addr TEXT,
ticket_id INTEGER, body TEXT);
""")
def create_ticket(key: str, title: str) -> int:
if IDEMPOTENT: # a repeat with the same key returns the first ticket
row = db.execute("SELECT id FROM tickets WHERE key = ?", (key,)).fetchone()
if row:
return row[0]
return db.execute("INSERT INTO tickets (key, title) VALUES (?, ?)",
(key, title)).lastrowid
def send_email(key: str, to_addr: str, ticket_id: int, body: str) -> int:
if IDEMPOTENT:
row = db.execute("SELECT id FROM emails WHERE key = ?", (key,)).fetchone()
if row:
return row[0]
return db.execute("INSERT INTO emails (key, to_addr, ticket_id, body) "
"VALUES (?, ?, ?, ?)", (key, to_addr, ticket_id, body)).lastrowidpython3 -m py_compile remote.py && echo "remote.py compiles"remote.py compiles03. Step 2: An agent that checkpoints and can crash
The agent has five steps: classify the ticket (a model call), look up the customer (read-only), create a ticket (side effect), draft a reply (a model call), and send the email (side effect). Its whole state is one dictionary. After each step, save() writes the step number and the state to checkpoints.sqlite. On start, main() loads the newest checkpoint for the run ID and skips every step up to it, so resuming is just "run the same command again".
Three details make the test honest. The idempotency key is run_id/step, so a repeated step sends the same key. maybe_crash() sends SIGKILL to its own process, which cannot be caught: no finally block runs and nothing is flushed, which is what an OOM kill or a lost machine does. And there are two crash points per step: before the step starts, and after_effect, when the step's work is done but its checkpoint is not yet saved. The second one is the crash window from lesson 1.
fake_model() logs every call to model_calls.log, so the harness can count how much model work a crash cost. Setting CHECKPOINT=end saves only when the run finishes, which you will use in step 7.
"""A five-step support agent that checkpoints after every step and can resume.
Usage: python agent_run.py RUN_ID
Env: CRASH_AT=<step>:<before|after_effect> kill -9 ourselves at that point
CHECKPOINT=end only save when the run finishes
"""
import json
import os
import random
import signal
import sqlite3
import sys
import remote
STEPS = ["classify", "lookup_customer", "create_ticket", "draft_reply", "send_email"]
TICKET = {"from": "[email protected]", "text": "I was charged twice for order 1042."}
ckpt = sqlite3.connect("checkpoints.sqlite", isolation_level=None)
ckpt.execute("CREATE TABLE IF NOT EXISTS checkpoints "
"(run_id TEXT, n INTEGER, state TEXT, PRIMARY KEY (run_id, n))")
def fake_model(task: str, state: dict) -> str:
"""Stands in for a model call: right answer, but wording varies per call."""
with open("model_calls.log", "a") as f:
f.write(task + "\n")
if task == "classify":
return "billing"
greeting = random.choice(["Hi Ana,", "Hello Ana,", "Dear Ana,"]) # unseeded
return f"{greeting} we opened ticket {state['ticket_id']} for the refund."
def maybe_crash(step: str, point: str) -> None:
if os.environ.get("CRASH_AT") == f"{step}:{point}":
os.kill(os.getpid(), signal.SIGKILL) # no finally blocks, no flush
def run_step(run_id: str, step: str, state: dict) -> None:
key = f"{run_id}/{step}" # stable idempotency key: same on every attempt
if step == "classify":
state["queue"] = fake_model("classify", state)
elif step == "lookup_customer":
state["customer"] = {"email": TICKET["from"], "plan": "pro"} # read-only
elif step == "create_ticket":
state["ticket_id"] = remote.create_ticket(key, "Double charge, order 1042")
elif step == "draft_reply":
state["reply"] = fake_model("draft_reply", state)
elif step == "send_email":
remote.send_email(key, state["customer"]["email"], state["ticket_id"],
state["reply"])
def save(run_id: str, n: int, state: dict) -> None:
ckpt.execute("INSERT OR REPLACE INTO checkpoints VALUES (?, ?, ?)",
(run_id, n, json.dumps(state)))
def main(run_id: str) -> None:
row = ckpt.execute("SELECT n, state FROM checkpoints WHERE run_id = ? "
"ORDER BY n DESC LIMIT 1", (run_id,)).fetchone()
done, state = (row[0], json.loads(row[1])) if row else (0, {})
print(f"start at step {done + 1}" if done < len(STEPS) else "already finished",
flush=True)
for n, step in enumerate(STEPS, start=1):
if n <= done:
continue # finished before the crash: its result is in `state`
maybe_crash(step, "before")
run_step(run_id, step, state)
maybe_crash(step, "after_effect") # effect done, checkpoint not yet saved
if os.environ.get("CHECKPOINT") != "end" or n == len(STEPS):
save(run_id, n, state)
if __name__ == "__main__":
main(sys.argv[1])python3 -m py_compile agent_run.py && echo "agent_run.py compiles"agent_run.py compiles04. Step 3: An uninterrupted run
show.py prints the tickets, the emails (without the body, whose wording varies), the keys stored in each checkpoint, and the model calls. Run the agent once without any crash to see the baseline by hand.
"""Print what the outside world and the checkpoint store now contain."""
import json
import sqlite3
remote = sqlite3.connect("remote.sqlite")
ckpt = sqlite3.connect("checkpoints.sqlite")
tickets = remote.execute("SELECT id, key, title FROM tickets").fetchall()
emails = remote.execute("SELECT id, to_addr, ticket_id FROM emails").fetchall()
print("tickets:", tickets)
print("emails: ", emails) # the body is left out: its wording varies
for n, state in ckpt.execute("SELECT n, state FROM checkpoints ORDER BY n"):
print(f"checkpoint {n}:", sorted(json.loads(state)))
print("model calls:", open("model_calls.log").read().split())rm -f *.sqlite model_calls.log
python3 agent_run.py run-1
python3 show.pystart at step 1
tickets: [(1, 'run-1/create_ticket', 'Double charge, order 1042')]
emails: [(1, '[email protected]', 1)]
checkpoint 1: ['queue']
checkpoint 2: ['customer', 'queue']
checkpoint 3: ['customer', 'queue', 'ticket_id']
checkpoint 4: ['customer', 'queue', 'reply', 'ticket_id']
checkpoint 5: ['customer', 'queue', 'reply', 'ticket_id']
model calls: ['classify', 'draft_reply']Each checkpoint holds everything later steps need: after step 3 the ticket ID is in the state, so draft_reply and send_email can use it after a restart. A value kept only in a local variable would be lost by a crash, and the resumed run would fail or, worse, do something different.
05. Step 4: One crash, by hand
The harness runs the agent as a child process, so it can see that the process was killed: subprocess reports a negative exit code, -9, for a process ended by signal 9 (SIGKILL). Its once mode crashes at one point, resumes, and prints what the agent printed both times.
"""Crash the agent at every point, resume it, and compare with a clean run."""
import os
import sqlite3
import subprocess
import sys
from agent_run import STEPS
PY = sys.executable
def fresh() -> None:
for name in ("remote.sqlite", "checkpoints.sqlite", "model_calls.log"):
if os.path.exists(name):
os.remove(name)
def agent(env_extra: dict, show: bool = False) -> int:
env = {**os.environ, **env_extra}
done = subprocess.run([PY, "agent_run.py", "run-1"], env=env,
capture_output=True, text=True)
if show:
print(f"agent printed {done.stdout.strip()!r}, exit code {done.returncode}")
return done.returncode # -9 means killed by SIGKILL
def outcome() -> dict:
"""What must match: business state and side effects, not model wording."""
remote = sqlite3.connect("remote.sqlite")
ckpt = sqlite3.connect("checkpoints.sqlite")
last = ckpt.execute("SELECT MAX(n) FROM checkpoints").fetchone()[0]
return {
"tickets": remote.execute("SELECT title FROM tickets").fetchall(),
"emails": remote.execute("SELECT to_addr, ticket_id FROM emails").fetchall(),
"finished": last == len(STEPS),
}
def summary(o: dict) -> str:
sent_for = [ticket for _, ticket in o["emails"]]
return (f"{len(o['tickets'])} ticket(s), emails for tickets {sent_for}, "
f"finished={o['finished']}")
def model_calls() -> int:
return len(open("model_calls.log").read().split())
def trial(crash_at: str, mode: dict, show=False) -> tuple[list[int], dict, int]:
fresh()
codes = [agent({**mode, "CRASH_AT": crash_at}, show)]
if codes[0] != 0:
codes.append(agent(mode, show)) # resume: same run id, no crash this time
return codes, outcome(), model_calls()
if __name__ == "__main__":
if sys.argv[1:2] == ["once"]: # python chaos.py once STEP:POINT
trial(sys.argv[2], {}, show=True)
sys.exit()
mode = {}
for arg in sys.argv[1:]: # e.g. REMOTE_IDEMPOTENT=0 or CHECKPOINT=end
name, _, value = arg.partition("=")
mode[name] = value
_, baseline, base_calls = trial("none", mode)
print(f"baseline: {summary(baseline)}, model calls {base_calls}")
failures = 0
for step in STEPS:
for point in ("before", "after_effect"):
codes, result, calls = trial(f"{step}:{point}", mode)
same = result == baseline
failures += not same
print(f"{step + ':' + point:<28} exits {str(codes):<9} "
f"model calls {calls} {'MATCH' if same else 'DIFFERENT'}")
if not same:
print(f"{'':<29}got: {summary(result)}")
print(f"{failures} of {2 * len(STEPS)} crash points differ from the baseline")
sys.exit(1 if failures else 0)python3 chaos.py once create_ticket:after_effect
python3 show.pyagent printed 'start at step 1', exit code -9
agent printed 'start at step 3', exit code 0
tickets: [(1, 'run-1/create_ticket', 'Double charge, order 1042')]
emails: [(1, '[email protected]', 1)]
checkpoint 1: ['queue']
checkpoint 2: ['customer', 'queue']
checkpoint 3: ['customer', 'queue', 'ticket_id']
checkpoint 4: ['customer', 'queue', 'reply', 'ticket_id']
checkpoint 5: ['customer', 'queue', 'reply', 'ticket_id']
model calls: ['classify', 'draft_reply']The first process was killed after the ticket existed but before checkpoint 3 was saved. The second process found checkpoint 2, started at step 3, and called create_ticket again with the same key, so the service returned ticket 1 instead of creating ticket 2. The end state is identical to the baseline. One crash point proves little, though; the next step tries all of them.
06. Step 5: Every crash point
Without arguments, chaos.py first runs a clean baseline, then for each of the ten crash points starts from empty files, crashes, resumes, and compares outcome() with the baseline. outcome() is the definition of "same result" from the start of the lab: ticket titles, who got an email about which ticket, and whether the run finished. It leaves out the idempotency keys and the email wording. The script exits with code 1 if any point differs, so you can run it in CI.
python3 chaos.py; echo "exit code: $?"baseline: 1 ticket(s), emails for tickets [1], finished=True, model calls 2
classify:before exits [-9, 0] model calls 2 MATCH
classify:after_effect exits [-9, 0] model calls 3 MATCH
lookup_customer:before exits [-9, 0] model calls 2 MATCH
lookup_customer:after_effect exits [-9, 0] model calls 2 MATCH
create_ticket:before exits [-9, 0] model calls 2 MATCH
create_ticket:after_effect exits [-9, 0] model calls 2 MATCH
draft_reply:before exits [-9, 0] model calls 2 MATCH
draft_reply:after_effect exits [-9, 0] model calls 3 MATCH
send_email:before exits [-9, 0] model calls 2 MATCH
send_email:after_effect exits [-9, 0] model calls 2 MATCH
0 of 10 crash points differ from the baseline
exit code: 0Every point matches. The model calls column shows the cost side: crashing just after classify or draft_reply repeats one model call, because the answer was not saved yet. With a real model that is real money and latency, and a different answer. That is fine here because the run resumes with whatever the new call returns, but it is a reason to checkpoint straight after expensive steps.
07. Step 6: Break idempotency and watch the test fail
A test that has never failed has not shown that it can. Turn off the keys in the remote services and run the sweep again.
python3 chaos.py REMOTE_IDEMPOTENT=0; echo "exit code: $?"baseline: 1 ticket(s), emails for tickets [1], finished=True, model calls 2
classify:before exits [-9, 0] model calls 2 MATCH
classify:after_effect exits [-9, 0] model calls 3 MATCH
lookup_customer:before exits [-9, 0] model calls 2 MATCH
lookup_customer:after_effect exits [-9, 0] model calls 2 MATCH
create_ticket:before exits [-9, 0] model calls 2 MATCH
create_ticket:after_effect exits [-9, 0] model calls 2 DIFFERENT
got: 2 ticket(s), emails for tickets [2], finished=True
draft_reply:before exits [-9, 0] model calls 2 MATCH
draft_reply:after_effect exits [-9, 0] model calls 3 MATCH
send_email:before exits [-9, 0] model calls 2 MATCH
send_email:after_effect exits [-9, 0] model calls 2 DIFFERENT
got: 1 ticket(s), emails for tickets [1, 1], finished=True
2 of 10 crash points differ from the baseline
exit code: 1Exactly the two after_effect points of the side-effecting steps differ. After the crash in create_ticket, the resumed step created ticket 2, and the customer was emailed about ticket 2 while ticket 1 sits open with nobody watching it. After the crash in send_email, the customer got the same email twice. Every other point still matches, which is why testing one or two crash points by hand would probably have missed this.
08. Step 7: Checkpoint only at the end
python3 chaos.py CHECKPOINT=end; echo "exit code: $?"baseline: 1 ticket(s), emails for tickets [1], finished=True, model calls 2
classify:before exits [-9, 0] model calls 2 MATCH
classify:after_effect exits [-9, 0] model calls 3 MATCH
lookup_customer:before exits [-9, 0] model calls 3 MATCH
lookup_customer:after_effect exits [-9, 0] model calls 3 MATCH
create_ticket:before exits [-9, 0] model calls 3 MATCH
create_ticket:after_effect exits [-9, 0] model calls 3 MATCH
draft_reply:before exits [-9, 0] model calls 3 MATCH
draft_reply:after_effect exits [-9, 0] model calls 4 MATCH
send_email:before exits [-9, 0] model calls 4 MATCH
send_email:after_effect exits [-9, 0] model calls 4 MATCH
0 of 10 crash points differ from the baseline
exit code: 0All points still match, because the keys absorb every repeated effect. But every resume now starts from step 1, and the model calls climb to 3 and 4: work that fine-grained checkpoints did not repeat. Correctness came from idempotency; checkpoint granularity decides how much work and money a crash costs. You need both, and this harness measures both.
09. Check your understanding
10. Apply it
Point the same harness at your practice agent. List its crash points (before and after the effect of every step), write an outcome() that captures what the outside world should look like, and add the sweep to CI so it fails on any difference. Then add a test this lab left out: a remote write that succeeds while its reply is lost, as in lesson 3, so the resumed step cannot tell whether it happened. Show that the agent reconciles by key or lookup, and that a call with no key and no lookup stops with an "unknown outcome" item for review instead of claiming success.
11. Review prompt
Without looking back, explain why the lab crashes with SIGKILL rather than raising an exception, why each step has two crash points, and what outcome() compares and leaves out. Then describe what the sweep showed when idempotency was off and when checkpoints were saved only at the end, and which of the two problems was a correctness bug and which was a cost.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.