Skip to main content

What Happens When Nobody Clicks Approve? Durable Approval Steps for Django Agent Runs (Part 13)

Park the run so no worker waits, record one decision under a row lock, escalate or reject on timeout, and resume from checkpoints with the answer.

Updated 18 min readMarkdown
What Happens When Nobody Clicks Approve? Durable Approval Steps for Django Agent Runs (Part 13)

On November 19, AWS made its Lambda Durable Execution SDK for Rust generally available. One of the use cases in the announcement is "pipelines that call AI models and pause for human review", and durable functions can "pause execution for up to one year when waiting on external events." Ten days earlier, Microsoft made the Durable Task extension for Microsoft Agent Framework generally available, and its pitch includes workflows that "wait for approvals or external events without keeping a worker running."

Compare that with the Claude Agent SDK's user input docs, which describe the in-process version: "The callback can stay pending indefinitely. Execution remains paused until your callback returns." The same page then gives the way out. If a user might take longer than your process can stay up, register a hook "that returns the defer decision instead of waiting in the callback, so the process can exit and resume later from the persisted session."

That's the whole post in two quotes. When an agent run waits for a person, the waiting belongs in the database as a state, not in a sleeping thread or a callback nobody returns.

This is Part 13 of Shipping AI Agents in Django. Part 1 modelled approvals as data: a proposal row, risk tiers, an append-only audit log, and expiry. Part 12 moved agent runs into a Postgres queue with leases and checkpointed steps. This part combines them: a background run reaches a step that needs a human, parks, and resumes with the decision, however long it takes.

Short version

  • Waiting is a run status, not a sleeping worker. The worker records an approval request, releases its lease and moves on. A waiting run doesn't hold the tenant's concurrency slot.
  • The request stores a snapshot of what the reviewer approves, plus its hash. The action is applied to that snapshot (or the reviewer's edit), never to a value recomputed later.
  • A decision is recorded once, under a row lock. A retried click gets a 200 replay. A different second decision gets a 409. A decision made against an old payload hash gets a 409 stale_payload.
  • A timer applies the deadline: escalate once, then reject. A timeout never approves anything with side effects.
  • Resume is Part 12's replay: finished steps and the decision come back from checkpoints, and the run continues past the gate.
  • Every request, decision, refusal, escalation and timeout is an audit row.

The demo is Part 12's Django 5.2 app plus an approvals module. On PostgreSQL 17.12 it has 127 passing tests: Part 12's 110, unchanged, plus 17 new.

What a wait costs if you do it in the worker

Part 12's workers hold a lease and extend it at each checkpoint. A worker that goes quiet for longer than lease_s (60 seconds in the demo) loses the run to the reaper, which counts a failure. Each tenant also has a concurrency cap: one running run for a standard tenant.

Now put time.sleep() in front of an approval. The worker has to keep extending its lease for as long as the reviewer takes, or the reaper requeues the run and a second worker asks again. The tenant's one slot is held by a run doing nothing. A deploy kills the sleeping process, and the wait starts over. AWS's durable functions best-practices page makes the same point about its own runtime: language sleeps "keep the invocation running and reset to zero on replay."

So the wait has to live somewhere that survives the worker. Every framework below agrees on that; the details are where they differ.

How the durable-execution tools handle a human wait

LangGraph pauses with interrupt() and resumes with Command(resume=...) on the same thread_id. Per the interrupts docs, the graph "waits indefinitely until you resume execution", and on resume "the runtime restarts the entire node from the beginning". Code before the interrupt() runs again, which is why the docs say "Side effects called before interrupt must be idempotent." They also cover the case where the request changes during the pause: "submit a new governed job instead of rewriting the original through the resume payload."

AWS Lambda durable functions use callbacks. The callback docs say "The function does not incur compute charges while suspended", and an external system resumes it with the callback ID. On resume, per the examples page, "Lambda invokes your function again and replays from the checkpoint, continuing with the approval result." The best-practices page is blunt: "Always set a timeout on waitForCallback to avoid stalled executions."

AWS Step Functions has .waitForTaskToken. Per the service integration docs, a waiting task "will wait until the execution reaches the one year service quota" unless you set HeartbeatSeconds.

Azure Durable Functions uses WaitForExternalEvent and RaiseEventAsync. The external events docs say the API "waits indefinitely by default", and for human approvals "you should race a durable timer against the external event so your orchestration can take action (escalate, reject, retry) if the event doesn't arrive within a deadline." They also warn that "external events have an at-least-once delivery guarantee" and recommend events carry "some kind of ID that allows them to be manually de-duplicated." In the Agent Framework GA post, the C# sample passes timeout: TimeSpan.FromHours(24). The Python sample calls wait_for_external_event("HumanApproval") with no timeout at all.

Dapr workflows handle the early event: if one arrives before the workflow waits for it, "the event will be saved into the workflow's history and consumed immediately after the workflow requests the event" (features and concepts).

Temporal offers Signals ("you cannot await any response or error") and Updates ("synchronous, tracked write requests"), per its message passing docs. One reason to pick an Update: "You want to validate the Update before accepting it into the Workflow and its history."

The OpenAI Agents SDK serializes a paused run as RunState. Its human-in-the-loop guide has the best security section I found: "Possession of a run ID or decision ID is not authorization", "Do not take the reviewer's identity from the approval request body", and "Coordinate consumption of each pending request with storage so concurrent or replayed submissions cannot resume the same snapshot twice." And: "Approval permits a tool call to execute; it does not guarantee exactly-once execution."

MCP elicitation isn't a durable wait, but its response model keeps a useful distinction. Besides accept and decline there's cancel: "User dismissed without making an explicit choice." Nobody answering isn't the same as someone saying no.

Put together, the docs agree on four things:

  1. The wait is persisted state; the worker goes away.
  2. Waits default to forever; the Azure and AWS docs tell you to add a deadline.
  3. Decisions can arrive twice, early or concurrently: dedupe, and pick one winner.
  4. Resuming means replaying. Code before the wait runs again unless it's checkpointed.

If you run one of these engines, use its primitive. If your runs live in Postgres, as in Part 12, all four fit in two tables.

Step 1: a status and a request row

The run gets one new status:

class Status(models.TextChoices):
    QUEUED = "queued"
    RUNNING = "running"
    WAITING = "waiting"   # Part 13: parked at an approval step; no worker, no lease
    DONE = "done"
    FAILED = "failed"

The approval request holds everything the decision needs, including the snapshot:

class ApprovalRequest(models.Model):
    run = models.ForeignKey(AgentRun, on_delete=models.CASCADE, related_name="approvals")
    step = models.CharField(max_length=150)                # the checkpoint name it gates
    tenant = models.CharField(max_length=50)
    action = models.CharField(max_length=50)               # picks the edit validator
    token = models.CharField(max_length=64, unique=True)   # reviewer link; NOT authorization
    payload = models.JSONField()
    payload_hash = models.CharField(max_length=64)
    allowed = models.JSONField()                           # e.g. ["approve", "reject", "edit"]
    on_timeout = models.CharField(max_length=10)           # "escalate" or "reject"
    status = models.CharField(max_length=10, choices=Status.choices, default=Status.PENDING)
    escalations = models.PositiveSmallIntegerField(default=0)
    expires_at = models.DateTimeField()
    decision = models.CharField(max_length=10, blank=True)
    decided_by = models.CharField(max_length=100, blank=True)
    final_payload = models.JSONField(null=True)            # payload, or the reviewer's edit
    # + id (UUID), decided_at, created_at; unique (run, step)

Next to it sits an append-only AuditEvent table: run, approval, kind (requested, decided, refused, escalated, timed_out, resumed), actor (a reviewer, worker:<id> or system:timer), detail and time.

The unique constraint on (run, step) is what makes "ask once" hold across crashes: a replayed run finds its existing request instead of opening a second one.

Step 2: ask, then park

The demo workflow re-checks a batch of posts (Part 12), then asks a person before emailing the authors of the hidden ones. A hide can be undone; an email can't, so the email goes behind the gate:

proposal = {"notify": hidden, "notice": data.get("notice", "Your post was hidden under our policy.")}
ok = ctx.approval("approve:author_notice", "author_notice", proposal,
                  allowed=("approve", "reject", "edit"), on_timeout="escalate")
if ok["decision"] == "reject":
    return {"checked": len(actions), "notified": [], "decision": "reject", "by": ok["by"]}
final = ok["payload"]                 # the snapshot the reviewer approved, or their edit
notify = import_string(settings.RUN_NOTIFY)
if final["notify"]:
    ctx.effect("send:author_notice", lambda key: notify(
        ctx.run.tenant, {"run": str(ctx.run.pk), "notify": final["notify"],
                         "notice": final["notice"]}, key))

ctx.approval() sits on top of Part 12's checkpoints:

def approval(self, name, action, payload, allowed=("approve", "reject"), on_timeout="escalate"):
    s = self.done.get(name)
    if s and s.status == RunStep.Status.DONE:
        return s.output                          # decided earlier: replay, don't ask again
    req = approvals.request(self, name, action, payload, allowed, on_timeout)
    self.effect(f"{name}:ask", lambda key: approvals.notify_reviewers(
        req, approvals.reviewers_for(req), key))
    req.refresh_from_db()
    if req.status not in approvals.FINAL:
        raise approvals.Park(req.pk)
    out = approvals.outcome(req)
    self._save(name, RunStep.Status.DONE, out, also=lambda: approvals.audit(
        self.run.pk, req, "resumed", f"worker:{self.run.worker}", {"decision": req.decision}))
    return out

request() creates the row inside a fenced transaction, so a zombie worker can't open approvals. The reviewer ping is a Part 12 effect() with a stable idempotency key: a worker that dies after the ping re-sends with the same key, and the receiver dedupes. The test for that window ends with one request row, two pings sharing one key, and no repeated model calls.

Park is an exception, like LangGraph's interrupt(), which per its docs "propagates up through the call stack and is caught by the runtime". The worker catches it and releases the lease:

def park(run, approval_id, release) -> str:
    """Release the lease as WAITING, unless the decision already landed while we were still
    running (a fast reviewer). Takes the same row lock as decide(), so no wake-up is lost."""
    with transaction.atomic():
        req = ApprovalRequest.objects.select_for_update().get(pk=approval_id)
        if req.status in FINAL:
            status, fields = "queued", {"available_at": _now(), "note": ""}
        else:
            status, fields = "waiting", {"note": f"approval:{req.step}"[:100]}
        ok = release(run, status=status, **fields)    # fenced: only the lease holder parks
    return status if ok else "lease_lost"

The row lock matters. A decision wakes a run by flipping it from waiting to queued. If a fast reviewer decides while the worker is still between "ask" and "park", there's no waiting row to flip yet. Without the lock and re-check, the worker would park a run whose decision already exists, and it would sit until the timer rejected it: the classic lost wake-up, the problem Dapr solves by saving early events into history. Here both sides take the approval row's lock, so either the decision sees a waiting run, or the park sees a decision. A test lands the decision exactly in that gap.

A parked run has no worker and no lease, so Part 12's reaper and concurrency count both ignore it, and the tenant's slot is free. The status endpoint reports waiting_for: "approval" with the request's id, deadline and allowed decisions (not its token), and poll_after_s: 60 instead of 2.

Step 3: one decision, and the ways to refuse one

The reviewer gets a link with the token, loads the snapshot and its hash, and posts a decision. Taking the OpenAI SDK's advice, the token only finds the request. Who's deciding comes from authentication (a header in the demo, your session middleware in real life) and is checked against the tenant's reviewer list.

def decide(token, tenant, reviewer, decision, payload_hash, edited=None) -> tuple[int, dict]:
    now = _now()
    with transaction.atomic():
        req = ApprovalRequest.objects.select_for_update().filter(token=token, tenant=tenant).first()
        if req is None:
            return 404, {"error": "not_found"}
        # refuse() writes an audit row, then returns the status and body
        if reviewer not in reviewers_for(req):
            return refuse(403, "not_a_reviewer")
        if req.status in FINAL:
            same = (req.status == DECIDED and req.decided_by == reviewer and req.decision == decision
                    and (decision != "edit" or _hash(edited) == _hash(req.final_payload)))
            if same:                          # a retried click: same answer, nothing new
                return 200, {"status": req.status, "decision": req.decision, "replayed": True}
            return refuse(409, "already_decided", decision=req.decision, decided_by=req.decided_by)
        if now >= req.expires_at:
            return refuse(409, "expired")     # the timer owns it now
        if decision not in req.allowed:
            return refuse(422, "decision_not_allowed", allowed=req.allowed)
        if payload_hash != req.payload_hash:
            return refuse(409, "stale_payload", payload_hash=req.payload_hash)
        if decision == "edit" and not _edit_ok(req, edited):
            return refuse(422, "invalid_edit")
        # record the decision and final_payload, audit "decided", then wake the run

Three choices in there are worth arguing about.

What counts as idempotent. A retry with the same reviewer, decision and edit gets replayed: true. Anything else after the first decision is a 409, including the same decision from a different reviewer. Bob clicking "approve" after Alice doesn't change the outcome, but a 200 would let him believe he was the approver. The 409 tells him who decided.

The hash is a precondition. The reviewer posts the hash of the snapshot they looked at. If it doesn't match (a stale tab, say), they get a 409 with the current hash. Same idea as Temporal's Update validators: check before accepting into history.

Edits can narrow, not widen. An edit is an approval with changes, checked against a per-action rule. The demo's rule is a heuristic, not a standard: a reviewer may drop recipients or reword the notice, but not add recipients. Widening is a new proposal that someone should approve as one, which is also LangGraph's advice above.

Every refusal writes an audit row in the same transaction, so "mallory had the link and tried to approve" is on the record.

Step 4: the timer decides what silence means

The demo's timer runs in each worker's loop, next to Part 12's lease reaper:

def expire() -> int:
    """Apply the timeout policy to overdue requests: escalate once, then reject."""
    now, n, to_notify = _now(), 0, []
    cfg = settings.APPROVALS
    with transaction.atomic():
        overdue = ApprovalRequest.objects.select_for_update(skip_locked=True).filter(
            status__in=OPEN, expires_at__lte=now)
        for req in overdue:
            n += 1
            if req.on_timeout == "escalate" and req.escalations < cfg["max_escalations"]:
                req.status, req.escalations = ESCALATED, req.escalations + 1
                req.expires_at = now + timedelta(seconds=cfg["escalate_ttl_s"])
                ...   # save, audit "escalated", queue a ping to reviewers + escalate_to
                continue
            # Out of escalations, or the policy says reject. Not approving is the safe default:
            # the run continues down its "rejected" branch, and nothing irreversible happens.
            req.status, req.decision, req.decided_by, req.decided_at = EXPIRED, "reject", "system:timeout", now
            ...   # save, audit "timed_out", wake the run

SKIP LOCKED means the timer steps around a request a reviewer is deciding right now, and picks it up next tick if it's still open. On PostgreSQL that's tested with a thread holding the row lock.

The policy vocabulary is deliberately small: escalate or reject. request() raises ValueError on on_timeout="approve", and a test keeps it that way. My heuristic: for any step with side effects, silence is never consent. If a step is safe to auto-approve after a deadline, it probably doesn't need a human gate at all; make it a notification instead.

Escalation adds the escalate_to reviewers for a second window; the original reviewers can still decide in it. After that, the request expires as a rejection by system:timeout, and the run finishes down the reject branch with nothing sent. A decision after the deadline but before the timer runs gets a 409 expired: the clock sets the deadline, not whoever clicks first.

In MCP's terms, this timeout is a cancel, not a decline: nobody chose. The demo records it with decided_by: "system:timeout", so you can tell the two apart in the audit log and in the run's result.

Step 5: resume is just replay

When a decision lands, the run goes back to queued with available_at = now. Any worker can claim it through Part 12's fair queue. The workflow starts from the top:

  • The per-post decide:* steps return from checkpoints: one model call per post, however often the run parks.
  • The :ask effect is done, so nobody is pinged again.
  • ctx.approval() finds the decided request, checkpoints its outcome with a resumed audit row, and returns it.
  • On approve or edit, send:author_notice runs once with its own idempotency key. On reject or timeout, it never runs.

One check comes first: request() recomputes the proposal's hash and compares it with the stored one. If they differ (a deploy changed the wording, or a step isn't deterministic), the run fails with approval_payload_changed instead of applying Alice's approval to something she never saw. Retrying wouldn't help, so it fails at once.

Even then, the OpenAI SDK's warning holds: approval doesn't make the send exactly-once. If the worker dies after the email provider accepted the message but before the checkpoint, the resumed run sends again with the same key. Only a receiver that dedupes on that key turns "at least once" into "once."

What the audit trail looks like

Approved: requested → decided → resumed. Nobody answered: requested → escalated → timed_out → resumed. Contested: requested → decided → refused → refused, each refusal with its reason and actor. As in Part 1, an edit is an eval case: final_payload next to payload is a labelled example of what the agent should have proposed.

Trade-offs I haven't solved

The escalation ping goes out after commit. If the process dies between the commit and the ping, the escalation is recorded but nobody hears about it. An outbox row written in the same transaction fixes that, and I haven't added one.

Snapshots hold data. If the payload contains personal data, it needs a retention rule like Part 12's step outputs. Store references where you can.

Reviewer lists are read live. If Bob leaves mid-wait, he can't decide, which is right, but editing the escalation list also changes who can act on old requests. And the demo doesn't re-check permission when the send actually happens.

One gate, one decider. A two-approver rule needs a count of decisions, not one row. The locking idea stays.

What the tests prove

pytest -q with DEMO_PG=1: 127 passed (Python 3.13.5, Django 5.2.19, PostgreSQL 17.12, psycopg 3.3.9, pydantic 2.14.3, pytest 9.2.0, pytest-django 4.14.0, redis-py 8.2.0, fakeredis 2.41.0 with lupa 2.8). It was stable over 10 runs and also passes against a real Redis 8.0.2. On SQLite: 122 passed and 5 skipped, the five tests that need real row locks.

The 17 new tests cover parking (worker and slot freed, no token in the status body), approve/edit/reject resumes (one model call per post, one ping, one send or none), replayed and conflicting decisions, every refusal code, escalate-then-reject, late decisions, on_timeout="approve" refused, a crash after the ping, a decision landing before the park, and a changed proposal failing the run. On Postgres only: two reviewers at once yield exactly one decision, and the timer skips a locked request.

Reviewers, pings, the receiver and the model are scripted. The tests prove bookkeeping, not how people answer approvals.

The series so far

  1. Human-in-the-loop AI agents in Django: approval gates
  2. Least-privilege agent identity in Django
  3. Your MCP server is a second API
  4. Permission-aware RAG without post-filters
  5. Cost per successful workflow
  6. Tracing agent runs with OpenTelemetry
  7. Structured outputs that don't break
  8. AI moderation helpers with appeals
  9. Shipping prompt and model changes safely
  10. Provider fallbacks without surprises
  11. Per-tenant rate limits and token budgets
  12. Background agent runs: fair queues, checkpoints, status
  13. Runs that wait for people (this post)

Next, Part 14: testing agent runs end to end against recorded traces. A run's checkpoints, decisions and audit rows are already a recording; Part 14 replays them in CI to catch a change that would take a different path.

Open question for readers

The trade-off I keep going back and forth on: should a reviewer approve the snapshot or the intent? This demo approves a snapshot. Alice approves "email these two authors with this text", and if anything about that proposal changes before the send, the run fails rather than act on something she didn't see. That's easy to audit, but snapshots go stale: wait three days, and one author may have deleted the post, so the approved email is now wrong.

The alternative is to approve the intent ("notify authors of hidden posts") and re-evaluate at send time. That handles drift, but the person on the audit record approved something slightly different from what went out.

Where do you draw that line? Do you re-validate approved actions at execution time, re-ask after some age, or treat any change as a new request? And if you've run approvals on Temporal, Step Functions or LangGraph, what timeout policy did you end up with? I'd like to hear what you run.

About the author

  • Custom software & AI development company. We build production-ready AI integrations, mobile apps, and web platforms for businesses that want real results. lycore.com

No comments yet. Be the first to comment.

More from this blog