Skip to main content
LearnMLAcademy
Advanced10 min read

Durable & Long-Running Agents with Human-in-the-Loop

Implement durable long-running AI agents with human-in-the-loop checkpoints, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Keep a task safe across pauses, approvals and failures

Durable agents persist progress so a task can survive restarts, wait for an external event or human decision, and resume from a checkpoint without repeating completed side effects. Human-in-the-loop checkpoints pause automation when risk, uncertainty, or policy requires an authorized person to approve, reject, edit, or clarify the next action.

What You Will Learn

  • Persist checkpoints so work survives restarts and long waits.
  • Pause on events instead of holding a request open.
  • Design meaningful human approval with evidence and choices.
  • Resume only after expiry, authorization, and external state are revalidated.

Waiting is a stored state, not a sleeping request

A task that may wait hours for a person or external event should save a checkpoint, release the worker, and resume from a queue, schedule, or event. Keeping one web request or process open wastes resources and is easily lost during restarts.

An approval can expire or be cancelled. Before resuming a consequential action, reload the checkpoint, confirm that the reviewer still has authority, verify the decision has not expired, and recheck prices, permissions, inventory, or other external conditions that may have changed while the task waited.

Checkpoint, wait and resume from recorded state

  1. Persist typed task state and a checkpoint after meaningful work, including receipts for completed side effects.

  2. Use queues, schedules, or events instead of keeping one request alive while waiting for a reply, approval, or external system.

  3. Pause before high-risk or irreversible actions and show the reviewer the evidence, proposed action, consequences, and permitted choices.

  4. Record approval, rejection, edits, clarification, expiry, cancellation, and timeout as explicit events in the task state.

  5. Resume from the saved checkpoint, verify authorization and current conditions again, and use idempotency keys so completed actions are not repeated.

Instructional figure

A durable task can pause and safely resume

What must be saved before a task waits for a human decision?

Work
process item
Checkpoint
state + receipts
Pause
release worker
Human review
approve / edit / reject
Revalidate
authority + expiry + state
Resume
execute once
The worker releases resources while the checkpoint waits. Resume rechecks authorization, expiry, and external conditions before any side effect executes once.

Designing useful human intervention

Designing useful human intervention
TriggerReviewer must seeAllowed decisionsResume behaviorAudit record
High-impact actionEvidence, amount, recipient, consequencesApprove, reject, editRevalidate then execute onceReviewer, time, decision, receipt
Low confidence / conflicting evidenceSources, conflict and proposed interpretationClarify, choose source, stopUpdate state and continue from decisionEvidence and rationale
Expired wait / changed conditionsOriginal proposal and current stateRenew, revise, cancelNever reuse stale approval silentlyExpiry and revalidation result

Worked Example: Resume a supplier payment without replaying stale authority

Task PAY-204 pauses with quote Q-17 for $4,800, reviewer requirement 'finance', approval A-51 expiring at 17:00, attempt count 0, and idempotency key PAY-204 stored in checkpoint version 3.

  1. Pause: the workflow persists the checkpoint and releases its worker while a finance reviewer inspects the quoted amount and evidence.
  2. Wait: approval A-51 arrives, but the task resumes after 17:00. The supplier has also replaced Q-17 with Q-22 for $5,050.
  3. Revalidate: the runtime reloads version 3, re-authenticates requester U-17, confirms reviewer F-09's current authority, detects the expired approval and changed quote, and refuses to execute the old proposal.
  4. Resume: reviewer F-09 approves the revised amount as A-62. The payment executes with the original logical key PAY-204; receipt P-880 is recorded and any retry returns that receipt instead of paying twice.

What the result means: Durability preserves progress, not stale permission. Version 4 records the fresh quote, revised approval, one execution attempt, and receipt, making the eventual side effect auditable and exactly-once from the workflow's perspective.

Checkpoint before pause and authoritative state after resume

Checkpoint before pause and authoritative state after resume
FieldBefore pauseAfter resume / revalidation
Task and statePAY-204; version 3PAY-204; version 4 with revalidation event
Pending actionPay supplier $4,800Price changed: proposed payment $5,050
EvidenceQuote Q-17Fresh quote Q-22 replaces Q-17
Requester / reviewerRequester U-17; finance reviewer requiredU-17 re-authenticated; reviewer F-09 still authorized
Approval / expiryApproval A-51; expires 17:00A-51 expired; revised approval A-62 valid
Attempt / idempotencyAttempt 0; key PAY-204Attempt 1; same key PAY-204; receipt P-880

Instructional figure

Checkpoint, wait, revalidate, then resume exactly once

Why can an old approval not be replayed after external state changes?

Checkpoint v3
Pause + release worker
Old approval expires
Reload + re-authenticate
Price changed → revise
New approval
Execute key PAY-204 once

A stale approval never authorizes the changed action; the checkpoint records both decisions and the one execution receipt.

The first approval expires while the price changes. Resume reloads authoritative state, re-authenticates, detects staleness, requests revised approval, and executes once with the original idempotency key.

A Realistic Example: A document review that pauses for an authorized decision

The agent reviews many documents and checkpoints each completed result. A sensitive finding pauses with supporting evidence for a reviewer. After approval or a process restart, the worker resumes at the first unfinished document and does not resend notifications already recorded as delivered.

Read the Mechanism in Code

Use the label and note to understand what this block represents before reading each line.

Conceptual pseudocode
state = load_checkpoint(task_id)
for document in pending_documents(state):
    result = review(document)
    save_result(task_id, document.id, result)

    if result.requires_human_decision:
        checkpoint(task_id, status="waiting_for_review")
        return approval_queue.submit(result, required_role="reviewer")

    checkpoint(task_id, completed=document.id)
Learner note: Conceptual checkpoint/approval pseudocode. Storage, queue, and authorization helpers represent application infrastructure.

Hands-On Runnable Python Lab: Reload a SQLite Checkpoint and Reject a Changed Quote

This example writes a real SQLite file inside an automatically cleaned temporary directory, closes the connection, then opens it again to represent a replacement worker. The original approval covers $4,800 and expires at time 100.

may_resume_write = approval_not_expired AND approved_amount = current_amount
At time 110, the old approval fails both checks: it expired and the current quote is $5,050. A new approval must explicitly cover that changed amount.
  1. Store the original pending payment and approval in SQLite, then close the first connection.
  2. Reopen the same file and reload the saved state to prove it survives the connection lifecycle.
  3. Compare the old approval with time=110 and the new 5,050 quote. Deny execution.
  4. Record a revised approval valid until time 200. Revalidation now permits execution, but the example still performs no real payment.

Saved progress survives the worker; old approval does not authorize new terms

Worker 1 saves approval for 4,800 to SQLite and exits. Worker 2 restores it, rejects the expired approval for a changed 5,050 quote, and requires renewal.Worker 1Worker 2Approve 4,800expires at 100SQLitecheckpoint savedRestoretime now = 110worker exitsQuote 5,050old approval: NONew approval + recheck → eligiblePersistence ≠ permission
The dashed divider separates worker lifetimes. SQLite carries the checkpoint across them, but the replacement worker must revalidate time and amount.

The dashed divider separates worker lifetimes. SQLite carries the checkpoint across them, but the replacement worker must revalidate time and amount.

Complete Python ExercisepythonRunnable
import json
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory

def authorized(record, now, current_amount):
    return (now < record["expires"]
            and record["approved_amount"] == current_amount)

with TemporaryDirectory() as folder:
    path = Path(folder) / "checkpoint.db"
    record = {"task": "PAY-204", "stage": "WAIT_APPROVAL",
              "approved_amount": 4800, "expires": 100, "key": "PAY-204"}
    db = sqlite3.connect(path)
    db.execute("CREATE TABLE checkpoints (id TEXT PRIMARY KEY, payload TEXT)")
    db.execute("INSERT INTO checkpoints VALUES (?, ?)",
               (record["task"], json.dumps(record)))
    db.commit()
    db.close()

    db = sqlite3.connect(path)
    saved = db.execute("SELECT payload FROM checkpoints WHERE id = ?",
                       ("PAY-204",)).fetchone()[0]
    restored = json.loads(saved)
    print("restored:", restored["task"], restored["stage"])
    current_amount, now = 5050, 110
    print("old approval permits write:", authorized(restored, now, current_amount))
    restored.update(approved_amount=5050, expires=200)
    db.execute("UPDATE checkpoints SET payload = ? WHERE id = ?",
               (json.dumps(restored), restored["task"]))
    db.commit()
    print("renewed approval permits write:", authorized(restored, now, current_amount))
    print("logical operation key:", restored["key"])
    db.close()
print("real payments executed: 0")
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
restored: PAY-204 WAIT_APPROVAL
old approval permits write: False
renewed approval permits write: True
logical operation key: PAY-204
real payments executed: 0
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. The restored values come from disk, not a dictionary shared by two functions.
  2. Changing a quote does not silently change the old approval; the revised record represents a separate reviewer decision.
  3. The logical operation key is retained because no payment was executed before the pause. Once a key has executed, it must not be reused for a different payload.

Recovery is successful only when progress and authority are both correct. A resumed agent should be able to explain what was restored, what was rechecked and why the next action is still permitted.

From the Exercise to an Application

From the Exercise to an Application
SituationPractical choiceImportant qualification
Waiting hours for reviewPersist, release the worker and resume on an eventDo not depend on an open browser or HTTP request.
Crash after an external writeReconcile receipt or retry idempotentlyA checkpoint alone cannot prove the write did not happen.
Changed proposalObtain fresh approval for the current actionDo not treat an old yes as approval for new terms.
Experiment: Set now=90 but leave the current quote at 5,050.

The old approval is still denied. Being unexpired is necessary but insufficient: it covers 4,800, not the new amount.

Summary / Key Takeaways

  • Durable agents persist task progress so work can survive process restarts, long waits, and external events.
  • Checkpoints should capture typed state and receipts for completed side effects so resume does not repeat finished actions.
  • Waiting should be event-driven rather than keeping a request or model call alive indefinitely.
  • Human-in-the-loop checkpoints belong before high-risk, irreversible, low-confidence, or policy-sensitive actions.
  • A reviewer needs evidence, proposed consequences, authority, and meaningful approve/reject/edit choices—not a decorative approval button.
  • After a pause, the system should revalidate authorization and current conditions before continuing.
  • Timeouts, expiry, cancellation, idempotency, and audit events are part of durable execution, not optional operational details.

Verified Further Reading

These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Durable & Long-Running Agents with Human-in-the-Loop"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why should a long-running agent save checkpoints after meaningful work?
Question 2 of 5practical selection
A task is waiting two days for manager approval. What is the preferred architecture?
Question 3 of 5conceptual
What makes a human approval checkpoint meaningful?
Question 4 of 5debugging/diagnostic
An email was sent before a crash. After restart, the agent sends it again. Which control was missing?
Question 5 of 5application/scenario
Why should authorization be rechecked after a long pause before a consequential action?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why should a long-running agent save checkpoints after meaningful work?▼

Correct Answer: So execution can resume without repeating already completed work

Checkpoints preserve task progress and side-effect receipts so a restart can continue safely.

2A task is waiting two days for manager approval. What is the preferred architecture?▼

Correct Answer: Persist state, emit an approval event/task, and resume when a decision arrives

Long waits should be event-driven with persisted state rather than keeping compute/request resources alive.

3What makes a human approval checkpoint meaningful?▼

Correct Answer: Evidence, proposed action, consequences, reviewer authority, and approve/reject/edit choices

Reviewers need enough information and authority to make a real decision, not merely confirm an opaque proposal.

4An email was sent before a crash. After restart, the agent sends it again. Which control was missing?▼

Correct Answer: A receipt/idempotency check for the completed side effect

Durable systems must record completed side effects and use idempotency so resume does not duplicate them.

5Why should authorization be rechecked after a long pause before a consequential action?▼

Correct Answer: Authorization can change while the task is waiting

Permissions, data, prices, policies, and other conditions may change while the task is paused, so resumption should revalidate them.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next