Sub topic 7
Pausing and resuming with saved state
This chapter covers how a workflow stops at an approval gate and later continues, possibly hours later and possibly in a different process. It assumes you have read the chapters on the agent loop and approval gates. You should be comfortable with Python dataclasses, JSON, and the idea of a background job.
Why a pause needs saved state
An approval gate that calls input() or waits on a thread works for a demo. It fails in production for three reasons:
- A reviewer may take hours or days to respond.
- The process may restart, deploy, or crash while it waits.
- Holding a worker, a connection, or a model session open for each pending approval wastes resources.
The fix is to treat a pause as the end of a run, not a wait inside it. The workflow writes down everything it needs, stops, and releases its resources. When a decision arrives, a new run loads that record and continues.
This changes what the gate is. It no longer returns a decision. It returns a signal that the run is suspended, and a separate entry point handles the decision later.
What belongs in a checkpoint
A checkpoint is the minimum data a fresh process needs to continue as if it had never stopped. For an agent loop, that usually means:
| Field | Purpose |
|---|---|
| `run_id` | Identifies the workflow run. |
| `messages` | The conversation so far, including earlier tool results. |
| `pending_call` | The tool name and arguments waiting for a decision. |
| `approval_id` | Links the checkpoint to one approval request. |
| `fingerprint` | Hash of the pending call, used later to bind the approval. |
| `status` | Where the run is in its life cycle. |
| `version` | A counter used to detect concurrent updates. |
Do not store things that cannot be serialized, such as open sockets, client objects, or function references. Store names and arguments, then look up the real tools again when the run resumes. This is why the earlier examples keep a tools dictionary separate from ToolCall.
A serializable state record
import hashlib
import json
import time
from dataclasses import dataclass, field, asdict
def fingerprint(name: str, args: dict) -> str:
payload = json.dumps({"name": name, "args": args}, sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()
@dataclass
class RunState:
run_id: str
messages: list
pending_call: dict | None = None
approval_id: str | None = None
fingerprint: str | None = None
status: str = "running" # running, waiting, done, rejected, expired
version: int = 0
updated_at: float = field(default_factory=time.time)
def to_json(self) -> str:
return json.dumps(asdict(self))
@classmethod
def from_json(cls, text: str) -> "RunState":
return cls(**json.loads(text))
state = RunState(
run_id="run-42",
messages=[{"role": "user", "content": "Email the weekly report to the team."}],
)
state.pending_call = {"name": "send_email", "args": {"to": "[email protected]"}}
state.fingerprint = fingerprint("send_email", {"to": "[email protected]"})
state.status = "waiting"
restored = RunState.from_json(state.to_json())
print(restored.status, restored.pending_call["name"])The round trip through JSON is the test of a good checkpoint. If from_json(to_json(state)) loses information, a resumed run will behave differently from an uninterrupted one.
The status life cycle
Giving the run an explicit status makes resume logic simple. Only a run in waiting accepts a decision. Every other status is a refusal.
This table is the same logic as a rulebook you can test:
| Current status | Event | Next status |
|---|---|---|
| `running` | gate reached | `waiting` |
| `waiting` | approve or edit | `running` |
| `waiting` | reject | `rejected` |
| `waiting` | timeout | `expired` |
| `running` | no more steps | `done` |
A decision that arrives for a run in any other state is a duplicate or a stale message. Ignore it, or report it, but never execute it.
Suspending at the gate
The earlier gate function ran the tool or returned a rejection. In a persistent design, the gate has a third outcome: suspend. The sketch below uses an in-memory dictionary as the store. A real system would swap it for a database table with the same interface.
import uuid
STORE: dict[str, str] = {} # run_id -> serialized RunState
def save(state: RunState) -> None:
state.version += 1
state.updated_at = time.time()
STORE[state.run_id] = state.to_json()
def load(run_id: str) -> RunState:
return RunState.from_json(STORE[run_id])
def suspend_for_approval(state: RunState, name: str, args: dict, notify) -> str:
approval_id = str(uuid.uuid4())
state.pending_call = {"name": name, "args": args}
state.fingerprint = fingerprint(name, args)
state.approval_id = approval_id
state.status = "waiting"
save(state) # write first
notify(approval_id, name, args) # then tell the reviewer
return approval_idThe order matters. Save the checkpoint before you notify the reviewer. If you notify first and the save fails, the reviewer can answer a request that has no stored run behind it. If you save first and the notification fails, you have a waiting run nobody knows about. That second failure is recoverable, because a periodic job can find old waiting runs and resend the request. The first is not.
Resuming from a decision
The resume function is the other half of the gate. It loads the state, checks that the decision is valid for it, applies the decision, and continues the loop.
def resume(run_id: str, approval_id: str, decision: dict, tools: dict) -> RunState:
state = load(run_id)
if state.status != "waiting" or state.approval_id != approval_id:
raise ValueError("No pending approval matches this decision")
call = state.pending_call
action = decision["action"]
if action == "reject":
state.status = "rejected"
state.messages.append({
"role": "tool",
"name": call["name"],
"content": f"Rejected by reviewer: {decision.get('reason', '')}",
})
save(state)
return state
args = call["args"]
if action == "edit":
args = decision["args"]
elif state.fingerprint != fingerprint(call["name"], args):
raise PermissionError("Stored call changed after approval was requested")
result = tools[call["name"]](**args)
state.messages.append({"role": "tool", "name": call["name"], "content": str(result)})
state.pending_call = None
state.approval_id = None
state.status = "running"
save(state)
return stateThree details are worth noting.
- The approval ID is checked, not just the run ID. A reviewer who answers an old request must not approve a newer one.
- Rejection is written into the conversation. The agent can then read the reason on its next step and choose another path. That is how feedback reaches the model.
- State is cleared after execution. Leaving
pending_callset would let a duplicate message run the same call twice.
After resume returns a running state, the caller starts the agent loop again with state.messages. The model sees the tool result as if the call had never been paused.
Edge cases
Duplicate and concurrent decisions
Two reviewers may click at the same time, or a webhook may be delivered twice. Both calls load a waiting state, and both execute. The status check alone does not stop this, because the check and the write are separate steps.
Use an atomic compare-and-set when saving. The version field exists for this purpose. In SQL, the update looks like this:
UPDATE run_state
SET status = 'running', version = version + 1
WHERE run_id = :run_id AND status = 'waiting' AND version = :seen_version;If the update changes zero rows, another process won, and this one must stop before running the tool. Claim the decision first, then execute. For tools that can run twice by mistake, such as sending an email, also pass an idempotency key derived from approval_id so the downstream service can reject a repeat.
Crash after execution but before save
If the process dies after the tool runs and before the state is saved, the run still looks like waiting. A retry would run the tool again. Two defenses help:
- Claim the decision before executing, with a status such as
executing, so a retry can tell the work started. - Use idempotency keys on the tool call so a second attempt is harmless.
You cannot make this perfectly safe for every external system. You can make it detectable, and an executing run that stays old is a clear signal for an operator to check.
Schema changes while a run is paused
A run saved on Monday may resume on Friday, after a deploy changed the state shape. Add a schema_version field when you expect long pauses. On load, upgrade old records to the current shape, or refuse them with a clear error. A from_json that fails with an unexpected-argument error is a poor way to find out.
Stale context
The world can change while a run waits. A record the agent planned to delete may already be gone. A customer's address may have changed. For long pauses, have the tool re-check its preconditions at execution time and return a clear error, rather than assuming the checkpoint is still true.
Sensitive data in checkpoints
The checkpoint holds the conversation and tool arguments. These may contain personal data or secrets. Encrypt the store, limit who can read it, and set a retention period. Never put credentials in messages or args. Have the tool fetch them at execution time.
Checking your understanding
A quick way to test a persistence design is to simulate the process boundary. Serialize, throw away every object, and resume from the stored text only.
tools = {"send_email": lambda to: f"sent to {to}"}
run = RunState(run_id="run-7", messages=[])
sent = []
approval_id = suspend_for_approval(
run, "send_email", {"to": "[email protected]"},
notify=lambda aid, name, args: sent.append(aid),
)
del run # simulate a restart: only STORE survives
final = resume("run-7", approval_id, {"action": "approve"}, tools)
print(final.status, final.messages[-1]["content"])
try:
resume("run-7", approval_id, {"action": "approve"}, tools)
except ValueError as err:
print("second decision refused:", err)The first resume prints running sent to [email protected]. The second raises, because the run no longer has a pending approval. Both outcomes confirm the checkpoint carries the whole decision context and that a repeat cannot run the tool again.
Exercise
A reviewer approves a request, but the worker crashes after the tool sends an email and before the new state is saved. When the decision is redelivered, the run still shows waiting. Name two changes that keep the email from being sent twice.
Show answer
First, claim the decision with an atomic update that moves the run to an executing status (using the version check) before calling the tool, so a retry can see the work already started and stop or hand it to an operator. Second, pass an idempotency key derived from the approval ID to the email service so a repeated send is ignored. Saving state after execution alone is not enough, because the crash can happen between the two steps.
Exercise
Why does suspend_for_approval save the checkpoint before it notifies the reviewer?
Show answer
If the notification went out first and the save then failed, the reviewer could answer a request with no stored run behind it, and the decision would be lost. Saving first only risks a waiting run the reviewer never heard about, which a periodic sweeper can find and re-notify.
Exercise
List four fields a checkpoint needs so a new process can resume a paused run, and say why you should not store a live client object in it.
Show answer
Any four of: run ID, messages, pending call, approval ID, fingerprint, status, version. A live client object such as a socket or SDK client cannot be serialized, and it would be invalid after a restart. Store names and arguments instead, and rebuild the tools from configuration when the run resumes.