Sub topic 8
Waiting for humans: timeouts and escalation
This chapter covers what happens while an approval is pending: how the workflow waits, how long it waits, and who gets asked next when nobody answers. It assumes you can read short Python programs, know what a background job or web request is, and have seen the approval gate and the saved-state idea from earlier chapters.
Why waiting is a design problem
A human reviewer is slow compared to code. They may answer in ten seconds, ten hours, or never. An agent workflow that treats approval like a function call, where it blocks until the answer returns, breaks in three ways:
- It holds a process, a thread, or a connection open for the whole wait.
- It loses the run if the process restarts during the wait.
- It has no answer to "what if nobody ever replies?"
The fix is to separate requesting an approval from resolving it. The workflow saves its state, records a pending request, and stops. Later, a separate event (a click, an API call, a timer) resolves the request and resumes the run.
A pending-approval store
The simplest store is a dictionary with an expiry time on each entry. A real system would use a database table, but the shape is the same.
import time
PENDING = {} # approval_id -> {"call": ..., "expires_at": ...}
def request_approval(approval_id, call, ttl_seconds=3600):
PENDING[approval_id] = {"call": call, "expires_at": time.time() + ttl_seconds}
def resolve(approval_id, decision):
item = PENDING.pop(approval_id, None)
if item is None:
raise KeyError("Unknown or already resolved approval")
if time.time() > item["expires_at"]:
return {"status": "expired"}
return {"status": decision, "call": item["call"]}Three behaviors in resolve matter:
popremoves the entry. A second click on the same approval link finds nothing and raisesKeyError. This is a basic defense against double execution, such as sending the same email twice.- Unknown IDs fail loudly. An ID that was never issued, or was already used, is an error, not a silent success.
- Expiry is checked at decision time. A reviewer who opens an old link and clicks "approve" after the deadline gets
expired, not a stale approval.
Notice that resolve pops the entry before it checks expiry. That means an expired entry is also consumed, which is the right outcome: once a request has expired, it should not be revivable.
Choosing a timeout
A timeout is a decision about what silence means. There are three common choices, and they differ in risk.
| Policy on timeout | What happens | Use when |
|---|---|---|
| Fail closed (reject or expire) | The action does not run. The agent is told it was not approved. | The action is high risk or irreversible. This is the default. |
| Escalate | The request goes to someone else. | The action is needed and a delay has a cost. |
| Fail open (auto-approve) | The action runs without a human. | Almost never. Only for low-impact actions where the approval was a courtesy. |
Treat fail open with suspicion. An approval step exists because the action needs a human decision. Letting a timer make that decision defeats the purpose, and an attacker or an outage that keeps reviewers away would then cause the risky action to run.
Pick the time limit from the action, not from a global constant. A refund request during business hours might expire in 30 minutes. A weekly report publication might wait 48 hours. Record the reasoning next to the setting so the next person can adjust it.
What the agent does with an expired request
An expired approval is a result the agent must handle, like a rejection. The workflow should turn it into a message the agent can use:
def outcome_for_agent(result):
status = result["status"]
if status == "approve":
return {"ok": True}
if status == "expired":
return {
"ok": False,
"reason": "No reviewer responded in time. The action was not performed.",
}
return {"ok": False, "reason": f"Request ended with status: {status}"}Be explicit that the action did not run. If the message is vague, a model may assume the action happened and tell the user it did. The agent should then pick a sensible next step: tell the user the action is waiting on a human, offer a different approach, or end the run. It should not retry the same call in a loop, which would flood reviewers with duplicate requests. Limit retries in the workflow code, not in the prompt.
Escalation
Escalation moves a request to a different person or channel when the first reviewer does not respond. A typical chain looks like this:
- At creation, notify the primary reviewer.
- After a reminder interval, send a reminder to the same person.
- After the first deadline, notify a backup reviewer or a team channel.
- After the final deadline, expire the request and tell the agent and the original user.
Represent the chain as data, so it can be changed without editing code:
ESCALATION = [
{"after_seconds": 0, "notify": "primary_reviewer"},
{"after_seconds": 900, "notify": "primary_reviewer", "kind": "reminder"},
{"after_seconds": 3600, "notify": "backup_reviewer"},
{"after_seconds": 7200, "notify": None, "kind": "expire"},
]
def due_steps(created_at, now, already_done):
"""Return the escalation steps that are due and not yet performed."""
return [
step
for index, step in enumerate(ESCALATION)
if now - created_at >= step["after_seconds"] and index not in already_done
]Something must call due_steps regularly. That is usually a scheduled job that scans pending requests every minute, or a delayed message in a queue created when the request is made. Keep the set of completed steps (already_done) in the stored request. Without it, a scheduler that runs every minute would send the reminder every minute.
Escalation gotchas
- The backup must have authority. If the backup cannot legitimately approve the action, escalating to them only creates noise. Check permissions at decision time, not only at notification time.
- Reviewers go off shift. Notify based on an on-call schedule, not a fixed name. A request created at 2 a.m. should reach whoever is on call.
- Avoid escalation storms. If an outage creates hundreds of pending requests, escalating each one separately can page the same person hundreds of times. Group notifications by reviewer.
- Do not skip the audit trail. Each reminder, escalation, and expiry is an event worth recording, so you can later explain why a request was approved by a person other than the first one asked.
Race conditions between deciders and timers
Two things can happen at nearly the same moment: a reviewer clicks "approve" and the expiry job marks the request expired. With the in-memory example above this cannot happen, because a single process handles both. With a database, both paths read and write the same row, so you need an atomic state change.
The pattern is a conditional update: change the status only if it is still pending, and check how many rows changed.
import sqlite3
def try_resolve(conn, approval_id, new_status):
cur = conn.execute(
"UPDATE approvals SET status = ? WHERE id = ? AND status = 'pending'",
(new_status, approval_id),
)
conn.commit()
return cur.rowcount == 1 # True only for the one caller that wonBoth the reviewer's handler and the expiry job call try_resolve. Exactly one gets True. The loser sees False and must not resume the workflow. Without this check, the run could resume twice: once as expired and once as approved.
Resuming the run
When a request resolves, the workflow needs to continue from where it stopped. This relies on the saved state from the earlier chapter on pausing and resuming. The resolution handler does four things in order:
- Win the conditional update, or return without doing anything.
- Load the saved run state by the approval's run ID.
- Check that the approval still matches the action, as covered in the chapter on binding approvals to actions.
- Continue the agent loop, passing the decision as the tool result.
Do the resume work in a background job, not inside the HTTP handler that received the click. The reviewer's browser should get a quick "recorded" response, and a slow model call should not tie up the request.
Telling the reviewer the clock is running
Reviewers act faster when the request shows its deadline and what happens at that point. Include in every notification:
- The time remaining, or the exact expiry time with a time zone.
- What happens on expiry, for example "The refund will not be issued."
- Who it escalates to, so the reviewer knows whether ignoring it is safe.
Do not use deadlines as pressure ("Approve now or the customer loses access!"). Urgent framing pushes reviewers to approve without reading, which is the failure covered in the chapter on approval fatigue.
Testing time-based behavior
Tests should not sleep. Make the clock an argument so a test can control it:
import time
def resolve_at(pending, approval_id, decision, now):
item = pending.pop(approval_id, None)
if item is None:
raise KeyError("Unknown or already resolved approval")
if now > item["expires_at"]:
return {"status": "expired"}
return {"status": decision, "call": item["call"]}
def test_expired_request_is_not_approved():
pending = {"a1": {"call": "send_email", "expires_at": 1000.0}}
result = resolve_at(pending, "a1", "approve", now=1001.0)
assert result == {"status": "expired"}
def test_double_resolution_fails():
pending = {"a1": {"call": "send_email", "expires_at": 1000.0}}
resolve_at(pending, "a1", "approve", now=999.0)
try:
resolve_at(pending, "a1", "approve", now=999.0)
except KeyError:
return
raise AssertionError("second resolution should fail")Cases worth covering: a decision just before and just after the deadline, a double click, a reminder that fires once and not twice, and a decision that arrives after escalation.
Common errors
- Blocking while waiting. Holding a worker for hours exhausts capacity and loses the run on restart.
- Auto-approve on timeout. This turns an outage into a security hole.
- No terminal state. Requests that never expire pile up and are approved months later against stale context.
- Resuming twice. Missing the atomic check lets a late click and the expiry job both continue the run.
- Vague expiry messages to the agent. The model may report that the action succeeded.
- One global timeout. Different actions have different urgency and risk.
Exercise
A reviewer clicks "approve" at the same moment a scheduled job marks the same request as expired. Both handlers read the request as pending. Describe a database-level change that guarantees only one of them resumes the run, and say what each handler does if it loses.
Show answer
Use a conditional update such as UPDATE approvals SET status = ? WHERE id = ? AND status = 'pending' and check that exactly one row changed. The handler that gets a row count of 1 wins and resumes the run with its status. The handler that gets 0 lost: it must not resume the workflow, and it should report that the request was already resolved (the reviewer sees "already expired" or "already approved", and the expiry job simply skips it).
Exercise
Your team proposes that a pending request for sending a customer email should be automatically approved after 24 hours with no response, "so the agent isn't stuck". Give two reasons this is risky and one safer alternative.
Show answer
First, silence does not mean a human judged the action safe, so the approval step no longer checks anything. Second, an outage, a wrong notification address, or an attacker who suppresses notifications would cause the email to be sent without review. A safer alternative is to escalate to a backup reviewer after a shorter interval and expire the request at the final deadline, telling the agent and the user that the email was not sent. If this action is low risk, classify it in advance with a policy rule instead.
Exercise
In the escalation example, why must already_done be stored with the pending request rather than kept in the scheduler's memory?
Show answer
The scheduler may restart or run on several workers. If the record of performed steps lives only in one process's memory, a restart or a second worker would repeat reminders and escalations. Storing it with the request makes the scheduler stateless and safe to run repeatedly.