Sub topic 7
Pausing and resuming with saved state
This chapter assumes you can read short Python programs, know how JSON serializes data, and know that a background job can run apart from the request that started it. It also assumes you have seen the approval gate from the earlier chapters.
Why a pause needs saved state
A simple gate calls ask_human and waits in the same process. That works in a terminal demo. It fails when the reviewer answers in an hour, when the server restarts, or when the request that started the run has already returned.
A paused run therefore has to exist outside the running process. When the agent reaches a gated call, you save everything needed to continue, stop the process, and resume later from the saved copy.
What to save
Save enough to rebuild the agent's situation, and nothing more:
- A run identifier, so the decision reaches the right run.
- The conversation so far, including earlier tool results.
- The pending tool call: its name and arguments.
- An approval identifier, used by the reviewer's response.
- An expiry time.
- Any step counters or budgets the loop tracks.
Do not save live objects such as open connections, clients, or function references. Store plain data and rebuild the objects on resume. If a value can't be written as JSON, it probably doesn't belong in the checkpoint.
The pause and resume cycle
The run moves through a small set of states. Only one decision can move it out of the paused state.
A minimal checkpoint store
This example keeps checkpoints in a dictionary. In production the dictionary becomes a database table, but the shape stays the same.
import json
import time
import uuid
STORE = {} # stands in for a database table
def pause(run_id, messages, call, ttl_seconds=3600):
approval_id = str(uuid.uuid4())
STORE[approval_id] = json.dumps({
"run_id": run_id,
"messages": messages,
"call": call,
"expires_at": time.time() + ttl_seconds,
})
return approval_id
def resume(approval_id, decision):
raw = STORE.pop(approval_id, None)
if raw is None:
raise KeyError("Unknown or already resolved approval")
state = json.loads(raw)
if time.time() > state["expires_at"]:
return {"status": "expired", "run_id": state["run_id"]}
return {"status": decision, "state": state}
messages = [{"role": "user", "content": "Email the report"}]
call = {"name": "send_email", "args": {"to": "[email protected]"}}
approval_id = pause("run-1", messages, call)
print(resume(approval_id, "approve")["status"])
try:
resume(approval_id, "approve")
except KeyError as error:
print("second attempt:", error)The first resume prints approve. The second raises an error, because pop removes the checkpoint as it reads it. Removing the entry on first use is what makes a decision single-use, so a repeated click or a retried webhook can't run the tool twice.
Common errors
- Saving state after the pause starts. Write the checkpoint before you notify the reviewer. Otherwise a fast reply can arrive before the state exists.
- Resuming without checking the checkpoint. Always check that the approval exists and hasn't expired before running anything.
- Reading and deleting in separate steps. With two workers, both can read the checkpoint before either deletes it. Use an atomic operation, such as a database transaction or a conditional update, to claim it.
- Pickling objects. Pickled state breaks when your code changes and is unsafe to load from untrusted storage. Use JSON.
- Ignoring schema changes. A run paused before a deploy may resume after it. Add a version field to the checkpoint so new code can reject or migrate old state.
Where this leads
A checkpoint tells you what was paused, but it doesn't prove the action that later runs matches what the reviewer saw. The binding chapter covers that with the fingerprint check.
Exercise
Two workers receive the same "approve" webhook at the same moment, and your resume code reads the checkpoint and then deletes it in a separate step. What can go wrong, and how do you fix it?
Show answer
Both workers can read the checkpoint before either deletes it, so both resume the run and the tool executes twice. Fix it by claiming the checkpoint atomically, for example with a single database transaction or a conditional update that succeeds for only one worker. The worker that fails to claim it should stop without running the tool.