Home / AI & GenAI

AI & GenAIRunbookAdvanced

Runbook: resuming long-running AI agent runs after a crash or deploy - checkpoints, leases and safe replay

Find agent runs orphaned by a pod restart, reclaim them with leases, and resume from the last checkpoint without re-running tool calls that already changed something.

Deepak Bhardwaj7 min read

Applies toPython agent workers on Kubernetes with a PostgreSQL run store; LangGraph 0.2+ checkpointers as an alternative (APIs vary by version)

An agent run that takes twenty minutes and forty tool calls will eventually meet a node drain, an OOM kill or a deploy. If run state lives only in the worker's memory, the run is lost, the user sees a spinner forever, and someone re-submits the task, which repeats every side effect. This runbook covers the recovery path when that happens, and the design it assumes: a durable run table, a step log and leases.

Symptoms

  • Runs stuck in running with no new steps for longer than any single step should take.
  • Users report a task that "stopped halfway"; the ticket or change it was working on is partly updated.
  • Worker pods restarted (kubectl get pods shows restarts or recent ages) around the time progress stopped.
  • After a naive retry: duplicate tickets, emails or changes.

The model this runbook assumes

CREATE TABLE agent_runs (
  run_id           uuid PRIMARY KEY,
  status           text NOT NULL,          -- queued|running|waiting_approval|done|failed|cancelled
  lease_owner      text,
  lease_expires_at timestamptz,
  attempt          int  NOT NULL DEFAULT 0,
  last_step        int  NOT NULL DEFAULT 0,
  updated_at       timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE agent_steps (
  run_id       uuid REFERENCES agent_runs,
  step_no      int,
  kind         text,                        -- llm|tool
  tool_name    text,
  idem_key     text,                        -- sent to the downstream API
  status       text,                        -- started|completed|failed
  request      jsonb,
  result       jsonb,
  started_at   timestamptz DEFAULT now(),
  completed_at timestamptz,
  PRIMARY KEY (run_id, step_no)
);

The rules that make recovery safe:

  1. Write a started step row, with its idempotency key, before calling a tool. Write completed with the result after.
  2. On resume, replay completed steps from the log: feed stored results back into the conversation. Never call those tools again.
  3. A step left in started is ambiguous. Resolve it by asking the downstream system, not by guessing.
  4. Workers hold a lease on a run and renew it. An expired lease means the owner is gone.

Step 1: Find orphaned runs

SELECT r.run_id, r.lease_owner, r.lease_expires_at, r.last_step, r.attempt,
       s.kind, s.tool_name, s.status AS step_status, s.started_at
FROM agent_runs r
LEFT JOIN agent_steps s
  ON s.run_id = r.run_id AND s.step_no = r.last_step
WHERE r.status = 'running'
  AND r.lease_expires_at < now() - interval '1 minute'
ORDER BY r.lease_expires_at;

Cross-check the lease owners against live pods. A lease owner that still exists but stopped renewing usually means a hung event loop, not a dead pod.

kubectl get pods -n agents -l app=agent-worker \
  -o custom-columns=NAME:.metadata.name,RESTARTS:.status.containerStatuses[0].restartCount,START:.status.startTime
kubectl logs -n agents <pod> --previous --tail=200   # why the old container died

Warning

Do not bulk-reset stuck runs to queued before checking the last step. If the last step is a started tool call, resuming blindly repeats it.

Step 2: Classify the last step

Last step state Meaning Action
No step, or completed Clean boundary Safe to resume automatically
started, kind llm Model call interrupted Safe to resume; the LLM call is simply repeated
started, read-only tool Lookup interrupted Safe to resume; re-run the read
started, write tool with idempotency key the API honours Downstream dedupes Resume; the retry with the same key is absorbed
started, write tool without idempotency support Unknown if it happened Check the downstream system, then mark the step manually
waiting_approval run Not orphaned, waiting on a human Leave it; check approval queue age instead

Check an ambiguous write against the target system using the key or a correlation ID you stored in request:

# Example: did the ticket get created? (ServiceNow-style API, adjust to your system)
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://itsm.example.com/api/now/table/incident?sysparm_query=correlation_id=$IDEM_KEY&sysparm_fields=number,sys_id"

Then record what you found so the resume replays it rather than re-executing:

-- It happened: store the real result
UPDATE agent_steps
SET status = 'completed', completed_at = now(),
    result = '{"recovered": true, "ticket": "INC0012345"}'::jsonb
WHERE run_id = :run_id AND step_no = :step_no AND status = 'started';

-- It did not happen: mark failed so the agent re-plans or retries with the same key
UPDATE agent_steps
SET status = 'failed', completed_at = now(),
    result = '{"recovered": true, "error": "not executed before crash"}'::jsonb
WHERE run_id = :run_id AND step_no = :step_no AND status = 'started';

Step 3: Reclaim and resume

Workers should pick up expired runs themselves. The claim query must be atomic so two workers can't take the same run:

UPDATE agent_runs
SET lease_owner = :worker_id,
    lease_expires_at = now() + interval '60 seconds',
    attempt = attempt + 1,
    updated_at = now()
WHERE run_id = (
  SELECT run_id FROM agent_runs
  WHERE status = 'running'
    AND lease_expires_at < now()
    AND attempt < 5
  ORDER BY lease_expires_at
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
RETURNING run_id, last_step;

The resume logic rebuilds the conversation from the step log:

def resume(run_id, db, llm, tools):
    steps = db.fetch_steps(run_id)                    # ordered by step_no
    messages = db.fetch_initial_messages(run_id)
    for s in steps:
        if s.status == "started" and s.kind == "tool" and tools[s.tool_name].writes:
            raise NeedsHumanReview(run_id, s.step_no)  # step 2 not done yet
        if s.status == "completed":
            messages.extend(replay_messages(s))       # assistant tool call + stored result
    return run_loop(run_id, messages, start_step=len(steps), db=db, llm=llm, tools=tools)

Cap attempt. A run that crashes its worker every time (a huge tool output, a poisoned input) should go to failed with an alert after a few attempts, not loop through every pod in the deployment.

Caution

The model may choose a different next step on resume, because LLM output is not deterministic. That is acceptable for the steps not yet taken, but it is the reason stored results must be replayed and never regenerated.

If you use LangGraph

LangGraph's checkpointers (for example the PostgreSQL saver) persist graph state per thread_id after each super-step. Re-invoking the compiled graph with the same thread_id and None as input continues from the last checkpoint. The checkpoint boundary is the node, so a node that calls a write tool and then crashes is re-run on resume: keep one side effect per node and pass an idempotency key derived from thread_id and the node name. Check the API for your installed version; package and class names have moved between releases.

Step 4: Close out

-- Runs that exhausted attempts: fail them and notify the requester
UPDATE agent_runs SET status = 'failed', updated_at = now()
WHERE status = 'running' AND attempt >= 5 AND lease_expires_at < now()
RETURNING run_id;

Tell users what state their task is in, including which steps completed. "Ticket created, change not yet applied" is better than a silent failure.

Prevent it next time

  • Handle SIGTERM in workers: stop taking new steps, finish or checkpoint the current one, release the lease. Set terminationGracePeriodSeconds longer than your slowest tool call.
  • Add a PodDisruptionBudget for the worker deployment so a node drain doesn't kill every worker at once.
  • Renew leases from a separate task, and alert when renewals lag; a blocked event loop looks like a dead worker.
  • Make every write tool accept an idempotency key, and reject tools that can't support one, or put them behind human approval.
  • Store large tool outputs by reference (blob path plus hash) so the step log stays small and replay is fast.
  • Alert on runs in running with no new step for longer than the step timeout, and on runs with attempt > 1.
  • Drill it: kill a worker mid-run in staging every release and check the run completes with no duplicate side effects.